holostaff-widget 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/BufferResource-Bh7Dg2tm.js +535 -0
- package/dist/BufferResource-Bh7Dg2tm.js.map +1 -0
- package/dist/CanvasRenderer-DVQieOII.js +976 -0
- package/dist/CanvasRenderer-DVQieOII.js.map +1 -0
- package/dist/RenderTargetSystem-B-GzTxxb.js +2500 -0
- package/dist/RenderTargetSystem-B-GzTxxb.js.map +1 -0
- package/dist/WebGLRenderer-D18tg5um.js +2938 -0
- package/dist/WebGLRenderer-D18tg5um.js.map +1 -0
- package/dist/WebGPURenderer-BuntxQ1w.js +1723 -0
- package/dist/WebGPURenderer-BuntxQ1w.js.map +1 -0
- package/dist/assets/idle-loop-green-8.mp4 +0 -0
- package/dist/assets/idle-loop-green.mp4 +0 -0
- package/dist/assets/idle-loop.mp4 +0 -0
- package/dist/assets/idle-loop.webm +0 -0
- package/dist/browserAll-DgNyjpqs.js +1872 -0
- package/dist/browserAll-DgNyjpqs.js.map +1 -0
- package/dist/hs-widget.es.js +5 -0
- package/dist/hs-widget.es.js.map +1 -0
- package/dist/hs-widget.umd.js +1003 -0
- package/dist/hs-widget.umd.js.map +1 -0
- package/dist/index-DjIeNhPr.js +23003 -0
- package/dist/index-DjIeNhPr.js.map +1 -0
- package/dist/webworkerAll-DndJ9Gy-.js +525 -0
- package/dist/webworkerAll-DndJ9Gy-.js.map +1 -0
- package/package.json +37 -0
|
@@ -0,0 +1,1003 @@
|
|
|
1
|
+
(function(ai,Zt){typeof exports=="object"&&typeof module<"u"?Zt(exports):typeof define=="function"&&define.amd?define(["exports"],Zt):(ai=typeof globalThis<"u"?globalThis:ai||self,Zt(ai.HolostaffWidget={}))})(this,(function(ai){"use strict";const Zt={position:"bottom-center",trigger:"scroll",scrollThreshold:.3,delayMs:3e3,theme:"light",accentColor:null,language:"en",backendUrl:"https://us-central1-holostaff-ai.cloudfunctions.net"};function vu(s){const t=s.dataset.staffId;if(!t)throw new Error("[HolostaffWidget] data-staff-id attribute is required");return{staffId:t,position:s.dataset.position??Zt.position,trigger:s.dataset.trigger??Zt.trigger,scrollThreshold:parseFloat(s.dataset.scrollThreshold??"")||Zt.scrollThreshold,delayMs:parseInt(s.dataset.delayMs??"",10)||Zt.delayMs,theme:s.dataset.theme??Zt.theme,accentColor:s.dataset.accentColor??Zt.accentColor,language:s.dataset.language??Zt.language,backendUrl:s.dataset.backendUrl??Zt.backendUrl}}const Eu=["bottom-center","bottom-left","bottom-right"],Tu=["scroll","delay","immediate"],Su=["light","dark","auto"];function Cu(s,t,e){const i={...s};return!t.dataset.trigger&&e.trigger&&Tu.includes(e.trigger)&&(i.trigger=e.trigger),!t.dataset.position&&e.position&&Eu.includes(e.position)&&(i.position=e.position),!t.dataset.theme&&e.theme&&Su.includes(e.theme)&&(i.theme=e.theme),!t.dataset.scrollThreshold&&e.scrollThreshold!=null&&(i.scrollThreshold=e.scrollThreshold),!t.dataset.delayMs&&e.delayMs!=null&&(i.delayMs=e.delayMs),i}const Ks="https://us-central1-holostaff-ai.cloudfunctions.net";async function wu(s,t=Ks){const e=await fetch(`${t}/widgetSession`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({staffId:s})});if(!e.ok){const i=await e.json().catch(()=>({error:e.statusText}));throw new Error(i.error||`Session request failed: ${e.status}`)}return e.json()}async function Au(s,t=Ks){const e=await fetch(`${t}/widgetConfig?staffId=${encodeURIComponent(s)}`);if(!e.ok){const i=await e.json().catch(()=>({error:e.statusText}));throw new Error(i.error||`Config request failed: ${e.status}`)}return e.json()}async function Ru(s,t,e,i=Ks){const r=await fetch(`${i}/widgetPageAction`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({staffId:s,domSnapshot:t,instruction:e})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||`Page action request failed: ${r.status}`)}return r.json()}var w=(s=>(s.Application="application",s.WebGLPipes="webgl-pipes",s.WebGLPipesAdaptor="webgl-pipes-adaptor",s.WebGLSystem="webgl-system",s.WebGPUPipes="webgpu-pipes",s.WebGPUPipesAdaptor="webgpu-pipes-adaptor",s.WebGPUSystem="webgpu-system",s.CanvasSystem="canvas-system",s.CanvasPipesAdaptor="canvas-pipes-adaptor",s.CanvasPipes="canvas-pipes",s.Asset="asset",s.LoadParser="load-parser",s.ResolveParser="resolve-parser",s.CacheParser="cache-parser",s.DetectionParser="detection-parser",s.MaskEffect="mask-effect",s.BlendMode="blend-mode",s.TextureSource="texture-source",s.Environment="environment",s.ShapeBuilder="shape-builder",s.Batcher="batcher",s))(w||{});const Zs=s=>{if(typeof s=="function"||typeof s=="object"&&s.extension){if(!s.extension)throw new Error("Extension class must have an extension object");s={...typeof s.extension!="object"?{type:s.extension}:s.extension,ref:s}}if(typeof s=="object")s={...s};else throw new Error("Invalid extension type");return typeof s.type=="string"&&(s.type=[s.type]),s},cs=(s,t)=>Zs(s).priority??t,J={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...s){return s.map(Zs).forEach(t=>{t.type.forEach(e=>{var i,r;return(r=(i=this._removeHandlers)[e])==null?void 0:r.call(i,t)})}),this},add(...s){return s.map(Zs).forEach(t=>{t.type.forEach(e=>{var n,o;const i=this._addHandlers,r=this._queue;i[e]?(o=i[e])==null||o.call(i,t):(r[e]=r[e]||[],(n=r[e])==null||n.push(t))})}),this},handle(s,t,e){var o;const i=this._addHandlers,r=this._removeHandlers;if(i[s]||r[s])throw new Error(`Extension type ${s} already has a handler`);i[s]=t,r[s]=e;const n=this._queue;return n[s]&&((o=n[s])==null||o.forEach(a=>t(a)),delete n[s]),this},handleByMap(s,t){return this.handle(s,e=>{e.name&&(t[e.name]=e.ref)},e=>{e.name&&delete t[e.name]})},handleByNamedList(s,t,e=-1){return this.handle(s,i=>{t.findIndex(n=>n.name===i.name)>=0||(t.push({name:i.name,value:i.ref}),t.sort((n,o)=>cs(o.value,e)-cs(n.value,e)))},i=>{const r=t.findIndex(n=>n.name===i.name);r!==-1&&t.splice(r,1)})},handleByList(s,t,e=-1){return this.handle(s,i=>{t.includes(i.ref)||(t.push(i.ref),t.sort((r,n)=>cs(n,e)-cs(r,e)))},i=>{const r=t.indexOf(i.ref);r!==-1&&t.splice(r,1)})},mixin(s,...t){for(const e of t)Object.defineProperties(s.prototype,Object.getOwnPropertyDescriptors(e))}},Pu={extension:{type:w.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await Promise.resolve().then(()=>jx)}},Iu={extension:{type:w.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await Promise.resolve().then(()=>Xx)}};class Ot{constructor(t,e,i){this._x=e||0,this._y=i||0,this._observer=t}clone(t){return new Ot(t??this._observer,this._x,this._y)}set(t=0,e=t){return(this._x!==t||this._y!==e)&&(this._x=t,this._y=e,this._observer._onUpdate(this)),this}copyFrom(t){return(this._x!==t.x||this._y!==t.y)&&(this._x=t.x,this._y=t.y,this._observer._onUpdate(this)),this}copyTo(t){return t.set(this._x,this._y),t}equals(t){return t.x===this._x&&t.y===this._y}toString(){return`[pixi.js/math:ObservablePoint x=${this._x} y=${this._y} scope=${this._observer}]`}get x(){return this._x}set x(t){this._x!==t&&(this._x=t,this._observer._onUpdate(this))}get y(){return this._y}set y(t){this._y!==t&&(this._y=t,this._observer._onUpdate(this))}}function oo(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Js={exports:{}},ao;function Mu(){return ao||(ao=1,(function(s){var t=Object.prototype.hasOwnProperty,e="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(e=!1));function r(l,h,c){this.fn=l,this.context=h,this.once=c||!1}function n(l,h,c,u,m){if(typeof c!="function")throw new TypeError("The listener must be a function");var f=new r(c,u||l,m),g=e?e+h:h;return l._events[g]?l._events[g].fn?l._events[g]=[l._events[g],f]:l._events[g].push(f):(l._events[g]=f,l._eventsCount++),l}function o(l,h){--l._eventsCount===0?l._events=new i:delete l._events[h]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var h=[],c,u;if(this._eventsCount===0)return h;for(u in c=this._events)t.call(c,u)&&h.push(e?u.slice(1):u);return Object.getOwnPropertySymbols?h.concat(Object.getOwnPropertySymbols(c)):h},a.prototype.listeners=function(h){var c=e?e+h:h,u=this._events[c];if(!u)return[];if(u.fn)return[u.fn];for(var m=0,f=u.length,g=new Array(f);m<f;m++)g[m]=u[m].fn;return g},a.prototype.listenerCount=function(h){var c=e?e+h:h,u=this._events[c];return u?u.fn?1:u.length:0},a.prototype.emit=function(h,c,u,m,f,g){var y=e?e+h:h;if(!this._events[y])return!1;var x=this._events[y],v=arguments.length,E,T;if(x.fn){switch(x.once&&this.removeListener(h,x.fn,void 0,!0),v){case 1:return x.fn.call(x.context),!0;case 2:return x.fn.call(x.context,c),!0;case 3:return x.fn.call(x.context,c,u),!0;case 4:return x.fn.call(x.context,c,u,m),!0;case 5:return x.fn.call(x.context,c,u,m,f),!0;case 6:return x.fn.call(x.context,c,u,m,f,g),!0}for(T=1,E=new Array(v-1);T<v;T++)E[T-1]=arguments[T];x.fn.apply(x.context,E)}else{var C=x.length,R;for(T=0;T<C;T++)switch(x[T].once&&this.removeListener(h,x[T].fn,void 0,!0),v){case 1:x[T].fn.call(x[T].context);break;case 2:x[T].fn.call(x[T].context,c);break;case 3:x[T].fn.call(x[T].context,c,u);break;case 4:x[T].fn.call(x[T].context,c,u,m);break;default:if(!E)for(R=1,E=new Array(v-1);R<v;R++)E[R-1]=arguments[R];x[T].fn.apply(x[T].context,E)}}return!0},a.prototype.on=function(h,c,u){return n(this,h,c,u,!1)},a.prototype.once=function(h,c,u){return n(this,h,c,u,!0)},a.prototype.removeListener=function(h,c,u,m){var f=e?e+h:h;if(!this._events[f])return this;if(!c)return o(this,f),this;var g=this._events[f];if(g.fn)g.fn===c&&(!m||g.once)&&(!u||g.context===u)&&o(this,f);else{for(var y=0,x=[],v=g.length;y<v;y++)(g[y].fn!==c||m&&!g[y].once||u&&g[y].context!==u)&&x.push(g[y]);x.length?this._events[f]=x.length===1?x[0]:x:o(this,f)}return this},a.prototype.removeAllListeners=function(h){var c;return h?(c=e?e+h:h,this._events[c]&&o(this,c)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=e,a.EventEmitter=a,s.exports=a})(Js)),Js.exports}var ku=Mu();const Jt=oo(ku),Bu=Math.PI*2,Ou=180/Math.PI,Du=Math.PI/180;class mt{constructor(t=0,e=0){this.x=0,this.y=0,this.x=t,this.y=e}clone(){return new mt(this.x,this.y)}copyFrom(t){return this.set(t.x,t.y),this}copyTo(t){return t.set(this.x,this.y),t}equals(t){return t.x===this.x&&t.y===this.y}set(t=0,e=t){return this.x=t,this.y=e,this}toString(){return`[pixi.js/math:Point x=${this.x} y=${this.y}]`}static get shared(){return Qs.x=0,Qs.y=0,Qs}}const Qs=new mt;class W{constructor(t=1,e=0,i=0,r=1,n=0,o=0){this.array=null,this.a=t,this.b=e,this.c=i,this.d=r,this.tx=n,this.ty=o}fromArray(t){this.a=t[0],this.b=t[1],this.c=t[3],this.d=t[4],this.tx=t[2],this.ty=t[5]}set(t,e,i,r,n,o){return this.a=t,this.b=e,this.c=i,this.d=r,this.tx=n,this.ty=o,this}toArray(t,e){this.array||(this.array=new Float32Array(9));const i=e||this.array;return t?(i[0]=this.a,i[1]=this.b,i[2]=0,i[3]=this.c,i[4]=this.d,i[5]=0,i[6]=this.tx,i[7]=this.ty,i[8]=1):(i[0]=this.a,i[1]=this.c,i[2]=this.tx,i[3]=this.b,i[4]=this.d,i[5]=this.ty,i[6]=0,i[7]=0,i[8]=1),i}apply(t,e){e=e||new mt;const i=t.x,r=t.y;return e.x=this.a*i+this.c*r+this.tx,e.y=this.b*i+this.d*r+this.ty,e}applyInverse(t,e){e=e||new mt;const i=this.a,r=this.b,n=this.c,o=this.d,a=this.tx,l=this.ty,h=1/(i*o+n*-r),c=t.x,u=t.y;return e.x=o*h*c+-n*h*u+(l*n-a*o)*h,e.y=i*h*u+-r*h*c+(-l*i+a*r)*h,e}translate(t,e){return this.tx+=t,this.ty+=e,this}scale(t,e){return this.a*=t,this.d*=e,this.c*=t,this.b*=e,this.tx*=t,this.ty*=e,this}rotate(t){const e=Math.cos(t),i=Math.sin(t),r=this.a,n=this.c,o=this.tx;return this.a=r*e-this.b*i,this.b=r*i+this.b*e,this.c=n*e-this.d*i,this.d=n*i+this.d*e,this.tx=o*e-this.ty*i,this.ty=o*i+this.ty*e,this}append(t){const e=this.a,i=this.b,r=this.c,n=this.d;return this.a=t.a*e+t.b*r,this.b=t.a*i+t.b*n,this.c=t.c*e+t.d*r,this.d=t.c*i+t.d*n,this.tx=t.tx*e+t.ty*r+this.tx,this.ty=t.tx*i+t.ty*n+this.ty,this}appendFrom(t,e){const i=t.a,r=t.b,n=t.c,o=t.d,a=t.tx,l=t.ty,h=e.a,c=e.b,u=e.c,m=e.d;return this.a=i*h+r*u,this.b=i*c+r*m,this.c=n*h+o*u,this.d=n*c+o*m,this.tx=a*h+l*u+e.tx,this.ty=a*c+l*m+e.ty,this}setTransform(t,e,i,r,n,o,a,l,h){return this.a=Math.cos(a+h)*n,this.b=Math.sin(a+h)*n,this.c=-Math.sin(a-l)*o,this.d=Math.cos(a-l)*o,this.tx=t-(i*this.a+r*this.c),this.ty=e-(i*this.b+r*this.d),this}prepend(t){const e=this.tx;if(t.a!==1||t.b!==0||t.c!==0||t.d!==1){const i=this.a,r=this.c;this.a=i*t.a+this.b*t.c,this.b=i*t.b+this.b*t.d,this.c=r*t.a+this.d*t.c,this.d=r*t.b+this.d*t.d}return this.tx=e*t.a+this.ty*t.c+t.tx,this.ty=e*t.b+this.ty*t.d+t.ty,this}decompose(t){const e=this.a,i=this.b,r=this.c,n=this.d,o=t.pivot,a=-Math.atan2(-r,n),l=Math.atan2(i,e),h=Math.abs(a+l);return h<1e-5||Math.abs(Bu-h)<1e-5?(t.rotation=l,t.skew.x=t.skew.y=0):(t.rotation=0,t.skew.x=a,t.skew.y=l),t.scale.x=Math.sqrt(e*e+i*i),t.scale.y=Math.sqrt(r*r+n*n),t.position.x=this.tx+(o.x*e+o.y*r),t.position.y=this.ty+(o.x*i+o.y*n),t}invert(){const t=this.a,e=this.b,i=this.c,r=this.d,n=this.tx,o=t*r-e*i;return this.a=r/o,this.b=-e/o,this.c=-i/o,this.d=t/o,this.tx=(i*this.ty-r*n)/o,this.ty=-(t*this.ty-e*n)/o,this}isIdentity(){return this.a===1&&this.b===0&&this.c===0&&this.d===1&&this.tx===0&&this.ty===0}identity(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this}clone(){const t=new W;return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t}copyTo(t){return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t}copyFrom(t){return this.a=t.a,this.b=t.b,this.c=t.c,this.d=t.d,this.tx=t.tx,this.ty=t.ty,this}equals(t){return t.a===this.a&&t.b===this.b&&t.c===this.c&&t.d===this.d&&t.tx===this.tx&&t.ty===this.ty}toString(){return`[pixi.js:Matrix a=${this.a} b=${this.b} c=${this.c} d=${this.d} tx=${this.tx} ty=${this.ty}]`}static get IDENTITY(){return Uu.identity()}static get shared(){return Gu.identity()}}const Gu=new W,Uu=new W,Ve=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],ze=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],$e=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],je=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],tr=[],lo=[],us=Math.sign;function Lu(){for(let s=0;s<16;s++){const t=[];tr.push(t);for(let e=0;e<16;e++){const i=us(Ve[s]*Ve[e]+$e[s]*ze[e]),r=us(ze[s]*Ve[e]+je[s]*ze[e]),n=us(Ve[s]*$e[e]+$e[s]*je[e]),o=us(ze[s]*$e[e]+je[s]*je[e]);for(let a=0;a<16;a++)if(Ve[a]===i&&ze[a]===r&&$e[a]===n&&je[a]===o){t.push(a);break}}}for(let s=0;s<16;s++){const t=new W;t.set(Ve[s],ze[s],$e[s],je[s],0,0),lo.push(t)}}Lu();const it={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MAIN_DIAGONAL:10,MIRROR_HORIZONTAL:12,REVERSE_DIAGONAL:14,uX:s=>Ve[s],uY:s=>ze[s],vX:s=>$e[s],vY:s=>je[s],inv:s=>s&8?s&15:-s&7,add:(s,t)=>tr[s][t],sub:(s,t)=>tr[s][it.inv(t)],rotate180:s=>s^4,isVertical:s=>(s&3)===2,byDirection:(s,t)=>Math.abs(s)*2<=Math.abs(t)?t>=0?it.S:it.N:Math.abs(t)*2<=Math.abs(s)?s>0?it.E:it.W:t>0?s>0?it.SE:it.SW:s>0?it.NE:it.NW,matrixAppendRotationInv:(s,t,e=0,i=0,r=0,n=0)=>{const o=lo[it.inv(t)],a=o.a,l=o.b,h=o.c,c=o.d,u=e-Math.min(0,a*r,h*n,a*r+h*n),m=i-Math.min(0,l*r,c*n,l*r+c*n),f=s.a,g=s.b,y=s.c,x=s.d;s.a=a*f+l*y,s.b=a*g+l*x,s.c=h*f+c*y,s.d=h*g+c*x,s.tx=u*f+m*y+s.tx,s.ty=u*g+m*x+s.ty},transformRectCoords:(s,t,e,i)=>{const{x:r,y:n,width:o,height:a}=s,{x:l,y:h,width:c,height:u}=t;return e===it.E?(i.set(r+l,n+h,o,a),i):e===it.S?i.set(c-n-a+l,r+h,a,o):e===it.W?i.set(c-r-o+l,u-n-a+h,o,a):e===it.N?i.set(n+l,u-r-o+h,a,o):i.set(r+l,n+h,o,a)}},ds=[new mt,new mt,new mt,new mt];class ut{constructor(t=0,e=0,i=0,r=0){this.type="rectangle",this.x=Number(t),this.y=Number(e),this.width=Number(i),this.height=Number(r)}get left(){return this.x}get right(){return this.x+this.width}get top(){return this.y}get bottom(){return this.y+this.height}isEmpty(){return this.left===this.right||this.top===this.bottom}static get EMPTY(){return new ut(0,0,0,0)}clone(){return new ut(this.x,this.y,this.width,this.height)}copyFromBounds(t){return this.x=t.minX,this.y=t.minY,this.width=t.maxX-t.minX,this.height=t.maxY-t.minY,this}copyFrom(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this}copyTo(t){return t.copyFrom(this),t}contains(t,e){return this.width<=0||this.height<=0?!1:t>=this.x&&t<this.x+this.width&&e>=this.y&&e<this.y+this.height}strokeContains(t,e,i,r=.5){const{width:n,height:o}=this;if(n<=0||o<=0)return!1;const a=this.x,l=this.y,h=i*(1-r),c=i-h,u=a-h,m=a+n+h,f=l-h,g=l+o+h,y=a+c,x=a+n-c,v=l+c,E=l+o-c;return t>=u&&t<=m&&e>=f&&e<=g&&!(t>y&&t<x&&e>v&&e<E)}intersects(t,e){if(!e){const N=this.x<t.x?t.x:this.x;if((this.right>t.right?t.right:this.right)<=N)return!1;const k=this.y<t.y?t.y:this.y;return(this.bottom>t.bottom?t.bottom:this.bottom)>k}const i=this.left,r=this.right,n=this.top,o=this.bottom;if(r<=i||o<=n)return!1;const a=ds[0].set(t.left,t.top),l=ds[1].set(t.left,t.bottom),h=ds[2].set(t.right,t.top),c=ds[3].set(t.right,t.bottom);if(h.x<=a.x||l.y<=a.y)return!1;const u=Math.sign(e.a*e.d-e.b*e.c);if(u===0||(e.apply(a,a),e.apply(l,l),e.apply(h,h),e.apply(c,c),Math.max(a.x,l.x,h.x,c.x)<=i||Math.min(a.x,l.x,h.x,c.x)>=r||Math.max(a.y,l.y,h.y,c.y)<=n||Math.min(a.y,l.y,h.y,c.y)>=o))return!1;const m=u*(l.y-a.y),f=u*(a.x-l.x),g=m*i+f*n,y=m*r+f*n,x=m*i+f*o,v=m*r+f*o;if(Math.max(g,y,x,v)<=m*a.x+f*a.y||Math.min(g,y,x,v)>=m*c.x+f*c.y)return!1;const E=u*(a.y-h.y),T=u*(h.x-a.x),C=E*i+T*n,R=E*r+T*n,A=E*i+T*o,I=E*r+T*o;return!(Math.max(C,R,A,I)<=E*a.x+T*a.y||Math.min(C,R,A,I)>=E*c.x+T*c.y)}pad(t=0,e=t){return this.x-=t,this.y-=e,this.width+=t*2,this.height+=e*2,this}fit(t){const e=Math.max(this.x,t.x),i=Math.min(this.x+this.width,t.x+t.width),r=Math.max(this.y,t.y),n=Math.min(this.y+this.height,t.y+t.height);return this.x=e,this.width=Math.max(i-e,0),this.y=r,this.height=Math.max(n-r,0),this}ceil(t=1,e=.001){const i=Math.ceil((this.x+this.width-e)*t)/t,r=Math.ceil((this.y+this.height-e)*t)/t;return this.x=Math.floor((this.x+e)*t)/t,this.y=Math.floor((this.y+e)*t)/t,this.width=i-this.x,this.height=r-this.y,this}scale(t,e=t){return this.x*=t,this.y*=e,this.width*=t,this.height*=e,this}enlarge(t){const e=Math.min(this.x,t.x),i=Math.max(this.x+this.width,t.x+t.width),r=Math.min(this.y,t.y),n=Math.max(this.y+this.height,t.y+t.height);return this.x=e,this.width=i-e,this.y=r,this.height=n-r,this}getBounds(t){return t||(t=new ut),t.copyFrom(this),t}containsRect(t){if(this.width<=0||this.height<=0)return!1;const e=t.x,i=t.y,r=t.x+t.width,n=t.y+t.height;return e>=this.x&&e<this.x+this.width&&i>=this.y&&i<this.y+this.height&&r>=this.x&&r<this.x+this.width&&n>=this.y&&n<this.y+this.height}set(t,e,i,r){return this.x=t,this.y=e,this.width=i,this.height=r,this}toString(){return`[pixi.js/math:Rectangle x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`}}const er={default:-1};function dt(s="default"){return er[s]===void 0&&(er[s]=-1),++er[s]}const ho=new Set,vt="8.0.0",Fu="8.3.4",li={quiet:!1,noColor:!1},K=((s,t,e=3)=>{if(li.quiet||ho.has(t))return;let i=new Error().stack;const r=`${t}
|
|
2
|
+
Deprecated since v${s}`,n=typeof console.groupCollapsed=="function"&&!li.noColor;typeof i>"u"?console.warn("PixiJS Deprecation Warning: ",r):(i=i.split(`
|
|
3
|
+
`).splice(e).join(`
|
|
4
|
+
`),n?(console.groupCollapsed("%cPixiJS Deprecation Warning: %c%s","color:#614108;background:#fffbe6","font-weight:normal;color:#614108;background:#fffbe6",r),console.warn(i),console.groupEnd()):(console.warn("PixiJS Deprecation Warning: ",r),console.warn(i))),ho.add(t)});Object.defineProperties(K,{quiet:{get:()=>li.quiet,set:s=>{li.quiet=s},enumerable:!0,configurable:!1},noColor:{get:()=>li.noColor,set:s=>{li.noColor=s},enumerable:!0,configurable:!1}});const co=()=>{};function hi(s){return s+=s===0?1:0,--s,s|=s>>>1,s|=s>>>2,s|=s>>>4,s|=s>>>8,s|=s>>>16,s+1}function uo(s){return!(s&s-1)&&!!s}function fo(s){const t={};for(const e in s)s[e]!==void 0&&(t[e]=s[e]);return t}const po=Object.create(null);function Nu(s){const t=po[s];return t===void 0&&(po[s]=dt("resource")),t}const mo=class su extends Jt{constructor(t={}){super(),this._resourceType="textureSampler",this._touched=0,this._maxAnisotropy=1,this.destroyed=!1,t={...su.defaultOptions,...t},this.addressMode=t.addressMode,this.addressModeU=t.addressModeU??this.addressModeU,this.addressModeV=t.addressModeV??this.addressModeV,this.addressModeW=t.addressModeW??this.addressModeW,this.scaleMode=t.scaleMode,this.magFilter=t.magFilter??this.magFilter,this.minFilter=t.minFilter??this.minFilter,this.mipmapFilter=t.mipmapFilter??this.mipmapFilter,this.lodMinClamp=t.lodMinClamp,this.lodMaxClamp=t.lodMaxClamp,this.compare=t.compare,this.maxAnisotropy=t.maxAnisotropy??1}set addressMode(t){this.addressModeU=t,this.addressModeV=t,this.addressModeW=t}get addressMode(){return this.addressModeU}set wrapMode(t){K(vt,"TextureStyle.wrapMode is now TextureStyle.addressMode"),this.addressMode=t}get wrapMode(){return this.addressMode}set scaleMode(t){this.magFilter=t,this.minFilter=t,this.mipmapFilter=t}get scaleMode(){return this.magFilter}set maxAnisotropy(t){this._maxAnisotropy=Math.min(t,16),this._maxAnisotropy>1&&(this.scaleMode="linear")}get maxAnisotropy(){return this._maxAnisotropy}get _resourceId(){return this._sharedResourceId||this._generateResourceId()}update(){this._sharedResourceId=null,this.emit("change",this)}_generateResourceId(){const t=`${this.addressModeU}-${this.addressModeV}-${this.addressModeW}-${this.magFilter}-${this.minFilter}-${this.mipmapFilter}-${this.lodMinClamp}-${this.lodMaxClamp}-${this.compare}-${this._maxAnisotropy}`;return this._sharedResourceId=Nu(t),this._resourceId}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this.removeAllListeners()}};mo.defaultOptions={addressMode:"clamp-to-edge",scaleMode:"linear"};let Xe=mo;const go=class ru extends Jt{constructor(t={}){super(),this.options=t,this._gpuData=Object.create(null),this._gcLastUsed=-1,this.uid=dt("textureSource"),this._resourceType="textureSource",this._resourceId=dt("resource"),this.uploadMethodId="unknown",this._resolution=1,this.pixelWidth=1,this.pixelHeight=1,this.width=1,this.height=1,this.sampleCount=1,this.mipLevelCount=1,this.autoGenerateMipmaps=!1,this.format="rgba8unorm",this.dimension="2d",this.viewDimension="2d",this.arrayLayerCount=1,this.antialias=!1,this._touched=0,this._batchTick=-1,this._textureBindLocation=-1,t={...ru.defaultOptions,...t},this.label=t.label??"",this.resource=t.resource,this.autoGarbageCollect=t.autoGarbageCollect,this._resolution=t.resolution,t.width?this.pixelWidth=t.width*this._resolution:this.pixelWidth=this.resource?this.resourceWidth??1:1,t.height?this.pixelHeight=t.height*this._resolution:this.pixelHeight=this.resource?this.resourceHeight??1:1,this.width=this.pixelWidth/this._resolution,this.height=this.pixelHeight/this._resolution,this.format=t.format,this.dimension=t.dimensions,this.viewDimension=t.viewDimension??t.dimensions,this.arrayLayerCount=t.arrayLayerCount,this.mipLevelCount=t.mipLevelCount,this.autoGenerateMipmaps=t.autoGenerateMipmaps,this.sampleCount=t.sampleCount,this.antialias=t.antialias,this.alphaMode=t.alphaMode,this.style=new Xe(fo(t)),this.destroyed=!1,this._refreshPOT()}get source(){return this}get style(){return this._style}set style(t){var e,i;this.style!==t&&((e=this._style)==null||e.off("change",this._onStyleChange,this),this._style=t,(i=this._style)==null||i.on("change",this._onStyleChange,this),this._onStyleChange())}set maxAnisotropy(t){this._style.maxAnisotropy=t}get maxAnisotropy(){return this._style.maxAnisotropy}get addressMode(){return this._style.addressMode}set addressMode(t){this._style.addressMode=t}get repeatMode(){return this._style.addressMode}set repeatMode(t){this._style.addressMode=t}get magFilter(){return this._style.magFilter}set magFilter(t){this._style.magFilter=t}get minFilter(){return this._style.minFilter}set minFilter(t){this._style.minFilter=t}get mipmapFilter(){return this._style.mipmapFilter}set mipmapFilter(t){this._style.mipmapFilter=t}get lodMinClamp(){return this._style.lodMinClamp}set lodMinClamp(t){this._style.lodMinClamp=t}get lodMaxClamp(){return this._style.lodMaxClamp}set lodMaxClamp(t){this._style.lodMaxClamp=t}_onStyleChange(){this.emit("styleChange",this)}update(){if(this.resource){const t=this._resolution;if(this.resize(this.resourceWidth/t,this.resourceHeight/t))return}this.emit("update",this)}destroy(){this.destroyed=!0,this.unload(),this.emit("destroy",this),this._style&&(this._style.destroy(),this._style=null),this.uploadMethodId=null,this.resource=null,this.removeAllListeners()}unload(){var t,e;this._resourceId=dt("resource"),this.emit("change",this),this.emit("unload",this);for(const i in this._gpuData)(e=(t=this._gpuData[i])==null?void 0:t.destroy)==null||e.call(t);this._gpuData=Object.create(null)}get resourceWidth(){const{resource:t}=this;return t.naturalWidth||t.videoWidth||t.displayWidth||t.width}get resourceHeight(){const{resource:t}=this;return t.naturalHeight||t.videoHeight||t.displayHeight||t.height}get resolution(){return this._resolution}set resolution(t){this._resolution!==t&&(this._resolution=t,this.width=this.pixelWidth/t,this.height=this.pixelHeight/t)}resize(t,e,i){i||(i=this._resolution),t||(t=this.width),e||(e=this.height);const r=Math.round(t*i),n=Math.round(e*i);return this.width=r/i,this.height=n/i,this._resolution=i,this.pixelWidth===r&&this.pixelHeight===n?!1:(this._refreshPOT(),this.pixelWidth=r,this.pixelHeight=n,this.emit("resize",this),this._resourceId=dt("resource"),this.emit("change",this),!0)}updateMipmaps(){this.autoGenerateMipmaps&&this.mipLevelCount>1&&this.emit("updateMipmaps",this)}set wrapMode(t){this._style.wrapMode=t}get wrapMode(){return this._style.wrapMode}set scaleMode(t){this._style.scaleMode=t}get scaleMode(){return this._style.scaleMode}_refreshPOT(){this.isPowerOfTwo=uo(this.pixelWidth)&&uo(this.pixelHeight)}static test(t){throw new Error("Unimplemented")}};go.defaultOptions={resolution:1,format:"bgra8unorm",alphaMode:"premultiply-alpha-on-upload",dimensions:"2d",viewDimension:"2d",arrayLayerCount:1,mipLevelCount:1,autoGenerateMipmaps:!1,sampleCount:1,antialias:!1,autoGarbageCollect:!1};let At=go;class ir extends At{constructor(t){const e=t.resource||new Float32Array(t.width*t.height*4);let i=t.format;i||(e instanceof Float32Array?i="rgba32float":e instanceof Int32Array||e instanceof Uint32Array?i="rgba32uint":e instanceof Int16Array||e instanceof Uint16Array?i="rgba16uint":(e instanceof Int8Array,i="bgra8unorm")),super({...t,resource:e,format:i}),this.uploadMethodId="buffer"}static test(t){return t instanceof Int8Array||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int16Array||t instanceof Uint16Array||t instanceof Int32Array||t instanceof Uint32Array||t instanceof Float32Array}}ir.extension=w.TextureSource;const _o=new W;class yo{constructor(t,e){this.mapCoord=new W,this.uClampFrame=new Float32Array(4),this.uClampOffset=new Float32Array(2),this._textureID=-1,this._updateID=0,this.clampOffset=0,typeof e>"u"?this.clampMargin=t.width<10?0:.5:this.clampMargin=e,this.isSimple=!1,this.texture=t}get texture(){return this._texture}set texture(t){var e;this.texture!==t&&((e=this._texture)==null||e.removeListener("update",this.update,this),this._texture=t,this._texture.addListener("update",this.update,this),this.update())}multiplyUvs(t,e){e===void 0&&(e=t);const i=this.mapCoord;for(let r=0;r<t.length;r+=2){const n=t[r],o=t[r+1];e[r]=n*i.a+o*i.c+i.tx,e[r+1]=n*i.b+o*i.d+i.ty}return e}update(){const t=this._texture;this._updateID++;const e=t.uvs;this.mapCoord.set(e.x1-e.x0,e.y1-e.y0,e.x3-e.x0,e.y3-e.y0,e.x0,e.y0);const i=t.orig,r=t.trim;r&&(_o.set(i.width/r.width,0,0,i.height/r.height,-r.x/r.width,-r.y/r.height),this.mapCoord.append(_o));const n=t.source,o=this.uClampFrame,a=this.clampMargin/n._resolution,l=this.clampOffset/n._resolution;return o[0]=(t.frame.x+a+l)/n.width,o[1]=(t.frame.y+a+l)/n.height,o[2]=(t.frame.x+t.frame.width-a+l)/n.width,o[3]=(t.frame.y+t.frame.height-a+l)/n.height,this.uClampOffset[0]=this.clampOffset/n.pixelWidth,this.uClampOffset[1]=this.clampOffset/n.pixelHeight,this.isSimple=t.frame.width===n.width&&t.frame.height===n.height&&t.rotate===0,!0}}class z extends Jt{constructor({source:t,label:e,frame:i,orig:r,trim:n,defaultAnchor:o,defaultBorders:a,rotate:l,dynamic:h}={}){if(super(),this.uid=dt("texture"),this.uvs={x0:0,y0:0,x1:0,y1:0,x2:0,y2:0,x3:0,y3:0},this.frame=new ut,this.noFrame=!1,this.dynamic=!1,this.isTexture=!0,this.label=e,this.source=(t==null?void 0:t.source)??new At,this.noFrame=!i,i)this.frame.copyFrom(i);else{const{width:c,height:u}=this._source;this.frame.width=c,this.frame.height=u}this.orig=r||this.frame,this.trim=n,this.rotate=l??0,this.defaultAnchor=o,this.defaultBorders=a,this.destroyed=!1,this.dynamic=h||!1,this.updateUvs()}set source(t){this._source&&this._source.off("resize",this.update,this),this._source=t,t.on("resize",this.update,this),this.emit("update",this)}get source(){return this._source}get textureMatrix(){return this._textureMatrix||(this._textureMatrix=new yo(this)),this._textureMatrix}get width(){return this.orig.width}get height(){return this.orig.height}updateUvs(){const{uvs:t,frame:e}=this,{width:i,height:r}=this._source,n=e.x/i,o=e.y/r,a=e.width/i,l=e.height/r;let h=this.rotate;if(h){const c=a/2,u=l/2,m=n+c,f=o+u;h=it.add(h,it.NW),t.x0=m+c*it.uX(h),t.y0=f+u*it.uY(h),h=it.add(h,2),t.x1=m+c*it.uX(h),t.y1=f+u*it.uY(h),h=it.add(h,2),t.x2=m+c*it.uX(h),t.y2=f+u*it.uY(h),h=it.add(h,2),t.x3=m+c*it.uX(h),t.y3=f+u*it.uY(h)}else t.x0=n,t.y0=o,t.x1=n+a,t.y1=o,t.x2=n+a,t.y2=o+l,t.x3=n,t.y3=o+l}destroy(t=!1){this._source&&(this._source.off("resize",this.update,this),t&&(this._source.destroy(),this._source=null)),this._textureMatrix=null,this.destroyed=!0,this.emit("destroy",this),this.removeAllListeners()}update(){this.noFrame&&(this.frame.width=this._source.width,this.frame.height=this._source.height),this.updateUvs(),this.emit("update",this)}get baseTexture(){return K(vt,"Texture.baseTexture is now Texture.source"),this._source}}z.EMPTY=new z({label:"EMPTY",source:new At({label:"EMPTY"})}),z.EMPTY.destroy=co,z.WHITE=new z({source:new ir({resource:new Uint8Array([255,255,255,255]),width:1,height:1,alphaMode:"premultiply-alpha-on-upload",label:"WHITE"}),label:"WHITE"}),z.WHITE.destroy=co;function xo(s,t,e){const{width:i,height:r}=e.orig,n=e.trim;if(n){const o=n.width,a=n.height;s.minX=n.x-t._x*i,s.maxX=s.minX+o,s.minY=n.y-t._y*r,s.maxY=s.minY+a}else s.minX=-t._x*i,s.maxX=s.minX+i,s.minY=-t._y*r,s.maxY=s.minY+r}const bo=new W;class Lt{constructor(t=1/0,e=1/0,i=-1/0,r=-1/0){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=bo,this.minX=t,this.minY=e,this.maxX=i,this.maxY=r}isEmpty(){return this.minX>this.maxX||this.minY>this.maxY}get rectangle(){this._rectangle||(this._rectangle=new ut);const t=this._rectangle;return this.minX>this.maxX||this.minY>this.maxY?(t.x=0,t.y=0,t.width=0,t.height=0):t.copyFromBounds(this),t}clear(){return this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=bo,this}set(t,e,i,r){this.minX=t,this.minY=e,this.maxX=i,this.maxY=r}addFrame(t,e,i,r,n){n||(n=this.matrix);const o=n.a,a=n.b,l=n.c,h=n.d,c=n.tx,u=n.ty;let m=this.minX,f=this.minY,g=this.maxX,y=this.maxY,x=o*t+l*e+c,v=a*t+h*e+u;x<m&&(m=x),v<f&&(f=v),x>g&&(g=x),v>y&&(y=v),x=o*i+l*e+c,v=a*i+h*e+u,x<m&&(m=x),v<f&&(f=v),x>g&&(g=x),v>y&&(y=v),x=o*t+l*r+c,v=a*t+h*r+u,x<m&&(m=x),v<f&&(f=v),x>g&&(g=x),v>y&&(y=v),x=o*i+l*r+c,v=a*i+h*r+u,x<m&&(m=x),v<f&&(f=v),x>g&&(g=x),v>y&&(y=v),this.minX=m,this.minY=f,this.maxX=g,this.maxY=y}addRect(t,e){this.addFrame(t.x,t.y,t.x+t.width,t.y+t.height,e)}addBounds(t,e){this.addFrame(t.minX,t.minY,t.maxX,t.maxY,e)}addBoundsMask(t){this.minX=this.minX>t.minX?this.minX:t.minX,this.minY=this.minY>t.minY?this.minY:t.minY,this.maxX=this.maxX<t.maxX?this.maxX:t.maxX,this.maxY=this.maxY<t.maxY?this.maxY:t.maxY}applyMatrix(t){const e=this.minX,i=this.minY,r=this.maxX,n=this.maxY,{a:o,b:a,c:l,d:h,tx:c,ty:u}=t;let m=o*e+l*i+c,f=a*e+h*i+u;this.minX=m,this.minY=f,this.maxX=m,this.maxY=f,m=o*r+l*i+c,f=a*r+h*i+u,this.minX=m<this.minX?m:this.minX,this.minY=f<this.minY?f:this.minY,this.maxX=m>this.maxX?m:this.maxX,this.maxY=f>this.maxY?f:this.maxY,m=o*e+l*n+c,f=a*e+h*n+u,this.minX=m<this.minX?m:this.minX,this.minY=f<this.minY?f:this.minY,this.maxX=m>this.maxX?m:this.maxX,this.maxY=f>this.maxY?f:this.maxY,m=o*r+l*n+c,f=a*r+h*n+u,this.minX=m<this.minX?m:this.minX,this.minY=f<this.minY?f:this.minY,this.maxX=m>this.maxX?m:this.maxX,this.maxY=f>this.maxY?f:this.maxY}fit(t){return this.minX<t.left&&(this.minX=t.left),this.maxX>t.right&&(this.maxX=t.right),this.minY<t.top&&(this.minY=t.top),this.maxY>t.bottom&&(this.maxY=t.bottom),this}fitBounds(t,e,i,r){return this.minX<t&&(this.minX=t),this.maxX>e&&(this.maxX=e),this.minY<i&&(this.minY=i),this.maxY>r&&(this.maxY=r),this}pad(t,e=t){return this.minX-=t,this.maxX+=t,this.minY-=e,this.maxY+=e,this}ceil(){return this.minX=Math.floor(this.minX),this.minY=Math.floor(this.minY),this.maxX=Math.ceil(this.maxX),this.maxY=Math.ceil(this.maxY),this}clone(){return new Lt(this.minX,this.minY,this.maxX,this.maxY)}scale(t,e=t){return this.minX*=t,this.minY*=e,this.maxX*=t,this.maxY*=e,this}get x(){return this.minX}set x(t){const e=this.maxX-this.minX;this.minX=t,this.maxX=t+e}get y(){return this.minY}set y(t){const e=this.maxY-this.minY;this.minY=t,this.maxY=t+e}get width(){return this.maxX-this.minX}set width(t){this.maxX=this.minX+t}get height(){return this.maxY-this.minY}set height(t){this.maxY=this.minY+t}get left(){return this.minX}get right(){return this.maxX}get top(){return this.minY}get bottom(){return this.maxY}get isPositive(){return this.maxX-this.minX>0&&this.maxY-this.minY>0}get isValid(){return this.minX+this.minY!==1/0}addVertexData(t,e,i,r){let n=this.minX,o=this.minY,a=this.maxX,l=this.maxY;r||(r=this.matrix);const h=r.a,c=r.b,u=r.c,m=r.d,f=r.tx,g=r.ty;for(let y=e;y<i;y+=2){const x=t[y],v=t[y+1],E=h*x+u*v+f,T=c*x+m*v+g;n=E<n?E:n,o=T<o?T:o,a=E>a?E:a,l=T>l?T:l}this.minX=n,this.minY=o,this.maxX=a,this.maxY=l}containsPoint(t,e){return this.minX<=t&&this.minY<=e&&this.maxX>=t&&this.maxY>=e}toString(){return`[pixi.js:Bounds minX=${this.minX} minY=${this.minY} maxX=${this.maxX} maxY=${this.maxY} width=${this.width} height=${this.height}]`}copyFrom(t){return this.minX=t.minX,this.minY=t.minY,this.maxX=t.maxX,this.maxY=t.maxY,this}}var Hu={grad:.9,turn:360,rad:360/(2*Math.PI)},ge=function(s){return typeof s=="string"?s.length>0:typeof s=="number"},It=function(s,t,e){return t===void 0&&(t=0),e===void 0&&(e=Math.pow(10,t)),Math.round(e*s)/e+0},Qt=function(s,t,e){return t===void 0&&(t=0),e===void 0&&(e=1),s>e?e:s>t?s:t},vo=function(s){return(s=isFinite(s)?s%360:0)>0?s:s+360},Eo=function(s){return{r:Qt(s.r,0,255),g:Qt(s.g,0,255),b:Qt(s.b,0,255),a:Qt(s.a)}},sr=function(s){return{r:It(s.r),g:It(s.g),b:It(s.b),a:It(s.a,3)}},Wu=/^#([0-9a-f]{3,8})$/i,fs=function(s){var t=s.toString(16);return t.length<2?"0"+t:t},To=function(s){var t=s.r,e=s.g,i=s.b,r=s.a,n=Math.max(t,e,i),o=n-Math.min(t,e,i),a=o?n===t?(e-i)/o:n===e?2+(i-t)/o:4+(t-e)/o:0;return{h:60*(a<0?a+6:a),s:n?o/n*100:0,v:n/255*100,a:r}},So=function(s){var t=s.h,e=s.s,i=s.v,r=s.a;t=t/360*6,e/=100,i/=100;var n=Math.floor(t),o=i*(1-e),a=i*(1-(t-n)*e),l=i*(1-(1-t+n)*e),h=n%6;return{r:255*[i,a,o,o,l,i][h],g:255*[l,i,i,a,o,o][h],b:255*[o,o,l,i,i,a][h],a:r}},Co=function(s){return{h:vo(s.h),s:Qt(s.s,0,100),l:Qt(s.l,0,100),a:Qt(s.a)}},wo=function(s){return{h:It(s.h),s:It(s.s),l:It(s.l),a:It(s.a,3)}},Ao=function(s){return So((e=(t=s).s,{h:t.h,s:(e*=((i=t.l)<50?i:100-i)/100)>0?2*e/(i+e)*100:0,v:i+e,a:t.a}));var t,e,i},Bi=function(s){return{h:(t=To(s)).h,s:(r=(200-(e=t.s))*(i=t.v)/100)>0&&r<200?e*i/100/(r<=100?r:200-r)*100:0,l:r/2,a:t.a};var t,e,i,r},Vu=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,zu=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,$u=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,ju=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,rr={string:[[function(s){var t=Wu.exec(s);return t?(s=t[1]).length<=4?{r:parseInt(s[0]+s[0],16),g:parseInt(s[1]+s[1],16),b:parseInt(s[2]+s[2],16),a:s.length===4?It(parseInt(s[3]+s[3],16)/255,2):1}:s.length===6||s.length===8?{r:parseInt(s.substr(0,2),16),g:parseInt(s.substr(2,2),16),b:parseInt(s.substr(4,2),16),a:s.length===8?It(parseInt(s.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(s){var t=$u.exec(s)||ju.exec(s);return t?t[2]!==t[4]||t[4]!==t[6]?null:Eo({r:Number(t[1])/(t[2]?100/255:1),g:Number(t[3])/(t[4]?100/255:1),b:Number(t[5])/(t[6]?100/255:1),a:t[7]===void 0?1:Number(t[7])/(t[8]?100:1)}):null},"rgb"],[function(s){var t=Vu.exec(s)||zu.exec(s);if(!t)return null;var e,i,r=Co({h:(e=t[1],i=t[2],i===void 0&&(i="deg"),Number(e)*(Hu[i]||1)),s:Number(t[3]),l:Number(t[4]),a:t[5]===void 0?1:Number(t[5])/(t[6]?100:1)});return Ao(r)},"hsl"]],object:[[function(s){var t=s.r,e=s.g,i=s.b,r=s.a,n=r===void 0?1:r;return ge(t)&&ge(e)&&ge(i)?Eo({r:Number(t),g:Number(e),b:Number(i),a:Number(n)}):null},"rgb"],[function(s){var t=s.h,e=s.s,i=s.l,r=s.a,n=r===void 0?1:r;if(!ge(t)||!ge(e)||!ge(i))return null;var o=Co({h:Number(t),s:Number(e),l:Number(i),a:Number(n)});return Ao(o)},"hsl"],[function(s){var t=s.h,e=s.s,i=s.v,r=s.a,n=r===void 0?1:r;if(!ge(t)||!ge(e)||!ge(i))return null;var o=(function(a){return{h:vo(a.h),s:Qt(a.s,0,100),v:Qt(a.v,0,100),a:Qt(a.a)}})({h:Number(t),s:Number(e),v:Number(i),a:Number(n)});return So(o)},"hsv"]]},Ro=function(s,t){for(var e=0;e<t.length;e++){var i=t[e][0](s);if(i)return[i,t[e][1]]}return[null,void 0]},Xu=function(s){return typeof s=="string"?Ro(s.trim(),rr.string):typeof s=="object"&&s!==null?Ro(s,rr.object):[null,void 0]},nr=function(s,t){var e=Bi(s);return{h:e.h,s:Qt(e.s+100*t,0,100),l:e.l,a:e.a}},or=function(s){return(299*s.r+587*s.g+114*s.b)/1e3/255},Po=function(s,t){var e=Bi(s);return{h:e.h,s:e.s,l:Qt(e.l+100*t,0,100),a:e.a}},ar=(function(){function s(t){this.parsed=Xu(t)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return s.prototype.isValid=function(){return this.parsed!==null},s.prototype.brightness=function(){return It(or(this.rgba),2)},s.prototype.isDark=function(){return or(this.rgba)<.5},s.prototype.isLight=function(){return or(this.rgba)>=.5},s.prototype.toHex=function(){return t=sr(this.rgba),e=t.r,i=t.g,r=t.b,o=(n=t.a)<1?fs(It(255*n)):"","#"+fs(e)+fs(i)+fs(r)+o;var t,e,i,r,n,o},s.prototype.toRgb=function(){return sr(this.rgba)},s.prototype.toRgbString=function(){return t=sr(this.rgba),e=t.r,i=t.g,r=t.b,(n=t.a)<1?"rgba("+e+", "+i+", "+r+", "+n+")":"rgb("+e+", "+i+", "+r+")";var t,e,i,r,n},s.prototype.toHsl=function(){return wo(Bi(this.rgba))},s.prototype.toHslString=function(){return t=wo(Bi(this.rgba)),e=t.h,i=t.s,r=t.l,(n=t.a)<1?"hsla("+e+", "+i+"%, "+r+"%, "+n+")":"hsl("+e+", "+i+"%, "+r+"%)";var t,e,i,r,n},s.prototype.toHsv=function(){return t=To(this.rgba),{h:It(t.h),s:It(t.s),v:It(t.v),a:It(t.a,3)};var t},s.prototype.invert=function(){return ae({r:255-(t=this.rgba).r,g:255-t.g,b:255-t.b,a:t.a});var t},s.prototype.saturate=function(t){return t===void 0&&(t=.1),ae(nr(this.rgba,t))},s.prototype.desaturate=function(t){return t===void 0&&(t=.1),ae(nr(this.rgba,-t))},s.prototype.grayscale=function(){return ae(nr(this.rgba,-1))},s.prototype.lighten=function(t){return t===void 0&&(t=.1),ae(Po(this.rgba,t))},s.prototype.darken=function(t){return t===void 0&&(t=.1),ae(Po(this.rgba,-t))},s.prototype.rotate=function(t){return t===void 0&&(t=15),this.hue(this.hue()+t)},s.prototype.alpha=function(t){return typeof t=="number"?ae({r:(e=this.rgba).r,g:e.g,b:e.b,a:t}):It(this.rgba.a,3);var e},s.prototype.hue=function(t){var e=Bi(this.rgba);return typeof t=="number"?ae({h:t,s:e.s,l:e.l,a:e.a}):It(e.h)},s.prototype.isEqual=function(t){return this.toHex()===ae(t).toHex()},s})(),ae=function(s){return s instanceof ar?s:new ar(s)},Io=[],Yu=function(s){s.forEach(function(t){Io.indexOf(t)<0&&(t(ar,rr),Io.push(t))})};function qu(s,t){var e={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},i={};for(var r in e)i[e[r]]=r;var n={};s.prototype.toName=function(o){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var a,l,h=i[this.toHex()];if(h)return h;if(o!=null&&o.closest){var c=this.toRgb(),u=1/0,m="black";if(!n.length)for(var f in e)n[f]=new s(e[f]).toRgb();for(var g in e){var y=(a=c,l=n[g],Math.pow(a.r-l.r,2)+Math.pow(a.g-l.g,2)+Math.pow(a.b-l.b,2));y<u&&(u=y,m=g)}return m}},t.string.push([function(o){var a=o.toLowerCase(),l=a==="transparent"?"#0000":e[a];return l?new s(l).toRgb():null},"name"])}Yu([qu]);const ci=class ls{constructor(t=16777215){this._value=null,this._components=new Float32Array(4),this._components.fill(1),this._int=16777215,this.value=t}get red(){return this._components[0]}get green(){return this._components[1]}get blue(){return this._components[2]}get alpha(){return this._components[3]}setValue(t){return this.value=t,this}set value(t){if(t instanceof ls)this._value=this._cloneSource(t._value),this._int=t._int,this._components.set(t._components);else{if(t===null)throw new Error("Cannot set Color#value to null");(this._value===null||!this._isSourceEqual(this._value,t))&&(this._value=this._cloneSource(t),this._normalize(this._value))}}get value(){return this._value}_cloneSource(t){return typeof t=="string"||typeof t=="number"||t instanceof Number||t===null?t:Array.isArray(t)||ArrayBuffer.isView(t)?t.slice(0):typeof t=="object"&&t!==null?{...t}:t}_isSourceEqual(t,e){const i=typeof t;if(i!==typeof e)return!1;if(i==="number"||i==="string"||t instanceof Number)return t===e;if(Array.isArray(t)&&Array.isArray(e)||ArrayBuffer.isView(t)&&ArrayBuffer.isView(e))return t.length!==e.length?!1:t.every((n,o)=>n===e[o]);if(t!==null&&e!==null){const n=Object.keys(t),o=Object.keys(e);return n.length!==o.length?!1:n.every(a=>t[a]===e[a])}return t===e}toRgba(){const[t,e,i,r]=this._components;return{r:t,g:e,b:i,a:r}}toRgb(){const[t,e,i]=this._components;return{r:t,g:e,b:i}}toRgbaString(){const[t,e,i]=this.toUint8RgbArray();return`rgba(${t},${e},${i},${this.alpha})`}toUint8RgbArray(t){const[e,i,r]=this._components;return this._arrayRgb||(this._arrayRgb=[]),t||(t=this._arrayRgb),t[0]=Math.round(e*255),t[1]=Math.round(i*255),t[2]=Math.round(r*255),t}toArray(t){this._arrayRgba||(this._arrayRgba=[]),t||(t=this._arrayRgba);const[e,i,r,n]=this._components;return t[0]=e,t[1]=i,t[2]=r,t[3]=n,t}toRgbArray(t){this._arrayRgb||(this._arrayRgb=[]),t||(t=this._arrayRgb);const[e,i,r]=this._components;return t[0]=e,t[1]=i,t[2]=r,t}toNumber(){return this._int}toBgrNumber(){const[t,e,i]=this.toUint8RgbArray();return(i<<16)+(e<<8)+t}toLittleEndianNumber(){const t=this._int;return(t>>16)+(t&65280)+((t&255)<<16)}multiply(t){const[e,i,r,n]=ls._temp.setValue(t)._components;return this._components[0]*=e,this._components[1]*=i,this._components[2]*=r,this._components[3]*=n,this._refreshInt(),this._value=null,this}premultiply(t,e=!0){return e&&(this._components[0]*=t,this._components[1]*=t,this._components[2]*=t),this._components[3]=t,this._refreshInt(),this._value=null,this}toPremultiplied(t,e=!0){if(t===1)return(255<<24)+this._int;if(t===0)return e?0:this._int;let i=this._int>>16&255,r=this._int>>8&255,n=this._int&255;return e&&(i=i*t+.5|0,r=r*t+.5|0,n=n*t+.5|0),(t*255<<24)+(i<<16)+(r<<8)+n}toHex(){const t=this._int.toString(16);return`#${"000000".substring(0,6-t.length)+t}`}toHexa(){const e=Math.round(this._components[3]*255).toString(16);return this.toHex()+"00".substring(0,2-e.length)+e}setAlpha(t){return this._components[3]=this._clamp(t),this._value=null,this}_normalize(t){let e,i,r,n;if((typeof t=="number"||t instanceof Number)&&t>=0&&t<=16777215){const o=t;e=(o>>16&255)/255,i=(o>>8&255)/255,r=(o&255)/255,n=1}else if((Array.isArray(t)||t instanceof Float32Array)&&t.length>=3&&t.length<=4)t=this._clamp(t),[e,i,r,n=1]=t;else if((t instanceof Uint8Array||t instanceof Uint8ClampedArray)&&t.length>=3&&t.length<=4)t=this._clamp(t,0,255),[e,i,r,n=255]=t,e/=255,i/=255,r/=255,n/=255;else if(typeof t=="string"||typeof t=="object"){if(typeof t=="string"){const a=ls.HEX_PATTERN.exec(t);a&&(t=`#${a[2]}`)}const o=ae(t);o.isValid()&&({r:e,g:i,b:r,a:n}=o.rgba,e/=255,i/=255,r/=255)}if(e!==void 0)this._components[0]=e,this._components[1]=i,this._components[2]=r,this._components[3]=n,this._refreshInt();else throw new Error(`Unable to convert color ${t}`)}_refreshInt(){this._clamp(this._components);const[t,e,i]=this._components;this._int=(t*255<<16)+(e*255<<8)+(i*255|0)}_clamp(t,e=0,i=1){return typeof t=="number"?Math.min(Math.max(t,e),i):(t.forEach((r,n)=>{t[n]=Math.min(Math.max(r,e),i)}),t)}static isColorLike(t){return typeof t=="number"||typeof t=="string"||t instanceof Number||t instanceof ls||Array.isArray(t)||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Float32Array||t.r!==void 0&&t.g!==void 0&&t.b!==void 0||t.r!==void 0&&t.g!==void 0&&t.b!==void 0&&t.a!==void 0||t.h!==void 0&&t.s!==void 0&&t.l!==void 0||t.h!==void 0&&t.s!==void 0&&t.l!==void 0&&t.a!==void 0||t.h!==void 0&&t.s!==void 0&&t.v!==void 0||t.h!==void 0&&t.s!==void 0&&t.v!==void 0&&t.a!==void 0}};ci.shared=new ci,ci._temp=new ci,ci.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let ct=ci;const Ku={cullArea:null,cullable:!1,cullableChildren:!0};let lr=0;const Mo=500;function tt(...s){lr!==Mo&&(lr++,lr===Mo?console.warn("PixiJS Warning: too many warnings, no more warnings will be reported to the console by PixiJS."):console.warn("PixiJS Warning: ",...s))}const ui={_registeredResources:new Set,register(s){this._registeredResources.add(s)},unregister(s){this._registeredResources.delete(s)},release(){this._registeredResources.forEach(s=>s.clear())},get registeredCount(){return this._registeredResources.size},isRegistered(s){return this._registeredResources.has(s)},reset(){this._registeredResources.clear()}};class Zu{constructor(t,e){this._pool=[],this._count=0,this._index=0,this._classType=t,e&&this.prepopulate(e)}prepopulate(t){for(let e=0;e<t;e++)this._pool[this._index++]=new this._classType;this._count+=t}get(t){var i;let e;return this._index>0?e=this._pool[--this._index]:(e=new this._classType,this._count++),(i=e.init)==null||i.call(e,t),e}return(t){var e;(e=t.reset)==null||e.call(t),this._pool[this._index++]=t}get totalSize(){return this._count}get totalFree(){return this._index}get totalUsed(){return this._count-this._index}clear(){if(this._pool.length>0&&this._pool[0].destroy)for(let t=0;t<this._index;t++)this._pool[t].destroy();this._pool.length=0,this._count=0,this._index=0}}class Ju{constructor(){this._poolsByClass=new Map}prepopulate(t,e){this.getPool(t).prepopulate(e)}get(t,e){return this.getPool(t).get(e)}return(t){this.getPool(t.constructor).return(t)}getPool(t){return this._poolsByClass.has(t)||this._poolsByClass.set(t,new Zu(t)),this._poolsByClass.get(t)}stats(){const t={};return this._poolsByClass.forEach(e=>{const i=t[e._classType.name]?e._classType.name+e._classType.ID:e._classType.name;t[i]={free:e.totalFree,used:e.totalUsed,size:e.totalSize}}),t}clear(){this._poolsByClass.forEach(t=>t.clear()),this._poolsByClass.clear()}}const Mt=new Ju;ui.register(Mt);const Qu={get isCachedAsTexture(){var s;return!!((s=this.renderGroup)!=null&&s.isCachedAsTexture)},cacheAsTexture(s){typeof s=="boolean"&&s===!1?this.disableRenderGroup():(this.enableRenderGroup(),this.renderGroup.enableCacheAsTexture(s===!0?{}:s))},updateCacheTexture(){var s;(s=this.renderGroup)==null||s.updateCacheTexture()},get cacheAsBitmap(){return this.isCachedAsTexture},set cacheAsBitmap(s){K("v8.6.0","cacheAsBitmap is deprecated, use cacheAsTexture instead."),this.cacheAsTexture(s)}};function ko(s,t,e){const i=s.length;let r;if(t>=i||e===0)return;e=t+e>i?i-t:e;const n=i-e;for(r=t;r<n;++r)s[r]=s[r+e];s.length=n}const td={allowChildren:!0,removeChildren(s=0,t){var n;const e=t??this.children.length,i=e-s,r=[];if(i>0&&i<=e){for(let a=e-1;a>=s;a--){const l=this.children[a];l&&(r.push(l),l.parent=null)}ko(this.children,s,e);const o=this.renderGroup||this.parentRenderGroup;o&&o.removeChildren(r);for(let a=0;a<r.length;++a){const l=r[a];(n=l.parentRenderLayer)==null||n.detach(l),this.emit("childRemoved",l,this,a),r[a].emit("removed",this)}return r.length>0&&this._didViewChangeTick++,r}else if(i===0&&this.children.length===0)return r;throw new RangeError("removeChildren: numeric values are outside the acceptable range.")},removeChildAt(s){const t=this.getChildAt(s);return this.removeChild(t)},getChildAt(s){if(s<0||s>=this.children.length)throw new Error(`getChildAt: Index (${s}) does not exist.`);return this.children[s]},setChildIndex(s,t){if(t<0||t>=this.children.length)throw new Error(`The index ${t} supplied is out of bounds ${this.children.length}`);this.getChildIndex(s),this.addChildAt(s,t)},getChildIndex(s){const t=this.children.indexOf(s);if(t===-1)throw new Error("The supplied Container must be a child of the caller");return t},addChildAt(s,t){this.allowChildren||K(vt,"addChildAt: Only Containers will be allowed to add children in v8.0.0");const{children:e}=this;if(t<0||t>e.length)throw new Error(`${s}addChildAt: The index ${t} supplied is out of bounds ${e.length}`);const i=s.parent===this;if(s.parent){const n=s.parent.children.indexOf(s);if(i){if(n===t)return s;s.parent.children.splice(n,1)}else s.removeFromParent()}t===e.length?e.push(s):e.splice(t,0,s),s.parent=this,s.didChange=!0,s._updateFlags=15;const r=this.renderGroup||this.parentRenderGroup;return r&&r.addChild(s),this.sortableChildren&&(this.sortDirty=!0),i||(this.emit("childAdded",s,this,t),s.emit("added",this)),s},swapChildren(s,t){if(s===t)return;const e=this.getChildIndex(s),i=this.getChildIndex(t);this.children[e]=t,this.children[i]=s;const r=this.renderGroup||this.parentRenderGroup;r&&(r.structureDidChange=!0),this._didContainerChangeTick++},removeFromParent(){var s;(s=this.parent)==null||s.removeChild(this)},reparentChild(...s){return s.length===1?this.reparentChildAt(s[0],this.children.length):(s.forEach(t=>this.reparentChildAt(t,this.children.length)),s[0])},reparentChildAt(s,t){if(s.parent===this)return this.setChildIndex(s,t),s;const e=s.worldTransform.clone();s.removeFromParent(),this.addChildAt(s,t);const i=this.worldTransform.clone();return i.invert(),e.prepend(i),s.setFromMatrix(e),s},replaceChild(s,t){s.updateLocalTransform(),this.addChildAt(t,this.getChildIndex(s)),t.setFromMatrix(s.localTransform),t.updateLocalTransform(),this.removeChild(s)}},ed={collectRenderables(s,t,e){this.parentRenderLayer&&this.parentRenderLayer!==e||this.globalDisplayStatus<7||!this.includeInBuild||(this.sortableChildren&&this.sortChildren(),this.isSimple?this.collectRenderablesSimple(s,t,e):this.renderGroup?t.renderPipes.renderGroup.addRenderGroup(this.renderGroup,s):this.collectRenderablesWithEffects(s,t,e))},collectRenderablesSimple(s,t,e){const i=this.children,r=i.length;for(let n=0;n<r;n++)i[n].collectRenderables(s,t,e)},collectRenderablesWithEffects(s,t,e){const{renderPipes:i}=t;for(let r=0;r<this.effects.length;r++){const n=this.effects[r];i[n.pipe].push(n,this,s)}this.collectRenderablesSimple(s,t,e);for(let r=this.effects.length-1;r>=0;r--){const n=this.effects[r];i[n.pipe].pop(n,this,s)}}};class ps{constructor(){this.pipe="filter",this.priority=1}destroy(){for(let t=0;t<this.filters.length;t++)this.filters[t].destroy();this.filters=null,this.filterArea=null}}class id{constructor(){this._effectClasses=[],this._tests=[],this._initialized=!1}init(){this._initialized||(this._initialized=!0,this._effectClasses.forEach(t=>{this.add({test:t.test,maskClass:t})}))}add(t){this._tests.push(t)}getMaskEffect(t){this._initialized||this.init();for(let e=0;e<this._tests.length;e++){const i=this._tests[e];if(i.test(t))return Mt.get(i.maskClass,t)}return t}returnMaskEffect(t){Mt.return(t)}}const hr=new id;J.handleByList(w.MaskEffect,hr._effectClasses);const sd={_maskEffect:null,_maskOptions:{inverse:!1},_filterEffect:null,effects:[],_markStructureAsChanged(){const s=this.renderGroup||this.parentRenderGroup;s&&(s.structureDidChange=!0)},addEffect(s){this.effects.indexOf(s)===-1&&(this.effects.push(s),this.effects.sort((e,i)=>e.priority-i.priority),this._markStructureAsChanged(),this._updateIsSimple())},removeEffect(s){const t=this.effects.indexOf(s);t!==-1&&(this.effects.splice(t,1),this._markStructureAsChanged(),this._updateIsSimple())},set mask(s){const t=this._maskEffect;(t==null?void 0:t.mask)!==s&&(t&&(this.removeEffect(t),hr.returnMaskEffect(t),this._maskEffect=null),s!=null&&(this._maskEffect=hr.getMaskEffect(s),this.addEffect(this._maskEffect)))},get mask(){var s;return(s=this._maskEffect)==null?void 0:s.mask},setMask(s){this._maskOptions={...this._maskOptions,...s},s.mask&&(this.mask=s.mask),this._markStructureAsChanged()},set filters(s){var n;!Array.isArray(s)&&s&&(s=[s]);const t=this._filterEffect||(this._filterEffect=new ps);s=s;const e=(s==null?void 0:s.length)>0,i=((n=t.filters)==null?void 0:n.length)>0,r=e!==i;s=Array.isArray(s)?s.slice(0):s,t.filters=Object.freeze(s),r&&(e?this.addEffect(t):(this.removeEffect(t),t.filters=s??null))},get filters(){var s;return(s=this._filterEffect)==null?void 0:s.filters},set filterArea(s){this._filterEffect||(this._filterEffect=new ps),this._filterEffect.filterArea=s},get filterArea(){var s;return(s=this._filterEffect)==null?void 0:s.filterArea}},rd={label:null,get name(){return K(vt,"Container.name property has been removed, use Container.label instead"),this.label},set name(s){K(vt,"Container.name property has been removed, use Container.label instead"),this.label=s},getChildByName(s,t=!1){return this.getChildByLabel(s,t)},getChildByLabel(s,t=!1){const e=this.children;for(let i=0;i<e.length;i++){const r=e[i];if(r.label===s||s instanceof RegExp&&s.test(r.label))return r}if(t)for(let i=0;i<e.length;i++){const n=e[i].getChildByLabel(s,!0);if(n)return n}return null},getChildrenByLabel(s,t=!1,e=[]){const i=this.children;for(let r=0;r<i.length;r++){const n=i[r];(n.label===s||s instanceof RegExp&&s.test(n.label))&&e.push(n)}if(t)for(let r=0;r<i.length;r++)i[r].getChildrenByLabel(s,!0,e);return e}},Ht=Mt.getPool(W),_e=Mt.getPool(Lt),nd=new W,od={getFastGlobalBounds(s,t){t||(t=new Lt),t.clear(),this._getGlobalBoundsRecursive(!!s,t,this.parentRenderLayer),t.isValid||t.set(0,0,0,0);const e=this.renderGroup||this.parentRenderGroup;return t.applyMatrix(e.worldTransform),t},_getGlobalBoundsRecursive(s,t,e){let i=t;if(s&&this.parentRenderLayer&&this.parentRenderLayer!==e||this.localDisplayStatus!==7||!this.measurable)return;const r=!!this.effects.length;if((this.renderGroup||r)&&(i=_e.get().clear()),this.boundsArea)t.addRect(this.boundsArea,this.worldTransform);else{if(this.renderPipeId){const o=this.bounds;i.addFrame(o.minX,o.minY,o.maxX,o.maxY,this.groupTransform)}const n=this.children;for(let o=0;o<n.length;o++)n[o]._getGlobalBoundsRecursive(s,i,e)}if(r){let n=!1;const o=this.renderGroup||this.parentRenderGroup;for(let a=0;a<this.effects.length;a++)this.effects[a].addBounds&&(n||(n=!0,i.applyMatrix(o.worldTransform)),this.effects[a].addBounds(i,!0));n&&i.applyMatrix(o.worldTransform.copyTo(nd).invert()),t.addBounds(i),_e.return(i)}else this.renderGroup&&(t.addBounds(i,this.relativeGroupTransform),_e.return(i))}};function cr(s,t,e){e.clear();let i,r;return s.parent?t?i=s.parent.worldTransform:(r=Ht.get().identity(),i=ur(s,r)):i=W.IDENTITY,Bo(s,e,i,t),r&&Ht.return(r),e.isValid||e.set(0,0,0,0),e}function Bo(s,t,e,i){var a,l;if(!s.visible||!s.measurable)return;let r;i?r=s.worldTransform:(s.updateLocalTransform(),r=Ht.get(),r.appendFrom(s.localTransform,e));const n=t,o=!!s.effects.length;if(o&&(t=_e.get().clear()),s.boundsArea)t.addRect(s.boundsArea,r);else{const h=s.bounds;h&&!h.isEmpty()&&(t.matrix=r,t.addBounds(h));for(let c=0;c<s.children.length;c++)Bo(s.children[c],t,r,i)}if(o){for(let h=0;h<s.effects.length;h++)(l=(a=s.effects[h]).addBounds)==null||l.call(a,t);n.addBounds(t,W.IDENTITY),_e.return(t)}i||Ht.return(r)}function ur(s,t){const e=s.parent;return e&&(ur(e,t),e.updateLocalTransform(),t.append(e.localTransform)),t}function di(s,t){if(s===16777215||!t)return t;if(t===16777215||!s)return s;const e=s>>16&255,i=s>>8&255,r=s&255,n=t>>16&255,o=t>>8&255,a=t&255,l=e*n/255|0,h=i*o/255|0,c=r*a/255|0;return(l<<16)+(h<<8)+c}const Oo=16777215;function ms(s,t){return s===Oo?t:t===Oo?s:di(s,t)}function fi(s){return((s&255)<<16)+(s&65280)+(s>>16&255)}const ad={getGlobalAlpha(s){if(s)return this.renderGroup?this.renderGroup.worldAlpha:this.parentRenderGroup?this.parentRenderGroup.worldAlpha*this.alpha:this.alpha;let t=this.alpha,e=this.parent;for(;e;)t*=e.alpha,e=e.parent;return t},getGlobalTransform(s=new W,t){if(t)return s.copyFrom(this.worldTransform);this.updateLocalTransform();const e=ur(this,Ht.get().identity());return s.appendFrom(this.localTransform,e),Ht.return(e),s},getGlobalTint(s){if(s)return this.renderGroup?fi(this.renderGroup.worldColor):this.parentRenderGroup?fi(ms(this.localColor,this.parentRenderGroup.worldColor)):this.tint;let t=this.localColor,e=this.parent;for(;e;)t=ms(t,e.localColor),e=e.parent;return fi(t)}};function dr(s,t,e){return t.clear(),e||(e=W.IDENTITY),Do(s,t,e,s,!0),t.isValid||t.set(0,0,0,0),t}function Do(s,t,e,i,r){var l,h;let n;if(r)n=Ht.get(),n=e.copyTo(n);else{if(!s.visible||!s.measurable)return;s.updateLocalTransform();const c=s.localTransform;n=Ht.get(),n.appendFrom(c,e)}const o=t,a=!!s.effects.length;if(a&&(t=_e.get().clear()),s.boundsArea)t.addRect(s.boundsArea,n);else{s.renderPipeId&&(t.matrix=n,t.addBounds(s.bounds));const c=s.children;for(let u=0;u<c.length;u++)Do(c[u],t,n,i,!1)}if(a){for(let c=0;c<s.effects.length;c++)(h=(l=s.effects[c]).addLocalBounds)==null||h.call(l,t,i);o.addBounds(t,W.IDENTITY),_e.return(t)}Ht.return(n)}function Go(s,t){const e=s.children;for(let i=0;i<e.length;i++){const r=e[i],n=r.uid,o=(r._didViewChangeTick&65535)<<16|r._didContainerChangeTick&65535,a=t.index;(t.data[a]!==n||t.data[a+1]!==o)&&(t.data[t.index]=n,t.data[t.index+1]=o,t.didChange=!0),t.index=a+2,r.children.length&&Go(r,t)}return t.didChange}const ld=new W,hd={_localBoundsCacheId:-1,_localBoundsCacheData:null,_setWidth(s,t){const e=Math.sign(this.scale.x)||1;t!==0?this.scale.x=s/t*e:this.scale.x=e},_setHeight(s,t){const e=Math.sign(this.scale.y)||1;t!==0?this.scale.y=s/t*e:this.scale.y=e},getLocalBounds(){this._localBoundsCacheData||(this._localBoundsCacheData={data:[],index:1,didChange:!1,localBounds:new Lt});const s=this._localBoundsCacheData;return s.index=1,s.didChange=!1,s.data[0]!==this._didViewChangeTick&&(s.didChange=!0,s.data[0]=this._didViewChangeTick),Go(this,s),s.didChange&&dr(this,s.localBounds,ld),s.localBounds},getBounds(s,t){return cr(this,s,t||new Lt)}},cd={_onRender:null,set onRender(s){const t=this.renderGroup||this.parentRenderGroup;if(!s){this._onRender&&(t==null||t.removeOnRender(this)),this._onRender=null;return}this._onRender||t==null||t.addOnRender(this),this._onRender=s},get onRender(){return this._onRender}},ud={_zIndex:0,sortDirty:!1,sortableChildren:!1,get zIndex(){return this._zIndex},set zIndex(s){this._zIndex!==s&&(this._zIndex=s,this.depthOfChildModified())},depthOfChildModified(){this.parent&&(this.parent.sortableChildren=!0,this.parent.sortDirty=!0),this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0)},sortChildren(){this.sortDirty&&(this.sortDirty=!1,this.children.sort(dd))}};function dd(s,t){return s._zIndex-t._zIndex}const fd={getGlobalPosition(s=new mt,t=!1){return this.parent?this.parent.toGlobal(this._position,s,t):(s.x=this._position.x,s.y=this._position.y),s},toGlobal(s,t,e=!1){const i=this.getGlobalTransform(Ht.get(),e);return t=i.apply(s,t),Ht.return(i),t},toLocal(s,t,e,i){t&&(s=t.toGlobal(s,e,i));const r=this.getGlobalTransform(Ht.get(),i);return e=r.applyInverse(s,e),Ht.return(r),e}};class fr{constructor(){this.uid=dt("instructionSet"),this.instructions=[],this.instructionSize=0,this.renderables=[],this.gcTick=0}reset(){this.instructionSize=0}destroy(){this.instructions.length=0,this.renderables.length=0,this.renderPipes=null,this.gcTick=0}add(t){this.instructions[this.instructionSize++]=t}log(){this.instructions.length=this.instructionSize,console.table(this.instructions,["type","action"])}}let pd=0;class md{constructor(t){this._poolKeyHash=Object.create(null),this._texturePool={},this.textureOptions=t||{},this.enableFullScreen=!1,this.textureStyle=new Xe(this.textureOptions)}createTexture(t,e,i,r){const n=new At({...this.textureOptions,width:t,height:e,resolution:1,antialias:i,autoGarbageCollect:!1,autoGenerateMipmaps:r});return new z({source:n,label:`texturePool_${pd++}`})}getOptimalTexture(t,e,i=1,r,n=!1){let o=Math.ceil(t*i-1e-6),a=Math.ceil(e*i-1e-6);o=hi(o),a=hi(a);const l=r?1:0,h=n?1:0,c=(o<<17)+(a<<2)+(h<<1)+l;this._texturePool[c]||(this._texturePool[c]=[]);let u=this._texturePool[c].pop();return u||(u=this.createTexture(o,a,r,n)),u.source._resolution=i,u.source.width=o/i,u.source.height=a/i,u.source.pixelWidth=o,u.source.pixelHeight=a,u.frame.x=0,u.frame.y=0,u.frame.width=t,u.frame.height=e,u.updateUvs(),this._poolKeyHash[u.uid]=c,u}getSameSizeTexture(t,e=!1){const i=t.source;return this.getOptimalTexture(t.width,t.height,i._resolution,e)}returnTexture(t,e=!1){const i=this._poolKeyHash[t.uid];e&&(t.source.style=this.textureStyle),this._texturePool[i].push(t)}clear(t){if(t=t!==!1,t)for(const e in this._texturePool){const i=this._texturePool[e];if(i)for(let r=0;r<i.length;r++)i[r].destroy(!0)}this._texturePool={}}}const Ft=new md;ui.register(Ft);class pr{constructor(){this.renderPipeId="renderGroup",this.root=null,this.canBundle=!1,this.renderGroupParent=null,this.renderGroupChildren=[],this.worldTransform=new W,this.worldColorAlpha=4294967295,this.worldColor=16777215,this.worldAlpha=1,this.childrenToUpdate=Object.create(null),this.updateTick=0,this.gcTick=0,this.childrenRenderablesToUpdate={list:[],index:0},this.structureDidChange=!0,this.instructionSet=new fr,this._onRenderContainers=[],this.textureNeedsUpdate=!0,this.isCachedAsTexture=!1,this._matrixDirty=7}init(t){this.root=t,t._onRender&&this.addOnRender(t),t.didChange=!0;const e=t.children;for(let i=0;i<e.length;i++){const r=e[i];r._updateFlags=15,this.addChild(r)}}enableCacheAsTexture(t={}){this.textureOptions=t,this.isCachedAsTexture=!0,this.textureNeedsUpdate=!0}disableCacheAsTexture(){this.isCachedAsTexture=!1,this.texture&&(Ft.returnTexture(this.texture,!0),this.texture=null)}updateCacheTexture(){this.textureNeedsUpdate=!0;const t=this._parentCacheAsTextureRenderGroup;t&&!t.textureNeedsUpdate&&t.updateCacheTexture()}reset(){this.renderGroupChildren.length=0;for(const t in this.childrenToUpdate){const e=this.childrenToUpdate[t];e.list.fill(null),e.index=0}this.childrenRenderablesToUpdate.index=0,this.childrenRenderablesToUpdate.list.fill(null),this.root=null,this.updateTick=0,this.structureDidChange=!0,this._onRenderContainers.length=0,this.renderGroupParent=null,this.disableCacheAsTexture()}get localTransform(){return this.root.localTransform}addRenderGroupChild(t){t.renderGroupParent&&t.renderGroupParent._removeRenderGroupChild(t),t.renderGroupParent=this,this.renderGroupChildren.push(t)}_removeRenderGroupChild(t){const e=this.renderGroupChildren.indexOf(t);e>-1&&this.renderGroupChildren.splice(e,1),t.renderGroupParent=null}addChild(t){if(this.structureDidChange=!0,t.parentRenderGroup=this,t.updateTick=-1,t.parent===this.root?t.relativeRenderGroupDepth=1:t.relativeRenderGroupDepth=t.parent.relativeRenderGroupDepth+1,t.didChange=!0,this.onChildUpdate(t),t.renderGroup){this.addRenderGroupChild(t.renderGroup);return}t._onRender&&this.addOnRender(t);const e=t.children;for(let i=0;i<e.length;i++)this.addChild(e[i])}removeChild(t){if(this.structureDidChange=!0,t._onRender&&(t.renderGroup||this.removeOnRender(t)),t.parentRenderGroup=null,t.renderGroup){this._removeRenderGroupChild(t.renderGroup);return}const e=t.children;for(let i=0;i<e.length;i++)this.removeChild(e[i])}removeChildren(t){for(let e=0;e<t.length;e++)this.removeChild(t[e])}onChildUpdate(t){let e=this.childrenToUpdate[t.relativeRenderGroupDepth];e||(e=this.childrenToUpdate[t.relativeRenderGroupDepth]={index:0,list:[]}),e.list[e.index++]=t}updateRenderable(t){t.globalDisplayStatus<7||(this.instructionSet.renderPipes[t.renderPipeId].updateRenderable(t),t.didViewUpdate=!1)}onChildViewUpdate(t){this.childrenRenderablesToUpdate.list[this.childrenRenderablesToUpdate.index++]=t}get isRenderable(){return this.root.localDisplayStatus===7&&this.worldAlpha>0}addOnRender(t){this._onRenderContainers.push(t)}removeOnRender(t){this._onRenderContainers.splice(this._onRenderContainers.indexOf(t),1)}runOnRender(t){for(let e=0;e<this._onRenderContainers.length;e++)this._onRenderContainers[e]._onRender(t)}destroy(){this.disableCacheAsTexture(),this.renderGroupParent=null,this.root=null,this.childrenRenderablesToUpdate=null,this.childrenToUpdate=null,this.renderGroupChildren=null,this._onRenderContainers=null,this.instructionSet=null}getChildren(t=[]){const e=this.root.children;for(let i=0;i<e.length;i++)this._getChildren(e[i],t);return t}_getChildren(t,e=[]){if(e.push(t),t.renderGroup)return e;const i=t.children;for(let r=0;r<i.length;r++)this._getChildren(i[r],e);return e}invalidateMatrices(){this._matrixDirty=7}get inverseWorldTransform(){return(this._matrixDirty&1)===0?this._inverseWorldTransform:(this._matrixDirty&=-2,this._inverseWorldTransform||(this._inverseWorldTransform=new W),this._inverseWorldTransform.copyFrom(this.worldTransform).invert())}get textureOffsetInverseTransform(){return(this._matrixDirty&2)===0?this._textureOffsetInverseTransform:(this._matrixDirty&=-3,this._textureOffsetInverseTransform||(this._textureOffsetInverseTransform=new W),this._textureOffsetInverseTransform.copyFrom(this.inverseWorldTransform).translate(-this._textureBounds.x,-this._textureBounds.y))}get inverseParentTextureTransform(){if((this._matrixDirty&4)===0)return this._inverseParentTextureTransform;this._matrixDirty&=-5;const t=this._parentCacheAsTextureRenderGroup;return t?(this._inverseParentTextureTransform||(this._inverseParentTextureTransform=new W),this._inverseParentTextureTransform.copyFrom(this.worldTransform).prepend(t.inverseWorldTransform).translate(-t._textureBounds.x,-t._textureBounds.y)):this.worldTransform}get cacheToLocalTransform(){return this.isCachedAsTexture?this.textureOffsetInverseTransform:this._parentCacheAsTextureRenderGroup?this._parentCacheAsTextureRenderGroup.textureOffsetInverseTransform:null}}function gd(s,t,e={}){for(const i in t)!e[i]&&t[i]!==void 0&&(s[i]=t[i])}const mr=new Ot(null),gs=new Ot(null),gr=new Ot(null,1,1),_s=new Ot(null),ys=1,_r=2,Oi=4;class kt extends Jt{constructor(t={}){var e,i;super(),this.uid=dt("renderable"),this._updateFlags=15,this.renderGroup=null,this.parentRenderGroup=null,this.parentRenderGroupIndex=0,this.didChange=!1,this.didViewUpdate=!1,this.relativeRenderGroupDepth=0,this.children=[],this.parent=null,this.includeInBuild=!0,this.measurable=!0,this.isSimple=!0,this.parentRenderLayer=null,this.updateTick=-1,this.localTransform=new W,this.relativeGroupTransform=new W,this.groupTransform=this.relativeGroupTransform,this.destroyed=!1,this._position=new Ot(this,0,0),this._scale=gr,this._pivot=gs,this._origin=_s,this._skew=mr,this._cx=1,this._sx=0,this._cy=0,this._sy=1,this._rotation=0,this.localColor=16777215,this.localAlpha=1,this.groupAlpha=1,this.groupColor=16777215,this.groupColorAlpha=4294967295,this.localBlendMode="inherit",this.groupBlendMode="normal",this.localDisplayStatus=7,this.globalDisplayStatus=7,this._didContainerChangeTick=0,this._didViewChangeTick=0,this._didLocalTransformChangeId=-1,this.effects=[],gd(this,t,{children:!0,parent:!0,effects:!0}),(e=t.children)==null||e.forEach(r=>this.addChild(r)),(i=t.parent)==null||i.addChild(this)}static mixin(t){K("8.8.0","Container.mixin is deprecated, please use extensions.mixin instead."),J.mixin(kt,t)}set _didChangeId(t){this._didViewChangeTick=t>>12&4095,this._didContainerChangeTick=t&4095}get _didChangeId(){return this._didContainerChangeTick&4095|(this._didViewChangeTick&4095)<<12}addChild(...t){if(this.allowChildren||K(vt,"addChild: Only Containers will be allowed to add children in v8.0.0"),t.length>1){for(let r=0;r<t.length;r++)this.addChild(t[r]);return t[0]}const e=t[0],i=this.renderGroup||this.parentRenderGroup;return e.parent===this?(this.children.splice(this.children.indexOf(e),1),this.children.push(e),i&&(i.structureDidChange=!0),e):(e.parent&&e.parent.removeChild(e),this.children.push(e),this.sortableChildren&&(this.sortDirty=!0),e.parent=this,e.didChange=!0,e._updateFlags=15,i&&i.addChild(e),this.emit("childAdded",e,this,this.children.length-1),e.emit("added",this),this._didViewChangeTick++,e._zIndex!==0&&e.depthOfChildModified(),e)}removeChild(...t){if(t.length>1){for(let r=0;r<t.length;r++)this.removeChild(t[r]);return t[0]}const e=t[0],i=this.children.indexOf(e);return i>-1&&(this._didViewChangeTick++,this.children.splice(i,1),this.renderGroup?this.renderGroup.removeChild(e):this.parentRenderGroup&&this.parentRenderGroup.removeChild(e),e.parentRenderLayer&&e.parentRenderLayer.detach(e),e.parent=null,this.emit("childRemoved",e,this,i),e.emit("removed",this)),e}_onUpdate(t){t&&t===this._skew&&this._updateSkew(),this._didContainerChangeTick++,!this.didChange&&(this.didChange=!0,this.parentRenderGroup&&this.parentRenderGroup.onChildUpdate(this))}set isRenderGroup(t){!!this.renderGroup!==t&&(t?this.enableRenderGroup():this.disableRenderGroup())}get isRenderGroup(){return!!this.renderGroup}enableRenderGroup(){if(this.renderGroup)return;const t=this.parentRenderGroup;t==null||t.removeChild(this),this.renderGroup=Mt.get(pr,this),this.groupTransform=W.IDENTITY,t==null||t.addChild(this),this._updateIsSimple()}disableRenderGroup(){if(!this.renderGroup)return;const t=this.parentRenderGroup;t==null||t.removeChild(this),Mt.return(this.renderGroup),this.renderGroup=null,this.groupTransform=this.relativeGroupTransform,t==null||t.addChild(this),this._updateIsSimple()}_updateIsSimple(){this.isSimple=!this.renderGroup&&this.effects.length===0}get worldTransform(){return this._worldTransform||(this._worldTransform=new W),this.renderGroup?this._worldTransform.copyFrom(this.renderGroup.worldTransform):this.parentRenderGroup&&this._worldTransform.appendFrom(this.relativeGroupTransform,this.parentRenderGroup.worldTransform),this._worldTransform}get x(){return this._position.x}set x(t){this._position.x=t}get y(){return this._position.y}set y(t){this._position.y=t}get position(){return this._position}set position(t){this._position.copyFrom(t)}get rotation(){return this._rotation}set rotation(t){this._rotation!==t&&(this._rotation=t,this._onUpdate(this._skew))}get angle(){return this.rotation*Ou}set angle(t){this.rotation=t*Du}get pivot(){return this._pivot===gs&&(this._pivot=new Ot(this,0,0)),this._pivot}set pivot(t){this._pivot===gs&&(this._pivot=new Ot(this,0,0),this._origin!==_s&&tt("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof t=="number"?this._pivot.set(t):this._pivot.copyFrom(t)}get skew(){return this._skew===mr&&(this._skew=new Ot(this,0,0)),this._skew}set skew(t){this._skew===mr&&(this._skew=new Ot(this,0,0)),this._skew.copyFrom(t)}get scale(){return this._scale===gr&&(this._scale=new Ot(this,1,1)),this._scale}set scale(t){this._scale===gr&&(this._scale=new Ot(this,0,0)),typeof t=="string"&&(t=parseFloat(t)),typeof t=="number"?this._scale.set(t):this._scale.copyFrom(t)}get origin(){return this._origin===_s&&(this._origin=new Ot(this,0,0)),this._origin}set origin(t){this._origin===_s&&(this._origin=new Ot(this,0,0),this._pivot!==gs&&tt("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof t=="number"?this._origin.set(t):this._origin.copyFrom(t)}get width(){return Math.abs(this.scale.x*this.getLocalBounds().width)}set width(t){const e=this.getLocalBounds().width;this._setWidth(t,e)}get height(){return Math.abs(this.scale.y*this.getLocalBounds().height)}set height(t){const e=this.getLocalBounds().height;this._setHeight(t,e)}getSize(t){t||(t={});const e=this.getLocalBounds();return t.width=Math.abs(this.scale.x*e.width),t.height=Math.abs(this.scale.y*e.height),t}setSize(t,e){const i=this.getLocalBounds();typeof t=="object"?(e=t.height??t.width,t=t.width):e??(e=t),t!==void 0&&this._setWidth(t,i.width),e!==void 0&&this._setHeight(e,i.height)}_updateSkew(){const t=this._rotation,e=this._skew;this._cx=Math.cos(t+e._y),this._sx=Math.sin(t+e._y),this._cy=-Math.sin(t-e._x),this._sy=Math.cos(t-e._x)}updateTransform(t){return this.position.set(typeof t.x=="number"?t.x:this.position.x,typeof t.y=="number"?t.y:this.position.y),this.scale.set(typeof t.scaleX=="number"?t.scaleX||1:this.scale.x,typeof t.scaleY=="number"?t.scaleY||1:this.scale.y),this.rotation=typeof t.rotation=="number"?t.rotation:this.rotation,this.skew.set(typeof t.skewX=="number"?t.skewX:this.skew.x,typeof t.skewY=="number"?t.skewY:this.skew.y),this.pivot.set(typeof t.pivotX=="number"?t.pivotX:this.pivot.x,typeof t.pivotY=="number"?t.pivotY:this.pivot.y),this.origin.set(typeof t.originX=="number"?t.originX:this.origin.x,typeof t.originY=="number"?t.originY:this.origin.y),this}setFromMatrix(t){t.decompose(this)}updateLocalTransform(){const t=this._didContainerChangeTick;if(this._didLocalTransformChangeId===t)return;this._didLocalTransformChangeId=t;const e=this.localTransform,i=this._scale,r=this._pivot,n=this._origin,o=this._position,a=i._x,l=i._y,h=r._x,c=r._y,u=-n._x,m=-n._y;e.a=this._cx*a,e.b=this._sx*a,e.c=this._cy*l,e.d=this._sy*l,e.tx=o._x-(h*e.a+c*e.c)+(u*e.a+m*e.c)-u,e.ty=o._y-(h*e.b+c*e.d)+(u*e.b+m*e.d)-m}set alpha(t){t!==this.localAlpha&&(this.localAlpha=t,this._updateFlags|=ys,this._onUpdate())}get alpha(){return this.localAlpha}set tint(t){const i=ct.shared.setValue(t??16777215).toBgrNumber();i!==this.localColor&&(this.localColor=i,this._updateFlags|=ys,this._onUpdate())}get tint(){return fi(this.localColor)}set blendMode(t){this.localBlendMode!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=_r,this.localBlendMode=t,this._onUpdate())}get blendMode(){return this.localBlendMode}get visible(){return!!(this.localDisplayStatus&2)}set visible(t){const e=t?2:0;(this.localDisplayStatus&2)!==e&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=Oi,this.localDisplayStatus^=2,this._onUpdate(),this.emit("visibleChanged",t))}get culled(){return!(this.localDisplayStatus&4)}set culled(t){const e=t?0:4;(this.localDisplayStatus&4)!==e&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=Oi,this.localDisplayStatus^=4,this._onUpdate())}get renderable(){return!!(this.localDisplayStatus&1)}set renderable(t){const e=t?1:0;(this.localDisplayStatus&1)!==e&&(this._updateFlags|=Oi,this.localDisplayStatus^=1,this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._onUpdate())}get isRenderable(){return this.localDisplayStatus===7&&this.groupAlpha>0}destroy(t=!1){var r;if(this.destroyed)return;this.destroyed=!0;let e;if(this.children.length&&(e=this.removeChildren(0,this.children.length)),this.removeFromParent(),this.parent=null,this._maskEffect=null,this._filterEffect=null,this.effects=null,this._position=null,this._scale=null,this._pivot=null,this._origin=null,this._skew=null,this.emit("destroyed",this),this.removeAllListeners(),(typeof t=="boolean"?t:t==null?void 0:t.children)&&e)for(let n=0;n<e.length;++n)e[n].destroy(t);(r=this.renderGroup)==null||r.destroy(),this.renderGroup=null}}J.mixin(kt,td,od,fd,cd,hd,sd,rd,ud,Ku,Qu,ad,ed);class yr extends kt{constructor(t){super(t),this.canBundle=!0,this.allowChildren=!1,this._roundPixels=0,this._lastUsed=-1,this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this._bounds=new Lt(0,1,0,0),this._boundsDirty=!0,this.autoGarbageCollect=t.autoGarbageCollect??!0}get bounds(){return this._boundsDirty?(this.updateBounds(),this._boundsDirty=!1,this._bounds):this._bounds}get roundPixels(){return!!this._roundPixels}set roundPixels(t){this._roundPixels=t?1:0}containsPoint(t){const e=this.bounds,{x:i,y:r}=t;return i>=e.minX&&i<=e.maxX&&r>=e.minY&&r<=e.maxY}onViewUpdate(){if(this._didViewChangeTick++,this._boundsDirty=!0,this.didViewUpdate)return;this.didViewUpdate=!0;const t=this.renderGroup||this.parentRenderGroup;t&&t.onChildViewUpdate(this)}unload(){var t;this.emit("unload",this);for(const e in this._gpuData)(t=this._gpuData[e])==null||t.destroy();this._gpuData=Object.create(null),this.onViewUpdate()}destroy(t){this.unload(),super.destroy(t),this._bounds=null}collectRenderablesSimple(t,e,i){const{renderPipes:r}=e;r.blendMode.pushBlendMode(this,this.groupBlendMode,t);const o=r[this.renderPipeId];o!=null&&o.addRenderable&&o.addRenderable(this,t),this.didViewUpdate=!1;const a=this.children,l=a.length;for(let h=0;h<l;h++)a[h].collectRenderables(t,e,i);r.blendMode.popBlendMode(t)}}class ye extends yr{constructor(t=z.EMPTY){t instanceof z&&(t={texture:t});const{texture:e=z.EMPTY,anchor:i,roundPixels:r,width:n,height:o,...a}=t;super({label:"Sprite",...a}),this.renderPipeId="sprite",this.batched=!0,this._visualBounds={minX:0,maxX:1,minY:0,maxY:0},this._anchor=new Ot({_onUpdate:()=>{this.onViewUpdate()}}),i?this.anchor=i:e.defaultAnchor&&(this.anchor=e.defaultAnchor),this.texture=e,this.allowChildren=!1,this.roundPixels=r??!1,n!==void 0&&(this.width=n),o!==void 0&&(this.height=o)}static from(t,e=!1){return t instanceof z?new ye(t):new ye(z.from(t,e))}set texture(t){t||(t=z.EMPTY);const e=this._texture;e!==t&&(e&&e.dynamic&&e.off("update",this.onViewUpdate,this),t.dynamic&&t.on("update",this.onViewUpdate,this),this._texture=t,this._width&&this._setWidth(this._width,this._texture.orig.width),this._height&&this._setHeight(this._height,this._texture.orig.height),this.onViewUpdate())}get texture(){return this._texture}get visualBounds(){return xo(this._visualBounds,this._anchor,this._texture),this._visualBounds}get sourceBounds(){return K("8.6.1","Sprite.sourceBounds is deprecated, use visualBounds instead."),this.visualBounds}updateBounds(){const t=this._anchor,e=this._texture,i=this._bounds,{width:r,height:n}=e.orig;i.minX=-t._x*r,i.maxX=i.minX+r,i.minY=-t._y*n,i.maxY=i.minY+n}destroy(t=!1){if(super.destroy(t),typeof t=="boolean"?t:t==null?void 0:t.texture){const i=typeof t=="boolean"?t:t==null?void 0:t.textureSource;this._texture.destroy(i)}this._texture=null,this._visualBounds=null,this._bounds=null,this._anchor=null}get anchor(){return this._anchor}set anchor(t){typeof t=="number"?this._anchor.set(t):this._anchor.copyFrom(t)}get width(){return Math.abs(this.scale.x)*this._texture.orig.width}set width(t){this._setWidth(t,this._texture.orig.width),this._width=t}get height(){return Math.abs(this.scale.y)*this._texture.orig.height}set height(t){this._setHeight(t,this._texture.orig.height),this._height=t}getSize(t){return t||(t={}),t.width=Math.abs(this.scale.x)*this._texture.orig.width,t.height=Math.abs(this.scale.y)*this._texture.orig.height,t}setSize(t,e){typeof t=="object"?(e=t.height??t.width,t=t.width):e??(e=t),t!==void 0&&this._setWidth(t,this._texture.orig.width),e!==void 0&&this._setHeight(e,this._texture.orig.height)}}const _d=new Lt;function Uo(s,t,e){const i=_d;s.measurable=!0,cr(s,e,i),t.addBoundsMask(i),s.measurable=!1}function Lo(s,t,e){const i=_e.get();s.measurable=!0;const r=Ht.get().identity(),n=Fo(s,e,r);dr(s,i,n),s.measurable=!1,t.addBoundsMask(i),Ht.return(r),_e.return(i)}function Fo(s,t,e){return s?(s!==t&&(Fo(s.parent,t,e),s.updateLocalTransform(),e.append(s.localTransform)),e):(tt("Mask bounds, renderable is not inside the root container"),e)}class No{constructor(t){this.priority=0,this.inverse=!1,this.pipe="alphaMask",t!=null&&t.mask&&this.init(t.mask)}init(t){this.mask=t,this.renderMaskToTexture=!(t instanceof ye),this.mask.renderable=this.renderMaskToTexture,this.mask.includeInBuild=!this.renderMaskToTexture,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask=null)}addBounds(t,e){this.inverse||Uo(this.mask,t,e)}addLocalBounds(t,e){Lo(this.mask,t,e)}containsPoint(t,e){const i=this.mask;return e(i,t)}destroy(){this.reset()}static test(t){return t instanceof ye}}No.extension=w.MaskEffect;class Ho{constructor(t){this.priority=0,this.pipe="colorMask",t!=null&&t.mask&&this.init(t.mask)}init(t){this.mask=t}destroy(){}static test(t){return typeof t=="number"}}Ho.extension=w.MaskEffect;class Wo{constructor(t){this.priority=0,this.pipe="stencilMask",t!=null&&t.mask&&this.init(t.mask)}init(t){this.mask=t,this.mask.includeInBuild=!1,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask.includeInBuild=!0,this.mask=null)}addBounds(t,e){Uo(this.mask,t,e)}addLocalBounds(t,e){Lo(this.mask,t,e)}containsPoint(t,e){const i=this.mask;return e(i,t)}destroy(){this.reset()}static test(t){return t instanceof kt}}Wo.extension=w.MaskEffect;let Vo={createCanvas:(s,t)=>{const e=document.createElement("canvas");return e.width=s,e.height=t,e},createImage:()=>new Image,getCanvasRenderingContext2D:()=>CanvasRenderingContext2D,getWebGLRenderingContext:()=>WebGLRenderingContext,getNavigator:()=>navigator,getBaseUrl:()=>document.baseURI??window.location.href,getFontFaceSet:()=>document.fonts,fetch:(s,t)=>fetch(s,t),parseXML:s=>new DOMParser().parseFromString(s,"text/xml")};const rt={get(){return Vo},set(s){Vo=s}};class le extends At{constructor(t){t.resource||(t.resource=rt.get().createCanvas()),t.width||(t.width=t.resource.width,t.autoDensity||(t.width/=t.resolution)),t.height||(t.height=t.resource.height,t.autoDensity||(t.height/=t.resolution)),super(t),this.uploadMethodId="image",this.autoDensity=t.autoDensity,this.resizeCanvas(),this.transparent=!!t.transparent}resizeCanvas(){this.autoDensity&&"style"in this.resource&&(this.resource.style.width=`${this.width}px`,this.resource.style.height=`${this.height}px`),(this.resource.width!==this.pixelWidth||this.resource.height!==this.pixelHeight)&&(this.resource.width=this.pixelWidth,this.resource.height=this.pixelHeight)}resize(t=this.width,e=this.height,i=this._resolution){const r=super.resize(t,e,i);return r&&this.resizeCanvas(),r}static test(t){return globalThis.HTMLCanvasElement&&t instanceof HTMLCanvasElement||globalThis.OffscreenCanvas&&t instanceof OffscreenCanvas}get context2D(){return this._context2D||(this._context2D=this.resource.getContext("2d"))}}le.extension=w.TextureSource;class xs extends At{constructor(t){super(t),this.uploadMethodId="image",this.autoGarbageCollect=!0}static test(t){return globalThis.HTMLImageElement&&t instanceof HTMLImageElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap||globalThis.VideoFrame&&t instanceof VideoFrame}}xs.extension=w.TextureSource;var pi=(s=>(s[s.INTERACTION=50]="INTERACTION",s[s.HIGH=25]="HIGH",s[s.NORMAL=0]="NORMAL",s[s.LOW=-25]="LOW",s[s.UTILITY=-50]="UTILITY",s))(pi||{});class xr{constructor(t,e=null,i=0,r=!1){this.next=null,this.previous=null,this._destroyed=!1,this._fn=t,this._context=e,this.priority=i,this._once=r}match(t,e=null){return this._fn===t&&this._context===e}emit(t){this._fn&&(this._context?this._fn.call(this._context,t):this._fn(t));const e=this.next;return this._once&&this.destroy(!0),this._destroyed&&(this.next=null),e}connect(t){this.previous=t,t.next&&(t.next.previous=this),this.next=t.next,t.next=this}destroy(t=!1){this._destroyed=!0,this._fn=null,this._context=null,this.previous&&(this.previous.next=this.next),this.next&&(this.next.previous=this.previous);const e=this.next;return this.next=t?null:e,this.previous=null,e}}const zo=class Kt{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/Kt.targetFPMS,this.elapsedMS=1/Kt.targetFPMS,this._tick=t=>{this._requestId=null,this.started&&(this.update(t),this.started&&this._requestId===null&&this._head.next&&(this._requestId=requestAnimationFrame(this._tick)))}}_requestIfNeeded(){this._requestId===null&&this._head.next&&(this.lastTime=performance.now(),this._lastFrame=this.lastTime,this._requestId=requestAnimationFrame(this._tick))}_cancelIfNeeded(){this._requestId!==null&&(cancelAnimationFrame(this._requestId),this._requestId=null)}_startIfPossible(){this.started?this._requestIfNeeded():this.autoStart&&this.start()}add(t,e,i=pi.NORMAL){return this._addListener(new xr(t,e,i))}addOnce(t,e,i=pi.NORMAL){return this._addListener(new xr(t,e,i,!0))}_addListener(t){let e=this._head.next,i=this._head;if(!e)t.connect(i);else{for(;e;){if(t.priority>e.priority){t.connect(i);break}i=e,e=e.next}t.previous||t.connect(i)}return this._startIfPossible(),this}remove(t,e){let i=this._head.next;for(;i;)i.match(t,e)?i=i.destroy():i=i.next;return this._head.next||this._cancelIfNeeded(),this}get count(){if(!this._head)return 0;let t=0,e=this._head;for(;e=e.next;)t++;return t}start(){this.started||(this.started=!0,this._requestIfNeeded())}stop(){this.started&&(this.started=!1,this._cancelIfNeeded())}destroy(){if(!this._protected){this.stop();let t=this._head.next;for(;t;)t=t.destroy(!0);this._head.destroy(),this._head=null}}update(t=performance.now()){let e;if(t>this.lastTime){if(e=this.elapsedMS=t-this.lastTime,e>this._maxElapsedMS&&(e=this._maxElapsedMS),e*=this.speed,this._minElapsedMS){const n=t-this._lastFrame|0;if(n<this._minElapsedMS)return;this._lastFrame=t-n%this._minElapsedMS}this.deltaMS=e,this.deltaTime=this.deltaMS*Kt.targetFPMS;const i=this._head;let r=i.next;for(;r;)r=r.emit(this);i.next||this._cancelIfNeeded()}else this.deltaTime=this.deltaMS=this.elapsedMS=0;this.lastTime=t}get FPS(){return 1e3/this.elapsedMS}get minFPS(){return 1e3/this._maxElapsedMS}set minFPS(t){const e=Math.min(Math.max(0,t)/1e3,Kt.targetFPMS);this._maxElapsedMS=1/e,this._minElapsedMS&&t>this.maxFPS&&(this.maxFPS=t)}get maxFPS(){return this._minElapsedMS?Math.round(1e3/this._minElapsedMS):0}set maxFPS(t){t===0?this._minElapsedMS=0:(t<this.minFPS&&(this.minFPS=t),this._minElapsedMS=1/(t/1e3))}static get shared(){if(!Kt._shared){const t=Kt._shared=new Kt;t.autoStart=!0,t._protected=!0}return Kt._shared}static get system(){if(!Kt._system){const t=Kt._system=new Kt;t.autoStart=!0,t._protected=!0}return Kt._system}};zo.targetFPMS=.06;let te=zo,br;async function yd(){return br??(br=(async()=>{var o;const t=rt.get().createCanvas(1,1).getContext("webgl");if(!t)return"premultiply-alpha-on-upload";const e=await new Promise(a=>{const l=document.createElement("video");l.onloadeddata=()=>a(l),l.onerror=()=>a(null),l.autoplay=!1,l.crossOrigin="anonymous",l.preload="auto",l.src="data:video/webm;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAHTEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHGTbuMU6uEElTDZ1OsggEXTbuMU6uEHFO7a1OsggG97AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmoCrXsYMPQkBNgIRMYXZmV0GETGF2ZkSJiEBEAAAAAAAAFlSua8yuAQAAAAAAAEPXgQFzxYgAAAAAAAAAAZyBACK1nIN1bmSIgQCGhVZfVlA5g4EBI+ODhAJiWgDglLCBArqBApqBAlPAgQFVsIRVuYEBElTDZ9Vzc9JjwItjxYgAAAAAAAAAAWfInEWjh0VOQ09ERVJEh49MYXZjIGxpYnZweC12cDlnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjA0MDAwMDAwMAAAH0O2dcfngQCgwqGggQAAAIJJg0IAABAAFgA4JBwYSgAAICAAEb///4r+AAB1oZ2mm+6BAaWWgkmDQgAAEAAWADgkHBhKAAAgIABIQBxTu2uRu4+zgQC3iveBAfGCAXHwgQM=",l.load()});if(!e)return"premultiply-alpha-on-upload";const i=t.createTexture();t.bindTexture(t.TEXTURE_2D,i);const r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i,0),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,t.NONE),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e);const n=new Uint8Array(4);return t.readPixels(0,0,1,1,t.RGBA,t.UNSIGNED_BYTE,n),t.deleteFramebuffer(r),t.deleteTexture(i),(o=t.getExtension("WEBGL_lose_context"))==null||o.loseContext(),n[0]<=n[3]?"premultiplied-alpha":"premultiply-alpha-on-upload"})()),br}const bs=class nu extends At{constructor(t){super(t),this.isReady=!1,this.uploadMethodId="video",t={...nu.defaultOptions,...t},this._autoUpdate=!0,this._isConnectedToTicker=!1,this._updateFPS=t.updateFPS||0,this._msToNextUpdate=0,this.autoPlay=t.autoPlay!==!1,this.alphaMode=t.alphaMode??"premultiply-alpha-on-upload",this._videoFrameRequestCallback=this._videoFrameRequestCallback.bind(this),this._videoFrameRequestCallbackHandle=null,this._load=null,this._resolve=null,this._reject=null,this._onCanPlay=this._onCanPlay.bind(this),this._onCanPlayThrough=this._onCanPlayThrough.bind(this),this._onError=this._onError.bind(this),this._onPlayStart=this._onPlayStart.bind(this),this._onPlayStop=this._onPlayStop.bind(this),this._onSeeked=this._onSeeked.bind(this),t.autoLoad!==!1&&this.load()}updateFrame(){if(!this.destroyed){if(this._updateFPS){const t=te.shared.elapsedMS*this.resource.playbackRate;this._msToNextUpdate=Math.floor(this._msToNextUpdate-t)}(!this._updateFPS||this._msToNextUpdate<=0)&&(this._msToNextUpdate=this._updateFPS?Math.floor(1e3/this._updateFPS):0),this.isValid&&this.update()}}_videoFrameRequestCallback(){this.updateFrame(),this.destroyed?this._videoFrameRequestCallbackHandle=null:this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback)}get isValid(){return!!this.resource.videoWidth&&!!this.resource.videoHeight}async load(){if(this._load)return this._load;const t=this.resource,e=this.options;return(t.readyState===t.HAVE_ENOUGH_DATA||t.readyState===t.HAVE_FUTURE_DATA)&&t.width&&t.height&&(t.complete=!0),t.addEventListener("play",this._onPlayStart),t.addEventListener("pause",this._onPlayStop),t.addEventListener("seeked",this._onSeeked),this._isSourceReady()?this._mediaReady():(e.preload||t.addEventListener("canplay",this._onCanPlay),t.addEventListener("canplaythrough",this._onCanPlayThrough),t.addEventListener("error",this._onError,!0)),this.alphaMode=await yd(),this._load=new Promise((i,r)=>{this.isValid?i(this):(this._resolve=i,this._reject=r,e.preloadTimeoutMs!==void 0&&(this._preloadTimeout=setTimeout(()=>{this._onError(new ErrorEvent(`Preload exceeded timeout of ${e.preloadTimeoutMs}ms`))})),t.load())}),this._load}_onError(t){this.resource.removeEventListener("error",this._onError,!0),this.emit("error",t),this._reject&&(this._reject(t),this._reject=null,this._resolve=null)}_isSourcePlaying(){const t=this.resource;return!t.paused&&!t.ended}_isSourceReady(){return this.resource.readyState>2}_onPlayStart(){this.isValid||this._mediaReady(),this._configureAutoUpdate()}_onPlayStop(){this._configureAutoUpdate()}_onSeeked(){this._autoUpdate&&!this._isSourcePlaying()&&(this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0)}_onCanPlay(){this.resource.removeEventListener("canplay",this._onCanPlay),this._mediaReady()}_onCanPlayThrough(){this.resource.removeEventListener("canplaythrough",this._onCanPlay),this._preloadTimeout&&(clearTimeout(this._preloadTimeout),this._preloadTimeout=void 0),this._mediaReady()}_mediaReady(){const t=this.resource;this.isValid&&(this.isReady=!0,this.resize(t.videoWidth,t.videoHeight)),this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0,this._resolve&&(this._resolve(this),this._resolve=null,this._reject=null),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.resource.play()}destroy(){this._configureAutoUpdate();const t=this.resource;t&&(t.removeEventListener("play",this._onPlayStart),t.removeEventListener("pause",this._onPlayStop),t.removeEventListener("seeked",this._onSeeked),t.removeEventListener("canplay",this._onCanPlay),t.removeEventListener("canplaythrough",this._onCanPlayThrough),t.removeEventListener("error",this._onError,!0),t.pause(),t.src="",t.load()),super.destroy()}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){t!==this._autoUpdate&&(this._autoUpdate=t,this._configureAutoUpdate())}get updateFPS(){return this._updateFPS}set updateFPS(t){t!==this._updateFPS&&(this._updateFPS=t,this._configureAutoUpdate())}_configureAutoUpdate(){this._autoUpdate&&this._isSourcePlaying()?!this._updateFPS&&this.resource.requestVideoFrameCallback?(this._isConnectedToTicker&&(te.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||(te.shared.add(this.updateFrame,this),this._isConnectedToTicker=!0,this._msToNextUpdate=0)):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker&&(te.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0))}static test(t){return globalThis.HTMLVideoElement&&t instanceof HTMLVideoElement}};bs.extension=w.TextureSource,bs.defaultOptions={...At.defaultOptions,autoLoad:!0,autoPlay:!0,updateFPS:0,crossorigin:!0,loop:!1,muted:!0,playsinline:!0,preload:!1},bs.MIME_TYPES={ogv:"video/ogg",mov:"video/quicktime",m4v:"video/mp4"};let xd=bs;const mi=(s,t,e=!1)=>(Array.isArray(s)||(s=[s]),t?s.map(i=>typeof i=="string"||e?t(i):i):s);class bd{constructor(){this._parsers=[],this._cache=new Map,this._cacheMap=new Map}reset(){this._cacheMap.clear(),this._cache.clear()}has(t){return this._cache.has(t)}get(t){const e=this._cache.get(t);return e||tt(`[Assets] Asset id ${t} was not found in the Cache`),e}set(t,e){const i=mi(t);let r;for(let l=0;l<this.parsers.length;l++){const h=this.parsers[l];if(h.test(e)){r=h.getCacheableAssets(i,e);break}}const n=new Map(Object.entries(r||{}));r||i.forEach(l=>{n.set(l,e)});const o=[...n.keys()],a={cacheKeys:o,keys:i};i.forEach(l=>{this._cacheMap.set(l,a)}),o.forEach(l=>{const h=r?r[l]:e;this._cache.has(l)&&this._cache.get(l)!==h&&tt("[Cache] already has key:",l),this._cache.set(l,n.get(l))})}remove(t){if(!this._cacheMap.has(t)){tt(`[Assets] Asset id ${t} was not found in the Cache`);return}const e=this._cacheMap.get(t);e.cacheKeys.forEach(r=>{this._cache.delete(r)}),e.keys.forEach(r=>{this._cacheMap.delete(r)})}get parsers(){return this._parsers}}const gi=new bd,vr=[];J.handleByList(w.TextureSource,vr);function $o(s={}){const t=s&&s.resource,e=t?s.resource:s,i=t?s:{resource:s};for(let r=0;r<vr.length;r++){const n=vr[r];if(n.test(e))return new n(i)}throw new Error(`Could not find a source type for resource: ${i.resource}`)}function vd(s={},t=!1){const e=s&&s.resource,i=e?s.resource:s,r=e?s:{resource:s};if(!t&&gi.has(i))return gi.get(i);const n=new z({source:$o(r)});return n.on("destroy",()=>{gi.has(i)&&gi.remove(i)}),t||gi.set(i,n),n}function Ed(s,t=!1){return typeof s=="string"?gi.get(s):s instanceof At?new z({source:s}):vd(s,t)}z.from=Ed,At.from=$o,J.add(No,Ho,Wo,xd,xs,le,ir);var jo=(s=>(s[s.Low=0]="Low",s[s.Normal=1]="Normal",s[s.High=2]="High",s))(jo||{});function ie(s){if(typeof s!="string")throw new TypeError(`Path must be a string. Received ${JSON.stringify(s)}`)}function Di(s){return s.split("?")[0].split("#")[0]}function Td(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Sd(s,t,e){return s.replace(new RegExp(Td(t),"g"),e)}function Cd(s,t){let e="",i=0,r=-1,n=0,o=-1;for(let a=0;a<=s.length;++a){if(a<s.length)o=s.charCodeAt(a);else{if(o===47)break;o=47}if(o===47){if(!(r===a-1||n===1))if(r!==a-1&&n===2){if(e.length<2||i!==2||e.charCodeAt(e.length-1)!==46||e.charCodeAt(e.length-2)!==46){if(e.length>2){const l=e.lastIndexOf("/");if(l!==e.length-1){l===-1?(e="",i=0):(e=e.slice(0,l),i=e.length-1-e.lastIndexOf("/")),r=a,n=0;continue}}else if(e.length===2||e.length===1){e="",i=0,r=a,n=0;continue}}}else e.length>0?e+=`/${s.slice(r+1,a)}`:e=s.slice(r+1,a),i=a-r-1;r=a,n=0}else o===46&&n!==-1?++n:n=-1}return e}const Gi={toPosix(s){return Sd(s,"\\","/")},isUrl(s){return/^https?:/.test(this.toPosix(s))},isDataUrl(s){return/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i.test(s)},isBlobUrl(s){return s.startsWith("blob:")},hasProtocol(s){return/^[^/:]+:/.test(this.toPosix(s))},getProtocol(s){ie(s),s=this.toPosix(s);const t=/^file:\/\/\//.exec(s);if(t)return t[0];const e=/^[^/:]+:\/{0,2}/.exec(s);return e?e[0]:""},toAbsolute(s,t,e){if(ie(s),this.isDataUrl(s)||this.isBlobUrl(s))return s;const i=Di(this.toPosix(t??rt.get().getBaseUrl())),r=Di(this.toPosix(e??this.rootname(i)));return s=this.toPosix(s),s.startsWith("/")?Gi.join(r,s.slice(1)):this.isAbsolute(s)?s:this.join(i,s)},normalize(s){if(ie(s),s.length===0)return".";if(this.isDataUrl(s)||this.isBlobUrl(s))return s;s=this.toPosix(s);let t="";const e=s.startsWith("/");this.hasProtocol(s)&&(t=this.rootname(s),s=s.slice(t.length));const i=s.endsWith("/");return s=Cd(s),s.length>0&&i&&(s+="/"),e?`/${s}`:t+s},isAbsolute(s){return ie(s),s=this.toPosix(s),this.hasProtocol(s)?!0:s.startsWith("/")},join(...s){if(s.length===0)return".";let t;for(let e=0;e<s.length;++e){const i=s[e];if(ie(i),i.length>0)if(t===void 0)t=i;else{const r=s[e-1]??"";this.joinExtensions.includes(this.extname(r).toLowerCase())?t+=`/../${i}`:t+=`/${i}`}}return t===void 0?".":this.normalize(t)},dirname(s){if(ie(s),s.length===0)return".";s=this.toPosix(s);let t=s.charCodeAt(0);const e=t===47;let i=-1,r=!0;const n=this.getProtocol(s),o=s;s=s.slice(n.length);for(let a=s.length-1;a>=1;--a)if(t=s.charCodeAt(a),t===47){if(!r){i=a;break}}else r=!1;return i===-1?e?"/":this.isUrl(o)?n+s:n:e&&i===1?"//":n+s.slice(0,i)},rootname(s){ie(s),s=this.toPosix(s);let t="";if(s.startsWith("/")?t="/":t=this.getProtocol(s),this.isUrl(s)){const e=s.indexOf("/",t.length);e!==-1?t=s.slice(0,e):t=s,t.endsWith("/")||(t+="/")}return t},basename(s,t){ie(s),t&&ie(t),s=Di(this.toPosix(s));let e=0,i=-1,r=!0,n;if(t!==void 0&&t.length>0&&t.length<=s.length){if(t.length===s.length&&t===s)return"";let o=t.length-1,a=-1;for(n=s.length-1;n>=0;--n){const l=s.charCodeAt(n);if(l===47){if(!r){e=n+1;break}}else a===-1&&(r=!1,a=n+1),o>=0&&(l===t.charCodeAt(o)?--o===-1&&(i=n):(o=-1,i=a))}return e===i?i=a:i===-1&&(i=s.length),s.slice(e,i)}for(n=s.length-1;n>=0;--n)if(s.charCodeAt(n)===47){if(!r){e=n+1;break}}else i===-1&&(r=!1,i=n+1);return i===-1?"":s.slice(e,i)},extname(s){ie(s),s=Di(this.toPosix(s));let t=-1,e=0,i=-1,r=!0,n=0;for(let o=s.length-1;o>=0;--o){const a=s.charCodeAt(o);if(a===47){if(!r){e=o+1;break}continue}i===-1&&(r=!1,i=o+1),a===46?t===-1?t=o:n!==1&&(n=1):t!==-1&&(n=-1)}return t===-1||i===-1||n===0||n===1&&t===i-1&&t===e+1?"":s.slice(t,i)},parse(s){ie(s);const t={root:"",dir:"",base:"",ext:"",name:""};if(s.length===0)return t;s=Di(this.toPosix(s));let e=s.charCodeAt(0);const i=this.isAbsolute(s);let r;t.root=this.rootname(s),i||this.hasProtocol(s)?r=1:r=0;let n=-1,o=0,a=-1,l=!0,h=s.length-1,c=0;for(;h>=r;--h){if(e=s.charCodeAt(h),e===47){if(!l){o=h+1;break}continue}a===-1&&(l=!1,a=h+1),e===46?n===-1?n=h:c!==1&&(c=1):n!==-1&&(c=-1)}return n===-1||a===-1||c===0||c===1&&n===a-1&&n===o+1?a!==-1&&(o===0&&i?t.base=t.name=s.slice(1,a):t.base=t.name=s.slice(o,a)):(o===0&&i?(t.name=s.slice(1,n),t.base=s.slice(1,a)):(t.name=s.slice(o,n),t.base=s.slice(o,a)),t.ext=s.slice(n,a)),t.dir=this.dirname(s),t},sep:"/",delimiter:":",joinExtensions:[".html"]};function Xo(s,t,e,i,r){const n=t[e];for(let o=0;o<n.length;o++){const a=n[o];e<t.length-1?Xo(s.replace(i[e],a),t,e+1,i,r):r.push(s.replace(i[e],a))}}function wd(s){const t=/\{(.*?)\}/g,e=s.match(t),i=[];if(e){const r=[];e.forEach(n=>{const o=n.substring(1,n.length-1).split(",");r.push(o)}),Xo(s,r,0,e,i)}else i.push(s);return i}const Yo=s=>!Array.isArray(s);class qo{constructor(){this._defaultBundleIdentifierOptions={connector:"-",createBundleAssetId:(t,e)=>`${t}${this._bundleIdConnector}${e}`,extractAssetIdFromBundle:(t,e)=>e.replace(`${t}${this._bundleIdConnector}`,"")},this._bundleIdConnector=this._defaultBundleIdentifierOptions.connector,this._createBundleAssetId=this._defaultBundleIdentifierOptions.createBundleAssetId,this._extractAssetIdFromBundle=this._defaultBundleIdentifierOptions.extractAssetIdFromBundle,this._assetMap={},this._preferredOrder=[],this._parsers=[],this._resolverHash={},this._bundles={}}setBundleIdentifier(t){if(this._bundleIdConnector=t.connector??this._bundleIdConnector,this._createBundleAssetId=t.createBundleAssetId??this._createBundleAssetId,this._extractAssetIdFromBundle=t.extractAssetIdFromBundle??this._extractAssetIdFromBundle,this._extractAssetIdFromBundle("foo",this._createBundleAssetId("foo","bar"))!=="bar")throw new Error("[Resolver] GenerateBundleAssetId are not working correctly")}prefer(...t){t.forEach(e=>{this._preferredOrder.push(e),e.priority||(e.priority=Object.keys(e.params))}),this._resolverHash={}}set basePath(t){this._basePath=t}get basePath(){return this._basePath}set rootPath(t){this._rootPath=t}get rootPath(){return this._rootPath}get parsers(){return this._parsers}reset(){this.setBundleIdentifier(this._defaultBundleIdentifierOptions),this._assetMap={},this._preferredOrder=[],this._resolverHash={},this._rootPath=null,this._basePath=null,this._manifest=null,this._bundles={},this._defaultSearchParams=null}setDefaultSearchParams(t){if(typeof t=="string")this._defaultSearchParams=t;else{const e=t;this._defaultSearchParams=Object.keys(e).map(i=>`${encodeURIComponent(i)}=${encodeURIComponent(e[i])}`).join("&")}}getAlias(t){const{alias:e,src:i}=t;return mi(e||i,n=>typeof n=="string"?n:Array.isArray(n)?n.map(o=>(o==null?void 0:o.src)??o):n!=null&&n.src?n.src:n,!0)}removeAlias(t,e){this._assetMap[t]&&(e&&e!==this._resolverHash[t]||(delete this._resolverHash[t],delete this._assetMap[t]))}addManifest(t){this._manifest&&tt("[Resolver] Manifest already exists, this will be overwritten"),this._manifest=t,t.bundles.forEach(e=>{this.addBundle(e.name,e.assets)})}addBundle(t,e){const i=[];let r=e;Array.isArray(e)||(r=Object.entries(e).map(([n,o])=>typeof o=="string"||Array.isArray(o)?{alias:n,src:o}:{alias:n,...o})),r.forEach(n=>{const o=n.src,a=n.alias;let l;if(typeof a=="string"){const h=this._createBundleAssetId(t,a);i.push(h),l=[a,h]}else{const h=a.map(c=>this._createBundleAssetId(t,c));i.push(...h),l=[...a,...h]}this.add({...n,alias:l,src:o})}),this._bundles[t]=i}add(t){const e=[];Array.isArray(t)?e.push(...t):e.push(t);let i;i=n=>{this.hasKey(n)&&tt(`[Resolver] already has key: ${n} overwriting`)},mi(e).forEach(n=>{const{src:o}=n;let{data:a,format:l,loadParser:h,parser:c}=n;const u=mi(o).map(y=>typeof y=="string"?wd(y):Array.isArray(y)?y:[y]),m=this.getAlias(n);Array.isArray(m)?m.forEach(i):i(m);const f=[],g=y=>{const x=this._parsers.find(v=>v.test(y));return{src:y,...x==null?void 0:x.parse(y)}};u.forEach(y=>{y.forEach(x=>{let v={};if(typeof x!="object"?v=g(x):(a=x.data??a,l=x.format??l,(x.loadParser||x.parser)&&(h=x.loadParser??h,c=x.parser??c),v={...g(x.src),...x}),!m)throw new Error(`[Resolver] alias is undefined for this asset: ${v.src}`);v=this._buildResolvedAsset(v,{aliases:m,data:a,format:l,loadParser:h,parser:c,progressSize:n.progressSize}),f.push(v)})}),m.forEach(y=>{this._assetMap[y]=f})})}resolveBundle(t){const e=Yo(t);t=mi(t);const i={};return t.forEach(r=>{const n=this._bundles[r];if(n){const o=this.resolve(n),a={};for(const l in o){const h=o[l];a[this._extractAssetIdFromBundle(r,l)]=h}i[r]=a}}),e?i[t[0]]:i}resolveUrl(t){const e=this.resolve(t);if(typeof t!="string"){const i={};for(const r in e)i[r]=e[r].src;return i}return e.src}resolve(t){const e=Yo(t);t=mi(t);const i={};return t.forEach(r=>{if(!this._resolverHash[r])if(this._assetMap[r]){let n=this._assetMap[r];const o=this._getPreferredOrder(n);o==null||o.priority.forEach(a=>{o.params[a].forEach(l=>{const h=n.filter(c=>c[a]?c[a]===l:!1);h.length&&(n=h)})}),this._resolverHash[r]=n[0]}else this._resolverHash[r]=this._buildResolvedAsset({alias:[r],src:r},{});i[r]=this._resolverHash[r]}),e?i[t[0]]:i}hasKey(t){return!!this._assetMap[t]}hasBundle(t){return!!this._bundles[t]}_getPreferredOrder(t){for(let e=0;e<t.length;e++){const i=t[e],r=this._preferredOrder.find(n=>n.params.format.includes(i.format));if(r)return r}return this._preferredOrder[0]}_appendDefaultSearchParams(t){if(!this._defaultSearchParams)return t;const e=/\?/.test(t)?"&":"?";return`${t}${e}${this._defaultSearchParams}`}_buildResolvedAsset(t,e){const{aliases:i,data:r,loadParser:n,parser:o,format:a,progressSize:l}=e;return(this._basePath||this._rootPath)&&(t.src=Gi.toAbsolute(t.src,this._basePath,this._rootPath)),t.alias=i??t.alias??[t.src],t.src=this._appendDefaultSearchParams(t.src),t.data={...r||{},...t.data},t.loadParser=n??t.loadParser,t.parser=o??t.parser,t.format=a??t.format??Ad(t.src),l!==void 0&&(t.progressSize=l),t}}qo.RETINA_PREFIX=/@([0-9\.]+)x/;function Ad(s){return s.split(".").pop().split("?").shift().split("#").shift()}const Ko=(s,t)=>{const e=t.split("?")[1];return e&&(s+=`?${e}`),s},Zo=class hs{constructor(t,e){this.linkedSheets=[];let i=t;(t==null?void 0:t.source)instanceof At&&(i={texture:t,data:e});const{texture:r,data:n,cachePrefix:o=""}=i;this.cachePrefix=o,this._texture=r instanceof z?r:null,this.textureSource=r.source,this.textures={},this.animations={},this.data=n;const a=parseFloat(n.meta.scale);a?(this.resolution=a,r.source.resolution=this.resolution):this.resolution=r.source._resolution,this._frames=this.data.frames,this._frameKeys=Object.keys(this._frames),this._batchIndex=0,this._callback=null}parse(){return new Promise(t=>{this._callback=t,this._batchIndex=0,this._frameKeys.length<=hs.BATCH_SIZE?(this._processFrames(0),this._processAnimations(),this._parseComplete()):this._nextBatch()})}parseSync(){return this._processFrames(0,!0),this._processAnimations(),this.textures}_processFrames(t,e=!1){let i=t;const r=e?1/0:hs.BATCH_SIZE;for(;i-t<r&&i<this._frameKeys.length;){const n=this._frameKeys[i],o=this._frames[n],a=o.frame;if(a){let l=null,h=null;const c=o.trimmed!==!1&&o.sourceSize?o.sourceSize:o.frame,u=new ut(0,0,Math.floor(c.w)/this.resolution,Math.floor(c.h)/this.resolution);o.rotated?l=new ut(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 ut(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 ut(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 z({source:this.textureSource,frame:l,orig:u,trim:h,rotate:o.rotated?2:0,defaultAnchor:o.anchor,defaultBorders:o.borders,label:n.toString()})}i++}}_processAnimations(){const t=this.data.animations||{};for(const e in t){this.animations[e]=[];for(let i=0;i<t[e].length;i++){const r=t[e][i];this.animations[e].push(this.textures[r])}}}_parseComplete(){const t=this._callback;this._callback=null,this._batchIndex=0,t.call(this,this.textures)}_nextBatch(){this._processFrames(this._batchIndex*hs.BATCH_SIZE),this._batchIndex++,setTimeout(()=>{this._batchIndex*hs.BATCH_SIZE<this._frameKeys.length?this._nextBatch():(this._processAnimations(),this._parseComplete())},0)}destroy(t=!1){var e;for(const i in this.textures)this.textures[i].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,t&&((e=this._texture)==null||e.destroy(),this.textureSource.destroy()),this._texture=null,this.textureSource=null,this.linkedSheets=[]}};Zo.BATCH_SIZE=1e3;let Jo=Zo;const Rd=["jpg","png","jpeg","avif","webp","basis","etc2","bc7","bc6h","bc5","bc4","bc3","bc2","bc1","eac","astc"];function Qo(s,t,e){const i={};if(s.forEach(r=>{i[r]=t}),Object.keys(t.textures).forEach(r=>{i[`${t.cachePrefix}${r}`]=t.textures[r]}),!e){const r=Gi.dirname(s[0]);t.linkedSheets.forEach((n,o)=>{const a=Qo([`${r}/${t.data.meta.related_multi_packs[o]}`],n,!0);Object.assign(i,a)})}return i}const Pd={extension:w.Asset,cache:{test:s=>s instanceof Jo,getCacheableAssets:(s,t)=>Qo(s,t,!1)},resolver:{extension:{type:w.ResolveParser,name:"resolveSpritesheet"},test:s=>{const e=s.split("?")[0].split("."),i=e.pop(),r=e.pop();return i==="json"&&Rd.includes(r)},parse:s=>{var e;const t=s.split(".");return{resolution:parseFloat(((e=qo.RETINA_PREFIX.exec(s))==null?void 0:e[1])??"1"),format:t[t.length-2],src:s}}},loader:{name:"spritesheetLoader",id:"spritesheet",extension:{type:w.LoadParser,priority:jo.Normal,name:"spritesheetLoader"},async testParse(s,t){return Gi.extname(t.src).toLowerCase()===".json"&&!!s.frames},async parse(s,t,e){var u,m;const{texture:i,imageFilename:r,textureOptions:n,cachePrefix:o}=(t==null?void 0:t.data)??{};let a=Gi.dirname(t.src);a&&a.lastIndexOf("/")!==a.length-1&&(a+="/");let l;if(i instanceof z)l=i;else{const f=Ko(a+(r??s.meta.image),t.src);l=(await e.load([{src:f,data:n}]))[f]}const h=new Jo({texture:l.source,data:s,cachePrefix:o});await h.parse();const c=(u=s==null?void 0:s.meta)==null?void 0:u.related_multi_packs;if(Array.isArray(c)){const f=[];for(const y of c){if(typeof y!="string")continue;let x=a+y;(m=t.data)!=null&&m.ignoreMultiPack||(x=Ko(x,t.src),f.push(e.load({src:x,data:{textureOptions:n,ignoreMultiPack:!0}})))}const g=await Promise.all(f);h.linkedSheets=g,g.forEach(y=>{y.linkedSheets=[h].concat(h.linkedSheets.filter(x=>x!==y))})}return h},async unload(s,t,e){await e.unload(s.textureSource._sourceOrigin),s.destroy(!1)}}};J.add(Pd);class ta{constructor(t){this._lastTransform="",this._observer=null,this._tickerAttached=!1,this.updateTranslation=()=>{if(!this._canvas)return;const e=this._canvas.getBoundingClientRect(),i=this._canvas.width,r=this._canvas.height,n=e.width/i*this._renderer.resolution,o=e.height/r*this._renderer.resolution,a=e.left,l=e.top,h=`translate(${a}px, ${l}px) scale(${n}, ${o})`;h!==this._lastTransform&&(this._domElement.style.transform=h,this._lastTransform=h)},this._domElement=t.domElement,this._renderer=t.renderer,!(globalThis.OffscreenCanvas&&this._renderer.canvas instanceof OffscreenCanvas)&&(this._canvas=this._renderer.canvas,this._attachObserver())}get canvas(){return this._canvas}ensureAttached(){!this._domElement.parentNode&&this._canvas.parentNode&&(this._canvas.parentNode.appendChild(this._domElement),this.updateTranslation())}_attachObserver(){"ResizeObserver"in globalThis?(this._observer&&(this._observer.disconnect(),this._observer=null),this._observer=new ResizeObserver(t=>{for(const e of t){if(e.target!==this._canvas)continue;const i=this.canvas.width,r=this.canvas.height,n=e.contentRect.width/i*this._renderer.resolution,o=e.contentRect.height/r*this._renderer.resolution;(this._lastScaleX!==n||this._lastScaleY!==o)&&(this.updateTranslation(),this._lastScaleX=n,this._lastScaleY=o)}}),this._observer.observe(this._canvas)):this._tickerAttached||te.shared.add(this.updateTranslation,this,pi.HIGH)}destroy(){this._observer?(this._observer.disconnect(),this._observer=null):this._tickerAttached&&te.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 Ui{constructor(t){this.bubbles=!0,this.cancelBubble=!0,this.cancelable=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=Ui.prototype.NONE,this.propagationStopped=!1,this.propagationImmediatelyStopped=!1,this.layer=new mt,this.page=new mt,this.NONE=0,this.CAPTURING_PHASE=1,this.AT_TARGET=2,this.BUBBLING_PHASE=3,this.manager=t}get layerX(){return this.layer.x}get layerY(){return this.layer.y}get pageX(){return this.page.x}get pageY(){return this.page.y}get data(){return this}composedPath(){return this.manager&&(!this.path||this.path[this.path.length-1]!==this.target)&&(this.path=this.target?this.manager.propagationPath(this.target):[]),this.path}initEvent(t,e,i){throw new Error("initEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}initUIEvent(t,e,i,r,n){throw new Error("initUIEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}preventDefault(){this.nativeEvent instanceof Event&&this.nativeEvent.cancelable&&this.nativeEvent.preventDefault(),this.defaultPrevented=!0}stopImmediatePropagation(){this.propagationImmediatelyStopped=!0}stopPropagation(){this.propagationStopped=!0}}var Er=/iPhone/i,ea=/iPod/i,ia=/iPad/i,sa=/\biOS-universal(?:.+)Mac\b/i,Tr=/\bAndroid(?:.+)Mobile\b/i,ra=/Android/i,_i=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,vs=/Silk/i,xe=/Windows Phone/i,na=/\bWindows(?:.+)ARM\b/i,oa=/BlackBerry/i,aa=/BB10/i,la=/Opera Mini/i,ha=/\b(CriOS|Chrome)(?:.+)Mobile/i,ca=/Mobile(?:.+)Firefox\b/i,ua=function(s){return typeof s<"u"&&s.platform==="MacIntel"&&typeof s.maxTouchPoints=="number"&&s.maxTouchPoints>1&&typeof MSStream>"u"};function Id(s){return function(t){return t.test(s)}}function da(s){var t={userAgent:"",platform:"",maxTouchPoints:0};!s&&typeof navigator<"u"?t={userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints||0}:typeof s=="string"?t.userAgent=s:s&&s.userAgent&&(t={userAgent:s.userAgent,platform:s.platform,maxTouchPoints:s.maxTouchPoints||0});var e=t.userAgent,i=e.split("[FBAN");typeof i[1]<"u"&&(e=i[0]),i=e.split("Twitter"),typeof i[1]<"u"&&(e=i[0]);var r=Id(e),n={apple:{phone:r(Er)&&!r(xe),ipod:r(ea),tablet:!r(Er)&&(r(ia)||ua(t))&&!r(xe),universal:r(sa),device:(r(Er)||r(ea)||r(ia)||r(sa)||ua(t))&&!r(xe)},amazon:{phone:r(_i),tablet:!r(_i)&&r(vs),device:r(_i)||r(vs)},android:{phone:!r(xe)&&r(_i)||!r(xe)&&r(Tr),tablet:!r(xe)&&!r(_i)&&!r(Tr)&&(r(vs)||r(ra)),device:!r(xe)&&(r(_i)||r(vs)||r(Tr)||r(ra))||r(/\bokhttp\b/i)},windows:{phone:r(xe),tablet:r(na),device:r(xe)||r(na)},other:{blackberry:r(oa),blackberry10:r(aa),opera:r(la),firefox:r(ca),chrome:r(ha),device:r(oa)||r(aa)||r(la)||r(ca)||r(ha)},any:!1,phone:!1,tablet:!1};return n.any=n.apple.device||n.android.device||n.windows.device||n.other.device,n.phone=n.apple.phone||n.android.phone||n.windows.phone,n.tablet=n.apple.tablet||n.android.tablet||n.windows.tablet,n}const Md=(da.default??da)(globalThis.navigator),kd=9,fa=100,Bd=0,Od=0,pa=2,ma=1,Dd=-1e3,Gd=-1e3,Ud=2,Sr=class ou{constructor(t,e=Md){this._mobileInfo=e,this.debug=!1,this._activateOnTab=!0,this._deactivateOnMouseMove=!0,this._isActive=!1,this._isMobileAccessibility=!1,this._div=null,this._pools={},this._renderId=0,this._children=[],this._androidUpdateCount=0,this._androidUpdateFrequency=500,this._isRunningTests=!1,this._boundOnKeyDown=this._onKeyDown.bind(this),this._boundOnMouseMove=this._onMouseMove.bind(this),this._hookDiv=null,(e.tablet||e.phone)&&this._createTouchHook(),this._renderer=t}get isActive(){return this._isActive}get isMobileAccessibility(){return this._isMobileAccessibility}get hookDiv(){return this._hookDiv}get div(){return this._div}_createTouchHook(){const t=document.createElement("button");t.style.width=`${ma}px`,t.style.height=`${ma}px`,t.style.position="absolute",t.style.top=`${Dd}px`,t.style.left=`${Gd}px`,t.style.zIndex=Ud.toString(),t.style.backgroundColor="#FF0000",t.title="select to enable accessibility for this content",t.addEventListener("focus",()=>{this._isMobileAccessibility=!0,this._activate(),this._destroyTouchHook()}),document.body.appendChild(t),this._hookDiv=t}_destroyTouchHook(){this._hookDiv&&(document.body.removeChild(this._hookDiv),this._hookDiv=null)}_activate(){if(this._isActive)return;this._isActive=!0,this._div||(this._div=document.createElement("div"),this._div.style.position="absolute",this._div.style.top=`${Bd}px`,this._div.style.left=`${Od}px`,this._div.style.pointerEvents="none",this._div.style.zIndex=pa.toString(),this._canvasObserver=new ta({domElement:this._div,renderer:this._renderer})),this._activateOnTab&&globalThis.addEventListener("keydown",this._boundOnKeyDown,!1),this._deactivateOnMouseMove&&globalThis.document.addEventListener("mousemove",this._boundOnMouseMove,!0);const t=this._renderer.view.canvas;if(t.parentNode)this._canvasObserver.ensureAttached(),this._initAccessibilitySetup();else{const e=new MutationObserver(()=>{t.parentNode&&(e.disconnect(),this._canvasObserver.ensureAttached(),this._initAccessibilitySetup())});e.observe(document.body,{childList:!0,subtree:!0})}}_initAccessibilitySetup(){this._renderer.runners.postrender.add(this),this._renderer.lastObjectRendered&&this._updateAccessibleObjects(this._renderer.lastObjectRendered)}_deactivate(){var t,e;if(!(!this._isActive||this._isMobileAccessibility)){this._isActive=!1,globalThis.document.removeEventListener("mousemove",this._boundOnMouseMove,!0),this._activateOnTab&&globalThis.addEventListener("keydown",this._boundOnKeyDown,!1),this._renderer.runners.postrender.remove(this);for(const i of this._children)(t=i._accessibleDiv)!=null&&t.parentNode&&(i._accessibleDiv.parentNode.removeChild(i._accessibleDiv),i._accessibleDiv=null),i._accessibleActive=!1;for(const i in this._pools)this._pools[i].forEach(n=>{n.parentNode&&n.parentNode.removeChild(n)}),delete this._pools[i];(e=this._div)!=null&&e.parentNode&&this._div.parentNode.removeChild(this._div),this._pools={},this._children=[]}}_updateAccessibleObjects(t){if(!t.visible||!t.accessibleChildren)return;t.accessible&&(t._accessibleActive||this._addChild(t),t._renderId=this._renderId);const e=t.children;if(e)for(let i=0;i<e.length;i++)this._updateAccessibleObjects(e[i])}init(t){const i={accessibilityOptions:{...ou.defaultOptions,...(t==null?void 0:t.accessibilityOptions)||{}}};this.debug=i.accessibilityOptions.debug,this._activateOnTab=i.accessibilityOptions.activateOnTab,this._deactivateOnMouseMove=i.accessibilityOptions.deactivateOnMouseMove,i.accessibilityOptions.enabledByDefault&&this._activate(),this._renderer.runners.postrender.remove(this)}postrender(){const t=performance.now();if(this._mobileInfo.android.device&&t<this._androidUpdateCount||(this._androidUpdateCount=t+this._androidUpdateFrequency,(!this._renderer.renderingToScreen||!this._renderer.view.canvas)&&!this._isRunningTests))return;const e=new Set;if(this._renderer.lastObjectRendered){this._updateAccessibleObjects(this._renderer.lastObjectRendered);for(const i of this._children)i._renderId===this._renderId&&e.add(this._children.indexOf(i))}for(let i=this._children.length-1;i>=0;i--){const r=this._children[i];e.has(i)||(r._accessibleDiv&&r._accessibleDiv.parentNode&&(r._accessibleDiv.parentNode.removeChild(r._accessibleDiv),this._getPool(r.accessibleType).push(r._accessibleDiv),r._accessibleDiv=null),r._accessibleActive=!1,ko(this._children,i,1))}this._renderer.renderingToScreen&&this._canvasObserver.ensureAttached();for(let i=0;i<this._children.length;i++){const r=this._children[i];if(!r._accessibleActive||!r._accessibleDiv)continue;const n=r._accessibleDiv,o=r.hitArea||r.getBounds().rectangle;if(r.hitArea){const a=r.worldTransform;n.style.left=`${a.tx+o.x*a.a}px`,n.style.top=`${a.ty+o.y*a.d}px`,n.style.width=`${o.width*a.a}px`,n.style.height=`${o.height*a.d}px`}else this._capHitArea(o),n.style.left=`${o.x}px`,n.style.top=`${o.y}px`,n.style.width=`${o.width}px`,n.style.height=`${o.height}px`}this._renderId++}_updateDebugHTML(t){t.innerHTML=`type: ${t.type}</br> title : ${t.title}</br> tabIndex: ${t.tabIndex}`}_capHitArea(t){t.x<0&&(t.width+=t.x,t.x=0),t.y<0&&(t.height+=t.y,t.y=0);const{width:e,height:i}=this._renderer;t.x+t.width>e&&(t.width=e-t.x),t.y+t.height>i&&(t.height=i-t.y)}_addChild(t){let i=this._getPool(t.accessibleType).pop();i?(i.innerHTML="",i.removeAttribute("title"),i.removeAttribute("aria-label"),i.tabIndex=0):(t.accessibleType==="button"?i=document.createElement("button"):(i=document.createElement(t.accessibleType),i.style.cssText=`
|
|
5
|
+
color: transparent;
|
|
6
|
+
pointer-events: none;
|
|
7
|
+
padding: 0;
|
|
8
|
+
margin: 0;
|
|
9
|
+
border: 0;
|
|
10
|
+
outline: 0;
|
|
11
|
+
background: transparent;
|
|
12
|
+
box-sizing: border-box;
|
|
13
|
+
user-select: none;
|
|
14
|
+
-webkit-user-select: none;
|
|
15
|
+
-moz-user-select: none;
|
|
16
|
+
-ms-user-select: none;
|
|
17
|
+
`,t.accessibleText&&(i.innerText=t.accessibleText)),i.style.width=`${fa}px`,i.style.height=`${fa}px`,i.style.backgroundColor=this.debug?"rgba(255,255,255,0.5)":"transparent",i.style.position="absolute",i.style.zIndex=pa.toString(),i.style.borderStyle="none",navigator.userAgent.toLowerCase().includes("chrome")?i.setAttribute("aria-live","off"):i.setAttribute("aria-live","polite"),navigator.userAgent.match(/rv:.*Gecko\//)?i.setAttribute("aria-relevant","additions"):i.setAttribute("aria-relevant","text"),i.addEventListener("click",this._onClick.bind(this)),i.addEventListener("focus",this._onFocus.bind(this)),i.addEventListener("focusout",this._onFocusOut.bind(this))),i.style.pointerEvents=t.accessiblePointerEvents,i.type=t.accessibleType,t.accessibleTitle&&t.accessibleTitle!==null?i.title=t.accessibleTitle:(!t.accessibleHint||t.accessibleHint===null)&&(i.title=`container ${t.tabIndex}`),t.accessibleHint&&t.accessibleHint!==null&&i.setAttribute("aria-label",t.accessibleHint),t.interactive?i.tabIndex=t.tabIndex:i.tabIndex=0,this.debug&&this._updateDebugHTML(i),t._accessibleActive=!0,t._accessibleDiv=i,i.container=t,this._children.push(t),this._div.appendChild(t._accessibleDiv)}_dispatchEvent(t,e){const{container:i}=t.target,r=this._renderer.events.rootBoundary,n=Object.assign(new Ui(r),{target:i});r.rootTarget=this._renderer.lastObjectRendered,e.forEach(o=>r.dispatchEvent(n,o))}_onClick(t){this._dispatchEvent(t,["click","pointertap","tap"])}_onFocus(t){t.target.getAttribute("aria-live")||t.target.setAttribute("aria-live","assertive"),this._dispatchEvent(t,["mouseover"])}_onFocusOut(t){t.target.getAttribute("aria-live")||t.target.setAttribute("aria-live","polite"),this._dispatchEvent(t,["mouseout"])}_onKeyDown(t){t.keyCode!==kd||!this._activateOnTab||this._activate()}_onMouseMove(t){t.movementX===0&&t.movementY===0||this._deactivate()}destroy(){var t;this._deactivate(),this._destroyTouchHook(),(t=this._canvasObserver)==null||t.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(t){t?this._activate():this._deactivate()}_getPool(t){return this._pools[t]||(this._pools[t]=[]),this._pools[t]}};Sr.extension={type:[w.WebGLSystem,w.WebGPUSystem],name:"accessibility"},Sr.defaultOptions={enabledByDefault:!1,debug:!1,activateOnTab:!0,deactivateOnMouseMove:!0};let Ld=Sr;const Fd={accessible:!1,accessibleTitle:null,accessibleHint:null,tabIndex:0,accessibleType:"button",accessibleText:null,accessiblePointerEvents:"auto",accessibleChildren:!0,_accessibleActive:!1,_accessibleDiv:null,_renderId:-1},Cr=Object.create(null),ga=Object.create(null);function Li(s,t){let e=ga[s];return e===void 0&&(Cr[t]===void 0&&(Cr[t]=1),ga[s]=e=Cr[t]++),e}let yi;function _a(){return(!yi||yi!=null&&yi.isContextLost())&&(yi=rt.get().createCanvas().getContext("webgl",{})),yi}let Es;function Nd(){if(!Es){Es="mediump";const s=_a();s&&s.getShaderPrecisionFormat&&(Es=s.getShaderPrecisionFormat(s.FRAGMENT_SHADER,s.HIGH_FLOAT).precision?"highp":"mediump")}return Es}function Hd(s,t,e){return t?s:e?(s=s.replace("out vec4 finalColor;",""),`
|
|
18
|
+
|
|
19
|
+
#ifdef GL_ES // This checks if it is WebGL1
|
|
20
|
+
#define in varying
|
|
21
|
+
#define finalColor gl_FragColor
|
|
22
|
+
#define texture texture2D
|
|
23
|
+
#endif
|
|
24
|
+
${s}
|
|
25
|
+
`):`
|
|
26
|
+
|
|
27
|
+
#ifdef GL_ES // This checks if it is WebGL1
|
|
28
|
+
#define in attribute
|
|
29
|
+
#define out varying
|
|
30
|
+
#endif
|
|
31
|
+
${s}
|
|
32
|
+
`}function Wd(s,t,e){const i=e?t.maxSupportedFragmentPrecision:t.maxSupportedVertexPrecision;if(s.substring(0,9)!=="precision"){let r=e?t.requestedFragmentPrecision:t.requestedVertexPrecision;return r==="highp"&&i!=="highp"&&(r="mediump"),`precision ${r} float;
|
|
33
|
+
${s}`}else if(i!=="highp"&&s.substring(0,15)==="precision highp")return s.replace("precision highp","precision mediump");return s}function Vd(s,t){return t?`#version 300 es
|
|
34
|
+
${s}`:s}const zd={},$d={};function jd(s,{name:t="pixi-program"},e=!0){t=t.replace(/\s+/g,"-"),t+=e?"-fragment":"-vertex";const i=e?zd:$d;return i[t]?(i[t]++,t+=`-${i[t]}`):i[t]=1,s.indexOf("#define SHADER_NAME")!==-1?s:`${`#define SHADER_NAME ${t}`}
|
|
35
|
+
${s}`}function Xd(s,t){return t?s.replace("#version 300 es",""):s}const wr={stripVersion:Xd,ensurePrecision:Wd,addProgramDefines:Hd,setProgramName:jd,insertVersion:Vd},Fi=Object.create(null),ya=class Jn{constructor(t){t={...Jn.defaultOptions,...t};const e=t.fragment.indexOf("#version 300 es")!==-1,i={stripVersion:e,ensurePrecision:{requestedFragmentPrecision:t.preferredFragmentPrecision,requestedVertexPrecision:t.preferredVertexPrecision,maxSupportedVertexPrecision:"highp",maxSupportedFragmentPrecision:Nd()},setProgramName:{name:t.name},addProgramDefines:e,insertVersion:e};let r=t.fragment,n=t.vertex;Object.keys(wr).forEach(o=>{const a=i[o];r=wr[o](r,a,!0),n=wr[o](n,a,!1)}),this.fragment=r,this.vertex=n,this.transformFeedbackVaryings=t.transformFeedbackVaryings,this._key=Li(`${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,Fi[this._cacheKey]=null}static from(t){const e=`${t.vertex}:${t.fragment}`;return Fi[e]||(Fi[e]=new Jn(t),Fi[e]._cacheKey=e),Fi[e]}};ya.defaultOptions={preferredVertexPrecision:"highp",preferredFragmentPrecision:"mediump"};let Ye=ya;const xa={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 Ni(s){return xa[s]??xa.float32}const Yd={f32:"float32","vec2<f32>":"float32x2","vec3<f32>":"float32x3","vec4<f32>":"float32x4",vec2f:"float32x2",vec3f:"float32x3",vec4f:"float32x4",i32:"sint32","vec2<i32>":"sint32x2","vec3<i32>":"sint32x3","vec4<i32>":"sint32x4",vec2i:"sint32x2",vec3i:"sint32x3",vec4i:"sint32x4",u32:"uint32","vec2<u32>":"uint32x2","vec3<u32>":"uint32x3","vec4<u32>":"uint32x4",vec2u:"uint32x2",vec3u:"uint32x3",vec4u:"uint32x4",bool:"uint32","vec2<bool>":"uint32x2","vec3<bool>":"uint32x3","vec4<bool>":"uint32x4"},ba=/@location\((\d+)\)\s+([a-zA-Z0-9_]+)\s*:\s*([a-zA-Z0-9_<>]+)(?:,|\s|\)|$)/g;function va(s,t){let e;for(;(e=ba.exec(s))!==null;){const i=Yd[e[3]]??"float32";t[e[2]]={location:parseInt(e[1],10),format:i,stride:Ni(i).stride,offset:0,instance:!1,start:0}}ba.lastIndex=0}function qd(s){return s.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"")}function Kd({source:s,entryPoint:t}){const e={},i=qd(s),r=i.indexOf(`fn ${t}(`);if(r===-1)return e;const n=i.indexOf("->",r);if(n===-1)return e;const o=i.substring(r,n);if(va(o,e),Object.keys(e).length===0){const a=o.match(/\(\s*\w+\s*:\s*(\w+)/);if(a){const l=a[1],h=new RegExp(`struct\\s+${l}\\s*\\{([^}]+)\\}`,"s"),c=i.match(h);c&&va(c[1],e)}}return e}function Ar(s){var u,m;const t=/(^|[^/])@(group|binding)\(\d+\)[^;]+;/g,e=/@group\((\d+)\)/,i=/@binding\((\d+)\)/,r=/var(<[^>]+>)? (\w+)/,n=/:\s*([\w<>]+)/,o=/struct\s+(\w+)\s*{([^}]+)}/g,a=/(\w+)\s*:\s*([\w\<\>]+)/g,l=/struct\s+(\w+)/,h=(u=s.match(t))==null?void 0:u.map(f=>({group:parseInt(f.match(e)[1],10),binding:parseInt(f.match(i)[1],10),name:f.match(r)[2],isUniform:f.match(r)[1]==="<uniform>",type:f.match(n)[1]}));if(!h)return{groups:[],structs:[]};const c=((m=s.match(o))==null?void 0:m.map(f=>{const g=f.match(l)[1],y=f.match(a).reduce((x,v)=>{const[E,T]=v.split(":");return x[E.trim()]=T.trim(),x},{});return y?{name:g,members:y}:null}).filter(({name:f})=>h.some(g=>g.type===f||g.type.includes(`<${f}>`))))??[];return{groups:h,structs:c}}var qe=(s=>(s[s.VERTEX=1]="VERTEX",s[s.FRAGMENT=2]="FRAGMENT",s[s.COMPUTE=4]="COMPUTE",s))(qe||{});function Zd({groups:s}){const t=[];for(let e=0;e<s.length;e++){const i=s[e];t[i.group]||(t[i.group]=[]),i.isUniform?t[i.group].push({binding:i.binding,visibility:qe.VERTEX|qe.FRAGMENT,buffer:{type:"uniform"}}):i.type==="sampler"?t[i.group].push({binding:i.binding,visibility:qe.FRAGMENT,sampler:{type:"filtering"}}):i.type==="texture_2d"||i.type.startsWith("texture_2d<")?t[i.group].push({binding:i.binding,visibility:qe.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d",multisampled:!1}}):i.type==="texture_2d_array"||i.type.startsWith("texture_2d_array<")?t[i.group].push({binding:i.binding,visibility:qe.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d-array",multisampled:!1}}):(i.type==="texture_cube"||i.type.startsWith("texture_cube<"))&&t[i.group].push({binding:i.binding,visibility:qe.FRAGMENT,texture:{sampleType:"float",viewDimension:"cube",multisampled:!1}})}for(let e=0;e<t.length;e++)t[e]||(t[e]=[]);return t}function Jd({groups:s}){const t=[];for(let e=0;e<s.length;e++){const i=s[e];t[i.group]||(t[i.group]={}),t[i.group][i.name]=i.binding}return t}function Qd(s,t){const e=new Set,i=new Set,r=[...s.structs,...t.structs].filter(o=>e.has(o.name)?!1:(e.add(o.name),!0)),n=[...s.groups,...t.groups].filter(o=>{const a=`${o.name}-${o.binding}`;return i.has(a)?!1:(i.add(a),!0)});return{structs:r,groups:n}}const Hi=Object.create(null);class Ke{constructor(t){var a,l;this._layoutKey=0,this._attributeLocationsKey=0;const{fragment:e,vertex:i,layout:r,gpuLayout:n,name:o}=t;if(this.name=o,this.fragment=e,this.vertex=i,e.source===i.source){const h=Ar(e.source);this.structsAndGroups=h}else{const h=Ar(i.source),c=Ar(e.source);this.structsAndGroups=Qd(h,c)}this.layout=r??Jd(this.structsAndGroups),this.gpuLayout=n??Zd(this.structsAndGroups),this.autoAssignGlobalUniforms=((a=this.layout[0])==null?void 0:a.globalUniforms)!==void 0,this.autoAssignLocalUniforms=((l=this.layout[1])==null?void 0:l.localUniforms)!==void 0,this._generateProgramKey()}_generateProgramKey(){const{vertex:t,fragment:e}=this,i=t.source+e.source+t.entryPoint+e.entryPoint;this._layoutKey=Li(i,"program")}get attributeData(){return this._attributeData??(this._attributeData=Kd(this.vertex)),this._attributeData}destroy(){this.gpuLayout=null,this.layout=null,this.structsAndGroups=null,this.fragment=null,this.vertex=null,Hi[this._cacheKey]=null}static from(t){const e=`${t.vertex.source}:${t.fragment.source}:${t.fragment.entryPoint}:${t.vertex.entryPoint}`;return Hi[e]||(Hi[e]=new Ke(t),Hi[e]._cacheKey=e),Hi[e]}}const Ea=["f32","i32","vec2<f32>","vec3<f32>","vec4<f32>","mat2x2<f32>","mat3x3<f32>","mat4x4<f32>","mat3x2<f32>","mat4x2<f32>","mat2x3<f32>","mat4x3<f32>","mat2x4<f32>","mat3x4<f32>","vec2<i32>","vec3<i32>","vec4<i32>"],tf=Ea.reduce((s,t)=>(s[t]=!0,s),{});function ef(s,t){switch(s){case"f32":return 0;case"vec2<f32>":return new Float32Array(2*t);case"vec3<f32>":return new Float32Array(3*t);case"vec4<f32>":return new Float32Array(4*t);case"mat2x2<f32>":return new Float32Array([1,0,0,1]);case"mat3x3<f32>":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4x4<f32>":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}const Ta=class au{constructor(t,e){this._touched=0,this.uid=dt("uniform"),this._resourceType="uniformGroup",this._resourceId=dt("resource"),this.isUniformGroup=!0,this._dirtyId=0,this.destroyed=!1,e={...au.defaultOptions,...e},this.uniformStructures=t;const i={};for(const r in t){const n=t[r];if(n.name=r,n.size=n.size??1,!tf[n.type]){const o=n.type.match(/^array<(\w+(?:<\w+>)?),\s*(\d+)>$/);if(o){const[,a,l]=o;throw new Error(`Uniform type ${n.type} is not supported. Use type: '${a}', size: ${l} instead.`)}throw new Error(`Uniform type ${n.type} is not supported. Supported uniform types are: ${Ea.join(", ")}`)}n.value??(n.value=ef(n.type,n.size)),i[r]=n.value}this.uniforms=i,this._dirtyId=1,this.ubo=e.ubo,this.isStatic=e.isStatic,this._signature=Li(Object.keys(i).map(r=>`${r}-${t[r].type}`).join("-"),"uniform-group")}update(){this._dirtyId++}};Ta.defaultOptions={ubo:!1,isStatic:!1};let he=Ta;class Me{constructor(t){this.resources=Object.create(null),this._dirty=!0;let e=0;for(const i in t){const r=t[i];this.setResource(r,e++)}this._updateKey()}_updateKey(){if(!this._dirty)return;this._dirty=!1;const t=[];let e=0;for(const i in this.resources)t[e++]=this.resources[i]._resourceId;this._key=t.join("|")}setResource(t,e){var r,n;const i=this.resources[e];t!==i&&((r=i==null?void 0:i.off)==null||r.call(i,"change",this.onResourceChange,this),(n=t.on)==null||n.call(t,"change",this.onResourceChange,this),this.resources[e]=t,this._dirty=!0)}getResource(t){return this.resources[t]}_touch(t,e){const i=this.resources;for(const r in i)i[r]._gcLastUsed=t,i[r]._touched=e}destroy(){var e;const t=this.resources;for(const i in t){const r=t[i];(e=r==null?void 0:r.off)==null||e.call(r,"change",this.onResourceChange,this)}this.resources=null}onResourceChange(t){this._dirty=!0,t.destroyed?this.destroy():this._updateKey()}}var ce=(s=>(s[s.WEBGL=1]="WEBGL",s[s.WEBGPU=2]="WEBGPU",s[s.CANVAS=4]="CANVAS",s[s.BOTH=3]="BOTH",s))(ce||{});class be extends Jt{constructor(t){super(),this.uid=dt("shader"),this._uniformBindMap=Object.create(null),this._ownedBindGroups=[],this._destroyed=!1;let{gpuProgram:e,glProgram:i,groups:r,resources:n,compatibleRenderers:o,groupMap:a}=t;this.gpuProgram=e,this.glProgram=i,o===void 0&&(o=0,e&&(o|=ce.WEBGPU),i&&(o|=ce.WEBGL)),this.compatibleRenderers=o;const l={};if(!n&&!r&&(n={}),n&&r)throw new Error("[Shader] Cannot have both resources and groups");if(!e&&r&&!a)throw new Error("[Shader] No group map or WebGPU shader provided - consider using resources instead.");if(!e&&r&&a)for(const h in a)for(const c in a[h]){const u=a[h][c];l[u]={group:h,binding:c,name:u}}else if(e&&r&&!a){const h=e.structsAndGroups.groups;a={},h.forEach(c=>{a[c.group]=a[c.group]||{},a[c.group][c.binding]=c.name,l[c.name]=c})}else if(n){r={},a={},e&&e.structsAndGroups.groups.forEach(u=>{a[u.group]=a[u.group]||{},a[u.group][u.binding]=u.name,l[u.name]=u});let h=0;for(const c in n)l[c]||(r[99]||(r[99]=new Me,this._ownedBindGroups.push(r[99])),l[c]={group:99,binding:h,name:c},a[99]=a[99]||{},a[99][h]=c,h++);for(const c in n){const u=c;let m=n[c];!m.source&&!m._resourceType&&(m=new he(m));const f=l[u];f&&(r[f.group]||(r[f.group]=new Me,this._ownedBindGroups.push(r[f.group])),r[f.group].setResource(m,f.binding))}}this.groups=r,this._uniformBindMap=a,this.resources=this._buildResourceAccessor(r,l)}addResource(t,e,i){var r,n;(r=this._uniformBindMap)[e]||(r[e]={}),(n=this._uniformBindMap[e])[i]||(n[i]=t),this.groups[e]||(this.groups[e]=new Me,this._ownedBindGroups.push(this.groups[e]))}_buildResourceAccessor(t,e){const i={};for(const r in e){const n=e[r];Object.defineProperty(i,n.name,{get(){return t[n.group].getResource(n.binding)},set(o){t[n.group].setResource(o,n.binding)}})}return i}destroy(t=!1){var e,i;this._destroyed||(this._destroyed=!0,this.emit("destroy",this),t&&((e=this.gpuProgram)==null||e.destroy(),(i=this.glProgram)==null||i.destroy()),this.gpuProgram=null,this.glProgram=null,this.removeAllListeners(),this._uniformBindMap=null,this._ownedBindGroups.forEach(r=>{r.destroy()}),this._ownedBindGroups=null,this.resources=null,this.groups=null)}static from(t){const{gpu:e,gl:i,...r}=t;let n,o;return e&&(n=Ke.from(e)),i&&(o=Ye.from(i)),new be({gpuProgram:n,glProgram:o,...r})}}const sf={normal:0,add:1,multiply:2,screen:3,overlay:4,erase:5,"normal-npm":6,"add-npm":7,"screen-npm":8,min:9,max:10},Rr=0,Pr=1,Ir=2,Mr=3,kr=4,Br=5,Or=class lu{constructor(){this.data=0,this.blendMode="normal",this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(this.data&1<<Rr)}set blend(t){!!(this.data&1<<Rr)!==t&&(this.data^=1<<Rr)}get offsets(){return!!(this.data&1<<Pr)}set offsets(t){!!(this.data&1<<Pr)!==t&&(this.data^=1<<Pr)}set cullMode(t){if(t==="none"){this.culling=!1;return}this.culling=!0,this.clockwiseFrontFace=t==="front"}get cullMode(){return this.culling?this.clockwiseFrontFace?"front":"back":"none"}get culling(){return!!(this.data&1<<Ir)}set culling(t){!!(this.data&1<<Ir)!==t&&(this.data^=1<<Ir)}get depthTest(){return!!(this.data&1<<Mr)}set depthTest(t){!!(this.data&1<<Mr)!==t&&(this.data^=1<<Mr)}get depthMask(){return!!(this.data&1<<Br)}set depthMask(t){!!(this.data&1<<Br)!==t&&(this.data^=1<<Br)}get clockwiseFrontFace(){return!!(this.data&1<<kr)}set clockwiseFrontFace(t){!!(this.data&1<<kr)!==t&&(this.data^=1<<kr)}get blendMode(){return this._blendMode}set blendMode(t){this.blend=t!=="none",this._blendMode=t,this._blendModeId=sf[t]||0}get polygonOffset(){return this._polygonOffset}set polygonOffset(t){this.offsets=!!t,this._polygonOffset=t}toString(){return`[pixi.js/core:State blendMode=${this.blendMode} clockwiseFrontFace=${this.clockwiseFrontFace} culling=${this.culling} depthMask=${this.depthMask} polygonOffset=${this.polygonOffset}]`}static for2d(){const t=new lu;return t.depthTest=!1,t.blend=!0,t}};Or.default2d=Or.for2d();let ve=Or;const Sa=class Qn extends be{constructor(t){t={...Qn.defaultOptions,...t},super(t),this.enabled=!0,this._state=ve.for2d(),this.blendMode=t.blendMode,this.padding=t.padding,typeof t.antialias=="boolean"?this.antialias=t.antialias?"on":"off":this.antialias=t.antialias,this.resolution=t.resolution,this.blendRequired=t.blendRequired,this.clipToViewport=t.clipToViewport,this.addResource("uTexture",0,1),t.blendRequired&&this.addResource("uBackTexture",0,3)}apply(t,e,i,r){t.applyFilter(this,e,i,r)}get blendMode(){return this._state.blendMode}set blendMode(t){this._state.blendMode=t}static from(t){const{gpu:e,gl:i,...r}=t;let n,o;return e&&(n=Ke.from(e)),i&&(o=Ye.from(i)),new Qn({gpuProgram:n,glProgram:o,...r})}};Sa.defaultOptions={blendMode:"normal",resolution:1,padding:0,antialias:"off",blendRequired:!1,clipToViewport:!0};let Dr=Sa;const Gr=[];J.handleByNamedList(w.Environment,Gr);async function rf(s){if(!s)for(let t=0;t<Gr.length;t++){const e=Gr[t];if(e.value.test()){await e.value.load();return}}}let Wi;function Ca(){if(typeof Wi=="boolean")return Wi;try{Wi=new Function("param1","param2","param3","return param1[param2] === param3;")({a:"b"},"a","b")===!0}catch{Wi=!1}return Wi}function wa(s,t,e=2){const i=t&&t.length,r=i?t[0]*e:s.length;let n=Aa(s,0,r,e,!0);const o=[];if(!n||n.next===n.prev)return o;let a,l,h;if(i&&(n=hf(s,t,n,e)),s.length>80*e){a=s[0],l=s[1];let c=a,u=l;for(let m=e;m<r;m+=e){const f=s[m],g=s[m+1];f<a&&(a=f),g<l&&(l=g),f>c&&(c=f),g>u&&(u=g)}h=Math.max(c-a,u-l),h=h!==0?32767/h:0}return Vi(n,o,e,a,l,h,0),o}function Aa(s,t,e,i,r){let n;if(r===bf(s,t,e,i)>0)for(let o=t;o<e;o+=i)n=Ma(o/i|0,s[o],s[o+1],n);else for(let o=e-i;o>=t;o-=i)n=Ma(o/i|0,s[o],s[o+1],n);return n&&xi(n,n.next)&&(ji(n),n=n.next),n}function Ze(s,t){if(!s)return s;t||(t=s);let e=s,i;do if(i=!1,!e.steiner&&(xi(e,e.next)||Et(e.prev,e,e.next)===0)){if(ji(e),e=t=e.prev,e===e.next)break;i=!0}else e=e.next;while(i||e!==t);return t}function Vi(s,t,e,i,r,n,o){if(!s)return;!o&&n&&pf(s,i,r,n);let a=s;for(;s.prev!==s.next;){const l=s.prev,h=s.next;if(n?of(s,i,r,n):nf(s)){t.push(l.i,s.i,h.i),ji(s),s=h.next,a=h.next;continue}if(s=h,s===a){o?o===1?(s=af(Ze(s),t),Vi(s,t,e,i,r,n,2)):o===2&&lf(s,t,e,i,r,n):Vi(Ze(s),t,e,i,r,n,1);break}}}function nf(s){const t=s.prev,e=s,i=s.next;if(Et(t,e,i)>=0)return!1;const r=t.x,n=e.x,o=i.x,a=t.y,l=e.y,h=i.y,c=Math.min(r,n,o),u=Math.min(a,l,h),m=Math.max(r,n,o),f=Math.max(a,l,h);let g=i.next;for(;g!==t;){if(g.x>=c&&g.x<=m&&g.y>=u&&g.y<=f&&zi(r,a,n,l,o,h,g.x,g.y)&&Et(g.prev,g,g.next)>=0)return!1;g=g.next}return!0}function of(s,t,e,i){const r=s.prev,n=s,o=s.next;if(Et(r,n,o)>=0)return!1;const a=r.x,l=n.x,h=o.x,c=r.y,u=n.y,m=o.y,f=Math.min(a,l,h),g=Math.min(c,u,m),y=Math.max(a,l,h),x=Math.max(c,u,m),v=Ur(f,g,t,e,i),E=Ur(y,x,t,e,i);let T=s.prevZ,C=s.nextZ;for(;T&&T.z>=v&&C&&C.z<=E;){if(T.x>=f&&T.x<=y&&T.y>=g&&T.y<=x&&T!==r&&T!==o&&zi(a,c,l,u,h,m,T.x,T.y)&&Et(T.prev,T,T.next)>=0||(T=T.prevZ,C.x>=f&&C.x<=y&&C.y>=g&&C.y<=x&&C!==r&&C!==o&&zi(a,c,l,u,h,m,C.x,C.y)&&Et(C.prev,C,C.next)>=0))return!1;C=C.nextZ}for(;T&&T.z>=v;){if(T.x>=f&&T.x<=y&&T.y>=g&&T.y<=x&&T!==r&&T!==o&&zi(a,c,l,u,h,m,T.x,T.y)&&Et(T.prev,T,T.next)>=0)return!1;T=T.prevZ}for(;C&&C.z<=E;){if(C.x>=f&&C.x<=y&&C.y>=g&&C.y<=x&&C!==r&&C!==o&&zi(a,c,l,u,h,m,C.x,C.y)&&Et(C.prev,C,C.next)>=0)return!1;C=C.nextZ}return!0}function af(s,t){let e=s;do{const i=e.prev,r=e.next.next;!xi(i,r)&&Pa(i,e,e.next,r)&&$i(i,r)&&$i(r,i)&&(t.push(i.i,e.i,r.i),ji(e),ji(e.next),e=s=r),e=e.next}while(e!==s);return Ze(e)}function lf(s,t,e,i,r,n){let o=s;do{let a=o.next.next;for(;a!==o.prev;){if(o.i!==a.i&&_f(o,a)){let l=Ia(o,a);o=Ze(o,o.next),l=Ze(l,l.next),Vi(o,t,e,i,r,n,0),Vi(l,t,e,i,r,n,0);return}a=a.next}o=o.next}while(o!==s)}function hf(s,t,e,i){const r=[];for(let n=0,o=t.length;n<o;n++){const a=t[n]*i,l=n<o-1?t[n+1]*i:s.length,h=Aa(s,a,l,i,!1);h===h.next&&(h.steiner=!0),r.push(gf(h))}r.sort(cf);for(let n=0;n<r.length;n++)e=uf(r[n],e);return e}function cf(s,t){let e=s.x-t.x;if(e===0&&(e=s.y-t.y,e===0)){const i=(s.next.y-s.y)/(s.next.x-s.x),r=(t.next.y-t.y)/(t.next.x-t.x);e=i-r}return e}function uf(s,t){const e=df(s,t);if(!e)return t;const i=Ia(e,s);return Ze(i,i.next),Ze(e,e.next)}function df(s,t){let e=t;const i=s.x,r=s.y;let n=-1/0,o;if(xi(s,e))return e;do{if(xi(s,e.next))return e.next;if(r<=e.y&&r>=e.next.y&&e.next.y!==e.y){const u=e.x+(r-e.y)*(e.next.x-e.x)/(e.next.y-e.y);if(u<=i&&u>n&&(n=u,o=e.x<e.next.x?e:e.next,u===i))return o}e=e.next}while(e!==t);if(!o)return null;const a=o,l=o.x,h=o.y;let c=1/0;e=o;do{if(i>=e.x&&e.x>=l&&i!==e.x&&Ra(r<h?i:n,r,l,h,r<h?n:i,r,e.x,e.y)){const u=Math.abs(r-e.y)/(i-e.x);$i(e,s)&&(u<c||u===c&&(e.x>o.x||e.x===o.x&&ff(o,e)))&&(o=e,c=u)}e=e.next}while(e!==a);return o}function ff(s,t){return Et(s.prev,s,t.prev)<0&&Et(t.next,s,s.next)<0}function pf(s,t,e,i){let r=s;do r.z===0&&(r.z=Ur(r.x,r.y,t,e,i)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next;while(r!==s);r.prevZ.nextZ=null,r.prevZ=null,mf(r)}function mf(s){let t,e=1;do{let i=s,r;s=null;let n=null;for(t=0;i;){t++;let o=i,a=0;for(let h=0;h<e&&(a++,o=o.nextZ,!!o);h++);let l=e;for(;a>0||l>0&&o;)a!==0&&(l===0||!o||i.z<=o.z)?(r=i,i=i.nextZ,a--):(r=o,o=o.nextZ,l--),n?n.nextZ=r:s=r,r.prevZ=n,n=r;i=o}n.nextZ=null,e*=2}while(t>1);return s}function Ur(s,t,e,i,r){return s=(s-e)*r|0,t=(t-i)*r|0,s=(s|s<<8)&16711935,s=(s|s<<4)&252645135,s=(s|s<<2)&858993459,s=(s|s<<1)&1431655765,t=(t|t<<8)&16711935,t=(t|t<<4)&252645135,t=(t|t<<2)&858993459,t=(t|t<<1)&1431655765,s|t<<1}function gf(s){let t=s,e=s;do(t.x<e.x||t.x===e.x&&t.y<e.y)&&(e=t),t=t.next;while(t!==s);return e}function Ra(s,t,e,i,r,n,o,a){return(r-o)*(t-a)>=(s-o)*(n-a)&&(s-o)*(i-a)>=(e-o)*(t-a)&&(e-o)*(n-a)>=(r-o)*(i-a)}function zi(s,t,e,i,r,n,o,a){return!(s===o&&t===a)&&Ra(s,t,e,i,r,n,o,a)}function _f(s,t){return s.next.i!==t.i&&s.prev.i!==t.i&&!yf(s,t)&&($i(s,t)&&$i(t,s)&&xf(s,t)&&(Et(s.prev,s,t.prev)||Et(s,t.prev,t))||xi(s,t)&&Et(s.prev,s,s.next)>0&&Et(t.prev,t,t.next)>0)}function Et(s,t,e){return(t.y-s.y)*(e.x-t.x)-(t.x-s.x)*(e.y-t.y)}function xi(s,t){return s.x===t.x&&s.y===t.y}function Pa(s,t,e,i){const r=Ss(Et(s,t,e)),n=Ss(Et(s,t,i)),o=Ss(Et(e,i,s)),a=Ss(Et(e,i,t));return!!(r!==n&&o!==a||r===0&&Ts(s,e,t)||n===0&&Ts(s,i,t)||o===0&&Ts(e,s,i)||a===0&&Ts(e,t,i))}function Ts(s,t,e){return t.x<=Math.max(s.x,e.x)&&t.x>=Math.min(s.x,e.x)&&t.y<=Math.max(s.y,e.y)&&t.y>=Math.min(s.y,e.y)}function Ss(s){return s>0?1:s<0?-1:0}function yf(s,t){let e=s;do{if(e.i!==s.i&&e.next.i!==s.i&&e.i!==t.i&&e.next.i!==t.i&&Pa(e,e.next,s,t))return!0;e=e.next}while(e!==s);return!1}function $i(s,t){return Et(s.prev,s,s.next)<0?Et(s,t,s.next)>=0&&Et(s,s.prev,t)>=0:Et(s,t,s.prev)<0||Et(s,s.next,t)<0}function xf(s,t){let e=s,i=!1;const r=(s.x+t.x)/2,n=(s.y+t.y)/2;do e.y>n!=e.next.y>n&&e.next.y!==e.y&&r<(e.next.x-e.x)*(n-e.y)/(e.next.y-e.y)+e.x&&(i=!i),e=e.next;while(e!==s);return i}function Ia(s,t){const e=Lr(s.i,s.x,s.y),i=Lr(t.i,t.x,t.y),r=s.next,n=t.prev;return s.next=t,t.prev=s,e.next=r,r.prev=e,i.next=e,e.prev=i,n.next=i,i.prev=n,i}function Ma(s,t,e,i){const r=Lr(s,t,e);return i?(r.next=i.next,r.prev=i,i.next.prev=r,i.next=r):(r.prev=r,r.next=r),r}function ji(s){s.next.prev=s.prev,s.prev.next=s.next,s.prevZ&&(s.prevZ.nextZ=s.nextZ),s.nextZ&&(s.nextZ.prevZ=s.prevZ)}function Lr(s,t,e){return{i:s,x:t,y:e,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function bf(s,t,e,i){let r=0;for(let n=t,o=e-i;n<e;n+=i)r+=(s[o]-s[n])*(s[n+1]+s[o+1]),o=n;return r}const vf=wa.default||wa;var Yt=(s=>(s[s.NONE=0]="NONE",s[s.COLOR=16384]="COLOR",s[s.STENCIL=1024]="STENCIL",s[s.DEPTH=256]="DEPTH",s[s.COLOR_DEPTH=16640]="COLOR_DEPTH",s[s.COLOR_STENCIL=17408]="COLOR_STENCIL",s[s.DEPTH_STENCIL=1280]="DEPTH_STENCIL",s[s.ALL=17664]="ALL",s))(Yt||{});class ka{constructor(t){this.items=[],this._name=t}emit(t,e,i,r,n,o,a,l){const{name:h,items:c}=this;for(let u=0,m=c.length;u<m;u++)c[u][h](t,e,i,r,n,o,a,l);return this}add(t){return t[this._name]&&(this.remove(t),this.items.push(t)),this}remove(t){const e=this.items.indexOf(t);return e!==-1&&this.items.splice(e,1),this}contains(t){return this.items.indexOf(t)!==-1}removeAll(){return this.items.length=0,this}destroy(){this.removeAll(),this.items=null,this._name=null}get empty(){return this.items.length===0}get name(){return this._name}}const Ef=["init","destroy","contextChange","resolutionChange","resetState","renderEnd","renderStart","render","update","postrender","prerender"],Ba=class hu extends Jt{constructor(t){super(),this.tick=0,this.uid=dt("renderer"),this.runners=Object.create(null),this.renderPipes=Object.create(null),this._initOptions={},this._systemsHash=Object.create(null),this.type=t.type,this.name=t.name,this.config=t;const e=[...Ef,...this.config.runners??[]];this._addRunners(...e),this._unsafeEvalCheck()}async init(t={}){const e=t.skipExtensionImports===!0?!0:t.manageImports===!1;await rf(e),this._addSystems(this.config.systems),this._addPipes(this.config.renderPipes,this.config.renderPipeAdaptors);for(const i in this._systemsHash)t={...this._systemsHash[i].constructor.defaultOptions,...t};t={...hu.defaultOptions,...t},this._roundPixels=t.roundPixels?1:0;for(let i=0;i<this.runners.init.items.length;i++)await this.runners.init.items[i].init(t);this._initOptions=t}render(t,e){this.tick++;let i=t;if(i instanceof kt&&(i={container:i},e&&(K(vt,"passing a second argument is deprecated, please use render options instead"),i.target=e.renderTexture)),i.target||(i.target=this.view.renderTarget),i.target===this.view.renderTarget&&(this._lastObjectRendered=i.container,i.clearColor??(i.clearColor=this.background.colorRgba),i.clear??(i.clear=this.background.clearBeforeRender)),i.clearColor){const r=Array.isArray(i.clearColor)&&i.clearColor.length===4;i.clearColor=r?i.clearColor:ct.shared.setValue(i.clearColor).toArray()}i.transform||(i.container.updateLocalTransform(),i.transform=i.container.localTransform),i.container.visible&&(i.container.enableRenderGroup(),this.runners.prerender.emit(i),this.runners.renderStart.emit(i),this.runners.render.emit(i),this.runners.renderEnd.emit(i),this.runners.postrender.emit(i))}resize(t,e,i){const r=this.view.resolution;this.view.resize(t,e,i),this.emit("resize",this.view.screen.width,this.view.screen.height,this.view.resolution),i!==void 0&&i!==r&&this.runners.resolutionChange.emit(i)}clear(t={}){const e=this;t.target||(t.target=e.renderTarget.renderTarget),t.clearColor||(t.clearColor=this.background.colorRgba),t.clear??(t.clear=Yt.ALL);const{clear:i,clearColor:r,target:n,mipLevel:o,layer:a}=t;ct.shared.setValue(r??this.background.colorRgba),e.renderTarget.clear(n,i,ct.shared.toArray(),o??0,a??0)}get resolution(){return this.view.resolution}set resolution(t){this.view.resolution=t,this.runners.resolutionChange.emit(t)}get width(){return this.view.texture.frame.width}get height(){return this.view.texture.frame.height}get canvas(){return this.view.canvas}get lastObjectRendered(){return this._lastObjectRendered}get renderingToScreen(){return this.renderTarget.renderingToScreen}get screen(){return this.view.screen}_addRunners(...t){t.forEach(e=>{this.runners[e]=new ka(e)})}_addSystems(t){let e;for(e in t){const i=t[e];this._addSystem(i.value,i.name)}}_addSystem(t,e){const i=new t(this);if(this[e])throw new Error(`Whoops! The name "${e}" is already in use`);this[e]=i,this._systemsHash[e]=i;for(const r in this.runners)this.runners[r].add(i);return this}_addPipes(t,e){const i=e.reduce((r,n)=>(r[n.name]=n.value,r),{});t.forEach(r=>{const n=r.value,o=r.name,a=i[o];this.renderPipes[o]=new n(this,a?new a:null),this.runners.destroy.add(this.renderPipes[o])})}destroy(t=!1){this.runners.destroy.items.reverse(),this.runners.destroy.emit(t),(t===!0||typeof t=="object"&&t.releaseGlobalResources)&&ui.release(),Object.values(this.runners).forEach(e=>{e.destroy()}),this._systemsHash=null,this.renderPipes=null,this.removeAllListeners()}generateTexture(t){return this.textureGenerator.generateTexture(t)}get roundPixels(){return!!this._roundPixels}_unsafeEvalCheck(){if(!Ca())throw new Error("Current environment does not allow unsafe-eval, please use pixi.js/unsafe-eval module to enable support.")}resetState(){this.runners.resetState.emit()}};Ba.defaultOptions={resolution:1,failIfMajorPerformanceCaveat:!1,roundPixels:!1};let Xi=Ba,Cs;function Tf(s){return Cs!==void 0||(Cs=(()=>{var e;const t={stencil:!0,failIfMajorPerformanceCaveat:s??Xi.defaultOptions.failIfMajorPerformanceCaveat};try{if(!rt.get().getWebGLRenderingContext())return!1;let r=rt.get().createCanvas().getContext("webgl",t);const n=!!((e=r==null?void 0:r.getContextAttributes())!=null&&e.stencil);if(r){const o=r.getExtension("WEBGL_lose_context");o&&o.loseContext()}return r=null,n}catch{return!1}})()),Cs}let ws;async function Sf(s={}){return ws!==void 0||(ws=await(async()=>{const t=rt.get().getNavigator().gpu;if(!t)return!1;try{return await(await t.requestAdapter(s)).requestDevice(),!0}catch{return!1}})()),ws}const Oa=["webgl","webgpu","canvas"];async function Cf(s){let t=[];s.preference?(t.push(s.preference),Oa.forEach(n=>{n!==s.preference&&t.push(n)})):t=Oa.slice();let e,i={};for(let n=0;n<t.length;n++){const o=t[n];if(o==="webgpu"&&await Sf()){const{WebGPURenderer:a}=await Promise.resolve().then(()=>gy);e=a,i={...s,...s.webgpu};break}else if(o==="webgl"&&Tf(s.failIfMajorPerformanceCaveat??Xi.defaultOptions.failIfMajorPerformanceCaveat)){const{WebGLRenderer:a}=await Promise.resolve().then(()=>Y_);e=a,i={...s,...s.webgl};break}else if(o==="canvas"){const{CanvasRenderer:a}=await Promise.resolve().then(()=>Xg);e=a,i={...s,...s.canvasOptions};break}}if(delete i.webgpu,delete i.webgl,delete i.canvasOptions,!e)throw new Error("No available renderer for the current environment");const r=new e;return await r.init(i),r}const As="8.17.1";class Da{static init(){var t;(t=globalThis.__PIXI_APP_INIT__)==null||t.call(globalThis,this,As)}static destroy(){}}Da.extension=w.Application;class Ga{constructor(t){this._renderer=t}init(){var t;(t=globalThis.__PIXI_RENDERER_INIT__)==null||t.call(globalThis,this._renderer,As)}destroy(){this._renderer=null}}Ga.extension={type:[w.WebGLSystem,w.WebGPUSystem],name:"initHook",priority:-10};class Ua{static init(t){Object.defineProperty(this,"resizeTo",{configurable:!0,set(e){globalThis.removeEventListener("resize",this.queueResize),this._resizeTo=e,e&&(globalThis.addEventListener("resize",this.queueResize),this.resize())},get(){return this._resizeTo}}),this.queueResize=()=>{this._resizeTo&&(this._cancelResize(),this._resizeId=requestAnimationFrame(()=>this.resize()))},this._cancelResize=()=>{this._resizeId&&(cancelAnimationFrame(this._resizeId),this._resizeId=null)},this.resize=()=>{if(!this._resizeTo)return;this._cancelResize();let e,i;if(this._resizeTo===globalThis.window)e=globalThis.innerWidth,i=globalThis.innerHeight;else{const{clientWidth:r,clientHeight:n}=this._resizeTo;e=r,i=n}this.renderer.resize(e,i),this.render()},this._resizeId=null,this._resizeTo=null,this.resizeTo=t.resizeTo||null}static destroy(){globalThis.removeEventListener("resize",this.queueResize),this._cancelResize(),this._cancelResize=null,this.queueResize=null,this.resizeTo=null,this.resize=null}}Ua.extension=w.Application;class La{static init(t){t=Object.assign({autoStart:!0,sharedTicker:!1},t),Object.defineProperty(this,"ticker",{configurable:!0,set(e){this._ticker&&this._ticker.remove(this.render,this),this._ticker=e,e&&e.add(this.render,this,pi.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=t.sharedTicker?te.shared:new te,t.autoStart&&this.start()}static destroy(){if(this._ticker){const t=this._ticker;this.ticker=null,t.destroy()}}}La.extension=w.Application,J.add(Ua),J.add(La);const Fa=class to{constructor(...t){this.stage=new kt,t[0]!==void 0&&K(vt,"Application constructor options are deprecated, please use Application.init() instead.")}async init(t){t={...t},this.stage||(this.stage=new kt),this.renderer=await Cf(t),to._plugins.forEach(e=>{e.init.call(this,t)})}render(){this.renderer.render({container:this.stage})}get canvas(){return this.renderer.canvas}get view(){return K(vt,"Application.view is deprecated, please use Application.canvas instead."),this.renderer.canvas}get screen(){return this.renderer.screen}destroy(t=!1,e=!1){const i=to._plugins.slice(0);i.reverse(),i.forEach(r=>{r.destroy.call(this)}),this.stage.destroy(e),this.stage=null,this.renderer.destroy(t),this.renderer=null}};Fa._plugins=[];let Na=Fa;J.handleByList(w.Application,Na._plugins),J.add(Da);var Fr,Ha;function wf(){if(Ha)return Fr;Ha=1,Fr=e;var s={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},t=/([astvzqmhlc])([^astvzqmhlc]*)/ig;function e(n){var o=[];return n.replace(t,function(a,l,h){var c=l.toLowerCase();for(h=r(h),c=="m"&&h.length>2&&(o.push([l].concat(h.splice(0,2))),c="l",l=l=="m"?"l":"L");;){if(h.length==s[c])return h.unshift(l),o.push(h);if(h.length<s[c])throw new Error("malformed path data");o.push([l].concat(h.splice(0,s[c])))}}),o}var i=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig;function r(n){var o=n.match(i);return o?o.map(Number):[]}return Fr}var Af=wf();const Rf=oo(Af);function Pf(s,t){const e=Rf(s),i=[];let r=null,n=0,o=0;for(let a=0;a<e.length;a++){const l=e[a],h=l[0],c=l;switch(h){case"M":n=c[1],o=c[2],t.moveTo(n,o);break;case"m":n+=c[1],o+=c[2],t.moveTo(n,o);break;case"H":n=c[1],t.lineTo(n,o);break;case"h":n+=c[1],t.lineTo(n,o);break;case"V":o=c[1],t.lineTo(n,o);break;case"v":o+=c[1],t.lineTo(n,o);break;case"L":n=c[1],o=c[2],t.lineTo(n,o);break;case"l":n+=c[1],o+=c[2],t.lineTo(n,o);break;case"C":n=c[5],o=c[6],t.bezierCurveTo(c[1],c[2],c[3],c[4],n,o);break;case"c":t.bezierCurveTo(n+c[1],o+c[2],n+c[3],o+c[4],n+c[5],o+c[6]),n+=c[5],o+=c[6];break;case"S":n=c[3],o=c[4],t.bezierCurveToShort(c[1],c[2],n,o);break;case"s":t.bezierCurveToShort(n+c[1],o+c[2],n+c[3],o+c[4]),n+=c[3],o+=c[4];break;case"Q":n=c[3],o=c[4],t.quadraticCurveTo(c[1],c[2],n,o);break;case"q":t.quadraticCurveTo(n+c[1],o+c[2],n+c[3],o+c[4]),n+=c[3],o+=c[4];break;case"T":n=c[1],o=c[2],t.quadraticCurveToShort(n,o);break;case"t":n+=c[1],o+=c[2],t.quadraticCurveToShort(n,o);break;case"A":n=c[6],o=c[7],t.arcToSvg(c[1],c[2],c[3],c[4],c[5],n,o);break;case"a":n+=c[6],o+=c[7],t.arcToSvg(c[1],c[2],c[3],c[4],c[5],n,o);break;case"Z":case"z":t.closePath(),i.length>0&&(r=i.pop(),r?(n=r.startX,o=r.startY):(n=0,o=0)),r=null;break;default:tt(`Unknown SVG path command: ${h}`)}h!=="Z"&&h!=="z"&&r===null&&(r={startX:n,startY:o},i.push(r))}return t}class Nr{constructor(t=0,e=0,i=0){this.type="circle",this.x=t,this.y=e,this.radius=i}clone(){return new Nr(this.x,this.y,this.radius)}contains(t,e){if(this.radius<=0)return!1;const i=this.radius*this.radius;let r=this.x-t,n=this.y-e;return r*=r,n*=n,r+n<=i}strokeContains(t,e,i,r=.5){if(this.radius===0)return!1;const n=this.x-t,o=this.y-e,a=this.radius,l=(1-r)*i,h=Math.sqrt(n*n+o*o);return h<=a+l&&h>a-(i-l)}getBounds(t){return t||(t=new ut),t.x=this.x-this.radius,t.y=this.y-this.radius,t.width=this.radius*2,t.height=this.radius*2,t}copyFrom(t){return this.x=t.x,this.y=t.y,this.radius=t.radius,this}copyTo(t){return t.copyFrom(this),t}toString(){return`[pixi.js/math:Circle x=${this.x} y=${this.y} radius=${this.radius}]`}}class Hr{constructor(t=0,e=0,i=0,r=0){this.type="ellipse",this.x=t,this.y=e,this.halfWidth=i,this.halfHeight=r}clone(){return new Hr(this.x,this.y,this.halfWidth,this.halfHeight)}contains(t,e){if(this.halfWidth<=0||this.halfHeight<=0)return!1;let i=(t-this.x)/this.halfWidth,r=(e-this.y)/this.halfHeight;return i*=i,r*=r,i+r<=1}strokeContains(t,e,i,r=.5){const{halfWidth:n,halfHeight:o}=this;if(n<=0||o<=0)return!1;const a=i*(1-r),l=i-a,h=n-l,c=o-l,u=n+a,m=o+a,f=t-this.x,g=e-this.y,y=f*f/(h*h)+g*g/(c*c),x=f*f/(u*u)+g*g/(m*m);return y>1&&x<=1}getBounds(t){return t||(t=new ut),t.x=this.x-this.halfWidth,t.y=this.y-this.halfHeight,t.width=this.halfWidth*2,t.height=this.halfHeight*2,t}copyFrom(t){return this.x=t.x,this.y=t.y,this.halfWidth=t.halfWidth,this.halfHeight=t.halfHeight,this}copyTo(t){return t.copyFrom(this),t}toString(){return`[pixi.js/math:Ellipse x=${this.x} y=${this.y} halfWidth=${this.halfWidth} halfHeight=${this.halfHeight}]`}}function If(s,t,e,i,r,n){const o=s-e,a=t-i,l=r-e,h=n-i,c=o*l+a*h,u=l*l+h*h;let m=-1;u!==0&&(m=c/u);let f,g;m<0?(f=e,g=i):m>1?(f=r,g=n):(f=e+m*l,g=i+m*h);const y=s-f,x=t-g;return y*y+x*x}let Mf,kf;class Yi{constructor(...t){this.type="polygon";let e=Array.isArray(t[0])?t[0]:t;if(typeof e[0]!="number"){const i=[];for(let r=0,n=e.length;r<n;r++)i.push(e[r].x,e[r].y);e=i}this.points=e,this.closePath=!0}isClockwise(){let t=0;const e=this.points,i=e.length;for(let r=0;r<i;r+=2){const n=e[r],o=e[r+1],a=e[(r+2)%i],l=e[(r+3)%i];t+=(a-n)*(l+o)}return t<0}containsPolygon(t){const e=this.getBounds(Mf),i=t.getBounds(kf);if(!e.containsRect(i))return!1;const r=t.points;for(let n=0;n<r.length;n+=2){const o=r[n],a=r[n+1];if(!this.contains(o,a))return!1}return!0}clone(){const t=this.points.slice(),e=new Yi(t);return e.closePath=this.closePath,e}contains(t,e){let i=!1;const r=this.points.length/2;for(let n=0,o=r-1;n<r;o=n++){const a=this.points[n*2],l=this.points[n*2+1],h=this.points[o*2],c=this.points[o*2+1];l>e!=c>e&&t<(h-a)*((e-l)/(c-l))+a&&(i=!i)}return i}strokeContains(t,e,i,r=.5){const n=i*i,o=n*(1-r),a=n-o,{points:l}=this,h=l.length-(this.closePath?0:2);for(let c=0;c<h;c+=2){const u=l[c],m=l[c+1],f=l[(c+2)%l.length],g=l[(c+3)%l.length],y=If(t,e,u,m,f,g),x=Math.sign((f-u)*(e-m)-(g-m)*(t-u));if(y<=(x<0?a:o))return!0}return!1}getBounds(t){t||(t=new ut);const e=this.points;let i=1/0,r=-1/0,n=1/0,o=-1/0;for(let a=0,l=e.length;a<l;a+=2){const h=e[a],c=e[a+1];i=h<i?h:i,r=h>r?h:r,n=c<n?c:n,o=c>o?c:o}return t.x=i,t.width=r-i,t.y=n,t.height=o-n,t}copyFrom(t){return this.points=t.points.slice(),this.closePath=t.closePath,this}copyTo(t){return t.copyFrom(this),t}toString(){return`[pixi.js/math:PolygoncloseStroke=${this.closePath}points=${this.points.reduce((t,e)=>`${t}, ${e}`,"")}]`}get lastX(){return this.points[this.points.length-2]}get lastY(){return this.points[this.points.length-1]}get x(){return K("8.11.0","Polygon.lastX is deprecated, please use Polygon.lastX instead."),this.points[this.points.length-2]}get y(){return K("8.11.0","Polygon.y is deprecated, please use Polygon.lastY instead."),this.points[this.points.length-1]}get startX(){return this.points[0]}get startY(){return this.points[1]}}const Rs=(s,t,e,i,r,n,o)=>{const a=s-e,l=t-i,h=Math.sqrt(a*a+l*l);return h>=r-n&&h<=r+o};class Wr{constructor(t=0,e=0,i=0,r=0,n=20){this.type="roundedRectangle",this.x=t,this.y=e,this.width=i,this.height=r,this.radius=n}getBounds(t){return t||(t=new ut),t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t}clone(){return new Wr(this.x,this.y,this.width,this.height,this.radius)}copyFrom(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this}copyTo(t){return t.copyFrom(this),t}contains(t,e){if(this.width<=0||this.height<=0)return!1;if(t>=this.x&&t<=this.x+this.width&&e>=this.y&&e<=this.y+this.height){const i=Math.max(0,Math.min(this.radius,Math.min(this.width,this.height)/2));if(e>=this.y+i&&e<=this.y+this.height-i||t>=this.x+i&&t<=this.x+this.width-i)return!0;let r=t-(this.x+i),n=e-(this.y+i);const o=i*i;if(r*r+n*n<=o||(r=t-(this.x+this.width-i),r*r+n*n<=o)||(n=e-(this.y+this.height-i),r*r+n*n<=o)||(r=t-(this.x+i),r*r+n*n<=o))return!0}return!1}strokeContains(t,e,i,r=.5){const{x:n,y:o,width:a,height:l,radius:h}=this,c=i*(1-r),u=i-c,m=n+h,f=o+h,g=a-h*2,y=l-h*2,x=n+a,v=o+l;return(t>=n-c&&t<=n+u||t>=x-u&&t<=x+c)&&e>=f&&e<=f+y||(e>=o-c&&e<=o+u||e>=v-u&&e<=v+c)&&t>=m&&t<=m+g?!0:t<m&&e<f&&Rs(t,e,m,f,h,u,c)||t>x-h&&e<f&&Rs(t,e,x-h,f,h,u,c)||t>x-h&&e>v-h&&Rs(t,e,x-h,v-h,h,u,c)||t<m&&e>v-h&&Rs(t,e,m,v-h,h,u,c)}toString(){return`[pixi.js/math:RoundedRectangle x=${this.x} y=${this.y}width=${this.width} height=${this.height} radius=${this.radius}]`}}const Wa={};function Vr(s,t,e){let i=2166136261;for(let r=0;r<t;r++)i^=s[r].uid,i=Math.imul(i,16777619),i>>>=0;return Wa[i]||Bf(s,t,i,e)}function Bf(s,t,e,i){const r={};let n=0;for(let a=0;a<i;a++){const l=a<t?s[a]:z.EMPTY.source;r[n++]=l.source,r[n++]=l.style}const o=new Me(r);return Wa[e]=o,o}class Va{constructor(t){typeof t=="number"?this.rawBinaryData=new ArrayBuffer(t):t instanceof Uint8Array?this.rawBinaryData=t.buffer:this.rawBinaryData=t,this.uint32View=new Uint32Array(this.rawBinaryData),this.float32View=new Float32Array(this.rawBinaryData),this.size=this.rawBinaryData.byteLength}get int8View(){return this._int8View||(this._int8View=new Int8Array(this.rawBinaryData)),this._int8View}get uint8View(){return this._uint8View||(this._uint8View=new Uint8Array(this.rawBinaryData)),this._uint8View}get int16View(){return this._int16View||(this._int16View=new Int16Array(this.rawBinaryData)),this._int16View}get int32View(){return this._int32View||(this._int32View=new Int32Array(this.rawBinaryData)),this._int32View}get float64View(){return this._float64Array||(this._float64Array=new Float64Array(this.rawBinaryData)),this._float64Array}get bigUint64View(){return this._bigUint64Array||(this._bigUint64Array=new BigUint64Array(this.rawBinaryData)),this._bigUint64Array}view(t){return this[`${t}View`]}destroy(){this.rawBinaryData=null,this.uint32View=null,this.float32View=null,this.uint16View=null,this._int8View=null,this._uint8View=null,this._int16View=null,this._int32View=null,this._float64Array=null,this._bigUint64Array=null}static sizeOf(t){switch(t){case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;default:throw new Error(`${t} isn't a valid view type`)}}}function zr(s,t,e,i){if(e??(e=0),i??(i=Math.min(s.byteLength-e,t.byteLength)),!(e&7)&&!(i&7)){const r=i/8;new Float64Array(t,0,r).set(new Float64Array(s,e,r))}else if(!(e&3)&&!(i&3)){const r=i/4;new Float32Array(t,0,r).set(new Float32Array(s,e,r))}else new Uint8Array(t).set(new Uint8Array(s,e,i))}const Of={normal:"normal-npm",add:"add-npm",screen:"screen-npm"};var wt=(s=>(s[s.DISABLED=0]="DISABLED",s[s.RENDERING_MASK_ADD=1]="RENDERING_MASK_ADD",s[s.MASK_ACTIVE=2]="MASK_ACTIVE",s[s.INVERSE_MASK_ACTIVE=3]="INVERSE_MASK_ACTIVE",s[s.RENDERING_MASK_REMOVE=4]="RENDERING_MASK_REMOVE",s[s.NONE=5]="NONE",s))(wt||{});function za(s,t){return t.alphaMode==="no-premultiply-alpha"&&Of[s]||s}const Df=["precision mediump float;","void main(void){","float test = 0.1;","%forloop%","gl_FragColor = vec4(0.0);","}"].join(`
|
|
36
|
+
`);function Gf(s){let t="";for(let e=0;e<s;++e)e>0&&(t+=`
|
|
37
|
+
else `),e<s-1&&(t+=`if(test == ${e}.0){}`);return t}function $a(s,t){if(s===0)throw new Error("Invalid value of `0` passed to `checkMaxIfStatementsInShader`");const e=t.createShader(t.FRAGMENT_SHADER);try{for(;;){const i=Df.replace(/%forloop%/gi,Gf(s));if(t.shaderSource(e,i),t.compileShader(e),!t.getShaderParameter(e,t.COMPILE_STATUS))s=s/2|0;else break}}finally{t.deleteShader(e)}return s}let bi=null;function Uf(){var t;if(bi)return bi;const s=_a();return bi=s.getParameter(s.MAX_TEXTURE_IMAGE_UNITS),bi=$a(bi,s),(t=s.getExtension("WEBGL_lose_context"))==null||t.loseContext(),bi}class Lf{constructor(){this.ids=Object.create(null),this.textures=[],this.count=0}clear(){for(let t=0;t<this.count;t++){const e=this.textures[t];this.textures[t]=null,this.ids[e.uid]=null}this.count=0}}class Ff{constructor(){this.renderPipeId="batch",this.action="startBatch",this.start=0,this.size=0,this.textures=new Lf,this.blendMode="normal",this.topology="triangle-strip",this.canBundle=!0}destroy(){this.textures=null,this.gpuBindGroup=null,this.bindGroup=null,this.batcher=null,this.elements=null}}const qi=[];let Ps=0;ui.register({clear:()=>{if(qi.length>0)for(const s of qi)s&&s.destroy();qi.length=0,Ps=0}});function ja(){return Ps>0?qi[--Ps]:new Ff}function Xa(s){s.elements=null,qi[Ps++]=s}let Ki=0;const Ya=class cu{constructor(t){this.uid=dt("batcher"),this.dirty=!0,this.batchIndex=0,this.batches=[],this._elements=[],t={...cu.defaultOptions,...t},t.maxTextures||(K("v8.8.0","maxTextures is a required option for Batcher now, please pass it in the options"),t.maxTextures=Uf());const{maxTextures:e,attributesInitialSize:i,indicesInitialSize:r}=t;this.attributeBuffer=new Va(i*4),this.indexBuffer=new Uint16Array(r),this.maxTextures=e}begin(){this.elementSize=0,this.elementStart=0,this.indexSize=0,this.attributeSize=0;for(let t=0;t<this.batchIndex;t++)Xa(this.batches[t]);this.batchIndex=0,this._batchIndexStart=0,this._batchIndexSize=0,this.dirty=!0}add(t){this._elements[this.elementSize++]=t,t._indexStart=this.indexSize,t._attributeStart=this.attributeSize,t._batcher=this,this.indexSize+=t.indexSize,this.attributeSize+=t.attributeSize*this.vertexSize}checkAndUpdateTexture(t,e){const i=t._batch.textures.ids[e._source.uid];return!i&&i!==0?!1:(t._textureId=i,t.texture=e,!0)}updateElement(t){this.dirty=!0;const e=this.attributeBuffer;t.packAsQuad?this.packQuadAttributes(t,e.float32View,e.uint32View,t._attributeStart,t._textureId):this.packAttributes(t,e.float32View,e.uint32View,t._attributeStart,t._textureId)}break(t){const e=this._elements;if(!e[this.elementStart])return;let i=ja(),r=i.textures;r.clear();const n=e[this.elementStart];let o=za(n.blendMode,n.texture._source),a=n.topology;this.attributeSize*4>this.attributeBuffer.size&&this._resizeAttributeBuffer(this.attributeSize*4),this.indexSize>this.indexBuffer.length&&this._resizeIndexBuffer(this.indexSize);const l=this.attributeBuffer.float32View,h=this.attributeBuffer.uint32View,c=this.indexBuffer;let u=this._batchIndexSize,m=this._batchIndexStart,f="startBatch",g=[];const y=this.maxTextures;for(let x=this.elementStart;x<this.elementSize;++x){const v=e[x];e[x]=null;const T=v.texture._source,C=za(v.blendMode,T),R=o!==C||a!==v.topology;if(T._batchTick===Ki&&!R){v._textureId=T._textureBindLocation,u+=v.indexSize,v.packAsQuad?(this.packQuadAttributes(v,l,h,v._attributeStart,v._textureId),this.packQuadIndex(c,v._indexStart,v._attributeStart/this.vertexSize)):(this.packAttributes(v,l,h,v._attributeStart,v._textureId),this.packIndex(v,c,v._indexStart,v._attributeStart/this.vertexSize)),v._batch=i,g.push(v);continue}T._batchTick=Ki,(r.count>=y||R)&&(this._finishBatch(i,m,u-m,r,o,a,t,f,g),f="renderBatch",m=u,o=C,a=v.topology,i=ja(),r=i.textures,r.clear(),g=[],++Ki),v._textureId=T._textureBindLocation=r.count,r.ids[T.uid]=r.count,r.textures[r.count++]=T,v._batch=i,g.push(v),u+=v.indexSize,v.packAsQuad?(this.packQuadAttributes(v,l,h,v._attributeStart,v._textureId),this.packQuadIndex(c,v._indexStart,v._attributeStart/this.vertexSize)):(this.packAttributes(v,l,h,v._attributeStart,v._textureId),this.packIndex(v,c,v._indexStart,v._attributeStart/this.vertexSize))}r.count>0&&(this._finishBatch(i,m,u-m,r,o,a,t,f,g),m=u,++Ki),this.elementStart=this.elementSize,this._batchIndexStart=m,this._batchIndexSize=u}_finishBatch(t,e,i,r,n,o,a,l,h){t.gpuBindGroup=null,t.bindGroup=null,t.action=l,t.batcher=this,t.textures=r,t.blendMode=n,t.topology=o,t.start=e,t.size=i,t.elements=h,++Ki,this.batches[this.batchIndex++]=t,a.add(t)}finish(t){this.break(t)}ensureAttributeBuffer(t){t*4<=this.attributeBuffer.size||this._resizeAttributeBuffer(t*4)}ensureIndexBuffer(t){t<=this.indexBuffer.length||this._resizeIndexBuffer(t)}_resizeAttributeBuffer(t){const e=Math.max(t,this.attributeBuffer.size*2),i=new Va(e);zr(this.attributeBuffer.rawBinaryData,i.rawBinaryData),this.attributeBuffer=i}_resizeIndexBuffer(t){const e=this.indexBuffer;let i=Math.max(t,e.length*1.5);i+=i%2;const r=i>65535?new Uint32Array(i):new Uint16Array(i);if(r.BYTES_PER_ELEMENT!==e.BYTES_PER_ELEMENT)for(let n=0;n<e.length;n++)r[n]=e[n];else zr(e.buffer,r.buffer);this.indexBuffer=r}packQuadIndex(t,e,i){t[e]=i+0,t[e+1]=i+1,t[e+2]=i+2,t[e+3]=i+0,t[e+4]=i+2,t[e+5]=i+3}packIndex(t,e,i,r){const n=t.indices,o=t.indexSize,a=t.indexOffset,l=t.attributeOffset;for(let h=0;h<o;h++)e[i++]=r+n[h+a]-l}destroy(t={}){var e;if(this.batches!==null){for(let i=0;i<this.batchIndex;i++)Xa(this.batches[i]);this.batches=null,this.geometry.destroy(!0),this.geometry=null,t.shader&&((e=this.shader)==null||e.destroy(),this.shader=null);for(let i=0;i<this._elements.length;i++)this._elements[i]&&(this._elements[i]._batch=null);this._elements=null,this.indexBuffer=null,this.attributeBuffer.destroy(),this.attributeBuffer=null}}};Ya.defaultOptions={maxTextures:null,attributesInitialSize:4,indicesInitialSize:6};let Nf=Ya;var yt=(s=>(s[s.MAP_READ=1]="MAP_READ",s[s.MAP_WRITE=2]="MAP_WRITE",s[s.COPY_SRC=4]="COPY_SRC",s[s.COPY_DST=8]="COPY_DST",s[s.INDEX=16]="INDEX",s[s.VERTEX=32]="VERTEX",s[s.UNIFORM=64]="UNIFORM",s[s.STORAGE=128]="STORAGE",s[s.INDIRECT=256]="INDIRECT",s[s.QUERY_RESOLVE=512]="QUERY_RESOLVE",s[s.STATIC=1024]="STATIC",s))(yt||{});class ke extends Jt{constructor(t){let{data:e,size:i}=t;const{usage:r,label:n,shrinkToFit:o}=t;super(),this._gpuData=Object.create(null),this._gcLastUsed=-1,this.autoGarbageCollect=!0,this.uid=dt("buffer"),this._resourceType="buffer",this._resourceId=dt("resource"),this._touched=0,this._updateID=1,this._dataInt32=null,this.shrinkToFit=!0,this.destroyed=!1,e instanceof Array&&(e=new Float32Array(e)),this._data=e,i??(i=e==null?void 0:e.byteLength);const a=!!e;this.descriptor={size:i,usage:r,mappedAtCreation:a,label:n},this.shrinkToFit=o??!0}get data(){return this._data}set data(t){this.setDataWithSize(t,t.length,!0)}get dataInt32(){return this._dataInt32||(this._dataInt32=new Int32Array(this.data.buffer)),this._dataInt32}get static(){return!!(this.descriptor.usage&yt.STATIC)}set static(t){t?this.descriptor.usage|=yt.STATIC:this.descriptor.usage&=~yt.STATIC}setDataWithSize(t,e,i){if(this._updateID++,this._updateSize=e*t.BYTES_PER_ELEMENT,this._data===t){i&&this.emit("update",this);return}const r=this._data;if(this._data=t,this._dataInt32=null,!r||r.length!==t.length){!this.shrinkToFit&&r&&t.byteLength<r.byteLength?i&&this.emit("update",this):(this.descriptor.size=t.byteLength,this._resourceId=dt("resource"),this.emit("change",this));return}i&&this.emit("update",this)}update(t){this._updateSize=t??this._updateSize,this._updateID++,this.emit("update",this)}unload(){var t;this.emit("unload",this);for(const e in this._gpuData)(t=this._gpuData[e])==null||t.destroy();this._gpuData=Object.create(null)}destroy(){this.destroyed=!0,this.unload(),this.emit("destroy",this),this.emit("change",this),this._data=null,this.descriptor=null,this.removeAllListeners()}}function qa(s,t){if(!(s instanceof ke)){let e=t?yt.INDEX:yt.VERTEX;s instanceof Array&&(t?(s=new Uint32Array(s),e=yt.INDEX|yt.COPY_DST):(s=new Float32Array(s),e=yt.VERTEX|yt.COPY_DST)),s=new ke({data:s,label:t?"index-mesh-buffer":"vertex-mesh-buffer",usage:e})}return s}function Hf(s,t,e){const i=s.getAttribute(t);if(!i)return e.minX=0,e.minY=0,e.maxX=0,e.maxY=0,e;const r=i.buffer.data;let n=1/0,o=1/0,a=-1/0,l=-1/0;const h=r.BYTES_PER_ELEMENT,c=(i.offset||0)/h,u=(i.stride||8)/h;for(let m=c;m<r.length;m+=u){const f=r[m],g=r[m+1];f>a&&(a=f),g>l&&(l=g),f<n&&(n=f),g<o&&(o=g)}return e.minX=n,e.minY=o,e.maxX=a,e.maxY=l,e}function Wf(s){return(s instanceof ke||Array.isArray(s)||s.BYTES_PER_ELEMENT)&&(s={buffer:s}),s.buffer=qa(s.buffer,!1),s}class $r extends Jt{constructor(t={}){super(),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=dt("geometry"),this._layoutKey=0,this.instanceCount=1,this._bounds=new Lt,this._boundsDirty=!0;const{attributes:e,indexBuffer:i,topology:r}=t;if(this.buffers=[],this.attributes={},e)for(const n in e)this.addAttribute(n,e[n]);this.instanceCount=t.instanceCount??1,i&&this.addIndex(i),this.topology=r||"triangle-list"}onBufferUpdate(){this._boundsDirty=!0,this.emit("update",this)}getAttribute(t){return this.attributes[t]}getIndex(){return this.indexBuffer}getBuffer(t){return this.getAttribute(t).buffer}getSize(){for(const t in this.attributes){const e=this.attributes[t];return e.buffer.data.length/(e.stride/4||e.size)}return 0}addAttribute(t,e){const i=Wf(e);this.buffers.indexOf(i.buffer)===-1&&(this.buffers.push(i.buffer),i.buffer.on("update",this.onBufferUpdate,this),i.buffer.on("change",this.onBufferUpdate,this)),this.attributes[t]=i}addIndex(t){this.indexBuffer=qa(t,!0),this.buffers.push(this.indexBuffer)}get bounds(){return this._boundsDirty?(this._boundsDirty=!1,Hf(this,"aPosition",this._bounds)):this._bounds}unload(){var t;this.emit("unload",this);for(const e in this._gpuData)(t=this._gpuData[e])==null||t.destroy();this._gpuData=Object.create(null)}destroy(t=!1){var e;this.emit("destroy",this),this.removeAllListeners(),t&&this.buffers.forEach(i=>i.destroy()),this.unload(),(e=this.indexBuffer)==null||e.destroy(),this.attributes=null,this.buffers=null,this.indexBuffer=null,this._bounds=null}}const Vf=new Float32Array(1),zf=new Uint32Array(1);class $f extends $r{constructor(){const e=new ke({data:Vf,label:"attribute-batch-buffer",usage:yt.VERTEX|yt.COPY_DST,shrinkToFit:!1}),i=new ke({data:zf,label:"index-batch-buffer",usage:yt.INDEX|yt.COPY_DST,shrinkToFit:!1}),r=24;super({attributes:{aPosition:{buffer:e,format:"float32x2",stride:r,offset:0},aUV:{buffer:e,format:"float32x2",stride:r,offset:8},aColor:{buffer:e,format:"unorm8x4",stride:r,offset:16},aTextureIdAndRound:{buffer:e,format:"uint16x2",stride:r,offset:20}},indexBuffer:i})}}function Ka(s,t,e){if(s)for(const i in s){const r=i.toLocaleLowerCase(),n=t[r];if(n){let o=s[i];i==="header"&&(o=o.replace(/@in\s+[^;]+;\s*/g,"").replace(/@out\s+[^;]+;\s*/g,"")),e&&n.push(`//----${e}----//`),n.push(o)}else tt(`${i} placement hook does not exist in shader`)}}const jf=/\{\{(.*?)\}\}/g;function Za(s){var i;const t={};return(((i=s.match(jf))==null?void 0:i.map(r=>r.replace(/[{()}]/g,"")))??[]).forEach(r=>{t[r]=[]}),t}function Ja(s,t){let e;const i=/@in\s+([^;]+);/g;for(;(e=i.exec(s))!==null;)t.push(e[1])}function Qa(s,t,e=!1){const i=[];Ja(t,i),s.forEach(a=>{a.header&&Ja(a.header,i)});const r=i;e&&r.sort();const n=r.map((a,l)=>` @location(${l}) ${a},`).join(`
|
|
38
|
+
`);let o=t.replace(/@in\s+[^;]+;\s*/g,"");return o=o.replace("{{in}}",`
|
|
39
|
+
${n}
|
|
40
|
+
`),o}function tl(s,t){let e;const i=/@out\s+([^;]+);/g;for(;(e=i.exec(s))!==null;)t.push(e[1])}function Xf(s){const e=/\b(\w+)\s*:/g.exec(s);return e?e[1]:""}function Yf(s){const t=/@.*?\s+/g;return s.replace(t,"")}function qf(s,t){const e=[];tl(t,e),s.forEach(l=>{l.header&&tl(l.header,e)});let i=0;const r=e.sort().map(l=>l.indexOf("builtin")>-1?l:`@location(${i++}) ${l}`).join(`,
|
|
41
|
+
`),n=e.sort().map(l=>` var ${Yf(l)};`).join(`
|
|
42
|
+
`),o=`return VSOutput(
|
|
43
|
+
${e.sort().map(l=>` ${Xf(l)}`).join(`,
|
|
44
|
+
`)});`;let a=t.replace(/@out\s+[^;]+;\s*/g,"");return a=a.replace("{{struct}}",`
|
|
45
|
+
${r}
|
|
46
|
+
`),a=a.replace("{{start}}",`
|
|
47
|
+
${n}
|
|
48
|
+
`),a=a.replace("{{return}}",`
|
|
49
|
+
${o}
|
|
50
|
+
`),a}function el(s,t){let e=s;for(const i in t){const r=t[i];r.join(`
|
|
51
|
+
`).length?e=e.replace(`{{${i}}}`,`//-----${i} START-----//
|
|
52
|
+
${r.join(`
|
|
53
|
+
`)}
|
|
54
|
+
//----${i} FINISH----//`):e=e.replace(`{{${i}}}`,"")}return e}const Be=Object.create(null),jr=new Map;let Kf=0;function Zf({template:s,bits:t}){const e=il(s,t);if(Be[e])return Be[e];const{vertex:i,fragment:r}=Qf(s,t);return Be[e]=sl(i,r,t),Be[e]}function Jf({template:s,bits:t}){const e=il(s,t);return Be[e]||(Be[e]=sl(s.vertex,s.fragment,t)),Be[e]}function Qf(s,t){const e=t.map(o=>o.vertex).filter(o=>!!o),i=t.map(o=>o.fragment).filter(o=>!!o);let r=Qa(e,s.vertex,!0);r=qf(e,r);const n=Qa(i,s.fragment,!0);return{vertex:r,fragment:n}}function il(s,t){return t.map(e=>(jr.has(e)||jr.set(e,Kf++),jr.get(e))).sort((e,i)=>e-i).join("-")+s.vertex+s.fragment}function sl(s,t,e){const i=Za(s),r=Za(t);return e.forEach(n=>{Ka(n.vertex,i,n.name),Ka(n.fragment,r,n.name)}),{vertex:el(s,i),fragment:el(t,r)}}const tp=`
|
|
55
|
+
@in aPosition: vec2<f32>;
|
|
56
|
+
@in aUV: vec2<f32>;
|
|
57
|
+
|
|
58
|
+
@out @builtin(position) vPosition: vec4<f32>;
|
|
59
|
+
@out vUV : vec2<f32>;
|
|
60
|
+
@out vColor : vec4<f32>;
|
|
61
|
+
|
|
62
|
+
{{header}}
|
|
63
|
+
|
|
64
|
+
struct VSOutput {
|
|
65
|
+
{{struct}}
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
@vertex
|
|
69
|
+
fn main( {{in}} ) -> VSOutput {
|
|
70
|
+
|
|
71
|
+
var worldTransformMatrix = globalUniforms.uWorldTransformMatrix;
|
|
72
|
+
var modelMatrix = mat3x3<f32>(
|
|
73
|
+
1.0, 0.0, 0.0,
|
|
74
|
+
0.0, 1.0, 0.0,
|
|
75
|
+
0.0, 0.0, 1.0
|
|
76
|
+
);
|
|
77
|
+
var position = aPosition;
|
|
78
|
+
var uv = aUV;
|
|
79
|
+
|
|
80
|
+
{{start}}
|
|
81
|
+
|
|
82
|
+
vColor = vec4<f32>(1., 1., 1., 1.);
|
|
83
|
+
|
|
84
|
+
{{main}}
|
|
85
|
+
|
|
86
|
+
vUV = uv;
|
|
87
|
+
|
|
88
|
+
var modelViewProjectionMatrix = globalUniforms.uProjectionMatrix * worldTransformMatrix * modelMatrix;
|
|
89
|
+
|
|
90
|
+
vPosition = vec4<f32>((modelViewProjectionMatrix * vec3<f32>(position, 1.0)).xy, 0.0, 1.0);
|
|
91
|
+
|
|
92
|
+
vColor *= globalUniforms.uWorldColorAlpha;
|
|
93
|
+
|
|
94
|
+
{{end}}
|
|
95
|
+
|
|
96
|
+
{{return}}
|
|
97
|
+
};
|
|
98
|
+
`,ep=`
|
|
99
|
+
@in vUV : vec2<f32>;
|
|
100
|
+
@in vColor : vec4<f32>;
|
|
101
|
+
|
|
102
|
+
{{header}}
|
|
103
|
+
|
|
104
|
+
@fragment
|
|
105
|
+
fn main(
|
|
106
|
+
{{in}}
|
|
107
|
+
) -> @location(0) vec4<f32> {
|
|
108
|
+
|
|
109
|
+
{{start}}
|
|
110
|
+
|
|
111
|
+
var outColor:vec4<f32>;
|
|
112
|
+
|
|
113
|
+
{{main}}
|
|
114
|
+
|
|
115
|
+
var finalColor:vec4<f32> = outColor * vColor;
|
|
116
|
+
|
|
117
|
+
{{end}}
|
|
118
|
+
|
|
119
|
+
return finalColor;
|
|
120
|
+
};
|
|
121
|
+
`,ip=`
|
|
122
|
+
in vec2 aPosition;
|
|
123
|
+
in vec2 aUV;
|
|
124
|
+
|
|
125
|
+
out vec4 vColor;
|
|
126
|
+
out vec2 vUV;
|
|
127
|
+
|
|
128
|
+
{{header}}
|
|
129
|
+
|
|
130
|
+
void main(void){
|
|
131
|
+
|
|
132
|
+
mat3 worldTransformMatrix = uWorldTransformMatrix;
|
|
133
|
+
mat3 modelMatrix = mat3(
|
|
134
|
+
1.0, 0.0, 0.0,
|
|
135
|
+
0.0, 1.0, 0.0,
|
|
136
|
+
0.0, 0.0, 1.0
|
|
137
|
+
);
|
|
138
|
+
vec2 position = aPosition;
|
|
139
|
+
vec2 uv = aUV;
|
|
140
|
+
|
|
141
|
+
{{start}}
|
|
142
|
+
|
|
143
|
+
vColor = vec4(1.);
|
|
144
|
+
|
|
145
|
+
{{main}}
|
|
146
|
+
|
|
147
|
+
vUV = uv;
|
|
148
|
+
|
|
149
|
+
mat3 modelViewProjectionMatrix = uProjectionMatrix * worldTransformMatrix * modelMatrix;
|
|
150
|
+
|
|
151
|
+
gl_Position = vec4((modelViewProjectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);
|
|
152
|
+
|
|
153
|
+
vColor *= uWorldColorAlpha;
|
|
154
|
+
|
|
155
|
+
{{end}}
|
|
156
|
+
}
|
|
157
|
+
`,sp=`
|
|
158
|
+
|
|
159
|
+
in vec4 vColor;
|
|
160
|
+
in vec2 vUV;
|
|
161
|
+
|
|
162
|
+
out vec4 finalColor;
|
|
163
|
+
|
|
164
|
+
{{header}}
|
|
165
|
+
|
|
166
|
+
void main(void) {
|
|
167
|
+
|
|
168
|
+
{{start}}
|
|
169
|
+
|
|
170
|
+
vec4 outColor;
|
|
171
|
+
|
|
172
|
+
{{main}}
|
|
173
|
+
|
|
174
|
+
finalColor = outColor * vColor;
|
|
175
|
+
|
|
176
|
+
{{end}}
|
|
177
|
+
}
|
|
178
|
+
`,rp={name:"global-uniforms-bit",vertex:{header:`
|
|
179
|
+
struct GlobalUniforms {
|
|
180
|
+
uProjectionMatrix:mat3x3<f32>,
|
|
181
|
+
uWorldTransformMatrix:mat3x3<f32>,
|
|
182
|
+
uWorldColorAlpha: vec4<f32>,
|
|
183
|
+
uResolution: vec2<f32>,
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
@group(0) @binding(0) var<uniform> globalUniforms : GlobalUniforms;
|
|
187
|
+
`}},np={name:"global-uniforms-bit",vertex:{header:`
|
|
188
|
+
uniform mat3 uProjectionMatrix;
|
|
189
|
+
uniform mat3 uWorldTransformMatrix;
|
|
190
|
+
uniform vec4 uWorldColorAlpha;
|
|
191
|
+
uniform vec2 uResolution;
|
|
192
|
+
`}};function Xr({bits:s,name:t}){const e=Zf({template:{fragment:ep,vertex:tp},bits:[rp,...s]});return Ke.from({name:t,vertex:{source:e.vertex,entryPoint:"main"},fragment:{source:e.fragment,entryPoint:"main"}})}function Yr({bits:s,name:t}){return new Ye({name:t,...Jf({template:{vertex:ip,fragment:sp},bits:[np,...s]})})}const rl={name:"color-bit",vertex:{header:`
|
|
193
|
+
@in aColor: vec4<f32>;
|
|
194
|
+
`,main:`
|
|
195
|
+
vColor *= vec4<f32>(aColor.rgb * aColor.a, aColor.a);
|
|
196
|
+
`}},nl={name:"color-bit",vertex:{header:`
|
|
197
|
+
in vec4 aColor;
|
|
198
|
+
`,main:`
|
|
199
|
+
vColor *= vec4(aColor.rgb * aColor.a, aColor.a);
|
|
200
|
+
`}},qr={};function op(s){const t=[];if(s===1)t.push("@group(1) @binding(0) var textureSource1: texture_2d<f32>;"),t.push("@group(1) @binding(1) var textureSampler1: sampler;");else{let e=0;for(let i=0;i<s;i++)t.push(`@group(1) @binding(${e++}) var textureSource${i+1}: texture_2d<f32>;`),t.push(`@group(1) @binding(${e++}) var textureSampler${i+1}: sampler;`)}return t.join(`
|
|
201
|
+
`)}function ap(s){const t=[];if(s===1)t.push("outColor = textureSampleGrad(textureSource1, textureSampler1, vUV, uvDx, uvDy);");else{t.push("switch vTextureId {");for(let e=0;e<s;e++)e===s-1?t.push(" default:{"):t.push(` case ${e}:{`),t.push(` outColor = textureSampleGrad(textureSource${e+1}, textureSampler${e+1}, vUV, uvDx, uvDy);`),t.push(" break;}");t.push("}")}return t.join(`
|
|
202
|
+
`)}function ol(s){return qr[s]||(qr[s]={name:"texture-batch-bit",vertex:{header:`
|
|
203
|
+
@in aTextureIdAndRound: vec2<u32>;
|
|
204
|
+
@out @interpolate(flat) vTextureId : u32;
|
|
205
|
+
`,main:`
|
|
206
|
+
vTextureId = aTextureIdAndRound.y;
|
|
207
|
+
`,end:`
|
|
208
|
+
if(aTextureIdAndRound.x == 1)
|
|
209
|
+
{
|
|
210
|
+
vPosition = vec4<f32>(roundPixels(vPosition.xy, globalUniforms.uResolution), vPosition.zw);
|
|
211
|
+
}
|
|
212
|
+
`},fragment:{header:`
|
|
213
|
+
@in @interpolate(flat) vTextureId: u32;
|
|
214
|
+
|
|
215
|
+
${op(s)}
|
|
216
|
+
`,main:`
|
|
217
|
+
var uvDx = dpdx(vUV);
|
|
218
|
+
var uvDy = dpdy(vUV);
|
|
219
|
+
|
|
220
|
+
${ap(s)}
|
|
221
|
+
`}}),qr[s]}const Kr={};function lp(s){const t=[];for(let e=0;e<s;e++)e>0&&t.push("else"),e<s-1&&t.push(`if(vTextureId < ${e}.5)`),t.push("{"),t.push(` outColor = texture(uTextures[${e}], vUV);`),t.push("}");return t.join(`
|
|
222
|
+
`)}function al(s){return Kr[s]||(Kr[s]={name:"texture-batch-bit",vertex:{header:`
|
|
223
|
+
in vec2 aTextureIdAndRound;
|
|
224
|
+
out float vTextureId;
|
|
225
|
+
|
|
226
|
+
`,main:`
|
|
227
|
+
vTextureId = aTextureIdAndRound.y;
|
|
228
|
+
`,end:`
|
|
229
|
+
if(aTextureIdAndRound.x == 1.)
|
|
230
|
+
{
|
|
231
|
+
gl_Position.xy = roundPixels(gl_Position.xy, uResolution);
|
|
232
|
+
}
|
|
233
|
+
`},fragment:{header:`
|
|
234
|
+
in float vTextureId;
|
|
235
|
+
|
|
236
|
+
uniform sampler2D uTextures[${s}];
|
|
237
|
+
|
|
238
|
+
`,main:`
|
|
239
|
+
|
|
240
|
+
${lp(s)}
|
|
241
|
+
`}}),Kr[s]}const Zr={name:"round-pixels-bit",vertex:{header:`
|
|
242
|
+
fn roundPixels(position: vec2<f32>, targetSize: vec2<f32>) -> vec2<f32>
|
|
243
|
+
{
|
|
244
|
+
return (floor(((position * 0.5 + 0.5) * targetSize) + 0.5) / targetSize) * 2.0 - 1.0;
|
|
245
|
+
}
|
|
246
|
+
`}},Jr={name:"round-pixels-bit",vertex:{header:`
|
|
247
|
+
vec2 roundPixels(vec2 position, vec2 targetSize)
|
|
248
|
+
{
|
|
249
|
+
return (floor(((position * 0.5 + 0.5) * targetSize) + 0.5) / targetSize) * 2.0 - 1.0;
|
|
250
|
+
}
|
|
251
|
+
`}},ll={};function hl(s){let t=ll[s];if(t)return t;const e=new Int32Array(s);for(let i=0;i<s;i++)e[i]=i;return t=ll[s]=new he({uTextures:{value:e,type:"i32",size:s}},{isStatic:!0}),t}class cl extends be{constructor(t){const e=Yr({name:"batch",bits:[nl,al(t),Jr]}),i=Xr({name:"batch",bits:[rl,ol(t),Zr]});super({glProgram:e,gpuProgram:i,resources:{batchSamplers:hl(t)}}),this.maxTextures=t}}let Zi=null;const ul=class uu extends Nf{constructor(t){super(t),this.geometry=new $f,this.name=uu.extension.name,this.vertexSize=6,Zi??(Zi=new cl(t.maxTextures)),this.shader=Zi}packAttributes(t,e,i,r,n){const o=n<<16|t.roundPixels&65535,a=t.transform,l=a.a,h=a.b,c=a.c,u=a.d,m=a.tx,f=a.ty,{positions:g,uvs:y}=t,x=t.color,v=t.attributeOffset,E=v+t.attributeSize;for(let T=v;T<E;T++){const C=T*2,R=g[C],A=g[C+1];e[r++]=l*R+c*A+m,e[r++]=u*A+h*R+f,e[r++]=y[C],e[r++]=y[C+1],i[r++]=x,i[r++]=o}}packQuadAttributes(t,e,i,r,n){const o=t.texture,a=t.transform,l=a.a,h=a.b,c=a.c,u=a.d,m=a.tx,f=a.ty,g=t.bounds,y=g.maxX,x=g.minX,v=g.maxY,E=g.minY,T=o.uvs,C=t.color,R=n<<16|t.roundPixels&65535;e[r+0]=l*x+c*E+m,e[r+1]=u*E+h*x+f,e[r+2]=T.x0,e[r+3]=T.y0,i[r+4]=C,i[r+5]=R,e[r+6]=l*y+c*E+m,e[r+7]=u*E+h*y+f,e[r+8]=T.x1,e[r+9]=T.y1,i[r+10]=C,i[r+11]=R,e[r+12]=l*y+c*v+m,e[r+13]=u*v+h*y+f,e[r+14]=T.x2,e[r+15]=T.y2,i[r+16]=C,i[r+17]=R,e[r+18]=l*x+c*v+m,e[r+19]=u*v+h*x+f,e[r+20]=T.x3,e[r+21]=T.y3,i[r+22]=C,i[r+23]=R}_updateMaxTextures(t){this.shader.maxTextures!==t&&(Zi=new cl(t),this.shader=Zi)}destroy(){this.shader=null,super.destroy()}};ul.extension={type:[w.Batcher],name:"default"};let Qr=ul;class ue{constructor(t){this.items=Object.create(null);const{renderer:e,type:i,onUnload:r,priority:n,name:o}=t;this._renderer=e,e.gc.addResourceHash(this,"items",i,n??0),this._onUnload=r,this.name=o}add(t){return this.items[t.uid]?!1:(this.items[t.uid]=t,t.once("unload",this.remove,this),t._gcLastUsed=this._renderer.gc.now,!0)}remove(t,...e){var r;if(!this.items[t.uid])return;const i=t._gpuData[this._renderer.uid];i&&((r=this._onUnload)==null||r.call(this,t,...e),i.destroy(),t._gpuData[this._renderer.uid]=null,this.items[t.uid]=null)}removeAll(...t){Object.values(this.items).forEach(e=>e&&this.remove(e,...t))}destroy(...t){this.removeAll(...t),this.items=Object.create(null),this._renderer=null,this._onUnload=null}}function hp(s,t,e,i,r,n,o,a=null){let l=0;e*=t,r*=n;const h=a.a,c=a.b,u=a.c,m=a.d,f=a.tx,g=a.ty;for(;l<o;){const y=s[e],x=s[e+1];i[r]=h*y+u*x+f,i[r+1]=c*y+m*x+g,r+=n,e+=t,l++}}function cp(s,t,e,i){let r=0;for(t*=e;r<i;)s[t]=0,s[t+1]=0,t+=e,r++}function dl(s,t,e,i,r){const n=t.a,o=t.b,a=t.c,l=t.d,h=t.tx,c=t.ty;e||(e=0),i||(i=2),r||(r=s.length/i-e);let u=e*i;for(let m=0;m<r;m++){const f=s[u],g=s[u+1];s[u]=n*f+a*g+h,s[u+1]=o*f+l*g+c,u+=i}}const up=new W;class tn{constructor(){this.packAsQuad=!1,this.batcherName="default",this.topology="triangle-list",this.applyTransform=!0,this.roundPixels=0,this._batcher=null,this._batch=null}get uvs(){return this.geometryData.uvs}get positions(){return this.geometryData.vertices}get indices(){return this.geometryData.indices}get blendMode(){return this.renderable&&this.applyTransform?this.renderable.groupBlendMode:"normal"}get color(){const t=this.baseColor,e=t>>16|t&65280|(t&255)<<16,i=this.renderable;return i?di(e,i.groupColor)+(this.alpha*i.groupAlpha*255<<24):e+(this.alpha*255<<24)}get transform(){var t;return((t=this.renderable)==null?void 0:t.groupTransform)||up}copyTo(t){t.indexOffset=this.indexOffset,t.indexSize=this.indexSize,t.attributeOffset=this.attributeOffset,t.attributeSize=this.attributeSize,t.baseColor=this.baseColor,t.alpha=this.alpha,t.texture=this.texture,t.geometryData=this.geometryData,t.topology=this.topology}reset(){this.applyTransform=!0,this.renderable=null,this.topology="triangle-list"}destroy(){this.renderable=null,this.texture=null,this.geometryData=null,this._batcher=null,this._batch=null}}const Ji={extension:{type:w.ShapeBuilder,name:"circle"},build(s,t){let e,i,r,n,o,a;if(s.type==="circle"){const C=s;if(o=a=C.radius,o<=0)return!1;e=C.x,i=C.y,r=n=0}else if(s.type==="ellipse"){const C=s;if(o=C.halfWidth,a=C.halfHeight,o<=0||a<=0)return!1;e=C.x,i=C.y,r=n=0}else{const C=s,R=C.width/2,A=C.height/2;e=C.x+R,i=C.y+A,o=a=Math.max(0,Math.min(C.radius,Math.min(R,A))),r=R-o,n=A-a}if(r<0||n<0)return!1;const l=Math.ceil(2.3*Math.sqrt(o+a)),h=l*8+(r?4:0)+(n?4:0);if(h===0)return!1;if(l===0)return t[0]=t[6]=e+r,t[1]=t[3]=i+n,t[2]=t[4]=e-r,t[5]=t[7]=i-n,!0;let c=0,u=l*4+(r?2:0)+2,m=u,f=h,g=r+o,y=n,x=e+g,v=e-g,E=i+y;if(t[c++]=x,t[c++]=E,t[--u]=E,t[--u]=v,n){const C=i-y;t[m++]=v,t[m++]=C,t[--f]=C,t[--f]=x}for(let C=1;C<l;C++){const R=Math.PI/2*(C/l),A=r+Math.cos(R)*o,I=n+Math.sin(R)*a,N=e+A,B=e-A,k=i+I,O=i-I;t[c++]=N,t[c++]=k,t[--u]=k,t[--u]=B,t[m++]=B,t[m++]=O,t[--f]=O,t[--f]=N}g=r,y=n+a,x=e+g,v=e-g,E=i+y;const T=i-y;return t[c++]=x,t[c++]=E,t[--f]=T,t[--f]=x,r&&(t[c++]=v,t[c++]=E,t[--f]=T,t[--f]=v),!0},triangulate(s,t,e,i,r,n){if(s.length===0)return;let o=0,a=0;for(let c=0;c<s.length;c+=2)o+=s[c],a+=s[c+1];o/=s.length/2,a/=s.length/2;let l=i;t[l*e]=o,t[l*e+1]=a;const h=l++;for(let c=0;c<s.length;c+=2)t[l*e]=s[c],t[l*e+1]=s[c+1],c>0&&(r[n++]=l,r[n++]=h,r[n++]=l-1),l++;r[n++]=h+1,r[n++]=h,r[n++]=l-1}},dp={...Ji,extension:{...Ji.extension,name:"ellipse"}},fp={...Ji,extension:{...Ji.extension,name:"roundedRectangle"}},fl=1e-4,pl=1e-4;function pp(s){const t=s.length;if(t<6)return 1;let e=0;for(let i=0,r=s[t-2],n=s[t-1];i<t;i+=2){const o=s[i],a=s[i+1];e+=(o-r)*(a+n),r=o,n=a}return e<0?-1:1}function ml(s,t,e,i,r,n,o,a){const l=s-e*r,h=t-i*r,c=s+e*n,u=t+i*n;let m,f;o?(m=i,f=-e):(m=-i,f=e);const g=l+m,y=h+f,x=c+m,v=u+f;return a.push(g,y),a.push(x,v),2}function Je(s,t,e,i,r,n,o,a){const l=e-s,h=i-t;let c=Math.atan2(l,h),u=Math.atan2(r-s,n-t);a&&c<u?c+=Math.PI*2:!a&&c>u&&(u+=Math.PI*2);let m=c;const f=u-c,g=Math.abs(f),y=Math.sqrt(l*l+h*h),x=(15*g*Math.sqrt(y)/Math.PI>>0)+1,v=f/x;if(m+=v,a){o.push(s,t),o.push(e,i);for(let E=1,T=m;E<x;E++,T+=v)o.push(s,t),o.push(s+Math.sin(T)*y,t+Math.cos(T)*y);o.push(s,t),o.push(r,n)}else{o.push(e,i),o.push(s,t);for(let E=1,T=m;E<x;E++,T+=v)o.push(s+Math.sin(T)*y,t+Math.cos(T)*y),o.push(s,t);o.push(r,n),o.push(s,t)}return x*2}function gl(s,t,e,i,r,n){const o=fl;if(s.length===0)return;const a=t;let l=a.alignment;if(t.alignment!==.5){let D=pp(s);l=(l-.5)*D+.5}const h=new mt(s[0],s[1]),c=new mt(s[s.length-2],s[s.length-1]),u=i,m=Math.abs(h.x-c.x)<o&&Math.abs(h.y-c.y)<o;if(u){s=s.slice(),m&&(s.pop(),s.pop(),c.set(s[s.length-2],s[s.length-1]));const D=(h.x+c.x)*.5,$=(c.y+h.y)*.5;s.unshift(D,$),s.push(D,$)}const f=r,g=s.length/2;let y=s.length;const x=f.length/2,v=a.width/2,E=v*v,T=a.miterLimit*a.miterLimit;let C=s[0],R=s[1],A=s[2],I=s[3],N=0,B=0,k=-(R-I),O=C-A,L=0,F=0,H=Math.sqrt(k*k+O*O);k/=H,O/=H,k*=v,O*=v;const at=l,G=(1-at)*2,U=at*2;u||(a.cap==="round"?y+=Je(C-k*(G-U)*.5,R-O*(G-U)*.5,C-k*G,R-O*G,C+k*U,R+O*U,f,!0)+2:a.cap==="square"&&(y+=ml(C,R,k,O,G,U,!0,f))),f.push(C-k*G,R-O*G),f.push(C+k*U,R+O*U);for(let D=1;D<g-1;++D){C=s[(D-1)*2],R=s[(D-1)*2+1],A=s[D*2],I=s[D*2+1],N=s[(D+1)*2],B=s[(D+1)*2+1],k=-(R-I),O=C-A,H=Math.sqrt(k*k+O*O),k/=H,O/=H,k*=v,O*=v,L=-(I-B),F=A-N,H=Math.sqrt(L*L+F*F),L/=H,F/=H,L*=v,F*=v;const $=A-C,Y=R-I,j=A-N,V=B-I,ot=$*j+Y*V,lt=Y*j-V*$,gt=lt<0;if(Math.abs(lt)<.001*Math.abs(ot)){f.push(A-k*G,I-O*G),f.push(A+k*U,I+O*U),ot>=0&&(a.join==="round"?y+=Je(A,I,A-k*G,I-O*G,A-L*G,I-F*G,f,!1)+4:y+=2,f.push(A-L*U,I-F*U),f.push(A+L*G,I+F*G));continue}const ht=(-k+C)*(-O+I)-(-k+A)*(-O+R),_t=(-L+N)*(-F+I)-(-L+A)*(-F+B),Z=($*_t-j*ht)/lt,Bt=(V*ht-Y*_t)/lt,$t=(Z-A)*(Z-A)+(Bt-I)*(Bt-I),xt=A+(Z-A)*G,Gt=I+(Bt-I)*G,Ut=A-(Z-A)*U,jt=I-(Bt-I)*U,We=Math.min($*$+Y*Y,j*j+V*V),pe=gt?G:U,ri=We+pe*pe*E;$t<=ri?a.join==="bevel"||$t/E>T?(gt?(f.push(xt,Gt),f.push(A+k*U,I+O*U),f.push(xt,Gt),f.push(A+L*U,I+F*U)):(f.push(A-k*G,I-O*G),f.push(Ut,jt),f.push(A-L*G,I-F*G),f.push(Ut,jt)),y+=2):a.join==="round"?gt?(f.push(xt,Gt),f.push(A+k*U,I+O*U),y+=Je(A,I,A+k*U,I+O*U,A+L*U,I+F*U,f,!0)+4,f.push(xt,Gt),f.push(A+L*U,I+F*U)):(f.push(A-k*G,I-O*G),f.push(Ut,jt),y+=Je(A,I,A-k*G,I-O*G,A-L*G,I-F*G,f,!1)+4,f.push(A-L*G,I-F*G),f.push(Ut,jt)):(f.push(xt,Gt),f.push(Ut,jt)):(f.push(A-k*G,I-O*G),f.push(A+k*U,I+O*U),a.join==="round"?gt?y+=Je(A,I,A+k*U,I+O*U,A+L*U,I+F*U,f,!0)+2:y+=Je(A,I,A-k*G,I-O*G,A-L*G,I-F*G,f,!1)+2:a.join==="miter"&&$t/E<=T&&(gt?(f.push(Ut,jt),f.push(Ut,jt)):(f.push(xt,Gt),f.push(xt,Gt)),y+=2),f.push(A-L*G,I-F*G),f.push(A+L*U,I+F*U),y+=2)}C=s[(g-2)*2],R=s[(g-2)*2+1],A=s[(g-1)*2],I=s[(g-1)*2+1],k=-(R-I),O=C-A,H=Math.sqrt(k*k+O*O),k/=H,O/=H,k*=v,O*=v,f.push(A-k*G,I-O*G),f.push(A+k*U,I+O*U),u||(a.cap==="round"?y+=Je(A-k*(G-U)*.5,I-O*(G-U)*.5,A-k*G,I-O*G,A+k*U,I+O*U,f,!1)+2:a.cap==="square"&&(y+=ml(A,I,k,O,G,U,!1,f)));const X=pl*pl;for(let D=x;D<y+x-2;++D)C=f[D*2],R=f[D*2+1],A=f[(D+1)*2],I=f[(D+1)*2+1],N=f[(D+2)*2],B=f[(D+2)*2+1],!(Math.abs(C*(I-B)+A*(B-R)+N*(R-I))<X)&&n.push(D,D+1,D+2)}function mp(s,t,e,i){const r=fl;if(s.length===0)return;const n=s[0],o=s[1],a=s[s.length-2],l=s[s.length-1],h=t||Math.abs(n-a)<r&&Math.abs(o-l)<r,c=e,u=s.length/2,m=c.length/2;for(let f=0;f<u;f++)c.push(s[f*2]),c.push(s[f*2+1]);for(let f=0;f<u-1;f++)i.push(m+f,m+f+1);h&&i.push(m+u-1,m)}function _l(s,t,e,i,r,n,o){const a=vf(s,t,2);if(!a)return;for(let h=0;h<a.length;h+=3)n[o++]=a[h]+r,n[o++]=a[h+1]+r,n[o++]=a[h+2]+r;let l=r*i;for(let h=0;h<s.length;h+=2)e[l]=s[h],e[l+1]=s[h+1],l+=i}const gp=[],_p={extension:{type:w.ShapeBuilder,name:"polygon"},build(s,t){for(let e=0;e<s.points.length;e++)t[e]=s.points[e];return!0},triangulate(s,t,e,i,r,n){_l(s,gp,t,e,i,r,n)}},yp={extension:{type:w.ShapeBuilder,name:"rectangle"},build(s,t){const e=s,i=e.x,r=e.y,n=e.width,o=e.height;return n>0&&o>0?(t[0]=i,t[1]=r,t[2]=i+n,t[3]=r,t[4]=i+n,t[5]=r+o,t[6]=i,t[7]=r+o,!0):!1},triangulate(s,t,e,i,r,n){let o=0;i*=e,t[i+o]=s[0],t[i+o+1]=s[1],o+=e,t[i+o]=s[2],t[i+o+1]=s[3],o+=e,t[i+o]=s[6],t[i+o+1]=s[7],o+=e,t[i+o]=s[4],t[i+o+1]=s[5],o+=e;const a=i/e;r[n++]=a,r[n++]=a+1,r[n++]=a+2,r[n++]=a+1,r[n++]=a+3,r[n++]=a+2}},xp={extension:{type:w.ShapeBuilder,name:"triangle"},build(s,t){return t[0]=s.x,t[1]=s.y,t[2]=s.x2,t[3]=s.y2,t[4]=s.x3,t[5]=s.y3,!0},triangulate(s,t,e,i,r,n){let o=0;i*=e,t[i+o]=s[0],t[i+o+1]=s[1],o+=e,t[i+o]=s[2],t[i+o+1]=s[3],o+=e,t[i+o]=s[4],t[i+o+1]=s[5];const a=i/e;r[n++]=a,r[n++]=a+1,r[n++]=a+2}},yl=[{offset:0,color:"white"},{offset:1,color:"black"}],en=class eo{constructor(...t){this.uid=dt("fillGradient"),this._tick=0,this.type="linear",this.colorStops=[];let e=bp(t);e={...e.type==="radial"?eo.defaultRadialOptions:eo.defaultLinearOptions,...fo(e)},this._textureSize=e.textureSize,this._wrapMode=e.wrapMode,e.type==="radial"?(this.center=e.center,this.outerCenter=e.outerCenter??this.center,this.innerRadius=e.innerRadius,this.outerRadius=e.outerRadius,this.scale=e.scale,this.rotation=e.rotation):(this.start=e.start,this.end=e.end),this.textureSpace=e.textureSpace,this.type=e.type,e.colorStops.forEach(r=>{this.addColorStop(r.offset,r.color)})}addColorStop(t,e){return this.colorStops.push({offset:t,color:ct.shared.setValue(e).toHexa()}),this}buildLinearGradient(){if(this.texture)return;let{x:t,y:e}=this.start,{x:i,y:r}=this.end,n=i-t,o=r-e;const a=n<0||o<0;if(this._wrapMode==="clamp-to-edge"){if(n<0){const x=t;t=i,i=x,n*=-1}if(o<0){const x=e;e=r,r=x,o*=-1}}const l=this.colorStops.length?this.colorStops:yl,h=this._textureSize,{canvas:c,context:u}=bl(h,1),m=a?u.createLinearGradient(this._textureSize,0,0,0):u.createLinearGradient(0,0,this._textureSize,0);xl(m,l),u.fillStyle=m,u.fillRect(0,0,h,1),this.texture=new z({source:new xs({resource:c,addressMode:this._wrapMode})});const f=Math.sqrt(n*n+o*o),g=Math.atan2(o,n),y=new W;y.scale(f/h,1),y.rotate(g),y.translate(t,e),this.textureSpace==="local"&&y.scale(h,h),this.transform=y}buildGradient(){this.texture||this._tick++,this.type==="linear"?this.buildLinearGradient():this.buildRadialGradient()}buildRadialGradient(){if(this.texture)return;const t=this.colorStops.length?this.colorStops:yl,e=this._textureSize,{canvas:i,context:r}=bl(e,e),{x:n,y:o}=this.center,{x:a,y:l}=this.outerCenter,h=this.innerRadius,c=this.outerRadius,u=a-c,m=l-c,f=e/(c*2),g=(n-u)*f,y=(o-m)*f,x=r.createRadialGradient(g,y,h*f,(a-u)*f,(l-m)*f,c*f);xl(x,t),r.fillStyle=t[t.length-1].color,r.fillRect(0,0,e,e),r.fillStyle=x,r.translate(g,y),r.rotate(this.rotation),r.scale(1,this.scale),r.translate(-g,-y),r.fillRect(0,0,e,e),this.texture=new z({source:new xs({resource:i,addressMode:this._wrapMode})});const v=new W;v.scale(1/f,1/f),v.translate(u,m),this.textureSpace==="local"&&v.scale(e,e),this.transform=v}destroy(){var t;(t=this.texture)==null||t.destroy(!0),this.texture=null,this.transform=null,this.colorStops=[],this.start=null,this.end=null,this.center=null,this.outerCenter=null}get styleKey(){return`fill-gradient-${this.uid}-${this._tick}`}};en.defaultLinearOptions={start:{x:0,y:0},end:{x:0,y:1},colorStops:[],textureSpace:"local",type:"linear",textureSize:256,wrapMode:"clamp-to-edge"},en.defaultRadialOptions={center:{x:.5,y:.5},innerRadius:0,outerRadius:.5,colorStops:[],scale:1,textureSpace:"local",type:"radial",textureSize:256,wrapMode:"clamp-to-edge"};let de=en;function xl(s,t){for(let e=0;e<t.length;e++){const i=t[e];s.addColorStop(i.offset,i.color)}}function bl(s,t){const e=rt.get().createCanvas(s,t),i=e.getContext("2d");return{canvas:e,context:i}}function bp(s){let t=s[0]??{};return(typeof t=="number"||s[1])&&(K("8.5.2","use options object instead"),t={type:"linear",start:{x:s[0],y:s[1]},end:{x:s[2],y:s[3]},textureSpace:s[4],textureSize:s[5]??de.defaultLinearOptions.textureSize}),t}const vp=new W,Ep=new ut;function vl(s,t,e,i){const r=t.matrix?s.copyFrom(t.matrix).invert():s.identity();if(t.textureSpace==="local"){const o=e.getBounds(Ep);t.width&&o.pad(t.width);const{x:a,y:l}=o,h=1/o.width,c=1/o.height,u=-a*h,m=-l*c,f=r.a,g=r.b,y=r.c,x=r.d;r.a*=h,r.b*=h,r.c*=c,r.d*=c,r.tx=u*f+m*y+r.tx,r.ty=u*g+m*x+r.ty}else r.translate(t.texture.frame.x,t.texture.frame.y),r.scale(1/t.texture.source.width,1/t.texture.source.height);const n=t.texture.source.style;return!(t.fill instanceof de)&&n.addressMode==="clamp-to-edge"&&(n.addressMode="repeat",n.update()),i&&r.append(vp.copyFrom(i).invert()),r}const Qi={};J.handleByMap(w.ShapeBuilder,Qi),J.add(yp,_p,xp,Ji,dp,fp);const Tp=new ut,Sp=new W;function Cp(s,t){const{geometryData:e,batches:i}=t;i.length=0,e.indices.length=0,e.vertices.length=0,e.uvs.length=0;for(let r=0;r<s.instructions.length;r++){const n=s.instructions[r];if(n.action==="texture")wp(n.data,i,e);else if(n.action==="fill"||n.action==="stroke"){const o=n.action==="stroke",a=n.data.path.shapePath,l=n.data.style,h=n.data.hole;o&&h&&El(h.shapePath,l,!0,i,e),h&&(a.shapePrimitives[a.shapePrimitives.length-1].holes=h.shapePath.shapePrimitives),El(a,l,o,i,e)}}}function wp(s,t,e){const i=[],r=Qi.rectangle,n=Tp;n.x=s.dx,n.y=s.dy,n.width=s.dw,n.height=s.dh;const o=s.transform;if(!r.build(n,i))return;const{vertices:a,uvs:l,indices:h}=e,c=h.length,u=a.length/2;o&&dl(i,o),r.triangulate(i,a,2,u,h,c);const m=s.image,f=m.uvs;l.push(f.x0,f.y0,f.x1,f.y1,f.x3,f.y3,f.x2,f.y2);const g=Mt.get(tn);g.indexOffset=c,g.indexSize=h.length-c,g.attributeOffset=u,g.attributeSize=a.length/2-u,g.baseColor=s.style,g.alpha=s.alpha,g.texture=m,g.geometryData=e,t.push(g)}function El(s,t,e,i,r){const{vertices:n,uvs:o,indices:a}=r;s.shapePrimitives.forEach(({shape:l,transform:h,holes:c})=>{const u=[],m=Qi[l.type];if(!m.build(l,u))return;const f=a.length,g=n.length/2;let y="triangle-list";if(h&&dl(u,h),e){const T=l.closePath??!0,C=t;C.pixelLine?(mp(u,T,n,a),y="line-list"):gl(u,C,!1,T,n,a)}else if(c){const T=[],C=u.slice();Ap(c).forEach(A=>{T.push(C.length/2),C.push(...A)}),_l(C,T,n,2,g,a,f)}else m.triangulate(u,n,2,g,a,f);const x=o.length/2,v=t.texture;if(v!==z.WHITE){const T=vl(Sp,t,l,h);hp(n,2,g,o,x,2,n.length/2-g,T)}else cp(o,x,2,n.length/2-g);const E=Mt.get(tn);E.indexOffset=f,E.indexSize=a.length-f,E.attributeOffset=g,E.attributeSize=n.length/2-g,E.baseColor=t.color,E.alpha=t.alpha,E.texture=v,E.geometryData=r,E.topology=y,i.push(E)})}function Ap(s){const t=[];for(let e=0;e<s.length;e++){const i=s[e].shape,r=[];Qi[i.type].build(i,r)&&t.push(r)}return t}class Rp{constructor(){this.batches=[],this.geometryData={vertices:[],uvs:[],indices:[]}}reset(){this.batches&&this.batches.forEach(t=>{Mt.return(t)}),this.graphicsData&&Mt.return(this.graphicsData),this.isBatchable=!1,this.context=null,this.batches.length=0,this.geometryData.indices.length=0,this.geometryData.vertices.length=0,this.geometryData.uvs.length=0,this.graphicsData=null}destroy(){this.reset(),this.batches=null,this.geometryData=null}}class Pp{constructor(){this.instructions=new fr}init(t){const e=t.maxTextures;this.batcher?this.batcher._updateMaxTextures(e):this.batcher=new Qr({maxTextures:e}),this.instructions.reset()}get geometry(){return K(Fu,"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 sn=class io{constructor(t){this._renderer=t,this._managedContexts=new ue({renderer:t,type:"resource",name:"graphicsContext"})}init(t){io.defaultOptions.bezierSmoothness=(t==null?void 0:t.bezierSmoothness)??io.defaultOptions.bezierSmoothness}getContextRenderData(t){return t._gpuData[this._renderer.uid].graphicsData||this._initContextRenderData(t)}updateGpuContext(t){const e=!!t._gpuData[this._renderer.uid],i=t._gpuData[this._renderer.uid]||this._initContext(t);if(t.dirty||!e){e&&i.reset(),Cp(t,i);const r=t.batchMode;t.customShader||r==="no-batch"?i.isBatchable=!1:r==="auto"?i.isBatchable=i.geometryData.vertices.length<400:i.isBatchable=!0,t.dirty=!1}return i}getGpuContext(t){return t._gpuData[this._renderer.uid]||this._initContext(t)}_initContextRenderData(t){const e=Mt.get(Pp,{maxTextures:this._renderer.limits.maxBatchableTextures}),i=t._gpuData[this._renderer.uid],{batches:r,geometryData:n}=i;i.graphicsData=e;const o=n.vertices.length,a=n.indices.length;for(let u=0;u<r.length;u++)r[u].applyTransform=!1;const l=e.batcher;l.ensureAttributeBuffer(o),l.ensureIndexBuffer(a),l.begin();for(let u=0;u<r.length;u++){const m=r[u];l.add(m)}l.finish(e.instructions);const h=l.geometry;h.indexBuffer.setDataWithSize(l.indexBuffer,l.indexSize,!0),h.buffers[0].setDataWithSize(l.attributeBuffer.float32View,l.attributeSize,!0);const c=l.batches;for(let u=0;u<c.length;u++){const m=c[u];m.bindGroup=Vr(m.textures.textures,m.textures.count,this._renderer.limits.maxBatchableTextures)}return e}_initContext(t){const e=new Rp;return e.context=t,t._gpuData[this._renderer.uid]=e,this._managedContexts.add(t),e}destroy(){this._managedContexts.destroy(),this._renderer=null}};sn.extension={type:[w.WebGLSystem,w.WebGPUSystem],name:"graphicsContext"},sn.defaultOptions={bezierSmoothness:.5};let rn=sn;const Ip=8,Is=11920929e-14,Mp=1;function Tl(s,t,e,i,r,n,o,a,l,h){const u=Math.min(.99,Math.max(0,h??rn.defaultOptions.bezierSmoothness));let m=(Mp-u)/1;return m*=m,kp(t,e,i,r,n,o,a,l,s,m),s}function kp(s,t,e,i,r,n,o,a,l,h){nn(s,t,e,i,r,n,o,a,l,h,0),l.push(o,a)}function nn(s,t,e,i,r,n,o,a,l,h,c){if(c>Ip)return;const u=(s+e)/2,m=(t+i)/2,f=(e+r)/2,g=(i+n)/2,y=(r+o)/2,x=(n+a)/2,v=(u+f)/2,E=(m+g)/2,T=(f+y)/2,C=(g+x)/2,R=(v+T)/2,A=(E+C)/2;if(c>0){let I=o-s,N=a-t;const B=Math.abs((e-o)*N-(i-a)*I),k=Math.abs((r-o)*N-(n-a)*I);if(B>Is&&k>Is){if((B+k)*(B+k)<=h*(I*I+N*N)){l.push(R,A);return}}else if(B>Is){if(B*B<=h*(I*I+N*N)){l.push(R,A);return}}else if(k>Is){if(k*k<=h*(I*I+N*N)){l.push(R,A);return}}else if(I=R-(s+o)/2,N=A-(t+a)/2,I*I+N*N<=h){l.push(R,A);return}}nn(s,t,u,m,v,E,R,A,l,h,c+1),nn(R,A,T,C,y,x,o,a,l,h,c+1)}const Bp=8,Op=11920929e-14,Dp=1;function Gp(s,t,e,i,r,n,o,a){const h=Math.min(.99,Math.max(0,a??rn.defaultOptions.bezierSmoothness));let c=(Dp-h)/1;return c*=c,Up(t,e,i,r,n,o,s,c),s}function Up(s,t,e,i,r,n,o,a){on(o,s,t,e,i,r,n,a,0),o.push(r,n)}function on(s,t,e,i,r,n,o,a,l){if(l>Bp)return;const h=(t+i)/2,c=(e+r)/2,u=(i+n)/2,m=(r+o)/2,f=(h+u)/2,g=(c+m)/2;let y=n-t,x=o-e;const v=Math.abs((i-n)*x-(r-o)*y);if(v>Op){if(v*v<=a*(y*y+x*x)){s.push(f,g);return}}else if(y=f-(t+n)/2,x=g-(e+o)/2,y*y+x*x<=a){s.push(f,g);return}on(s,t,e,h,c,f,g,a,l+1),on(s,f,g,u,m,n,o,a,l+1)}function Sl(s,t,e,i,r,n,o,a){let l=Math.abs(r-n);(!o&&r>n||o&&n>r)&&(l=2*Math.PI-l),a||(a=Math.max(6,Math.floor(6*Math.pow(i,1/3)*(l/Math.PI)))),a=Math.max(a,3);let h=l/a,c=r;h*=o?-1:1;for(let u=0;u<a+1;u++){const m=Math.cos(c),f=Math.sin(c),g=t+m*i,y=e+f*i;s.push(g,y),c+=h}}function Lp(s,t,e,i,r,n){const o=s[s.length-2],l=s[s.length-1]-e,h=o-t,c=r-e,u=i-t,m=Math.abs(l*u-h*c);if(m<1e-8||n===0){(s[s.length-2]!==t||s[s.length-1]!==e)&&s.push(t,e);return}const f=l*l+h*h,g=c*c+u*u,y=l*c+h*u,x=n*Math.sqrt(f)/m,v=n*Math.sqrt(g)/m,E=x*y/f,T=v*y/g,C=x*u+v*h,R=x*c+v*l,A=h*(v+E),I=l*(v+E),N=u*(x+T),B=c*(x+T),k=Math.atan2(I-R,A-C),O=Math.atan2(B-R,N-C);Sl(s,C+t,R+e,n,k,O,h*c>u*l)}const ts=Math.PI*2,an={centerX:0,centerY:0,ang1:0,ang2:0},ln=({x:s,y:t},e,i,r,n,o,a,l)=>{s*=e,t*=i;const h=r*s-n*t,c=n*s+r*t;return l.x=h+o,l.y=c+a,l};function Fp(s,t){const e=t===-1.5707963267948966?-.551915024494:1.3333333333333333*Math.tan(t/4),i=t===1.5707963267948966?.551915024494:e,r=Math.cos(s),n=Math.sin(s),o=Math.cos(s+t),a=Math.sin(s+t);return[{x:r-n*i,y:n+r*i},{x:o+a*i,y:a-o*i},{x:o,y:a}]}const Cl=(s,t,e,i)=>{const r=s*i-t*e<0?-1:1;let n=s*e+t*i;return n>1&&(n=1),n<-1&&(n=-1),r*Math.acos(n)},Np=(s,t,e,i,r,n,o,a,l,h,c,u,m)=>{const f=Math.pow(r,2),g=Math.pow(n,2),y=Math.pow(c,2),x=Math.pow(u,2);let v=f*g-f*x-g*y;v<0&&(v=0),v/=f*x+g*y,v=Math.sqrt(v)*(o===a?-1:1);const E=v*r/n*u,T=v*-n/r*c,C=h*E-l*T+(s+e)/2,R=l*E+h*T+(t+i)/2,A=(c-E)/r,I=(u-T)/n,N=(-c-E)/r,B=(-u-T)/n,k=Cl(1,0,A,I);let O=Cl(A,I,N,B);a===0&&O>0&&(O-=ts),a===1&&O<0&&(O+=ts),m.centerX=C,m.centerY=R,m.ang1=k,m.ang2=O};function Hp(s,t,e,i,r,n,o,a=0,l=0,h=0){if(n===0||o===0)return;const c=Math.sin(a*ts/360),u=Math.cos(a*ts/360),m=u*(t-i)/2+c*(e-r)/2,f=-c*(t-i)/2+u*(e-r)/2;if(m===0&&f===0)return;n=Math.abs(n),o=Math.abs(o);const g=Math.pow(m,2)/Math.pow(n,2)+Math.pow(f,2)/Math.pow(o,2);g>1&&(n*=Math.sqrt(g),o*=Math.sqrt(g)),Np(t,e,i,r,n,o,l,h,c,u,m,f,an);let{ang1:y,ang2:x}=an;const{centerX:v,centerY:E}=an;let T=Math.abs(x)/(ts/4);Math.abs(1-T)<1e-7&&(T=1);const C=Math.max(Math.ceil(T),1);x/=C;let R=s[s.length-2],A=s[s.length-1];const I={x:0,y:0};for(let N=0;N<C;N++){const B=Fp(y,x),{x:k,y:O}=ln(B[0],n,o,u,c,v,E,I),{x:L,y:F}=ln(B[1],n,o,u,c,v,E,I),{x:H,y:at}=ln(B[2],n,o,u,c,v,E,I);Tl(s,R,A,k,O,L,F,H,at),R=H,A=at,y+=x}}function Wp(s,t,e){const i=(o,a)=>{const l=a.x-o.x,h=a.y-o.y,c=Math.sqrt(l*l+h*h),u=l/c,m=h/c;return{len:c,nx:u,ny:m}},r=(o,a)=>{o===0?s.moveTo(a.x,a.y):s.lineTo(a.x,a.y)};let n=t[t.length-1];for(let o=0;o<t.length;o++){const a=t[o%t.length],l=a.radius??e;if(l<=0){r(o,a),n=a;continue}const h=t[(o+1)%t.length],c=i(a,n),u=i(a,h);if(c.len<1e-4||u.len<1e-4){r(o,a),n=a;continue}let m=Math.asin(c.nx*u.ny-c.ny*u.nx),f=1,g=!1;c.nx*u.nx-c.ny*-u.ny<0?m<0?m=Math.PI+m:(m=Math.PI-m,f=-1,g=!0):m>0&&(f=-1,g=!0);const y=m/2;let x,v=Math.abs(Math.cos(y)*l/Math.sin(y));v>Math.min(c.len/2,u.len/2)?(v=Math.min(c.len/2,u.len/2),x=Math.abs(v*Math.sin(y)/Math.cos(y))):x=l;const E=a.x+u.nx*v+-u.ny*x*f,T=a.y+u.ny*v+u.nx*x*f,C=Math.atan2(c.ny,c.nx)+Math.PI/2*f,R=Math.atan2(u.ny,u.nx)-Math.PI/2*f;o===0&&s.moveTo(E+Math.cos(C)*x,T+Math.sin(C)*x),s.arc(E,T,x,C,R,g),n=a}}function Vp(s,t,e,i){const r=(a,l)=>Math.sqrt((a.x-l.x)**2+(a.y-l.y)**2),n=(a,l,h)=>({x:a.x+(l.x-a.x)*h,y:a.y+(l.y-a.y)*h}),o=t.length;for(let a=0;a<o;a++){const l=t[(a+1)%o],h=l.radius??e;if(h<=0){a===0?s.moveTo(l.x,l.y):s.lineTo(l.x,l.y);continue}const c=t[a],u=t[(a+2)%o],m=r(c,l);let f;if(m<1e-4)f=l;else{const x=Math.min(m/2,h);f=n(l,c,x/m)}const g=r(u,l);let y;if(g<1e-4)y=l;else{const x=Math.min(g/2,h);y=n(l,u,x/g)}a===0?s.moveTo(f.x,f.y):s.lineTo(f.x,f.y),s.quadraticCurveTo(l.x,l.y,y.x,y.y,i)}}const zp=new ut;class $p{constructor(t){this.shapePrimitives=[],this._currentPoly=null,this._bounds=new Lt,this._graphicsPath2D=t,this.signed=t.checkForHoles}moveTo(t,e){return this.startPoly(t,e),this}lineTo(t,e){this._ensurePoly();const i=this._currentPoly.points,r=i[i.length-2],n=i[i.length-1];return(r!==t||n!==e)&&i.push(t,e),this}arc(t,e,i,r,n,o){this._ensurePoly(!1);const a=this._currentPoly.points;return Sl(a,t,e,i,r,n,o),this}arcTo(t,e,i,r,n){this._ensurePoly();const o=this._currentPoly.points;return Lp(o,t,e,i,r,n),this}arcToSvg(t,e,i,r,n,o,a){const l=this._currentPoly.points;return Hp(l,this._currentPoly.lastX,this._currentPoly.lastY,o,a,t,e,i,r,n),this}bezierCurveTo(t,e,i,r,n,o,a){this._ensurePoly();const l=this._currentPoly;return Tl(this._currentPoly.points,l.lastX,l.lastY,t,e,i,r,n,o,a),this}quadraticCurveTo(t,e,i,r,n){this._ensurePoly();const o=this._currentPoly;return Gp(this._currentPoly.points,o.lastX,o.lastY,t,e,i,r,n),this}closePath(){return this.endPoly(!0),this}addPath(t,e){this.endPoly(),e&&!e.isIdentity()&&(t=t.clone(!0),t.transform(e));const i=this.shapePrimitives,r=i.length;for(let n=0;n<t.instructions.length;n++){const o=t.instructions[n];this[o.action](...o.data)}if(t.checkForHoles&&i.length-r>1){let n=null;for(let o=r;o<i.length;o++){const a=i[o];if(a.shape.type==="polygon"){const l=a.shape,h=n==null?void 0:n.shape;h&&h.containsPolygon(l)?(n.holes||(n.holes=[]),n.holes.push(a),i.copyWithin(o,o+1),i.length--,o--):n=a}}}return this}finish(t=!1){this.endPoly(t)}rect(t,e,i,r,n){return this.drawShape(new ut(t,e,i,r),n),this}circle(t,e,i,r){return this.drawShape(new Nr(t,e,i),r),this}poly(t,e,i){const r=new Yi(t);return r.closePath=e,this.drawShape(r,i),this}regularPoly(t,e,i,r,n=0,o){r=Math.max(r|0,3);const a=-1*Math.PI/2+n,l=Math.PI*2/r,h=[];for(let c=0;c<r;c++){const u=a-c*l;h.push(t+i*Math.cos(u),e+i*Math.sin(u))}return this.poly(h,!0,o),this}roundPoly(t,e,i,r,n,o=0,a){if(r=Math.max(r|0,3),n<=0)return this.regularPoly(t,e,i,r,o);const l=i*Math.sin(Math.PI/r)-.001;n=Math.min(n,l);const h=-1*Math.PI/2+o,c=Math.PI*2/r,u=(r-2)*Math.PI/r/2;for(let m=0;m<r;m++){const f=m*c+h,g=t+i*Math.cos(f),y=e+i*Math.sin(f),x=f+Math.PI+u,v=f-Math.PI-u,E=g+n*Math.cos(x),T=y+n*Math.sin(x),C=g+n*Math.cos(v),R=y+n*Math.sin(v);m===0?this.moveTo(E,T):this.lineTo(E,T),this.quadraticCurveTo(g,y,C,R,a)}return this.closePath()}roundShape(t,e,i=!1,r){return t.length<3?this:(i?Vp(this,t,e,r):Wp(this,t,e),this.closePath())}filletRect(t,e,i,r,n){if(n===0)return this.rect(t,e,i,r);const o=Math.min(i,r)/2,a=Math.min(o,Math.max(-o,n)),l=t+i,h=e+r,c=a<0?-a:0,u=Math.abs(a);return this.moveTo(t,e+u).arcTo(t+c,e+c,t+u,e,u).lineTo(l-u,e).arcTo(l-c,e+c,l,e+u,u).lineTo(l,h-u).arcTo(l-c,h-c,t+i-u,h,u).lineTo(t+u,h).arcTo(t+c,h-c,t,h-u,u).closePath()}chamferRect(t,e,i,r,n,o){if(n<=0)return this.rect(t,e,i,r);const a=Math.min(n,Math.min(i,r)/2),l=t+i,h=e+r,c=[t+a,e,l-a,e,l,e+a,l,h-a,l-a,h,t+a,h,t,h-a,t,e+a];for(let u=c.length-1;u>=2;u-=2)c[u]===c[u-2]&&c[u-1]===c[u-3]&&c.splice(u-1,2);return this.poly(c,!0,o)}ellipse(t,e,i,r,n){return this.drawShape(new Hr(t,e,i,r),n),this}roundRect(t,e,i,r,n,o){return this.drawShape(new Wr(t,e,i,r,n),o),this}drawShape(t,e){return this.endPoly(),this.shapePrimitives.push({shape:t,transform:e}),this}startPoly(t,e){let i=this._currentPoly;return i&&this.endPoly(),i=new Yi,i.points.push(t,e),this._currentPoly=i,this}endPoly(t=!1){const e=this._currentPoly;return e&&e.points.length>2&&(e.closePath=t,this.shapePrimitives.push({shape:e})),this._currentPoly=null,this}_ensurePoly(t=!0){if(!this._currentPoly&&(this._currentPoly=new Yi,t)){const e=this.shapePrimitives[this.shapePrimitives.length-1];if(e){let i=e.shape.x,r=e.shape.y;if(e.transform&&!e.transform.isIdentity()){const n=e.transform,o=i;i=n.a*i+n.c*r+n.tx,r=n.b*o+n.d*r+n.ty}this._currentPoly.points.push(i,r)}else this._currentPoly.points.push(0,0)}}buildPath(){const t=this._graphicsPath2D;this.shapePrimitives.length=0,this._currentPoly=null;for(let e=0;e<t.instructions.length;e++){const i=t.instructions[e];this[i.action](...i.data)}this.finish()}get bounds(){const t=this._bounds;t.clear();const e=this.shapePrimitives;for(let i=0;i<e.length;i++){const r=e[i],n=r.shape.getBounds(zp);r.transform?t.addRect(n,r.transform):t.addRect(n)}return t}}class Ee{constructor(t,e=!1){this.instructions=[],this.uid=dt("graphicsPath"),this._dirty=!0,this.checkForHoles=e,typeof t=="string"?Pf(t,this):this.instructions=(t==null?void 0:t.slice())??[]}get shapePath(){return this._shapePath||(this._shapePath=new $p(this)),this._dirty&&(this._dirty=!1,this._shapePath.buildPath()),this._shapePath}addPath(t,e){return t=t.clone(),this.instructions.push({action:"addPath",data:[t,e]}),this._dirty=!0,this}arc(...t){return this.instructions.push({action:"arc",data:t}),this._dirty=!0,this}arcTo(...t){return this.instructions.push({action:"arcTo",data:t}),this._dirty=!0,this}arcToSvg(...t){return this.instructions.push({action:"arcToSvg",data:t}),this._dirty=!0,this}bezierCurveTo(...t){return this.instructions.push({action:"bezierCurveTo",data:t}),this._dirty=!0,this}bezierCurveToShort(t,e,i,r,n){const o=this.instructions[this.instructions.length-1],a=this.getLastPoint(mt.shared);let l=0,h=0;if(!o||o.action!=="bezierCurveTo")l=a.x,h=a.y;else{l=o.data[2],h=o.data[3];const c=a.x,u=a.y;l=c+(c-l),h=u+(u-h)}return this.instructions.push({action:"bezierCurveTo",data:[l,h,t,e,i,r,n]}),this._dirty=!0,this}closePath(){return this.instructions.push({action:"closePath",data:[]}),this._dirty=!0,this}ellipse(...t){return this.instructions.push({action:"ellipse",data:t}),this._dirty=!0,this}lineTo(...t){return this.instructions.push({action:"lineTo",data:t}),this._dirty=!0,this}moveTo(...t){return this.instructions.push({action:"moveTo",data:t}),this}quadraticCurveTo(...t){return this.instructions.push({action:"quadraticCurveTo",data:t}),this._dirty=!0,this}quadraticCurveToShort(t,e,i){const r=this.instructions[this.instructions.length-1],n=this.getLastPoint(mt.shared);let o=0,a=0;if(!r||r.action!=="quadraticCurveTo")o=n.x,a=n.y;else{o=r.data[0],a=r.data[1];const l=n.x,h=n.y;o=l+(l-o),a=h+(h-a)}return this.instructions.push({action:"quadraticCurveTo",data:[o,a,t,e,i]}),this._dirty=!0,this}rect(t,e,i,r,n){return this.instructions.push({action:"rect",data:[t,e,i,r,n]}),this._dirty=!0,this}circle(t,e,i,r){return this.instructions.push({action:"circle",data:[t,e,i,r]}),this._dirty=!0,this}roundRect(...t){return this.instructions.push({action:"roundRect",data:t}),this._dirty=!0,this}poly(...t){return this.instructions.push({action:"poly",data:t}),this._dirty=!0,this}regularPoly(...t){return this.instructions.push({action:"regularPoly",data:t}),this._dirty=!0,this}roundPoly(...t){return this.instructions.push({action:"roundPoly",data:t}),this._dirty=!0,this}roundShape(...t){return this.instructions.push({action:"roundShape",data:t}),this._dirty=!0,this}filletRect(...t){return this.instructions.push({action:"filletRect",data:t}),this._dirty=!0,this}chamferRect(...t){return this.instructions.push({action:"chamferRect",data:t}),this._dirty=!0,this}star(t,e,i,r,n,o,a){n||(n=r/2);const l=-1*Math.PI/2+o,h=i*2,c=Math.PI*2/h,u=[];for(let m=0;m<h;m++){const f=m%2?n:r,g=m*c+l;u.push(t+f*Math.cos(g),e+f*Math.sin(g))}return this.poly(u,!0,a),this}clone(t=!1){const e=new Ee;if(e.checkForHoles=this.checkForHoles,!t)e.instructions=this.instructions.slice();else for(let i=0;i<this.instructions.length;i++){const r=this.instructions[i];e.instructions.push({action:r.action,data:r.data.slice()})}return e}clear(){return this.instructions.length=0,this._dirty=!0,this}transform(t){if(t.isIdentity())return this;const e=t.a,i=t.b,r=t.c,n=t.d,o=t.tx,a=t.ty;let l=0,h=0,c=0,u=0,m=0,f=0,g=0,y=0;for(let x=0;x<this.instructions.length;x++){const v=this.instructions[x],E=v.data;switch(v.action){case"moveTo":case"lineTo":l=E[0],h=E[1],E[0]=e*l+r*h+o,E[1]=i*l+n*h+a;break;case"bezierCurveTo":c=E[0],u=E[1],m=E[2],f=E[3],l=E[4],h=E[5],E[0]=e*c+r*u+o,E[1]=i*c+n*u+a,E[2]=e*m+r*f+o,E[3]=i*m+n*f+a,E[4]=e*l+r*h+o,E[5]=i*l+n*h+a;break;case"quadraticCurveTo":c=E[0],u=E[1],l=E[2],h=E[3],E[0]=e*c+r*u+o,E[1]=i*c+n*u+a,E[2]=e*l+r*h+o,E[3]=i*l+n*h+a;break;case"arcToSvg":l=E[5],h=E[6],g=E[0],y=E[1],E[0]=e*g+r*y,E[1]=i*g+n*y,E[5]=e*l+r*h+o,E[6]=i*l+n*h+a;break;case"circle":E[4]=es(E[3],t);break;case"rect":E[4]=es(E[4],t);break;case"ellipse":E[8]=es(E[8],t);break;case"roundRect":E[5]=es(E[5],t);break;case"addPath":E[0].transform(t);break;case"poly":E[2]=es(E[2],t);break;default:tt("unknown transform action",v.action);break}}return this._dirty=!0,this}get bounds(){return this.shapePath.bounds}getLastPoint(t){let e=this.instructions.length-1,i=this.instructions[e];if(!i)return t.x=0,t.y=0,t;for(;i.action==="closePath";){if(e--,e<0)return t.x=0,t.y=0,t;i=this.instructions[e]}switch(i.action){case"moveTo":case"lineTo":t.x=i.data[0],t.y=i.data[1];break;case"quadraticCurveTo":t.x=i.data[2],t.y=i.data[3];break;case"bezierCurveTo":t.x=i.data[4],t.y=i.data[5];break;case"arc":case"arcToSvg":t.x=i.data[5],t.y=i.data[6];break;case"addPath":i.data[0].getLastPoint(t);break}return t}}function es(s,t){return s?s.prepend(t):t.clone()}function Tt(s,t,e){const i=s.getAttribute(t);return i?Number(i):e}function jp(s,t){const e=s.querySelectorAll("defs");for(let i=0;i<e.length;i++){const r=e[i];for(let n=0;n<r.children.length;n++){const o=r.children[n];switch(o.nodeName.toLowerCase()){case"lineargradient":t.defs[o.id]=Xp(o);break;case"radialgradient":t.defs[o.id]=Yp();break}}}}function Xp(s){const t=Tt(s,"x1",0),e=Tt(s,"y1",0),i=Tt(s,"x2",1),r=Tt(s,"y2",0),n=s.getAttribute("gradientUnits")||"objectBoundingBox",o=new de(t,e,i,r,n==="objectBoundingBox"?"local":"global");for(let a=0;a<s.children.length;a++){const l=s.children[a],h=Tt(l,"offset",0),c=ct.shared.setValue(l.getAttribute("stop-color")).toNumber();o.addColorStop(h,c)}return o}function Yp(s){return tt("[SVG Parser] Radial gradients are not yet supported"),new de(0,0,1,0)}function wl(s){const t=s.match(/url\s*\(\s*['"]?\s*#([^'"\s)]+)\s*['"]?\s*\)/i);return t?t[1]:""}const Al={fill:{type:"paint",default:0},"fill-opacity":{type:"number",default:1},stroke:{type:"paint",default:0},"stroke-width":{type:"number",default:1},"stroke-opacity":{type:"number",default:1},"stroke-linecap":{type:"string",default:"butt"},"stroke-linejoin":{type:"string",default:"miter"},"stroke-miterlimit":{type:"number",default:10},"stroke-dasharray":{type:"string",default:"none"},"stroke-dashoffset":{type:"number",default:0},opacity:{type:"number",default:1}};function Rl(s,t){const e=s.getAttribute("style"),i={},r={},n={strokeStyle:i,fillStyle:r,useFill:!1,useStroke:!1};for(const o in Al){const a=s.getAttribute(o);a&&Pl(t,n,o,a.trim())}if(e){const o=e.split(";");for(let a=0;a<o.length;a++){const l=o[a].trim(),[h,c]=l.split(":");Al[h]&&Pl(t,n,h,c.trim())}}return{strokeStyle:n.useStroke?i:null,fillStyle:n.useFill?r:null,useFill:n.useFill,useStroke:n.useStroke}}function Pl(s,t,e,i){switch(e){case"stroke":if(i!=="none"){if(i.startsWith("url(")){const r=wl(i);t.strokeStyle.fill=s.defs[r]}else t.strokeStyle.color=ct.shared.setValue(i).toNumber();t.useStroke=!0}break;case"stroke-width":t.strokeStyle.width=Number(i);break;case"fill":if(i!=="none"){if(i.startsWith("url(")){const r=wl(i);t.fillStyle.fill=s.defs[r]}else t.fillStyle.color=ct.shared.setValue(i).toNumber();t.useFill=!0}break;case"fill-opacity":t.fillStyle.alpha=Number(i);break;case"stroke-opacity":t.strokeStyle.alpha=Number(i);break;case"opacity":t.fillStyle.alpha=Number(i),t.strokeStyle.alpha=Number(i);break}}function qp(s){if(s.length<=2)return!0;const t=s.map(a=>a.area).sort((a,l)=>l-a),[e,i]=t,r=t[t.length-1],n=e/i,o=i/r;return!(n>3&&o<2)}function Kp(s){return s.split(/(?=[Mm])/).filter(i=>i.trim().length>0)}function Zp(s){const t=s.match(/[-+]?[0-9]*\.?[0-9]+/g);if(!t||t.length<4)return 0;const e=t.map(Number),i=[],r=[];for(let c=0;c<e.length;c+=2)c+1<e.length&&(i.push(e[c]),r.push(e[c+1]));if(i.length===0||r.length===0)return 0;const n=Math.min(...i),o=Math.max(...i),a=Math.min(...r),l=Math.max(...r);return(o-n)*(l-a)}function Il(s,t){const e=new Ee(s,!1);for(const i of e.instructions)t.instructions.push(i)}function Jp(s,t){if(typeof s=="string"){const o=document.createElement("div");o.innerHTML=s.trim(),s=o.querySelector("svg")}const e={context:t,defs:{},path:new Ee};jp(s,e);const i=s.children,{fillStyle:r,strokeStyle:n}=Rl(s,e);for(let o=0;o<i.length;o++){const a=i[o];a.nodeName.toLowerCase()!=="defs"&&Ml(a,e,r,n)}return t}function Ml(s,t,e,i){const r=s.children,{fillStyle:n,strokeStyle:o}=Rl(s,t);n&&e?e={...e,...n}:n&&(e=n),o&&i?i={...i,...o}:o&&(i=o);const a=!e&&!i;a&&(e={color:0});let l,h,c,u,m,f,g,y,x,v,E,T,C,R,A,I,N;switch(s.nodeName.toLowerCase()){case"path":{R=s.getAttribute("d");const B=s.getAttribute("fill-rule"),k=Kp(R),O=B==="evenodd",L=k.length>1;if(O&&L){const H=k.map(G=>({path:G,area:Zp(G)}));if(H.sort((G,U)=>U.area-G.area),k.length>3||!qp(H))for(let G=0;G<H.length;G++){const U=H[G],X=G===0;t.context.beginPath();const D=new Ee(void 0,!0);Il(U.path,D),t.context.path(D),X?(e&&t.context.fill(e),i&&t.context.stroke(i)):t.context.cut()}else for(let G=0;G<H.length;G++){const U=H[G],X=G%2===1;t.context.beginPath();const D=new Ee(void 0,!0);Il(U.path,D),t.context.path(D),X?t.context.cut():(e&&t.context.fill(e),i&&t.context.stroke(i))}}else{const H=B?B==="evenodd":!0;A=new Ee(R,H),t.context.path(A),e&&t.context.fill(e),i&&t.context.stroke(i)}break}case"circle":g=Tt(s,"cx",0),y=Tt(s,"cy",0),x=Tt(s,"r",0),t.context.ellipse(g,y,x,x),e&&t.context.fill(e),i&&t.context.stroke(i);break;case"rect":l=Tt(s,"x",0),h=Tt(s,"y",0),I=Tt(s,"width",0),N=Tt(s,"height",0),v=Tt(s,"rx",0),E=Tt(s,"ry",0),v||E?t.context.roundRect(l,h,I,N,v||E):t.context.rect(l,h,I,N),e&&t.context.fill(e),i&&t.context.stroke(i);break;case"ellipse":g=Tt(s,"cx",0),y=Tt(s,"cy",0),v=Tt(s,"rx",0),E=Tt(s,"ry",0),t.context.beginPath(),t.context.ellipse(g,y,v,E),e&&t.context.fill(e),i&&t.context.stroke(i);break;case"line":c=Tt(s,"x1",0),u=Tt(s,"y1",0),m=Tt(s,"x2",0),f=Tt(s,"y2",0),t.context.beginPath(),t.context.moveTo(c,u),t.context.lineTo(m,f),i&&t.context.stroke(i);break;case"polygon":C=s.getAttribute("points"),T=C.match(/-?\d+/g).map(B=>parseInt(B,10)),t.context.poly(T,!0),e&&t.context.fill(e),i&&t.context.stroke(i);break;case"polyline":C=s.getAttribute("points"),T=C.match(/-?\d+/g).map(B=>parseInt(B,10)),t.context.poly(T,!1),i&&t.context.stroke(i);break;case"g":case"svg":break;default:{tt(`[SVG parser] <${s.nodeName}> elements unsupported`);break}}a&&(e=null);for(let B=0;B<r.length;B++)Ml(r[B],t,e,i)}const kl={repeat:{addressModeU:"repeat",addressModeV:"repeat"},"repeat-x":{addressModeU:"repeat",addressModeV:"clamp-to-edge"},"repeat-y":{addressModeU:"clamp-to-edge",addressModeV:"repeat"},"no-repeat":{addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}};class is{constructor(t,e){this.uid=dt("fillPattern"),this._tick=0,this.transform=new W,this.texture=t,this.transform.scale(1/t.frame.width,1/t.frame.height),e&&(t.source.style.addressModeU=kl[e].addressModeU,t.source.style.addressModeV=kl[e].addressModeV)}setTransform(t){const e=this.texture;this.transform.copyFrom(t),this.transform.invert(),this.transform.scale(1/e.frame.width,1/e.frame.height),this._tick++}get texture(){return this._texture}set texture(t){this._texture!==t&&(this._texture=t,this._tick++)}get styleKey(){return`fill-pattern-${this.uid}-${this._tick}`}destroy(){this.texture.destroy(!0),this.texture=null}}function Qp(s){return ct.isColorLike(s)}function Bl(s){return s instanceof is}function Ol(s){return s instanceof de}function tm(s){return s instanceof z}function em(s,t,e){const i=ct.shared.setValue(t??0);return s.color=i.toNumber(),s.alpha=i.alpha===1?e.alpha:i.alpha,s.texture=z.WHITE,{...e,...s}}function im(s,t,e){return s.texture=t,{...e,...s}}function Dl(s,t,e){return s.fill=t,s.color=16777215,s.texture=t.texture,s.matrix=t.transform,{...e,...s}}function Gl(s,t,e){return t.buildGradient(),s.fill=t,s.color=16777215,s.texture=t.texture,s.matrix=t.transform,s.textureSpace=t.textureSpace,{...e,...s}}function sm(s,t){const e={...t,...s},i=ct.shared.setValue(e.color);return e.alpha*=i.alpha,e.color=i.toNumber(),e}function Qe(s,t){if(s==null)return null;const e={},i=s;return Qp(s)?em(e,s,t):tm(s)?im(e,s,t):Bl(s)?Dl(e,s,t):Ol(s)?Gl(e,s,t):i.fill&&Bl(i.fill)?Dl(i,i.fill,t):i.fill&&Ol(i.fill)?Gl(i,i.fill,t):sm(i,t)}function Ms(s,t){const{width:e,alignment:i,miterLimit:r,cap:n,join:o,pixelLine:a,...l}=t,h=Qe(s,l);return h?{width:e,alignment:i,miterLimit:r,cap:n,join:o,pixelLine:a,...h}:null}function rm(s,t){let e=1;const i=s.shapePath.shapePrimitives;for(let r=0;r<i.length;r++){const n=i[r].shape;if(n.type!=="polygon")continue;const o=n.points,a=o.length;if(a<6)continue;const l=n.closePath;for(let h=0;h<a;h+=2){if(!l&&(h===0||h===a-2))continue;const c=(h-2+a)%a,u=(h+2)%a,m=o[c],f=o[c+1],g=o[h],y=o[h+1],x=o[u],v=o[u+1],E=m-g,T=f-y,C=x-g,R=v-y,A=E*E+T*T,I=C*C+R*R;if(A<1e-12||I<1e-12)continue;let k=(E*C+T*R)/Math.sqrt(A*I);k<-1?k=-1:k>1&&(k=1);const O=Math.sqrt((1-k)*.5);if(O<1e-6)continue;const L=Math.min(1/O,t);L>e&&(e=L)}}return e}const nm=new mt,Ul=new W,hn=class me extends Jt{constructor(){super(...arguments),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=dt("graphicsContext"),this.dirty=!0,this.batchMode="auto",this.instructions=[],this.destroyed=!1,this._activePath=new Ee,this._transform=new W,this._fillStyle={...me.defaultFillStyle},this._strokeStyle={...me.defaultStrokeStyle},this._stateStack=[],this._tick=0,this._bounds=new Lt,this._boundsDirty=!0}clone(){const t=new me;return t.batchMode=this.batchMode,t.instructions=this.instructions.slice(),t._activePath=this._activePath.clone(),t._transform=this._transform.clone(),t._fillStyle={...this._fillStyle},t._strokeStyle={...this._strokeStyle},t._stateStack=this._stateStack.slice(),t._bounds=this._bounds.clone(),t._boundsDirty=!0,t}get fillStyle(){return this._fillStyle}set fillStyle(t){this._fillStyle=Qe(t,me.defaultFillStyle)}get strokeStyle(){return this._strokeStyle}set strokeStyle(t){this._strokeStyle=Ms(t,me.defaultStrokeStyle)}setFillStyle(t){return this._fillStyle=Qe(t,me.defaultFillStyle),this}setStrokeStyle(t){return this._strokeStyle=Qe(t,me.defaultStrokeStyle),this}texture(t,e,i,r,n,o){return this.instructions.push({action:"texture",data:{image:t,dx:i||0,dy:r||0,dw:n||t.frame.width,dh:o||t.frame.height,transform:this._transform.clone(),alpha:this._fillStyle.alpha,style:e||e===0?ct.shared.setValue(e).toNumber():16777215}}),this.onUpdate(),this}beginPath(){return this._activePath=new Ee,this}fill(t,e){let i;const r=this.instructions[this.instructions.length-1];return this._tick===0&&(r==null?void 0:r.action)==="stroke"?i=r.data.path:i=this._activePath.clone(),i?(t!=null&&(e!==void 0&&typeof t=="number"&&(K(vt,"GraphicsContext.fill(color, alpha) is deprecated, use GraphicsContext.fill({ color, alpha }) instead"),t={color:t,alpha:e}),this._fillStyle=Qe(t,me.defaultFillStyle)),this.instructions.push({action:"fill",data:{style:this.fillStyle,path:i}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}_initNextPathLocation(){const{x:t,y:e}=this._activePath.getLastPoint(mt.shared);this._activePath.clear(),this._activePath.moveTo(t,e)}stroke(t){let e;const i=this.instructions[this.instructions.length-1];return this._tick===0&&(i==null?void 0:i.action)==="fill"?e=i.data.path:e=this._activePath.clone(),e?(t!=null&&(this._strokeStyle=Ms(t,me.defaultStrokeStyle)),this.instructions.push({action:"stroke",data:{style:this.strokeStyle,path:e}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}cut(){for(let t=0;t<2;t++){const e=this.instructions[this.instructions.length-1-t],i=this._activePath.clone();if(e&&(e.action==="stroke"||e.action==="fill"))if(e.data.hole)e.data.hole.addPath(i);else{e.data.hole=i;break}}return this._initNextPathLocation(),this}arc(t,e,i,r,n,o){this._tick++;const a=this._transform;return this._activePath.arc(a.a*t+a.c*e+a.tx,a.b*t+a.d*e+a.ty,i,r,n,o),this}arcTo(t,e,i,r,n){this._tick++;const o=this._transform;return this._activePath.arcTo(o.a*t+o.c*e+o.tx,o.b*t+o.d*e+o.ty,o.a*i+o.c*r+o.tx,o.b*i+o.d*r+o.ty,n),this}arcToSvg(t,e,i,r,n,o,a){this._tick++;const l=this._transform;return this._activePath.arcToSvg(t,e,i,r,n,l.a*o+l.c*a+l.tx,l.b*o+l.d*a+l.ty),this}bezierCurveTo(t,e,i,r,n,o,a){this._tick++;const l=this._transform;return this._activePath.bezierCurveTo(l.a*t+l.c*e+l.tx,l.b*t+l.d*e+l.ty,l.a*i+l.c*r+l.tx,l.b*i+l.d*r+l.ty,l.a*n+l.c*o+l.tx,l.b*n+l.d*o+l.ty,a),this}closePath(){var t;return this._tick++,(t=this._activePath)==null||t.closePath(),this}ellipse(t,e,i,r){return this._tick++,this._activePath.ellipse(t,e,i,r,this._transform.clone()),this}circle(t,e,i){return this._tick++,this._activePath.circle(t,e,i,this._transform.clone()),this}path(t){return this._tick++,this._activePath.addPath(t,this._transform.clone()),this}lineTo(t,e){this._tick++;const i=this._transform;return this._activePath.lineTo(i.a*t+i.c*e+i.tx,i.b*t+i.d*e+i.ty),this}moveTo(t,e){this._tick++;const i=this._transform,r=this._activePath.instructions,n=i.a*t+i.c*e+i.tx,o=i.b*t+i.d*e+i.ty;return r.length===1&&r[0].action==="moveTo"?(r[0].data[0]=n,r[0].data[1]=o,this):(this._activePath.moveTo(n,o),this)}quadraticCurveTo(t,e,i,r,n){this._tick++;const o=this._transform;return this._activePath.quadraticCurveTo(o.a*t+o.c*e+o.tx,o.b*t+o.d*e+o.ty,o.a*i+o.c*r+o.tx,o.b*i+o.d*r+o.ty,n),this}rect(t,e,i,r){return this._tick++,this._activePath.rect(t,e,i,r,this._transform.clone()),this}roundRect(t,e,i,r,n){return this._tick++,this._activePath.roundRect(t,e,i,r,n,this._transform.clone()),this}poly(t,e){return this._tick++,this._activePath.poly(t,e,this._transform.clone()),this}regularPoly(t,e,i,r,n=0,o){return this._tick++,this._activePath.regularPoly(t,e,i,r,n,o),this}roundPoly(t,e,i,r,n,o){return this._tick++,this._activePath.roundPoly(t,e,i,r,n,o),this}roundShape(t,e,i,r){return this._tick++,this._activePath.roundShape(t,e,i,r),this}filletRect(t,e,i,r,n){return this._tick++,this._activePath.filletRect(t,e,i,r,n),this}chamferRect(t,e,i,r,n,o){return this._tick++,this._activePath.chamferRect(t,e,i,r,n,o),this}star(t,e,i,r,n=0,o=0){return this._tick++,this._activePath.star(t,e,i,r,n,o,this._transform.clone()),this}svg(t){return this._tick++,Jp(t,this),this}restore(){const t=this._stateStack.pop();return t&&(this._transform=t.transform,this._fillStyle=t.fillStyle,this._strokeStyle=t.strokeStyle),this}save(){return this._stateStack.push({transform:this._transform.clone(),fillStyle:{...this._fillStyle},strokeStyle:{...this._strokeStyle}}),this}getTransform(){return this._transform}resetTransform(){return this._transform.identity(),this}rotate(t){return this._transform.rotate(t),this}scale(t,e=t){return this._transform.scale(t,e),this}setTransform(t,e,i,r,n,o){return t instanceof W?(this._transform.set(t.a,t.b,t.c,t.d,t.tx,t.ty),this):(this._transform.set(t,e,i,r,n,o),this)}transform(t,e,i,r,n,o){return t instanceof W?(this._transform.append(t),this):(Ul.set(t,e,i,r,n,o),this._transform.append(Ul),this)}translate(t,e=t){return this._transform.translate(t,e),this}clear(){return this._activePath.clear(),this.instructions.length=0,this.resetTransform(),this.onUpdate(),this}onUpdate(){this._boundsDirty=!0,this.dirty=!0,this.emit("update",this,16)}get bounds(){if(!this._boundsDirty)return this._bounds;this._boundsDirty=!1;const t=this._bounds;t.clear();for(let e=0;e<this.instructions.length;e++){const i=this.instructions[e],r=i.action;if(r==="fill"){const n=i.data;t.addBounds(n.path.bounds)}else if(r==="texture"){const n=i.data;t.addFrame(n.dx,n.dy,n.dx+n.dw,n.dy+n.dh,n.transform)}if(r==="stroke"){const n=i.data,o=n.style.alignment;let a=n.style.width*(1-o);n.style.join==="miter"&&(a*=rm(n.path,n.style.miterLimit));const l=n.path.bounds;t.addFrame(l.minX-a,l.minY-a,l.maxX+a,l.maxY+a)}}return t.isValid||t.set(0,0,0,0),t}containsPoint(t){var r;if(!this.bounds.containsPoint(t.x,t.y))return!1;const e=this.instructions;let i=!1;for(let n=0;n<e.length;n++){const o=e[n],a=o.data,l=a.path;if(!o.action||!l)continue;const h=a.style,c=l.shapePath.shapePrimitives;for(let u=0;u<c.length;u++){const m=c[u].shape;if(!h||!m)continue;const f=c[u].transform,g=f?f.applyInverse(t,nm):t;if(o.action==="fill")i=m.contains(g.x,g.y);else{const x=h;i=m.strokeContains(g.x,g.y,x.width,x.alignment)}const y=a.hole;if(y){const x=(r=y.shapePath)==null?void 0:r.shapePrimitives;if(x)for(let v=0;v<x.length;v++)x[v].shape.contains(g.x,g.y)&&(i=!1)}if(i)return!0}}return i}unload(){var t;this.emit("unload",this);for(const e in this._gpuData)(t=this._gpuData[e])==null||t.destroy();this._gpuData=Object.create(null)}destroy(t=!1){if(this.destroyed)return;if(this.destroyed=!0,this._stateStack.length=0,this._transform=null,this.unload(),this.emit("destroy",this),this.removeAllListeners(),typeof t=="boolean"?t:t==null?void 0:t.texture){const i=typeof t=="boolean"?t:t==null?void 0:t.textureSource;this._fillStyle.texture&&(this._fillStyle.fill&&"uid"in this._fillStyle.fill?this._fillStyle.fill.destroy():this._fillStyle.texture.destroy(i)),this._strokeStyle.texture&&(this._strokeStyle.fill&&"uid"in this._strokeStyle.fill?this._strokeStyle.fill.destroy():this._strokeStyle.texture.destroy(i))}this._fillStyle=null,this._strokeStyle=null,this.instructions=null,this._activePath=null,this._bounds=null,this._stateStack=null,this.customShader=null,this._transform=null}};hn.defaultFillStyle={color:16777215,alpha:1,texture:z.WHITE,matrix:null,fill:null,textureSpace:"local"},hn.defaultStrokeStyle={width:1,color:16777215,alpha:1,alignment:.5,miterLimit:10,cap:"butt",join:"miter",texture:z.WHITE,matrix:null,fill:null,textureSpace:"local",pixelLine:!1};let se=hn;class Ll{constructor(t){this._attachedDomElements=[],this._renderer=t,this._renderer.runners.postrender.add(this),this._renderer.runners.init.add(this),this._domElement=document.createElement("div"),this._domElement.style.position="absolute",this._domElement.style.top="0",this._domElement.style.left="0",this._domElement.style.pointerEvents="none",this._domElement.style.zIndex="1000"}init(){this._canvasObserver=new ta({domElement:this._domElement,renderer:this._renderer})}addRenderable(t,e){this._attachedDomElements.includes(t)||this._attachedDomElements.push(t)}updateRenderable(t){}validateRenderable(t){return!0}postrender(){const t=this._attachedDomElements;if(t.length===0){this._domElement.remove();return}this._canvasObserver.ensureAttached();for(let e=0;e<t.length;e++){const i=t[e],r=i.element;if(!i.parent||i.globalDisplayStatus<7)r==null||r.remove(),t.splice(e,1),e--;else{this._domElement.contains(r)||(r.style.position="absolute",r.style.pointerEvents="auto",this._domElement.appendChild(r));const n=i.worldTransform,o=i._anchor,a=i.width*o.x,l=i.height*o.y;r.style.transformOrigin=`${a}px ${l}px`,r.style.transform=`matrix(${n.a}, ${n.b}, ${n.c}, ${n.d}, ${n.tx-a}, ${n.ty-l})`,r.style.opacity=i.groupAlpha.toString()}}}destroy(){var t;this._renderer.runners.postrender.remove(this);for(let e=0;e<this._attachedDomElements.length;e++)(t=this._attachedDomElements[e].element)==null||t.remove();this._attachedDomElements.length=0,this._domElement.remove(),this._canvasObserver.destroy(),this._renderer=null}}Ll.extension={type:[w.WebGLPipes,w.WebGPUPipes,w.CanvasPipes],name:"dom"};class om{constructor(){this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}init(t){this.removeTickerListener(),this.events=t,this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}get pauseUpdate(){return this._pauseUpdate}set pauseUpdate(t){this._pauseUpdate=t}addTickerListener(){this._tickerAdded||!this.domElement||(te.system.add(this._tickerUpdate,this,pi.INTERACTION),this._tickerAdded=!0)}removeTickerListener(){this._tickerAdded&&(te.system.remove(this._tickerUpdate,this),this._tickerAdded=!1)}pointerMoved(){this._didMove=!0}_update(){if(!this.domElement||this._pauseUpdate)return;if(this._didMove){this._didMove=!1;return}const t=this.events._rootPointerEvent;this.events.supportsTouchEvents&&t.pointerType==="touch"||globalThis.document.dispatchEvent(this.events.supportsPointerEvents?new PointerEvent("pointermove",{clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,pointerId:t.pointerId}):new MouseEvent("mousemove",{clientX:t.clientX,clientY:t.clientY}))}_tickerUpdate(t){this._deltaTime+=t.deltaTime,!(this._deltaTime<this.interactionFrequency)&&(this._deltaTime=0,this._update())}destroy(){this.removeTickerListener(),this.events=null,this.domElement=null,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}}const Te=new om;class ks extends Ui{constructor(){super(...arguments),this.client=new mt,this.movement=new mt,this.offset=new mt,this.global=new mt,this.screen=new mt}get clientX(){return this.client.x}get clientY(){return this.client.y}get x(){return this.clientX}get y(){return this.clientY}get movementX(){return this.movement.x}get movementY(){return this.movement.y}get offsetX(){return this.offset.x}get offsetY(){return this.offset.y}get globalX(){return this.global.x}get globalY(){return this.global.y}get screenX(){return this.screen.x}get screenY(){return this.screen.y}getLocalPosition(t,e,i){return t.worldTransform.applyInverse(i||this.global,e)}getModifierState(t){return"getModifierState"in this.nativeEvent&&this.nativeEvent.getModifierState(t)}initMouseEvent(t,e,i,r,n,o,a,l,h,c,u,m,f,g,y){throw new Error("Method not implemented.")}}class re extends ks{constructor(){super(...arguments),this.width=0,this.height=0,this.isPrimary=!1}getCoalescedEvents(){return this.type==="pointermove"||this.type==="mousemove"||this.type==="touchmove"?[this]:[]}getPredictedEvents(){throw new Error("getPredictedEvents is not supported!")}}class vi extends ks{constructor(){super(...arguments),this.DOM_DELTA_PIXEL=0,this.DOM_DELTA_LINE=1,this.DOM_DELTA_PAGE=2}}vi.DOM_DELTA_PIXEL=0,vi.DOM_DELTA_LINE=1,vi.DOM_DELTA_PAGE=2;const am=2048,lm=new mt,ss=new mt;class hm{constructor(t){this.dispatch=new Jt,this.moveOnAll=!1,this.enableGlobalMoveEvents=!0,this.mappingState={trackingData:{}},this.eventPool=new Map,this._allInteractiveElements=[],this._hitElements=[],this._isPointerMoveEvent=!1,this.rootTarget=t,this.hitPruneFn=this.hitPruneFn.bind(this),this.hitTestFn=this.hitTestFn.bind(this),this.mapPointerDown=this.mapPointerDown.bind(this),this.mapPointerMove=this.mapPointerMove.bind(this),this.mapPointerOut=this.mapPointerOut.bind(this),this.mapPointerOver=this.mapPointerOver.bind(this),this.mapPointerUp=this.mapPointerUp.bind(this),this.mapPointerUpOutside=this.mapPointerUpOutside.bind(this),this.mapWheel=this.mapWheel.bind(this),this.mappingTable={},this.addEventMapping("pointerdown",this.mapPointerDown),this.addEventMapping("pointermove",this.mapPointerMove),this.addEventMapping("pointerout",this.mapPointerOut),this.addEventMapping("pointerleave",this.mapPointerOut),this.addEventMapping("pointerover",this.mapPointerOver),this.addEventMapping("pointerup",this.mapPointerUp),this.addEventMapping("pointerupoutside",this.mapPointerUpOutside),this.addEventMapping("wheel",this.mapWheel)}addEventMapping(t,e){this.mappingTable[t]||(this.mappingTable[t]=[]),this.mappingTable[t].push({fn:e,priority:0}),this.mappingTable[t].sort((i,r)=>i.priority-r.priority)}dispatchEvent(t,e){t.propagationStopped=!1,t.propagationImmediatelyStopped=!1,this.propagate(t,e),this.dispatch.emit(e||t.type,t)}mapEvent(t){if(!this.rootTarget)return;const e=this.mappingTable[t.type];if(e)for(let i=0,r=e.length;i<r;i++)e[i].fn(t);else tt(`[EventBoundary]: Event mapping not defined for ${t.type}`)}hitTest(t,e){Te.pauseUpdate=!0;const r=this._isPointerMoveEvent&&this.enableGlobalMoveEvents?"hitTestMoveRecursive":"hitTestRecursive",n=this[r](this.rootTarget,this.rootTarget.eventMode,lm.set(t,e),this.hitTestFn,this.hitPruneFn);return n&&n[0]}propagate(t,e){if(!t.target)return;const i=t.composedPath();t.eventPhase=t.CAPTURING_PHASE;for(let r=0,n=i.length-1;r<n;r++)if(t.currentTarget=i[r],this.notifyTarget(t,e),t.propagationStopped||t.propagationImmediatelyStopped)return;if(t.eventPhase=t.AT_TARGET,t.currentTarget=t.target,this.notifyTarget(t,e),!(t.propagationStopped||t.propagationImmediatelyStopped)){t.eventPhase=t.BUBBLING_PHASE;for(let r=i.length-2;r>=0;r--)if(t.currentTarget=i[r],this.notifyTarget(t,e),t.propagationStopped||t.propagationImmediatelyStopped)return}}all(t,e,i=this._allInteractiveElements){if(i.length===0)return;t.eventPhase=t.BUBBLING_PHASE;const r=Array.isArray(e)?e:[e];for(let n=i.length-1;n>=0;n--)r.forEach(o=>{t.currentTarget=i[n],this.notifyTarget(t,o)})}propagationPath(t){const e=[t];for(let i=0;i<am&&t!==this.rootTarget&&t.parent;i++){if(!t.parent)throw new Error("Cannot find propagation path to disconnected target");e.push(t.parent),t=t.parent}return e.reverse(),e}hitTestMoveRecursive(t,e,i,r,n,o=!1){let a=!1;if(this._interactivePrune(t))return null;if((t.eventMode==="dynamic"||e==="dynamic")&&(Te.pauseUpdate=!1),t.interactiveChildren&&t.children){const c=t.children;for(let u=c.length-1;u>=0;u--){const m=c[u],f=this.hitTestMoveRecursive(m,this._isInteractive(e)?e:m.eventMode,i,r,n,o||n(t,i));if(f){if(f.length>0&&!f[f.length-1].parent)continue;const g=t.isInteractive();(f.length>0||g)&&(g&&this._allInteractiveElements.push(t),f.push(t)),this._hitElements.length===0&&(this._hitElements=f),a=!0}}}const l=this._isInteractive(e),h=t.isInteractive();return h&&h&&this._allInteractiveElements.push(t),o||this._hitElements.length>0?null:a?this._hitElements:l&&!n(t,i)&&r(t,i)?h?[t]:[]:null}hitTestRecursive(t,e,i,r,n){if(this._interactivePrune(t)||n(t,i))return null;if((t.eventMode==="dynamic"||e==="dynamic")&&(Te.pauseUpdate=!1),t.interactiveChildren&&t.children){const l=t.children,h=i;for(let c=l.length-1;c>=0;c--){const u=l[c],m=this.hitTestRecursive(u,this._isInteractive(e)?e:u.eventMode,h,r,n);if(m){if(m.length>0&&!m[m.length-1].parent)continue;const f=t.isInteractive();return(m.length>0||f)&&m.push(t),m}}}const o=this._isInteractive(e),a=t.isInteractive();return o&&r(t,i)?a?[t]:[]:null}_isInteractive(t){return t==="static"||t==="dynamic"}_interactivePrune(t){return!t||!t.visible||!t.renderable||!t.measurable||t.eventMode==="none"||t.eventMode==="passive"&&!t.interactiveChildren}hitPruneFn(t,e){if(t.hitArea&&(t.worldTransform.applyInverse(e,ss),!t.hitArea.contains(ss.x,ss.y)))return!0;if(t.effects&&t.effects.length)for(let i=0;i<t.effects.length;i++){const r=t.effects[i];if(r.containsPoint&&!r.containsPoint(e,this.hitTestFn))return!0}return!1}hitTestFn(t,e){return t.hitArea?!0:t!=null&&t.containsPoint?(t.worldTransform.applyInverse(e,ss),t.containsPoint(ss)):!1}notifyTarget(t,e){var n,o;if(!t.currentTarget.isInteractive())return;e??(e=t.type);const i=`on${e}`;(o=(n=t.currentTarget)[i])==null||o.call(n,t);const r=t.eventPhase===t.CAPTURING_PHASE||t.eventPhase===t.AT_TARGET?`${e}capture`:e;this._notifyListeners(t,r),t.eventPhase===t.AT_TARGET&&this._notifyListeners(t,e)}mapPointerDown(t){if(!(t instanceof re)){tt("EventBoundary cannot map a non-pointer event as a pointer event");return}const e=this.createPointerEvent(t);if(this.dispatchEvent(e,"pointerdown"),e.pointerType==="touch")this.dispatchEvent(e,"touchstart");else if(e.pointerType==="mouse"||e.pointerType==="pen"){const r=e.button===2;this.dispatchEvent(e,r?"rightdown":"mousedown")}const i=this.trackingData(t.pointerId);i.pressTargetsByButton[t.button]=e.composedPath(),this.freeEvent(e)}mapPointerMove(t){var l,h;if(!(t instanceof re)){tt("EventBoundary cannot map a non-pointer event as a pointer event");return}this._allInteractiveElements.length=0,this._hitElements.length=0,this._isPointerMoveEvent=!0;const e=this.createPointerEvent(t);this._isPointerMoveEvent=!1;const i=e.pointerType==="mouse"||e.pointerType==="pen",r=this.trackingData(t.pointerId),n=this.findMountedTarget(r.overTargets);if(((l=r.overTargets)==null?void 0:l.length)>0&&n!==e.target){const c=t.type==="mousemove"?"mouseout":"pointerout",u=this.createPointerEvent(t,c,n);if(this.dispatchEvent(u,"pointerout"),i&&this.dispatchEvent(u,"mouseout"),!e.composedPath().includes(n)){const m=this.createPointerEvent(t,"pointerleave",n);for(m.eventPhase=m.AT_TARGET;m.target&&!e.composedPath().includes(m.target);)m.currentTarget=m.target,this.notifyTarget(m),i&&this.notifyTarget(m,"mouseleave"),m.target=m.target.parent;this.freeEvent(m)}this.freeEvent(u)}if(n!==e.target){const c=t.type==="mousemove"?"mouseover":"pointerover",u=this.clonePointerEvent(e,c);this.dispatchEvent(u,"pointerover"),i&&this.dispatchEvent(u,"mouseover");let m=n==null?void 0:n.parent;for(;m&&m!==this.rootTarget.parent&&m!==e.target;)m=m.parent;if(!m||m===this.rootTarget.parent){const g=this.clonePointerEvent(e,"pointerenter");for(g.eventPhase=g.AT_TARGET;g.target&&g.target!==n&&g.target!==this.rootTarget.parent;)g.currentTarget=g.target,this.notifyTarget(g),i&&this.notifyTarget(g,"mouseenter"),g.target=g.target.parent;this.freeEvent(g)}this.freeEvent(u)}const o=[],a=this.enableGlobalMoveEvents??!0;this.moveOnAll?o.push("pointermove"):this.dispatchEvent(e,"pointermove"),a&&o.push("globalpointermove"),e.pointerType==="touch"&&(this.moveOnAll?o.splice(1,0,"touchmove"):this.dispatchEvent(e,"touchmove"),a&&o.push("globaltouchmove")),i&&(this.moveOnAll?o.splice(1,0,"mousemove"):this.dispatchEvent(e,"mousemove"),a&&o.push("globalmousemove"),this.cursor=(h=e.target)==null?void 0:h.cursor),o.length>0&&this.all(e,o),this._allInteractiveElements.length=0,this._hitElements.length=0,r.overTargets=e.composedPath(),this.freeEvent(e)}mapPointerOver(t){var o;if(!(t instanceof re)){tt("EventBoundary cannot map a non-pointer event as a pointer event");return}const e=this.trackingData(t.pointerId),i=this.createPointerEvent(t),r=i.pointerType==="mouse"||i.pointerType==="pen";this.dispatchEvent(i,"pointerover"),r&&this.dispatchEvent(i,"mouseover"),i.pointerType==="mouse"&&(this.cursor=(o=i.target)==null?void 0:o.cursor);const n=this.clonePointerEvent(i,"pointerenter");for(n.eventPhase=n.AT_TARGET;n.target&&n.target!==this.rootTarget.parent;)n.currentTarget=n.target,this.notifyTarget(n),r&&this.notifyTarget(n,"mouseenter"),n.target=n.target.parent;e.overTargets=i.composedPath(),this.freeEvent(i),this.freeEvent(n)}mapPointerOut(t){if(!(t instanceof re)){tt("EventBoundary cannot map a non-pointer event as a pointer event");return}const e=this.trackingData(t.pointerId);if(e.overTargets){const i=t.pointerType==="mouse"||t.pointerType==="pen",r=this.findMountedTarget(e.overTargets),n=this.createPointerEvent(t,"pointerout",r);this.dispatchEvent(n),i&&this.dispatchEvent(n,"mouseout");const o=this.createPointerEvent(t,"pointerleave",r);for(o.eventPhase=o.AT_TARGET;o.target&&o.target!==this.rootTarget.parent;)o.currentTarget=o.target,this.notifyTarget(o),i&&this.notifyTarget(o,"mouseleave"),o.target=o.target.parent;e.overTargets=null,this.freeEvent(n),this.freeEvent(o)}this.cursor=null}mapPointerUp(t){if(!(t instanceof re)){tt("EventBoundary cannot map a non-pointer event as a pointer event");return}const e=performance.now(),i=this.createPointerEvent(t);if(this.dispatchEvent(i,"pointerup"),i.pointerType==="touch")this.dispatchEvent(i,"touchend");else if(i.pointerType==="mouse"||i.pointerType==="pen"){const a=i.button===2;this.dispatchEvent(i,a?"rightup":"mouseup")}const r=this.trackingData(t.pointerId),n=this.findMountedTarget(r.pressTargetsByButton[t.button]);let o=n;if(n&&!i.composedPath().includes(n)){let a=n;for(;a&&!i.composedPath().includes(a);){if(i.currentTarget=a,this.notifyTarget(i,"pointerupoutside"),i.pointerType==="touch")this.notifyTarget(i,"touchendoutside");else if(i.pointerType==="mouse"||i.pointerType==="pen"){const l=i.button===2;this.notifyTarget(i,l?"rightupoutside":"mouseupoutside")}a=a.parent}delete r.pressTargetsByButton[t.button],o=a}if(o){const a=this.clonePointerEvent(i,"click");a.target=o,a.path=null,r.clicksByButton[t.button]||(r.clicksByButton[t.button]={clickCount:0,target:a.target,timeStamp:e});const l=r.clicksByButton[t.button];if(l.target===a.target&&e-l.timeStamp<200?++l.clickCount:l.clickCount=1,l.target=a.target,l.timeStamp=e,a.detail=l.clickCount,a.pointerType==="mouse"){const h=a.button===2;this.dispatchEvent(a,h?"rightclick":"click")}else a.pointerType==="touch"&&this.dispatchEvent(a,"tap");this.dispatchEvent(a,"pointertap"),this.freeEvent(a)}this.freeEvent(i)}mapPointerUpOutside(t){if(!(t instanceof re)){tt("EventBoundary cannot map a non-pointer event as a pointer event");return}const e=this.trackingData(t.pointerId),i=this.findMountedTarget(e.pressTargetsByButton[t.button]),r=this.createPointerEvent(t);if(i){let n=i;for(;n;)r.currentTarget=n,this.notifyTarget(r,"pointerupoutside"),r.pointerType==="touch"?this.notifyTarget(r,"touchendoutside"):(r.pointerType==="mouse"||r.pointerType==="pen")&&this.notifyTarget(r,r.button===2?"rightupoutside":"mouseupoutside"),n=n.parent;delete e.pressTargetsByButton[t.button]}this.freeEvent(r)}mapWheel(t){if(!(t instanceof vi)){tt("EventBoundary cannot map a non-wheel event as a wheel event");return}const e=this.createWheelEvent(t);this.dispatchEvent(e),this.freeEvent(e)}findMountedTarget(t){if(!t)return null;let e=t[0];for(let i=1;i<t.length&&t[i].parent===e;i++)e=t[i];return e}createPointerEvent(t,e,i){const r=this.allocateEvent(re);return this.copyPointerData(t,r),this.copyMouseData(t,r),this.copyData(t,r),r.nativeEvent=t.nativeEvent,r.originalEvent=t,r.target=i??this.hitTest(r.global.x,r.global.y)??this._hitElements[0],typeof e=="string"&&(r.type=e),r}createWheelEvent(t){const e=this.allocateEvent(vi);return this.copyWheelData(t,e),this.copyMouseData(t,e),this.copyData(t,e),e.nativeEvent=t.nativeEvent,e.originalEvent=t,e.target=this.hitTest(e.global.x,e.global.y),e}clonePointerEvent(t,e){const i=this.allocateEvent(re);return i.nativeEvent=t.nativeEvent,i.originalEvent=t.originalEvent,this.copyPointerData(t,i),this.copyMouseData(t,i),this.copyData(t,i),i.target=t.target,i.path=t.composedPath().slice(),i.type=e??i.type,i}copyWheelData(t,e){e.deltaMode=t.deltaMode,e.deltaX=t.deltaX,e.deltaY=t.deltaY,e.deltaZ=t.deltaZ}copyPointerData(t,e){t instanceof re&&e instanceof re&&(e.pointerId=t.pointerId,e.width=t.width,e.height=t.height,e.isPrimary=t.isPrimary,e.pointerType=t.pointerType,e.pressure=t.pressure,e.tangentialPressure=t.tangentialPressure,e.tiltX=t.tiltX,e.tiltY=t.tiltY,e.twist=t.twist)}copyMouseData(t,e){t instanceof ks&&e instanceof ks&&(e.altKey=t.altKey,e.button=t.button,e.buttons=t.buttons,e.client.copyFrom(t.client),e.ctrlKey=t.ctrlKey,e.metaKey=t.metaKey,e.movement.copyFrom(t.movement),e.screen.copyFrom(t.screen),e.shiftKey=t.shiftKey,e.global.copyFrom(t.global))}copyData(t,e){e.isTrusted=t.isTrusted,e.srcElement=t.srcElement,e.timeStamp=performance.now(),e.type=t.type,e.detail=t.detail,e.view=t.view,e.which=t.which,e.layer.copyFrom(t.layer),e.page.copyFrom(t.page)}trackingData(t){return this.mappingState.trackingData[t]||(this.mappingState.trackingData[t]={pressTargetsByButton:{},clicksByButton:{},overTarget:null}),this.mappingState.trackingData[t]}allocateEvent(t){this.eventPool.has(t)||this.eventPool.set(t,[]);const e=this.eventPool.get(t).pop()||new t(this);return e.eventPhase=e.NONE,e.currentTarget=null,e.defaultPrevented=!1,e.path=null,e.target=null,e}freeEvent(t){if(t.manager!==this)throw new Error("It is illegal to free an event not managed by this EventBoundary!");const e=t.constructor;this.eventPool.has(e)||this.eventPool.set(e,[]),this.eventPool.get(e).push(t)}_notifyListeners(t,e){const i=t.currentTarget._events[e];if(i)if("fn"in i)i.once&&t.currentTarget.removeListener(e,i.fn,void 0,!0),i.fn.call(i.context,t);else for(let r=0,n=i.length;r<n&&!t.propagationImmediatelyStopped;r++)i[r].once&&t.currentTarget.removeListener(e,i[r].fn,void 0,!0),i[r].fn.call(i[r].context,t)}}const cm=1,um={touchstart:"pointerdown",touchend:"pointerup",touchendoutside:"pointerupoutside",touchmove:"pointermove",touchcancel:"pointercancel"},cn=class so{constructor(t){this.supportsTouchEvents="ontouchstart"in globalThis,this.supportsPointerEvents=!!globalThis.PointerEvent,this.domElement=null,this.resolution=1,this.renderer=t,this.rootBoundary=new hm(null),Te.init(this),this.autoPreventDefault=!0,this._eventsAdded=!1,this._rootPointerEvent=new re(null),this._rootWheelEvent=new vi(null),this.cursorStyles={default:"inherit",pointer:"pointer"},this.features=new Proxy({...so.defaultEventFeatures},{set:(e,i,r)=>(i==="globalMove"&&(this.rootBoundary.enableGlobalMoveEvents=r),e[i]=r,!0)}),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._onPointerOverOut=this._onPointerOverOut.bind(this),this.onWheel=this.onWheel.bind(this)}static get defaultEventMode(){return this._defaultEventMode}init(t){const{canvas:e,resolution:i}=this.renderer;this.setTargetElement(e),this.resolution=i,so._defaultEventMode=t.eventMode??"passive",Object.assign(this.features,t.eventFeatures??{}),this.rootBoundary.enableGlobalMoveEvents=this.features.globalMove}resolutionChange(t){this.resolution=t}destroy(){Te.destroy(),this.setTargetElement(null),this.renderer=null,this._currentCursor=null}setCursor(t){t||(t="default");let e=!0;if(globalThis.OffscreenCanvas&&this.domElement instanceof OffscreenCanvas&&(e=!1),this._currentCursor===t)return;this._currentCursor=t;const i=this.cursorStyles[t];if(i)switch(typeof i){case"string":e&&(this.domElement.style.cursor=i);break;case"function":i(t);break;case"object":e&&Object.assign(this.domElement.style,i);break}else e&&typeof t=="string"&&!Object.prototype.hasOwnProperty.call(this.cursorStyles,t)&&(this.domElement.style.cursor=t)}get pointer(){return this._rootPointerEvent}_onPointerDown(t){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const e=this._normalizeToPointerData(t);this.autoPreventDefault&&e[0].isNormalized&&(t.cancelable||!("cancelable"in t))&&t.preventDefault();for(let i=0,r=e.length;i<r;i++){const n=e[i],o=this._bootstrapEvent(this._rootPointerEvent,n);this.rootBoundary.mapEvent(o)}this.setCursor(this.rootBoundary.cursor)}_onPointerMove(t){if(!this.features.move)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,Te.pointerMoved();const e=this._normalizeToPointerData(t);for(let i=0,r=e.length;i<r;i++){const n=this._bootstrapEvent(this._rootPointerEvent,e[i]);this.rootBoundary.mapEvent(n)}this.setCursor(this.rootBoundary.cursor)}_onPointerUp(t){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;let e=t.target;t.composedPath&&t.composedPath().length>0&&(e=t.composedPath()[0]);const i=e!==this.domElement?"outside":"",r=this._normalizeToPointerData(t);for(let n=0,o=r.length;n<o;n++){const a=this._bootstrapEvent(this._rootPointerEvent,r[n]);a.type+=i,this.rootBoundary.mapEvent(a)}this.setCursor(this.rootBoundary.cursor)}_onPointerOverOut(t){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const e=this._normalizeToPointerData(t);for(let i=0,r=e.length;i<r;i++){const n=this._bootstrapEvent(this._rootPointerEvent,e[i]);this.rootBoundary.mapEvent(n)}this.setCursor(this.rootBoundary.cursor)}onWheel(t){if(!this.features.wheel)return;const e=this.normalizeWheelEvent(t);this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,this.rootBoundary.mapEvent(e)}setTargetElement(t){this._removeEvents(),this.domElement=t,Te.domElement=t,this._addEvents()}_addEvents(){if(this._eventsAdded||!this.domElement)return;Te.addTickerListener();const t=this.domElement.style;t&&(globalThis.navigator.msPointerEnabled?(t.msContentZooming="none",t.msTouchAction="none"):this.supportsPointerEvents&&(t.touchAction="none")),this.supportsPointerEvents?(globalThis.document.addEventListener("pointermove",this._onPointerMove,!0),this.domElement.addEventListener("pointerdown",this._onPointerDown,!0),this.domElement.addEventListener("pointerleave",this._onPointerOverOut,!0),this.domElement.addEventListener("pointerover",this._onPointerOverOut,!0),globalThis.addEventListener("pointerup",this._onPointerUp,!0)):(globalThis.document.addEventListener("mousemove",this._onPointerMove,!0),this.domElement.addEventListener("mousedown",this._onPointerDown,!0),this.domElement.addEventListener("mouseout",this._onPointerOverOut,!0),this.domElement.addEventListener("mouseover",this._onPointerOverOut,!0),globalThis.addEventListener("mouseup",this._onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.addEventListener("touchstart",this._onPointerDown,!0),this.domElement.addEventListener("touchend",this._onPointerUp,!0),this.domElement.addEventListener("touchmove",this._onPointerMove,!0))),this.domElement.addEventListener("wheel",this.onWheel,{passive:!0,capture:!0}),this._eventsAdded=!0}_removeEvents(){if(!this._eventsAdded||!this.domElement)return;Te.removeTickerListener();const t=this.domElement.style;t&&(globalThis.navigator.msPointerEnabled?(t.msContentZooming="",t.msTouchAction=""):this.supportsPointerEvents&&(t.touchAction="")),this.supportsPointerEvents?(globalThis.document.removeEventListener("pointermove",this._onPointerMove,!0),this.domElement.removeEventListener("pointerdown",this._onPointerDown,!0),this.domElement.removeEventListener("pointerleave",this._onPointerOverOut,!0),this.domElement.removeEventListener("pointerover",this._onPointerOverOut,!0),globalThis.removeEventListener("pointerup",this._onPointerUp,!0)):(globalThis.document.removeEventListener("mousemove",this._onPointerMove,!0),this.domElement.removeEventListener("mousedown",this._onPointerDown,!0),this.domElement.removeEventListener("mouseout",this._onPointerOverOut,!0),this.domElement.removeEventListener("mouseover",this._onPointerOverOut,!0),globalThis.removeEventListener("mouseup",this._onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.removeEventListener("touchstart",this._onPointerDown,!0),this.domElement.removeEventListener("touchend",this._onPointerUp,!0),this.domElement.removeEventListener("touchmove",this._onPointerMove,!0))),this.domElement.removeEventListener("wheel",this.onWheel,!0),this.domElement=null,this._eventsAdded=!1}mapPositionToPoint(t,e,i){const r=this.domElement.isConnected?this.domElement.getBoundingClientRect():{width:this.domElement.width,height:this.domElement.height,left:0,top:0},n=1/this.resolution;t.x=(e-r.left)*(this.domElement.width/r.width)*n,t.y=(i-r.top)*(this.domElement.height/r.height)*n}_normalizeToPointerData(t){const e=[];if(this.supportsTouchEvents&&t instanceof TouchEvent)for(let i=0,r=t.changedTouches.length;i<r;i++){const n=t.changedTouches[i];typeof n.button>"u"&&(n.button=0),typeof n.buttons>"u"&&(n.buttons=1),typeof n.isPrimary>"u"&&(n.isPrimary=t.touches.length===1&&t.type==="touchstart"),typeof n.width>"u"&&(n.width=n.radiusX||1),typeof n.height>"u"&&(n.height=n.radiusY||1),typeof n.tiltX>"u"&&(n.tiltX=0),typeof n.tiltY>"u"&&(n.tiltY=0),typeof n.pointerType>"u"&&(n.pointerType="touch"),typeof n.pointerId>"u"&&(n.pointerId=n.identifier||0),typeof n.pressure>"u"&&(n.pressure=n.force||.5),typeof n.twist>"u"&&(n.twist=0),typeof n.tangentialPressure>"u"&&(n.tangentialPressure=0),typeof n.layerX>"u"&&(n.layerX=n.offsetX=n.clientX),typeof n.layerY>"u"&&(n.layerY=n.offsetY=n.clientY),n.isNormalized=!0,n.type=t.type,n.altKey??(n.altKey=t.altKey),n.ctrlKey??(n.ctrlKey=t.ctrlKey),n.metaKey??(n.metaKey=t.metaKey),n.shiftKey??(n.shiftKey=t.shiftKey),e.push(n)}else if(!globalThis.MouseEvent||t instanceof MouseEvent&&(!this.supportsPointerEvents||!(t instanceof globalThis.PointerEvent))){const i=t;typeof i.isPrimary>"u"&&(i.isPrimary=!0),typeof i.width>"u"&&(i.width=1),typeof i.height>"u"&&(i.height=1),typeof i.tiltX>"u"&&(i.tiltX=0),typeof i.tiltY>"u"&&(i.tiltY=0),typeof i.pointerType>"u"&&(i.pointerType="mouse"),typeof i.pointerId>"u"&&(i.pointerId=cm),typeof i.pressure>"u"&&(i.pressure=.5),typeof i.twist>"u"&&(i.twist=0),typeof i.tangentialPressure>"u"&&(i.tangentialPressure=0),i.isNormalized=!0,e.push(i)}else e.push(t);return e}normalizeWheelEvent(t){const e=this._rootWheelEvent;return this._transferMouseData(e,t),e.deltaX=t.deltaX,e.deltaY=t.deltaY,e.deltaZ=t.deltaZ,e.deltaMode=t.deltaMode,this.mapPositionToPoint(e.screen,t.clientX,t.clientY),e.global.copyFrom(e.screen),e.offset.copyFrom(e.screen),e.nativeEvent=t,e.type=t.type,e}_bootstrapEvent(t,e){return t.originalEvent=null,t.nativeEvent=e,t.pointerId=e.pointerId,t.width=e.width,t.height=e.height,t.isPrimary=e.isPrimary,t.pointerType=e.pointerType,t.pressure=e.pressure,t.tangentialPressure=e.tangentialPressure,t.tiltX=e.tiltX,t.tiltY=e.tiltY,t.twist=e.twist,this._transferMouseData(t,e),this.mapPositionToPoint(t.screen,e.clientX,e.clientY),t.global.copyFrom(t.screen),t.offset.copyFrom(t.screen),t.isTrusted=e.isTrusted,t.type==="pointerleave"&&(t.type="pointerout"),t.type.startsWith("mouse")&&(t.type=t.type.replace("mouse","pointer")),t.type.startsWith("touch")&&(t.type=um[t.type]||t.type),t}_transferMouseData(t,e){t.isTrusted=e.isTrusted,t.srcElement=e.srcElement,t.timeStamp=performance.now(),t.type=e.type,t.altKey=e.altKey,t.button=e.button,t.buttons=e.buttons,t.client.x=e.clientX,t.client.y=e.clientY,t.ctrlKey=e.ctrlKey,t.metaKey=e.metaKey,t.movement.x=e.movementX,t.movement.y=e.movementY,t.page.x=e.pageX,t.page.y=e.pageY,t.relatedTarget=null,t.shiftKey=e.shiftKey}};cn.extension={name:"events",type:[w.WebGLSystem,w.CanvasSystem,w.WebGPUSystem],priority:-1},cn.defaultEventFeatures={move:!0,globalMove:!0,click:!0,wheel:!0};let Fl=cn;const dm={onclick:null,onmousedown:null,onmouseenter:null,onmouseleave:null,onmousemove:null,onglobalmousemove:null,onmouseout:null,onmouseover:null,onmouseup:null,onmouseupoutside:null,onpointercancel:null,onpointerdown:null,onpointerenter:null,onpointerleave:null,onpointermove:null,onglobalpointermove:null,onpointerout:null,onpointerover:null,onpointertap:null,onpointerup:null,onpointerupoutside:null,onrightclick:null,onrightdown:null,onrightup:null,onrightupoutside:null,ontap:null,ontouchcancel:null,ontouchend:null,ontouchendoutside:null,ontouchmove:null,onglobaltouchmove:null,ontouchstart:null,onwheel:null,get interactive(){return this.eventMode==="dynamic"||this.eventMode==="static"},set interactive(s){this.eventMode=s?"static":"passive"},_internalEventMode:void 0,get eventMode(){return this._internalEventMode??Fl.defaultEventMode},set eventMode(s){this._internalEventMode=s},isInteractive(){return this.eventMode==="static"||this.eventMode==="dynamic"},interactiveChildren:!0,hitArea:null,addEventListener(s,t,e){const i=typeof e=="boolean"&&e||typeof e=="object"&&e.capture,r=typeof e=="object"?e.signal:void 0,n=typeof e=="object"?e.once===!0:!1,o=typeof t=="function"?void 0:t;s=i?`${s}capture`:s;const a=typeof t=="function"?t:t.handleEvent,l=this;r&&r.addEventListener("abort",()=>{l.off(s,a,o)}),n?l.once(s,a,o):l.on(s,a,o)},removeEventListener(s,t,e){const i=typeof e=="boolean"&&e||typeof e=="object"&&e.capture,r=typeof t=="function"?void 0:t;s=i?`${s}capture`:s,t=typeof t=="function"?t:t.handleEvent,this.off(s,t,r)},dispatchEvent(s){if(!(s instanceof Ui))throw new Error("Container cannot propagate events outside of the Federated Events API");return s.defaultPrevented=!1,s.path=null,s.target=this,s.manager.dispatchEvent(s),!s.defaultPrevented}};var fm=`in vec2 aPosition;
|
|
252
|
+
out vec2 vTextureCoord;
|
|
253
|
+
|
|
254
|
+
uniform vec4 uInputSize;
|
|
255
|
+
uniform vec4 uOutputFrame;
|
|
256
|
+
uniform vec4 uOutputTexture;
|
|
257
|
+
|
|
258
|
+
vec4 filterVertexPosition( void )
|
|
259
|
+
{
|
|
260
|
+
vec2 position = aPosition * uOutputFrame.zw + uOutputFrame.xy;
|
|
261
|
+
|
|
262
|
+
position.x = position.x * (2.0 / uOutputTexture.x) - 1.0;
|
|
263
|
+
position.y = position.y * (2.0*uOutputTexture.z / uOutputTexture.y) - uOutputTexture.z;
|
|
264
|
+
|
|
265
|
+
return vec4(position, 0.0, 1.0);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
vec2 filterTextureCoord( void )
|
|
269
|
+
{
|
|
270
|
+
return aPosition * (uOutputFrame.zw * uInputSize.zw);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
void main(void)
|
|
274
|
+
{
|
|
275
|
+
gl_Position = filterVertexPosition();
|
|
276
|
+
vTextureCoord = filterTextureCoord();
|
|
277
|
+
}
|
|
278
|
+
`,pm=`in vec2 vTextureCoord;
|
|
279
|
+
out vec4 finalColor;
|
|
280
|
+
uniform sampler2D uTexture;
|
|
281
|
+
void main() {
|
|
282
|
+
finalColor = texture(uTexture, vTextureCoord);
|
|
283
|
+
}
|
|
284
|
+
`,Nl=`struct GlobalFilterUniforms {
|
|
285
|
+
uInputSize: vec4<f32>,
|
|
286
|
+
uInputPixel: vec4<f32>,
|
|
287
|
+
uInputClamp: vec4<f32>,
|
|
288
|
+
uOutputFrame: vec4<f32>,
|
|
289
|
+
uGlobalFrame: vec4<f32>,
|
|
290
|
+
uOutputTexture: vec4<f32>,
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
@group(0) @binding(0) var <uniform> gfu: GlobalFilterUniforms;
|
|
294
|
+
@group(0) @binding(1) var uTexture: texture_2d<f32>;
|
|
295
|
+
@group(0) @binding(2) var uSampler: sampler;
|
|
296
|
+
|
|
297
|
+
struct VSOutput {
|
|
298
|
+
@builtin(position) position: vec4<f32>,
|
|
299
|
+
@location(0) uv: vec2<f32>
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
fn filterVertexPosition(aPosition: vec2<f32>) -> vec4<f32>
|
|
303
|
+
{
|
|
304
|
+
var position = aPosition * gfu.uOutputFrame.zw + gfu.uOutputFrame.xy;
|
|
305
|
+
|
|
306
|
+
position.x = position.x * (2.0 / gfu.uOutputTexture.x) - 1.0;
|
|
307
|
+
position.y = position.y * (2.0 * gfu.uOutputTexture.z / gfu.uOutputTexture.y) - gfu.uOutputTexture.z;
|
|
308
|
+
|
|
309
|
+
return vec4(position, 0.0, 1.0);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
fn filterTextureCoord(aPosition: vec2<f32>) -> vec2<f32>
|
|
313
|
+
{
|
|
314
|
+
return aPosition * (gfu.uOutputFrame.zw * gfu.uInputSize.zw);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
@vertex
|
|
318
|
+
fn mainVertex(
|
|
319
|
+
@location(0) aPosition: vec2<f32>,
|
|
320
|
+
) -> VSOutput {
|
|
321
|
+
return VSOutput(
|
|
322
|
+
filterVertexPosition(aPosition),
|
|
323
|
+
filterTextureCoord(aPosition)
|
|
324
|
+
);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
@fragment
|
|
328
|
+
fn mainFragment(
|
|
329
|
+
@location(0) uv: vec2<f32>,
|
|
330
|
+
) -> @location(0) vec4<f32> {
|
|
331
|
+
return textureSample(uTexture, uSampler, uv);
|
|
332
|
+
}
|
|
333
|
+
`;class mm extends Dr{constructor(){const t=Ke.from({vertex:{source:Nl,entryPoint:"mainVertex"},fragment:{source:Nl,entryPoint:"mainFragment"},name:"passthrough-filter"}),e=Ye.from({vertex:fm,fragment:pm,name:"passthrough-filter"});super({gpuProgram:t,glProgram:e})}}class Hl{constructor(t){this._renderer=t}push(t,e,i){this._renderer.renderPipes.batch.break(i),i.add({renderPipeId:"filter",canBundle:!1,action:"pushFilter",container:e,filterEffect:t})}pop(t,e,i){this._renderer.renderPipes.batch.break(i),i.add({renderPipeId:"filter",action:"popFilter",canBundle:!1})}execute(t){t.action==="pushFilter"?this._renderer.filter.push(t):t.action==="popFilter"&&this._renderer.filter.pop()}destroy(){this._renderer=null}}Hl.extension={type:[w.WebGLPipes,w.WebGPUPipes,w.CanvasPipes],name:"filter"};const Wl=new W;function gm(s,t){t.clear();const e=t.matrix;for(let i=0;i<s.length;i++){const r=s[i];if(r.globalDisplayStatus<7)continue;const n=r.renderGroup??r.parentRenderGroup;n!=null&&n.isCachedAsTexture?t.matrix=Wl.copyFrom(n.textureOffsetInverseTransform).append(r.worldTransform):n!=null&&n._parentCacheAsTextureRenderGroup?t.matrix=Wl.copyFrom(n._parentCacheAsTextureRenderGroup.inverseWorldTransform).append(r.groupTransform):t.matrix=r.worldTransform,t.addBounds(r.bounds)}return t.matrix=e,t}const _m=new $r({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 ym{constructor(){this.skip=!1,this.inputTexture=null,this.backTexture=null,this.filters=null,this.bounds=new Lt,this.container=null,this.blendRequired=!1,this.outputRenderSurface=null,this.globalFrame={x:0,y:0,width:0,height:0},this.firstEnabledIndex=-1,this.lastEnabledIndex=-1}}class Vl{constructor(t){this._filterStackIndex=0,this._filterStack=[],this._filterGlobalUniforms=new he({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 Me({}),this.renderer=t}get activeBackTexture(){var t;return(t=this._activeFilterData)==null?void 0:t.backTexture}push(t){const e=this.renderer,i=t.filterEffect.filters,r=this._pushFilterData();r.skip=!1,r.filters=i,r.container=t.container,r.outputRenderSurface=e.renderTarget.renderSurface;const n=e.renderTarget.renderTarget.colorTexture.source,o=n.resolution,a=n.antialias;if(i.every(f=>!f.enabled)){r.skip=!0;return}const l=r.bounds;if(this._calculateFilterArea(t,l),this._calculateFilterBounds(r,e.renderTarget.rootViewPort,a,o,1),r.skip)return;const h=this._getPreviousFilterData(),c=this._findFilterResolution(o);let u=0,m=0;h&&(u=h.bounds.minX,m=h.bounds.minY),this._calculateGlobalFrame(r,u,m,c,n.width,n.height),this._setupFilterTextures(r,l,e,h)}generateFilteredTexture({texture:t,filters:e}){const i=this._pushFilterData();this._activeFilterData=i,i.skip=!1,i.filters=e;const r=t.source,n=r.resolution,o=r.antialias;if(e.every(f=>!f.enabled))return i.skip=!0,t;const a=i.bounds;if(a.addRect(t.frame),this._calculateFilterBounds(i,a.rectangle,o,n,0),i.skip)return t;const l=n;this._calculateGlobalFrame(i,0,0,l,r.width,r.height),i.outputRenderSurface=Ft.getOptimalTexture(a.width,a.height,i.resolution,i.antialias),i.backTexture=z.EMPTY,i.inputTexture=t,this.renderer.renderTarget.finishRenderPass(),this._applyFiltersToTexture(i,!0);const m=i.outputRenderSurface;return m.source.alphaMode="premultiplied-alpha",m}pop(){const t=this.renderer,e=this._popFilterData();e.skip||(t.globalUniforms.pop(),t.renderTarget.finishRenderPass(),this._activeFilterData=e,this._applyFiltersToTexture(e,!1),e.blendRequired&&Ft.returnTexture(e.backTexture),Ft.returnTexture(e.inputTexture))}getBackTexture(t,e,i){const r=t.colorTexture.source._resolution,n=Ft.getOptimalTexture(e.width,e.height,r,!1);let o=e.minX,a=e.minY;i&&(o-=i.minX,a-=i.minY),o=Math.floor(o*r),a=Math.floor(a*r);const l=Math.ceil(e.width*r),h=Math.ceil(e.height*r);return this.renderer.renderTarget.copyToTexture(t,n,{x:o,y:a},{width:l,height:h},{x:0,y:0}),n}applyFilter(t,e,i,r){const n=this.renderer,o=this._activeFilterData,l=o.outputRenderSurface===i,h=n.renderTarget.rootRenderTarget.colorTexture.source._resolution,c=this._findFilterResolution(h);let u=0,m=0;if(l){const g=this._findPreviousFilterOffset();u=g.x,m=g.y}this._updateFilterUniforms(e,i,o,u,m,c,l,r);const f=t.enabled?t:this._getPassthroughFilter();this._setupBindGroupsAndRender(f,e,n)}calculateSpriteMatrix(t,e){const i=this._activeFilterData,r=t.set(i.inputTexture._source.width,0,0,i.inputTexture._source.height,i.bounds.minX,i.bounds.minY),n=e.worldTransform.copyTo(W.shared),o=e.renderGroup||e.parentRenderGroup;return o&&o.cacheToLocalTransform&&n.prepend(o.cacheToLocalTransform),n.invert(),r.prepend(n),r.scale(1/e.texture.orig.width,1/e.texture.orig.height),r.translate(e.anchor.x,e.anchor.y),r}destroy(){var t;(t=this._passthroughFilter)==null||t.destroy(!0),this._passthroughFilter=null}_getPassthroughFilter(){return this._passthroughFilter??(this._passthroughFilter=new mm),this._passthroughFilter}_setupBindGroupsAndRender(t,e,i){if(i.renderPipes.uniformBatch){const r=i.renderPipes.uniformBatch.getUboResource(this._filterGlobalUniforms);this._globalFilterBindGroup.setResource(r,0)}else this._globalFilterBindGroup.setResource(this._filterGlobalUniforms,0);this._globalFilterBindGroup.setResource(e.source,1),this._globalFilterBindGroup.setResource(e.source.style,2),t.groups[0]=this._globalFilterBindGroup,i.encoder.draw({geometry:_m,shader:t,state:t._state,topology:"triangle-list"}),i.type===ce.WEBGL&&i.renderTarget.finishRenderPass()}_setupFilterTextures(t,e,i,r){if(t.backTexture=z.EMPTY,t.inputTexture=Ft.getOptimalTexture(e.width,e.height,t.resolution,t.antialias),t.blendRequired){i.renderTarget.finishRenderPass();const n=i.renderTarget.getRenderTarget(t.outputRenderSurface);t.backTexture=this.getBackTexture(n,e,r==null?void 0:r.bounds)}i.renderTarget.bind(t.inputTexture,!0),i.globalUniforms.push({offset:e})}_calculateGlobalFrame(t,e,i,r,n,o){const a=t.globalFrame;a.x=e*r,a.y=i*r,a.width=n*r,a.height=o*r}_updateFilterUniforms(t,e,i,r,n,o,a,l){const h=this._filterGlobalUniforms.uniforms,c=h.uOutputFrame,u=h.uInputSize,m=h.uInputPixel,f=h.uInputClamp,g=h.uGlobalFrame,y=h.uOutputTexture;a?(c[0]=i.bounds.minX-r,c[1]=i.bounds.minY-n):(c[0]=0,c[1]=0),c[2]=t.frame.width,c[3]=t.frame.height,u[0]=t.source.width,u[1]=t.source.height,u[2]=1/u[0],u[3]=1/u[1],m[0]=t.source.pixelWidth,m[1]=t.source.pixelHeight,m[2]=1/m[0],m[3]=1/m[1],f[0]=.5*m[2],f[1]=.5*m[3],f[2]=t.frame.width*u[2]-.5*m[2],f[3]=t.frame.height*u[3]-.5*m[3];const x=this.renderer.renderTarget.rootRenderTarget.colorTexture;g[0]=r*o,g[1]=n*o,g[2]=x.source.width*o,g[3]=x.source.height*o,e instanceof z&&(e.source.resource=null);const v=this.renderer.renderTarget.getRenderTarget(e);this.renderer.renderTarget.bind(e,!!l),e instanceof z?(y[0]=e.frame.width,y[1]=e.frame.height):(y[0]=v.width,y[1]=v.height),y[2]=v.isRoot?-1:1,this._filterGlobalUniforms.update()}_findFilterResolution(t){let e=this._filterStackIndex-1;for(;e>0&&this._filterStack[e].skip;)--e;return e>0&&this._filterStack[e].inputTexture?this._filterStack[e].inputTexture.source._resolution:t}_findPreviousFilterOffset(){let t=0,e=0,i=this._filterStackIndex;for(;i>0;){i--;const r=this._filterStack[i];if(!r.skip){t=r.bounds.minX,e=r.bounds.minY;break}}return{x:t,y:e}}_calculateFilterArea(t,e){if(t.renderables?gm(t.renderables,e):t.filterEffect.filterArea?(e.clear(),e.addRect(t.filterEffect.filterArea),e.applyMatrix(t.container.worldTransform)):t.container.getFastGlobalBounds(!0,e),t.container){const r=(t.container.renderGroup||t.container.parentRenderGroup).cacheToLocalTransform;r&&e.applyMatrix(r)}}_applyFiltersToTexture(t,e){const i=t.inputTexture,r=t.bounds,n=t.filters,o=t.firstEnabledIndex,a=t.lastEnabledIndex;if(this._globalFilterBindGroup.setResource(i.source.style,2),this._globalFilterBindGroup.setResource(t.backTexture.source,3),o===a)n[o].apply(this,i,t.outputRenderSurface,e);else{let l=t.inputTexture;const h=Ft.getOptimalTexture(r.width,r.height,l.source._resolution,!1);let c=h;for(let u=o;u<a;u++){const m=n[u];if(!m.enabled)continue;m.apply(this,l,c,!0);const f=l;l=c,c=f}n[a].apply(this,l,t.outputRenderSurface,e),Ft.returnTexture(h)}}_calculateFilterBounds(t,e,i,r,n){var v;const o=this.renderer,a=t.bounds,l=t.filters;let h=1/0,c=0,u=!0,m=!1,f=!1,g=!0,y=-1,x=-1;for(let E=0;E<l.length;E++){const T=l[E];if(!T.enabled)continue;if(y===-1&&(y=E),x=E,h=Math.min(h,T.resolution==="inherit"?r:T.resolution),c+=T.padding,T.antialias==="off"?u=!1:T.antialias==="inherit"&&u&&(u=i),T.clipToViewport||(g=!1),!!!(T.compatibleRenderers&o.type)){f=!1;break}if(T.blendRequired&&!(((v=o.backBuffer)==null?void 0:v.useBackBuffer)??!0)){tt("Blend filter requires backBuffer on WebGL renderer to be enabled. Set `useBackBuffer: true` in the renderer options."),f=!1;break}f=!0,m||(m=T.blendRequired)}if(!f){t.skip=!0;return}if(g&&a.fitBounds(0,e.width/r,0,e.height/r),a.scale(h).ceil().scale(1/h).pad((c|0)*n),!a.isPositive){t.skip=!0;return}t.antialias=u,t.resolution=h,t.blendRequired=m,t.firstEnabledIndex=y,t.lastEnabledIndex=x}_popFilterData(){return this._filterStackIndex--,this._filterStack[this._filterStackIndex]}_getPreviousFilterData(){let t,e=this._filterStackIndex-1;for(;e>0&&(e--,t=this._filterStack[e],!!t.skip););return t}_pushFilterData(){let t=this._filterStack[this._filterStackIndex];return t||(t=this._filterStack[this._filterStackIndex]=new ym),this._filterStackIndex++,t}}Vl.extension={type:[w.WebGLSystem,w.WebGPUSystem],name:"filter"};var xm=`in vec2 vMaskCoord;
|
|
334
|
+
in vec2 vTextureCoord;
|
|
335
|
+
|
|
336
|
+
uniform sampler2D uTexture;
|
|
337
|
+
uniform sampler2D uMaskTexture;
|
|
338
|
+
|
|
339
|
+
uniform float uAlpha;
|
|
340
|
+
uniform vec4 uMaskClamp;
|
|
341
|
+
uniform float uInverse;
|
|
342
|
+
|
|
343
|
+
out vec4 finalColor;
|
|
344
|
+
|
|
345
|
+
void main(void)
|
|
346
|
+
{
|
|
347
|
+
float clip = step(3.5,
|
|
348
|
+
step(uMaskClamp.x, vMaskCoord.x) +
|
|
349
|
+
step(uMaskClamp.y, vMaskCoord.y) +
|
|
350
|
+
step(vMaskCoord.x, uMaskClamp.z) +
|
|
351
|
+
step(vMaskCoord.y, uMaskClamp.w));
|
|
352
|
+
|
|
353
|
+
// TODO look into why this is needed
|
|
354
|
+
float npmAlpha = uAlpha;
|
|
355
|
+
vec4 original = texture(uTexture, vTextureCoord);
|
|
356
|
+
vec4 masky = texture(uMaskTexture, vMaskCoord);
|
|
357
|
+
float alphaMul = 1.0 - npmAlpha * (1.0 - masky.a);
|
|
358
|
+
|
|
359
|
+
float a = alphaMul * masky.r * npmAlpha * clip;
|
|
360
|
+
|
|
361
|
+
if (uInverse == 1.0) {
|
|
362
|
+
a = 1.0 - a;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
finalColor = original * a;
|
|
366
|
+
}
|
|
367
|
+
`,bm=`in vec2 aPosition;
|
|
368
|
+
|
|
369
|
+
out vec2 vTextureCoord;
|
|
370
|
+
out vec2 vMaskCoord;
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
uniform vec4 uInputSize;
|
|
374
|
+
uniform vec4 uOutputFrame;
|
|
375
|
+
uniform vec4 uOutputTexture;
|
|
376
|
+
uniform mat3 uFilterMatrix;
|
|
377
|
+
|
|
378
|
+
vec4 filterVertexPosition( vec2 aPosition )
|
|
379
|
+
{
|
|
380
|
+
vec2 position = aPosition * uOutputFrame.zw + uOutputFrame.xy;
|
|
381
|
+
|
|
382
|
+
position.x = position.x * (2.0 / uOutputTexture.x) - 1.0;
|
|
383
|
+
position.y = position.y * (2.0*uOutputTexture.z / uOutputTexture.y) - uOutputTexture.z;
|
|
384
|
+
|
|
385
|
+
return vec4(position, 0.0, 1.0);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
vec2 filterTextureCoord( vec2 aPosition )
|
|
389
|
+
{
|
|
390
|
+
return aPosition * (uOutputFrame.zw * uInputSize.zw);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
vec2 getFilterCoord( vec2 aPosition )
|
|
394
|
+
{
|
|
395
|
+
return ( uFilterMatrix * vec3( filterTextureCoord(aPosition), 1.0) ).xy;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
void main(void)
|
|
399
|
+
{
|
|
400
|
+
gl_Position = filterVertexPosition(aPosition);
|
|
401
|
+
vTextureCoord = filterTextureCoord(aPosition);
|
|
402
|
+
vMaskCoord = getFilterCoord(aPosition);
|
|
403
|
+
}
|
|
404
|
+
`,zl=`struct GlobalFilterUniforms {
|
|
405
|
+
uInputSize:vec4<f32>,
|
|
406
|
+
uInputPixel:vec4<f32>,
|
|
407
|
+
uInputClamp:vec4<f32>,
|
|
408
|
+
uOutputFrame:vec4<f32>,
|
|
409
|
+
uGlobalFrame:vec4<f32>,
|
|
410
|
+
uOutputTexture:vec4<f32>,
|
|
411
|
+
};
|
|
412
|
+
|
|
413
|
+
struct MaskUniforms {
|
|
414
|
+
uFilterMatrix:mat3x3<f32>,
|
|
415
|
+
uMaskClamp:vec4<f32>,
|
|
416
|
+
uAlpha:f32,
|
|
417
|
+
uInverse:f32,
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
@group(0) @binding(0) var<uniform> gfu: GlobalFilterUniforms;
|
|
421
|
+
@group(0) @binding(1) var uTexture: texture_2d<f32>;
|
|
422
|
+
@group(0) @binding(2) var uSampler : sampler;
|
|
423
|
+
|
|
424
|
+
@group(1) @binding(0) var<uniform> filterUniforms : MaskUniforms;
|
|
425
|
+
@group(1) @binding(1) var uMaskTexture: texture_2d<f32>;
|
|
426
|
+
|
|
427
|
+
struct VSOutput {
|
|
428
|
+
@builtin(position) position: vec4<f32>,
|
|
429
|
+
@location(0) uv : vec2<f32>,
|
|
430
|
+
@location(1) filterUv : vec2<f32>,
|
|
431
|
+
};
|
|
432
|
+
|
|
433
|
+
fn filterVertexPosition(aPosition:vec2<f32>) -> vec4<f32>
|
|
434
|
+
{
|
|
435
|
+
var position = aPosition * gfu.uOutputFrame.zw + gfu.uOutputFrame.xy;
|
|
436
|
+
|
|
437
|
+
position.x = position.x * (2.0 / gfu.uOutputTexture.x) - 1.0;
|
|
438
|
+
position.y = position.y * (2.0*gfu.uOutputTexture.z / gfu.uOutputTexture.y) - gfu.uOutputTexture.z;
|
|
439
|
+
|
|
440
|
+
return vec4(position, 0.0, 1.0);
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
fn filterTextureCoord( aPosition:vec2<f32> ) -> vec2<f32>
|
|
444
|
+
{
|
|
445
|
+
return aPosition * (gfu.uOutputFrame.zw * gfu.uInputSize.zw);
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
fn globalTextureCoord( aPosition:vec2<f32> ) -> vec2<f32>
|
|
449
|
+
{
|
|
450
|
+
return (aPosition.xy / gfu.uGlobalFrame.zw) + (gfu.uGlobalFrame.xy / gfu.uGlobalFrame.zw);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
fn getFilterCoord(aPosition:vec2<f32> ) -> vec2<f32>
|
|
454
|
+
{
|
|
455
|
+
return ( filterUniforms.uFilterMatrix * vec3( filterTextureCoord(aPosition), 1.0) ).xy;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
fn getSize() -> vec2<f32>
|
|
459
|
+
{
|
|
460
|
+
return gfu.uGlobalFrame.zw;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
@vertex
|
|
464
|
+
fn mainVertex(
|
|
465
|
+
@location(0) aPosition : vec2<f32>,
|
|
466
|
+
) -> VSOutput {
|
|
467
|
+
return VSOutput(
|
|
468
|
+
filterVertexPosition(aPosition),
|
|
469
|
+
filterTextureCoord(aPosition),
|
|
470
|
+
getFilterCoord(aPosition)
|
|
471
|
+
);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
@fragment
|
|
475
|
+
fn mainFragment(
|
|
476
|
+
@location(0) uv: vec2<f32>,
|
|
477
|
+
@location(1) filterUv: vec2<f32>,
|
|
478
|
+
@builtin(position) position: vec4<f32>
|
|
479
|
+
) -> @location(0) vec4<f32> {
|
|
480
|
+
|
|
481
|
+
var maskClamp = filterUniforms.uMaskClamp;
|
|
482
|
+
var uAlpha = filterUniforms.uAlpha;
|
|
483
|
+
|
|
484
|
+
var clip = step(3.5,
|
|
485
|
+
step(maskClamp.x, filterUv.x) +
|
|
486
|
+
step(maskClamp.y, filterUv.y) +
|
|
487
|
+
step(filterUv.x, maskClamp.z) +
|
|
488
|
+
step(filterUv.y, maskClamp.w));
|
|
489
|
+
|
|
490
|
+
var mask = textureSample(uMaskTexture, uSampler, filterUv);
|
|
491
|
+
var source = textureSample(uTexture, uSampler, uv);
|
|
492
|
+
var alphaMul = 1.0 - uAlpha * (1.0 - mask.a);
|
|
493
|
+
|
|
494
|
+
var a: f32 = alphaMul * mask.r * uAlpha * clip;
|
|
495
|
+
|
|
496
|
+
if (filterUniforms.uInverse == 1.0) {
|
|
497
|
+
a = 1.0 - a;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
return source * a;
|
|
501
|
+
}
|
|
502
|
+
`;class vm extends Dr{constructor(t){const{sprite:e,...i}=t,r=new yo(e.texture),n=new he({uFilterMatrix:{value:new W,type:"mat3x3<f32>"},uMaskClamp:{value:r.uClampFrame,type:"vec4<f32>"},uAlpha:{value:1,type:"f32"},uInverse:{value:t.inverse?1:0,type:"f32"}}),o=Ke.from({vertex:{source:zl,entryPoint:"mainVertex"},fragment:{source:zl,entryPoint:"mainFragment"}}),a=Ye.from({vertex:bm,fragment:xm,name:"mask-filter"});super({...i,gpuProgram:o,glProgram:a,clipToViewport:!1,resources:{filterUniforms:n,uMaskTexture:e.texture.source}}),this.sprite=e,this._textureMatrix=r}set inverse(t){this.resources.filterUniforms.uniforms.uInverse=t?1:0}get inverse(){return this.resources.filterUniforms.uniforms.uInverse===1}apply(t,e,i,r){this._textureMatrix.texture=this.sprite.texture,t.calculateSpriteMatrix(this.resources.filterUniforms.uniforms.uFilterMatrix,this.sprite).prepend(this._textureMatrix.mapCoord),this.resources.uMaskTexture=this.sprite.texture.source,t.applyFilter(this,e,i,r)}}class Em{constructor(){this.isBatchable=!1}reset(){this.isBatchable=!1,this.context=null,this.graphicsData&&(this.graphicsData.destroy(),this.graphicsData=null)}destroy(){this.reset()}}class Tm{constructor(){this.instructions=new fr}init(){this.instructions.reset()}destroy(){this.instructions.destroy(),this.instructions=null}}const un=class ro{constructor(t){this._renderer=t,this._managedContexts=new ue({renderer:t,type:"resource",name:"graphicsContext"})}init(t){ro.defaultOptions.bezierSmoothness=(t==null?void 0:t.bezierSmoothness)??ro.defaultOptions.bezierSmoothness}getContextRenderData(t){return this.getGpuContext(t).graphicsData||this._initContextRenderData(t)}updateGpuContext(t){const e=t._gpuData,i=!!e[this._renderer.uid],r=e[this._renderer.uid]||this._initContext(t);return(t.dirty||!i)&&(i&&r.reset(),r.isBatchable=!1,t.dirty=!1),r}getGpuContext(t){return t._gpuData[this._renderer.uid]||this._initContext(t)}_initContextRenderData(t){const e=new Tm,i=this.getGpuContext(t);return i.graphicsData=e,e.init(),e}_initContext(t){const e=new Em;return e.context=t,t._gpuData[this._renderer.uid]=e,this._managedContexts.add(t),e}destroy(){this._managedContexts.destroy(),this._renderer=null}};un.extension={type:[w.CanvasSystem],name:"graphicsContext"},un.defaultOptions={bezierSmoothness:.5};let Sm=un;class $l{constructor(t,e){this.state=ve.for2d(),this.renderer=t,this._adaptor=e,this.renderer.runners.contextChange.add(this),this._managedGraphics=new ue({renderer:t,type:"renderable",priority:-1,name:"graphics"})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(t){return!1}addRenderable(t,e){this._managedGraphics.add(t),this.renderer.renderPipes.batch.break(e),e.add(t)}updateRenderable(t){}execute(t){t.isRenderable&&this._adaptor.execute(this,t)}destroy(){this._managedGraphics.destroy(),this.renderer=null,this._adaptor.destroy(),this._adaptor=null}}$l.extension={type:[w.CanvasPipes],name:"graphics"};function jl(s,t,e){const i=(s>>24&255)/255;t[e++]=(s&255)/255*i,t[e++]=(s>>8&255)/255*i,t[e++]=(s>>16&255)/255*i,t[e++]=i}class Cm{constructor(){this.batches=[],this.batched=!1}destroy(){this.batches.forEach(t=>{Mt.return(t)}),this.batches.length=0}}class Xl{constructor(t,e){this.state=ve.for2d(),this.renderer=t,this._adaptor=e,this.renderer.runners.contextChange.add(this),this._managedGraphics=new ue({renderer:t,type:"renderable",priority:-1,name:"graphics"})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(t){const e=t.context,i=!!t._gpuData,n=this.renderer.graphicsContext.updateGpuContext(e);return!!(n.isBatchable||i!==n.isBatchable)}addRenderable(t,e){const r=this.renderer.graphicsContext.updateGpuContext(t.context);t.didViewUpdate&&this._rebuild(t),r.isBatchable?this._addToBatcher(t,e):(this.renderer.renderPipes.batch.break(e),e.add(t))}updateRenderable(t){const i=this._getGpuDataForRenderable(t).batches;for(let r=0;r<i.length;r++){const n=i[r];n._batcher.updateElement(n)}}execute(t){if(!t.isRenderable)return;const e=this.renderer,i=t.context;if(!e.graphicsContext.getGpuContext(i).batches.length)return;const n=i.customShader||this._adaptor.shader;this.state.blendMode=t.groupBlendMode;const o=n.resources.localUniforms.uniforms;o.uTransformMatrix=t.groupTransform,o.uRound=e._roundPixels|t._roundPixels,jl(t.groupColorAlpha,o.uColor,0),this._adaptor.execute(this,t)}_rebuild(t){const e=this._getGpuDataForRenderable(t),r=this.renderer.graphicsContext.updateGpuContext(t.context);e.destroy(),r.isBatchable&&this._updateBatchesForRenderable(t,e)}_addToBatcher(t,e){const i=this.renderer.renderPipes.batch,r=this._getGpuDataForRenderable(t).batches;for(let n=0;n<r.length;n++){const o=r[n];i.addToBatch(o,e)}}_getGpuDataForRenderable(t){return t._gpuData[this.renderer.uid]||this._initGpuDataForRenderable(t)}_initGpuDataForRenderable(t){const e=new Cm;return t._gpuData[this.renderer.uid]=e,this._managedGraphics.add(t),e}_updateBatchesForRenderable(t,e){const i=t.context,n=this.renderer.graphicsContext.getGpuContext(i),o=this.renderer._roundPixels|t._roundPixels;e.batches=n.batches.map(a=>{const l=Mt.get(tn);return a.copyTo(l),l.renderable=t,l.roundPixels=o,l})}destroy(){this._managedGraphics.destroy(),this.renderer=null,this._adaptor.destroy(),this._adaptor=null,this.state=null}}Xl.extension={type:[w.WebGLPipes,w.WebGPUPipes],name:"graphics"},J.add($l),J.add(Xl),J.add(Sm),J.add(rn);class Se extends yr{constructor(t){t instanceof se&&(t={context:t});const{context:e,roundPixels:i,...r}=t||{};super({label:"Graphics",...r}),this.renderPipeId="graphics",e?this.context=e:(this.context=this._ownedContext=new se,this.context.autoGarbageCollect=this.autoGarbageCollect),this.didViewUpdate=!0,this.allowChildren=!1,this.roundPixels=i??!1}set context(t){t!==this._context&&(this._context&&(this._context.off("update",this.onViewUpdate,this),this._context.off("unload",this.unload,this)),this._context=t,this._context.on("update",this.onViewUpdate,this),this._context.on("unload",this.unload,this),this.onViewUpdate())}get context(){return this._context}get bounds(){return this._context.bounds}updateBounds(){}containsPoint(t){return this._context.containsPoint(t)}destroy(t){this._ownedContext&&!t?this._ownedContext.destroy(t):(t===!0||(t==null?void 0:t.context)===!0)&&this._context.destroy(t),this._ownedContext=null,this._context=null,super.destroy(t)}_onTouch(t){this._gcLastUsed=t,this._context._gcLastUsed=t}_callContextMethod(t,e){return this.context[t](...e),this}setFillStyle(...t){return this._callContextMethod("setFillStyle",t)}setStrokeStyle(...t){return this._callContextMethod("setStrokeStyle",t)}fill(...t){return this._callContextMethod("fill",t)}stroke(...t){return this._callContextMethod("stroke",t)}texture(...t){return this._callContextMethod("texture",t)}beginPath(){return this._callContextMethod("beginPath",[])}cut(){return this._callContextMethod("cut",[])}arc(...t){return this._callContextMethod("arc",t)}arcTo(...t){return this._callContextMethod("arcTo",t)}arcToSvg(...t){return this._callContextMethod("arcToSvg",t)}bezierCurveTo(...t){return this._callContextMethod("bezierCurveTo",t)}closePath(){return this._callContextMethod("closePath",[])}ellipse(...t){return this._callContextMethod("ellipse",t)}circle(...t){return this._callContextMethod("circle",t)}path(...t){return this._callContextMethod("path",t)}lineTo(...t){return this._callContextMethod("lineTo",t)}moveTo(...t){return this._callContextMethod("moveTo",t)}quadraticCurveTo(...t){return this._callContextMethod("quadraticCurveTo",t)}rect(...t){return this._callContextMethod("rect",t)}roundRect(...t){return this._callContextMethod("roundRect",t)}poly(...t){return this._callContextMethod("poly",t)}regularPoly(...t){return this._callContextMethod("regularPoly",t)}roundPoly(...t){return this._callContextMethod("roundPoly",t)}roundShape(...t){return this._callContextMethod("roundShape",t)}filletRect(...t){return this._callContextMethod("filletRect",t)}chamferRect(...t){return this._callContextMethod("chamferRect",t)}star(...t){return this._callContextMethod("star",t)}svg(...t){return this._callContextMethod("svg",t)}restore(...t){return this._callContextMethod("restore",t)}save(){return this._callContextMethod("save",[])}getTransform(){return this.context.getTransform()}resetTransform(){return this._callContextMethod("resetTransform",[])}rotateTransform(...t){return this._callContextMethod("rotate",t)}scaleTransform(...t){return this._callContextMethod("scale",t)}setTransform(...t){return this._callContextMethod("setTransform",t)}transform(...t){return this._callContextMethod("transform",t)}translateTransform(...t){return this._callContextMethod("translate",t)}clear(){return this._callContextMethod("clear",[])}get fillStyle(){return this._context.fillStyle}set fillStyle(t){this._context.fillStyle=t}get strokeStyle(){return this._context.strokeStyle}set strokeStyle(t){this._context.strokeStyle=t}clone(t=!1){return t?new Se(this._context.clone()):(this._ownedContext=null,new Se(this._context))}lineStyle(t,e,i){K(vt,"Graphics#lineStyle is no longer needed. Use Graphics#setStrokeStyle to set the stroke style.");const r={};return t&&(r.width=t),e&&(r.color=e),i&&(r.alpha=i),this.context.strokeStyle=r,this}beginFill(t,e){K(vt,"Graphics#beginFill is no longer needed. Use Graphics#fill to fill the shape with the desired style.");const i={};return t!==void 0&&(i.color=t),e!==void 0&&(i.alpha=e),this.context.fillStyle=i,this}endFill(){K(vt,"Graphics#endFill is no longer needed. Use Graphics#fill to fill the shape with the desired style."),this.context.fill();const t=this.context.strokeStyle;return(t.width!==se.defaultStrokeStyle.width||t.color!==se.defaultStrokeStyle.color||t.alpha!==se.defaultStrokeStyle.alpha)&&this.context.stroke(),this}drawCircle(...t){return K(vt,"Graphics#drawCircle has been renamed to Graphics#circle"),this._callContextMethod("circle",t)}drawEllipse(...t){return K(vt,"Graphics#drawEllipse has been renamed to Graphics#ellipse"),this._callContextMethod("ellipse",t)}drawPolygon(...t){return K(vt,"Graphics#drawPolygon has been renamed to Graphics#poly"),this._callContextMethod("poly",t)}drawRect(...t){return K(vt,"Graphics#drawRect has been renamed to Graphics#rect"),this._callContextMethod("rect",t)}drawRoundedRect(...t){return K(vt,"Graphics#drawRoundedRect has been renamed to Graphics#roundRect"),this._callContextMethod("roundRect",t)}drawStar(...t){return K(vt,"Graphics#drawStar has been renamed to Graphics#star"),this._callContextMethod("star",t)}}let Ei;function Yl(s){const t=rt.get().createCanvas(6,1),e=t.getContext("2d");return e.fillStyle=s,e.fillRect(0,0,6,1),t}function ql(){if(Ei!==void 0)return Ei;try{const s=Yl("#ff00ff"),t=Yl("#ffff00"),i=rt.get().createCanvas(6,1).getContext("2d");i.globalCompositeOperation="multiply",i.drawImage(s,0,0),i.drawImage(t,2,0);const r=i.getImageData(2,0,1,1);if(!r)Ei=!1;else{const n=r.data;Ei=n[0]===255&&n[1]===0&&n[2]===0}}catch{Ei=!1}return Ei}const st={canvas:null,convertTintToImage:!1,cacheStepsPerColorChannel:8,canUseMultiply:ql(),tintMethod:null,_canvasSourceCache:new WeakMap,_unpremultipliedCache:new WeakMap,getCanvasSource:s=>{const t=s.source,e=t==null?void 0:t.resource;if(!e)return null;const i=t.alphaMode==="premultiplied-alpha",r=t.resourceWidth??t.pixelWidth,n=t.resourceHeight??t.pixelHeight,o=r!==t.pixelWidth||n!==t.pixelHeight;if(i){if((e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)&&!o)return e;const a=st._unpremultipliedCache.get(t);if((a==null?void 0:a.resourceId)===t._resourceId)return a.canvas}if(e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int8Array||e instanceof Uint16Array||e instanceof Int16Array||e instanceof Uint32Array||e instanceof Int32Array||e instanceof Float32Array||e instanceof ArrayBuffer){const a=st._canvasSourceCache.get(t);if((a==null?void 0:a.resourceId)===t._resourceId)return a.canvas;const l=rt.get().createCanvas(t.pixelWidth,t.pixelHeight),h=l.getContext("2d"),c=h.createImageData(t.pixelWidth,t.pixelHeight),u=c.data,m=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(t.format==="bgra8unorm")for(let f=0;f<u.length&&f+3<m.length;f+=4)u[f]=m[f+2],u[f+1]=m[f+1],u[f+2]=m[f],u[f+3]=m[f+3];else u.set(m.subarray(0,u.length));return h.putImageData(c,0,0),st._canvasSourceCache.set(t,{canvas:l,resourceId:t._resourceId}),l}if(i){const a=rt.get().createCanvas(t.pixelWidth,t.pixelHeight),l=a.getContext("2d",{willReadFrequently:!0});a.width=t.pixelWidth,a.height=t.pixelHeight,l.drawImage(e,0,0);const h=l.getImageData(0,0,a.width,a.height),c=h.data;for(let u=0;u<c.length;u+=4){const m=c[u+3];if(m>0){const f=255/m;c[u]=Math.min(255,c[u]*f+.5),c[u+1]=Math.min(255,c[u+1]*f+.5),c[u+2]=Math.min(255,c[u+2]*f+.5)}}return l.putImageData(h,0,0),st._unpremultipliedCache.set(t,{canvas:a,resourceId:t._resourceId}),a}if(o){const a=st._canvasSourceCache.get(t);if((a==null?void 0:a.resourceId)===t._resourceId)return a.canvas;const l=rt.get().createCanvas(t.pixelWidth,t.pixelHeight),h=l.getContext("2d");return l.width=t.pixelWidth,l.height=t.pixelHeight,h.drawImage(e,0,0),st._canvasSourceCache.set(t,{canvas:l,resourceId:t._resourceId}),l}return e},getTintedCanvas:(s,t)=>{const e=s.texture,i=ct.shared.setValue(t).toHex(),r=e.tintCache||(e.tintCache={}),n=r[i],o=e.source._resourceId;if((n==null?void 0:n.tintId)===o)return n;const a=n&&"getContext"in n?n:rt.get().createCanvas();return st.tintMethod(e,t,a),a.tintId=o,r[i]=a,r[i]},getTintedPattern:(s,t)=>{const e=ct.shared.setValue(t).toHex(),i=s.patternCache||(s.patternCache={}),r=s.source._resourceId;let n=i[e];return(n==null?void 0:n.tintId)===r||(st.canvas||(st.canvas=rt.get().createCanvas()),st.tintMethod(s,t,st.canvas),n=st.canvas.getContext("2d").createPattern(st.canvas,"repeat"),n.tintId=r,i[e]=n),n},applyPatternTransform:(s,t,e=!0)=>{if(!t)return;const i=s;if(!i.setTransform)return;const r=globalThis.DOMMatrix;if(!r)return;const n=new r([t.a,t.b,t.c,t.d,t.tx,t.ty]);i.setTransform(e?n.inverse():n)},tintWithMultiply:(s,t,e)=>{const i=e.getContext("2d"),r=s.frame.clone(),n=s.source._resolution??s.source.resolution??1,o=s.rotate;r.x*=n,r.y*=n,r.width*=n,r.height*=n;const a=it.isVertical(o),l=a?r.height:r.width,h=a?r.width:r.height;e.width=Math.ceil(l),e.height=Math.ceil(h),i.save(),i.fillStyle=ct.shared.setValue(t).toHex(),i.fillRect(0,0,l,h),i.globalCompositeOperation="multiply";const c=st.getCanvasSource(s);if(!c){i.restore();return}o&&st._applyInverseRotation(i,o,r.width,r.height),i.drawImage(c,r.x,r.y,r.width,r.height,0,0,r.width,r.height),i.globalCompositeOperation="destination-atop",i.drawImage(c,r.x,r.y,r.width,r.height,0,0,r.width,r.height),i.restore()},tintWithOverlay:(s,t,e)=>{const i=e.getContext("2d"),r=s.frame.clone(),n=s.source._resolution??s.source.resolution??1,o=s.rotate;r.x*=n,r.y*=n,r.width*=n,r.height*=n;const a=it.isVertical(o),l=a?r.height:r.width,h=a?r.width:r.height;e.width=Math.ceil(l),e.height=Math.ceil(h),i.save(),i.globalCompositeOperation="copy",i.fillStyle=ct.shared.setValue(t).toHex(),i.fillRect(0,0,l,h),i.globalCompositeOperation="destination-atop";const c=st.getCanvasSource(s);if(!c){i.restore();return}o&&st._applyInverseRotation(i,o,r.width,r.height),i.drawImage(c,r.x,r.y,r.width,r.height,0,0,r.width,r.height),i.restore()},tintWithPerPixel:(s,t,e)=>{const i=e.getContext("2d"),r=s.frame.clone(),n=s.source._resolution??s.source.resolution??1,o=s.rotate;r.x*=n,r.y*=n,r.width*=n,r.height*=n;const a=it.isVertical(o),l=a?r.height:r.width,h=a?r.width:r.height;e.width=Math.ceil(l),e.height=Math.ceil(h),i.save(),i.globalCompositeOperation="copy";const c=st.getCanvasSource(s);if(!c){i.restore();return}o&&st._applyInverseRotation(i,o,r.width,r.height),i.drawImage(c,r.x,r.y,r.width,r.height,0,0,r.width,r.height),i.restore();const u=t>>16&255,m=t>>8&255,f=t&255,g=i.getImageData(0,0,l,h),y=g.data;for(let x=0;x<y.length;x+=4)y[x]=y[x]*u/255,y[x+1]=y[x+1]*m/255,y[x+2]=y[x+2]*f/255;i.putImageData(g,0,0)},_applyInverseRotation:(s,t,e,i)=>{const r=it.inv(t),n=it.uX(r),o=it.uY(r),a=it.vX(r),l=it.vY(r),h=-Math.min(0,n*e,a*i,n*e+a*i),c=-Math.min(0,o*e,l*i,o*e+l*i);s.transform(n,o,a,l,h,c)}};st.tintMethod=st.canUseMultiply?st.tintWithMultiply:st.tintWithPerPixel;const Bs={name:"local-uniform-bit",vertex:{header:`
|
|
503
|
+
|
|
504
|
+
struct LocalUniforms {
|
|
505
|
+
uTransformMatrix:mat3x3<f32>,
|
|
506
|
+
uColor:vec4<f32>,
|
|
507
|
+
uRound:f32,
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
@group(1) @binding(0) var<uniform> localUniforms : LocalUniforms;
|
|
511
|
+
`,main:`
|
|
512
|
+
vColor *= localUniforms.uColor;
|
|
513
|
+
modelMatrix *= localUniforms.uTransformMatrix;
|
|
514
|
+
`,end:`
|
|
515
|
+
if(localUniforms.uRound == 1)
|
|
516
|
+
{
|
|
517
|
+
vPosition = vec4(roundPixels(vPosition.xy, globalUniforms.uResolution), vPosition.zw);
|
|
518
|
+
}
|
|
519
|
+
`}},wm={...Bs,vertex:{...Bs.vertex,header:Bs.vertex.header.replace("group(1)","group(2)")}},Kl={name:"local-uniform-bit",vertex:{header:`
|
|
520
|
+
|
|
521
|
+
uniform mat3 uTransformMatrix;
|
|
522
|
+
uniform vec4 uColor;
|
|
523
|
+
uniform float uRound;
|
|
524
|
+
`,main:`
|
|
525
|
+
vColor *= uColor;
|
|
526
|
+
modelMatrix = uTransformMatrix;
|
|
527
|
+
`,end:`
|
|
528
|
+
if(uRound == 1.)
|
|
529
|
+
{
|
|
530
|
+
gl_Position.xy = roundPixels(gl_Position.xy, uResolution);
|
|
531
|
+
}
|
|
532
|
+
`}};class Am extends yr{constructor(t,e){const{text:i,resolution:r,style:n,anchor:o,width:a,height:l,roundPixels:h,...c}=t;super({...c}),this.batched=!0,this._resolution=null,this._autoResolution=!0,this._didTextUpdate=!0,this._styleClass=e,this.text=i??"",this.style=n,this.resolution=r??null,this.allowChildren=!1,this._anchor=new Ot({_onUpdate:()=>{this.onViewUpdate()}}),o&&(this.anchor=o),this.roundPixels=h??!1,a!==void 0&&(this.width=a),l!==void 0&&(this.height=l)}get anchor(){return this._anchor}set anchor(t){typeof t=="number"?this._anchor.set(t):this._anchor.copyFrom(t)}set text(t){t=t.toString(),this._text!==t&&(this._text=t,this.onViewUpdate())}get text(){return this._text}set resolution(t){this._autoResolution=t===null,this._resolution=t,this.onViewUpdate()}get resolution(){return this._resolution}get style(){return this._style}set style(t){var e;t||(t={}),(e=this._style)==null||e.off("update",this.onViewUpdate,this),t instanceof this._styleClass?this._style=t:this._style=new this._styleClass(t),this._style.on("update",this.onViewUpdate,this),this.onViewUpdate()}get width(){return Math.abs(this.scale.x)*this.bounds.width}set width(t){this._setWidth(t,this.bounds.width)}get height(){return Math.abs(this.scale.y)*this.bounds.height}set height(t){this._setHeight(t,this.bounds.height)}getSize(t){return t||(t={}),t.width=Math.abs(this.scale.x)*this.bounds.width,t.height=Math.abs(this.scale.y)*this.bounds.height,t}setSize(t,e){typeof t=="object"?(e=t.height??t.width,t=t.width):e??(e=t),t!==void 0&&this._setWidth(t,this.bounds.width),e!==void 0&&this._setHeight(e,this.bounds.height)}containsPoint(t){const e=this.bounds.width,i=this.bounds.height,r=-e*this.anchor.x;let n=0;return t.x>=r&&t.x<=r+e&&(n=-i*this.anchor.y,t.y>=n&&t.y<=n+i)}onViewUpdate(){this.didViewUpdate||(this._didTextUpdate=!0),super.onViewUpdate()}destroy(t=!1){super.destroy(t),this.owner=null,this._bounds=null,this._anchor=null,(typeof t=="boolean"?t:t!=null&&t.style)&&this._style.destroy(t),this._style=null,this._text=null}get styleKey(){return`${this._text}:${this._style.styleKey}:${this._resolution}`}}function Rm(s,t){let e=s[0]??{};return(typeof e=="string"||s[1])&&(K(vt,`use new ${t}({ text: "hi!", style }) instead`),e={text:e,style:s[1]}),e}class Pm{constructor(t){this._canvasPool=Object.create(null),this.canvasOptions=t||{},this.enableFullScreen=!1}_createCanvasAndContext(t,e){const i=rt.get().createCanvas();i.width=t,i.height=e;const r=i.getContext("2d");return{canvas:i,context:r}}getOptimalCanvasAndContext(t,e,i=1){t=Math.ceil(t*i-1e-6),e=Math.ceil(e*i-1e-6),t=hi(t),e=hi(e);const r=(t<<17)+(e<<1);this._canvasPool[r]||(this._canvasPool[r]=[]);let n=this._canvasPool[r].pop();return n||(n=this._createCanvasAndContext(t,e)),n}returnCanvasAndContext(t){const e=t.canvas,{width:i,height:r}=e,n=(i<<17)+(r<<1);t.context.resetTransform(),t.context.clearRect(0,0,i,r),this._canvasPool[n].push(t)}clear(){this._canvasPool={}}}const rs=new Pm;ui.register(rs);let ti=null,Ce=null;function Im(s,t){ti||(ti=rt.get().createCanvas(256,128),Ce=ti.getContext("2d",{willReadFrequently:!0}),Ce.globalCompositeOperation="copy",Ce.globalAlpha=1),(ti.width<s||ti.height<t)&&(ti.width=hi(s),ti.height=hi(t))}function Zl(s,t,e){for(let i=0,r=4*e*t;i<t;++i,r+=4)if(s[r+3]!==0)return!1;return!0}function Jl(s,t,e,i,r){const n=4*t;for(let o=i,a=i*n+4*e;o<=r;++o,a+=n)if(s[a+3]!==0)return!1;return!0}function Mm(...s){let t=s[0];t.canvas||(t={canvas:s[0],resolution:s[1]});const{canvas:e}=t,i=Math.min(t.resolution??1,1),r=t.width??e.width,n=t.height??e.height;let o=t.output;if(Im(r,n),!Ce)throw new TypeError("Failed to get canvas 2D context");Ce.drawImage(e,0,0,r,n,0,0,r*i,n*i);const l=Ce.getImageData(0,0,r,n).data;let h=0,c=0,u=r-1,m=n-1;for(;c<n&&Zl(l,r,c);)++c;if(c===n)return ut.EMPTY;for(;Zl(l,r,m);)--m;for(;Jl(l,r,h,c,m);)++h;for(;Jl(l,r,u,c,m);)--u;return++u,++m,Ce.globalCompositeOperation="source-over",Ce.strokeRect(h,c,u-h,m-c),Ce.globalCompositeOperation="copy",o??(o=new ut),o.set(h/i,c/i,(u-h)/i,(m-c)/i),o}/**
|
|
533
|
+
* tiny-lru
|
|
534
|
+
*
|
|
535
|
+
* @copyright 2026 Jason Mulligan <jason.mulligan@avoidwork.com>
|
|
536
|
+
* @license BSD-3-Clause
|
|
537
|
+
* @version 11.4.7
|
|
538
|
+
*/class km{constructor(t=0,e=0,i=!1){this.first=null,this.items=Object.create(null),this.last=null,this.max=t,this.resetTtl=i,this.size=0,this.ttl=e}clear(){return this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this}delete(t){if(this.has(t)){const e=this.items[t];delete this.items[t],this.size--,e.prev!==null&&(e.prev.next=e.next),e.next!==null&&(e.next.prev=e.prev),this.first===e&&(this.first=e.next),this.last===e&&(this.last=e.prev)}return this}entries(t=this.keys()){const e=new Array(t.length);for(let i=0;i<t.length;i++){const r=t[i];e[i]=[r,this.get(r)]}return e}evict(t=!1){if(t||this.size>0){const e=this.first;delete this.items[e.key],--this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}return this}expiresAt(t){let e;return this.has(t)&&(e=this.items[t].expiry),e}get(t){const e=this.items[t];if(e!==void 0){if(this.ttl>0&&e.expiry<=Date.now()){this.delete(t);return}return this.moveToEnd(e),e.value}}has(t){return t in this.items}moveToEnd(t){this.last!==t&&(t.prev!==null&&(t.prev.next=t.next),t.next!==null&&(t.next.prev=t.prev),this.first===t&&(this.first=t.next),t.prev=this.last,t.next=null,this.last!==null&&(this.last.next=t),this.last=t,this.first===null&&(this.first=t))}keys(){const t=new Array(this.size);let e=this.first,i=0;for(;e!==null;)t[i++]=e.key,e=e.next;return t}setWithEvicted(t,e,i=this.resetTtl){let r=null;if(this.has(t))this.set(t,e,!0,i);else{this.max>0&&this.size===this.max&&(r={...this.first},this.evict(!0));let n=this.items[t]={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:t,prev:this.last,next:null,value:e};++this.size===1?this.first=n:this.last.next=n,this.last=n}return r}set(t,e,i=!1,r=this.resetTtl){let n=this.items[t];return i||n!==void 0?(n.value=e,i===!1&&r&&(n.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl),this.moveToEnd(n)):(this.max>0&&this.size===this.max&&this.evict(!0),n=this.items[t]={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:t,prev:this.last,next:null,value:e},++this.size===1?this.first=n:this.last.next=n,this.last=n),this}values(t=this.keys()){const e=new Array(t.length);for(let i=0;i<t.length;i++)e[i]=this.get(t[i]);return e}}function Bm(s=1e3,t=0,e=!1){if(isNaN(s)||s<0)throw new TypeError("Invalid max value");if(isNaN(t)||t<0)throw new TypeError("Invalid ttl value");if(typeof e!="boolean")throw new TypeError("Invalid resetTtl value");return new km(s,t,e)}function Ql(s){return!!s.tagStyles&&Object.keys(s.tagStyles).length>0}function th(s){return s.includes("<")}function Om(s,t){return s.clone().assign(t)}function Dm(s,t){const e=[],i=t.tagStyles;if(!Ql(t)||!th(s))return e.push({text:s,style:t}),e;const r=[t],n=[];let o="",a=0;for(;a<s.length;){const l=s[a];if(l==="<"){const h=s.indexOf(">",a);if(h===-1){o+=l,a++;continue}const c=s.slice(a+1,h);if(c.startsWith("/")){const u=c.slice(1).trim();if(n.length>0&&n[n.length-1]===u){o.length>0&&(e.push({text:o,style:r[r.length-1]}),o=""),r.pop(),n.pop(),a=h+1;continue}else{o+=s.slice(a,h+1),a=h+1;continue}}else{const u=c.trim();if(i[u]){o.length>0&&(e.push({text:o,style:r[r.length-1]}),o="");const m=r[r.length-1],f=Om(m,i[u]);r.push(f),n.push(u),a=h+1;continue}else{o+=s.slice(a,h+1),a=h+1;continue}}}else o+=l,a++}return o.length>0&&e.push({text:o,style:r[r.length-1]}),e}const Gm=[10,13],Um=new Set(Gm),Lm=[9,32,8192,8193,8194,8195,8196,8197,8198,8200,8201,8202,8287,12288],Fm=new Set(Lm),Nm=[9,32];new Set(Nm);const Hm=[45,8208,8211,8212,173],Wm=new Set(Hm),Vm=/(\r\n|\r|\n)/,zm=/(?:\r\n|\r|\n)/;function Os(s){return typeof s!="string"?!1:Um.has(s.charCodeAt(0))}function ee(s,t){return typeof s!="string"?!1:Fm.has(s.charCodeAt(0))}function $m(s){return typeof s!="string"?!1:Wm.has(s.charCodeAt(0))}function eh(s){return s==="normal"||s==="pre-line"}function ih(s){return s==="normal"}function we(s){if(typeof s!="string")return"";let t=s.length-1;for(;t>=0&&ee(s[t]);)t--;return t<s.length-1?s.slice(0,t+1):s}function sh(s){const t=[],e=[];if(typeof s!="string")return t;for(let i=0;i<s.length;i++){const r=s[i],n=s[i+1];if(ee(r)||Os(r)){e.length>0&&(t.push(e.join("")),e.length=0),r==="\r"&&n===`
|
|
539
|
+
`?(t.push(`\r
|
|
540
|
+
`),i++):t.push(r);continue}e.push(r),$m(r)&&n&&!ee(n)&&!Os(n)&&(t.push(e.join("")),e.length=0)}return e.length>0&&t.push(e.join("")),t}function rh(s,t,e,i){const r=e(s),n=[];for(let o=0;o<r.length;o++){let a=r[o],l=a,h=1;for(;r[o+h];){const c=r[o+h];if(!i(l,c,s,o,t))a+=c,l=c,h++;else break}o+=h-1,n.push(a)}return n}const jm=/\r\n|\r|\n/g;function Xm(s,t,e,i,r,n,o,a){var at,G;const l=Dm(s,t);if(ih(t.whiteSpace))for(let U=0;U<l.length;U++){const X=l[U];l[U]={text:X.text.replace(jm," "),style:X.style}}const c=[];let u=[];for(const U of l){const X=U.text.split(Vm);for(let D=0;D<X.length;D++){const $=X[D];$===`\r
|
|
541
|
+
`||$==="\r"||$===`
|
|
542
|
+
`?(c.push(u),u=[]):$.length>0&&u.push({text:$,style:U.style})}}(u.length>0||c.length===0)&&c.push(u);const m=e?Ym(c,t,i,r,o,a):c,f=[],g=[],y=[],x=[],v=[];let E=0;const T=t._fontString,C=n(T);C.fontSize===0&&(C.fontSize=t.fontSize,C.ascent=t.fontSize);let R="",A=!!t.dropShadow,I=((at=t._stroke)==null?void 0:at.width)||0;for(const U of m){let X=0,D=C.ascent,$=C.descent,Y="";for(const V of U){const ot=V.style._fontString,lt=n(ot);ot!==R&&(i.font=ot,R=ot);const gt=r(V.text,V.style.letterSpacing,i);X+=gt,D=Math.max(D,lt.ascent),$=Math.max($,lt.descent),Y+=V.text;const ht=((G=V.style._stroke)==null?void 0:G.width)||0;ht>I&&(I=ht),!A&&V.style.dropShadow&&(A=!0)}U.length===0&&(D=C.ascent,$=C.descent),f.push(X),g.push(D),y.push($),v.push(Y);const j=t.lineHeight||D+$;x.push(j+t.leading),E=Math.max(E,X)}const N=I,O=(e&&t.align!=="left"?Math.max(E,t.wordWrapWidth):E)+N+(t.dropShadow?t.dropShadow.distance:0);let L=0;for(let U=0;U<x.length;U++)L+=x[U];L=Math.max(L,x[0]+N);const F=L+(t.dropShadow?t.dropShadow.distance:0),H=t.lineHeight||C.fontSize;return{width:O,height:F,lines:v,lineWidths:f,lineHeight:H+t.leading,maxLineWidth:E,fontProperties:C,runsByLine:m,lineAscents:g,lineDescents:y,lineHeights:x,hasDropShadow:A}}function Ym(s,t,e,i,r,n){var x;const{letterSpacing:o,whiteSpace:a,wordWrapWidth:l,breakWords:h}=t,c=eh(a),u=l+o,m={};let f="";const g=(v,E)=>{const T=`${v}|${E.styleKey}`;let C=m[T];if(C===void 0){const R=E._fontString;R!==f&&(e.font=R,f=R),C=i(v,E.letterSpacing,e)+E.letterSpacing,m[T]=C}return C},y=[];for(const v of s){const E=qm(v),T=y.length,C=L=>{let F=0,H=L;do{const{token:at,style:G}=E[H];F+=g(at,G),H++}while(H<E.length&&E[H].continuesFromPrevious);return F},R=L=>{const F=[];let H=L;do F.push({token:E[H].token,style:E[H].style}),H++;while(H<E.length&&E[H].continuesFromPrevious);return F};let A=[],I=0,N=!c,B=null;const k=()=>{B&&B.text.length>0&&A.push(B),B=null},O=()=>{if(k(),A.length>0){const L=A[A.length-1];L.text=we(L.text),L.text.length===0&&A.pop()}y.push(A),A=[],I=0,N=!1};for(let L=0;L<E.length;L++){const{token:F,style:H,continuesFromPrevious:at}=E[L],G=g(F,H);if(c){const D=ee(F),$=(B==null?void 0:B.text[B.text.length-1])??((x=A[A.length-1])==null?void 0:x.text.slice(-1))??"",Y=$?ee($):!1;if(D&&Y)continue}const U=!at,X=U?C(L):G;if(X>u&&U)if(I>0&&O(),h){const D=R(L);for(let $=0;$<D.length;$++){const Y=D[$].token,j=D[$].style,V=rh(Y,h,n,r);for(const ot of V){const lt=g(ot,j);lt+I>u&&O(),!B||B.style!==j?(k(),B={text:ot,style:j}):B.text+=ot,I+=lt}}L+=D.length-1}else{const D=R(L);k(),y.push(D.map($=>({text:$.token,style:$.style}))),N=!1,L+=D.length-1}else if(X+I>u&&U){if(ee(F)){N=!1;continue}O(),B={text:F,style:H},I=G}else if(at&&!h)!B||B.style!==H?(k(),B={text:F,style:H}):B.text+=F,I+=G;else{const D=ee(F);if(I===0&&D&&!N)continue;!B||B.style!==H?(k(),B={text:F,style:H}):B.text+=F,I+=G}}if(k(),A.length>0){const L=A[A.length-1];L.text=we(L.text),L.text.length===0&&A.pop()}(A.length>0||y.length===T)&&y.push(A)}return y}function qm(s){const t=[];let e=!1;for(const i of s){const r=sh(i.text);let n=!0;for(const o of r){const a=ee(o)||Os(o),l=n&&e&&!a;t.push({token:o,style:i.style,continuesFromPrevious:l}),e=!a,n=!1}}return t}const Km={willReadFrequently:!0};function nh(s,t,e,i,r){let n=e[s];return typeof n!="number"&&(n=r(s,t,i)+t,e[s]=n),n}function Zm(s,t,e,i,r,n,o){const a=e.getContext("2d",Km);a.font=t._fontString;let l=0,h="";const c=[],u=Object.create(null),{letterSpacing:m,whiteSpace:f}=t,g=eh(f),y=ih(f);let x=!g;const v=t.wordWrapWidth+m,E=sh(s);for(let C=0;C<E.length;C++){let R=E[C];if(Os(R)){if(!y){c.push(we(h)),x=!g,h="",l=0;continue}R=" "}if(g){const I=ee(R),N=ee(h[h.length-1]);if(I&&N)continue}const A=nh(R,m,u,a,i);if(A>v)if(h!==""&&(c.push(we(h)),h="",l=0),r(R,t.breakWords)){const I=rh(R,t.breakWords,o,n);for(const N of I){const B=nh(N,m,u,a,i);B+l>v&&(c.push(we(h)),x=!1,h="",l=0),h+=N,l+=B}}else h.length>0&&(c.push(we(h)),h="",l=0),c.push(we(R)),x=!1,h="",l=0;else A+l>v&&(x=!1,c.push(we(h)),h="",l=0),(h.length>0||!ee(R)||x)&&(h+=R,l+=A)}const T=we(h);return T.length>0&&c.push(T),c.join(`
|
|
543
|
+
`)}const oh={willReadFrequently:!0},Ae=class q{static get experimentalLetterSpacingSupported(){let t=q._experimentalLetterSpacingSupported;if(t===void 0){const e=rt.get().getCanvasRenderingContext2D().prototype;t=q._experimentalLetterSpacingSupported="letterSpacing"in e||"textLetterSpacing"in e}return t}constructor(t,e,i,r,n,o,a,l,h,c){this.text=t,this.style=e,this.width=i,this.height=r,this.lines=n,this.lineWidths=o,this.lineHeight=a,this.maxLineWidth=l,this.fontProperties=h,c&&(this.runsByLine=c.runsByLine,this.lineAscents=c.lineAscents,this.lineDescents=c.lineDescents,this.lineHeights=c.lineHeights,this.hasDropShadow=c.hasDropShadow)}static measureText(t=" ",e,i=q._canvas,r=e.wordWrap){var R;const n=`${t}-${e.styleKey}-wordWrap-${r}`;if(q._measurementCache.has(n))return q._measurementCache.get(n);if(Ql(e)&&th(t)){const A=Xm(t,e,r,q._context,q._measureText,q.measureFont,q.canBreakChars,q.wordWrapSplit),I=new q(t,e,A.width,A.height,A.lines,A.lineWidths,A.lineHeight,A.maxLineWidth,A.fontProperties,{runsByLine:A.runsByLine,lineAscents:A.lineAscents,lineDescents:A.lineDescents,lineHeights:A.lineHeights,hasDropShadow:A.hasDropShadow});return q._measurementCache.set(n,I),I}const a=e._fontString,l=q.measureFont(a);l.fontSize===0&&(l.fontSize=e.fontSize,l.ascent=e.fontSize,l.descent=0);const h=q._context;h.font=a;const u=(r?q._wordWrap(t,e,i):t).split(zm),m=new Array(u.length);let f=0;for(let A=0;A<u.length;A++){const I=q._measureText(u[A],e.letterSpacing,h);m[A]=I,f=Math.max(f,I)}const g=((R=e._stroke)==null?void 0:R.width)??0,y=e.lineHeight||l.fontSize,x=q._getAlignWidth(f,e,r),v=q._adjustWidthForStyle(x,e),E=Math.max(y,l.fontSize+g)+(u.length-1)*(y+e.leading),T=q._adjustHeightForStyle(E,e),C=new q(t,e,v,T,u,m,y+e.leading,f,l);return q._measurementCache.set(n,C),C}static _adjustWidthForStyle(t,e){var n;const i=((n=e._stroke)==null?void 0:n.width)||0;let r=t+i;return e.dropShadow&&(r+=e.dropShadow.distance),r}static _adjustHeightForStyle(t,e){let i=t;return e.dropShadow&&(i+=e.dropShadow.distance),i}static _getAlignWidth(t,e,i){return i&&e.align!=="left"?Math.max(t,e.wordWrapWidth):t}static _measureText(t,e,i){let r=!1;q.experimentalLetterSpacingSupported&&(q.experimentalLetterSpacing?(i.letterSpacing=`${e}px`,i.textLetterSpacing=`${e}px`,r=!0):(i.letterSpacing="0px",i.textLetterSpacing="0px"));const n=i.measureText(t);let o=n.width;const a=-(n.actualBoundingBoxLeft??0);let h=(n.actualBoundingBoxRight??0)-a;if(o>0)if(r)o-=e,h-=e;else{const c=(q.graphemeSegmenter(t).length-1)*e;o+=c,h+=c}return Math.max(o,h)}static _wordWrap(t,e,i=q._canvas){return Zm(t,e,i,q._measureText,q.canBreakWords,q.canBreakChars,q.wordWrapSplit)}static isBreakingSpace(t,e){return ee(t)}static canBreakWords(t,e){return e}static canBreakChars(t,e,i,r,n){return!0}static wordWrapSplit(t){return q.graphemeSegmenter(t)}static measureFont(t){if(q._fonts[t])return q._fonts[t];const e=q._context;e.font=t;const i=e.measureText(q.METRICS_STRING+q.BASELINE_SYMBOL),r=i.actualBoundingBoxAscent??0,n=i.actualBoundingBoxDescent??0,o={ascent:r,descent:n,fontSize:r+n};return q._fonts[t]=o,o}static clearMetrics(t=""){t?delete q._fonts[t]:q._fonts={}}static get _canvas(){if(!q.__canvas){let t;try{const e=new OffscreenCanvas(0,0),i=e.getContext("2d",oh);if(i!=null&&i.measureText)return q.__canvas=e,e;t=rt.get().createCanvas()}catch{t=rt.get().createCanvas()}t.width=t.height=10,q.__canvas=t}return q.__canvas}static get _context(){return q.__context||(q.__context=q._canvas.getContext("2d",oh)),q.__context}};Ae.METRICS_STRING="|ÉqÅ",Ae.BASELINE_SYMBOL="M",Ae.BASELINE_MULTIPLIER=1.4,Ae.HEIGHT_MULTIPLIER=2,Ae.graphemeSegmenter=(()=>{if(typeof(Intl==null?void 0:Intl.Segmenter)=="function"){const s=new Intl.Segmenter;return t=>{const e=s.segment(t),i=[];let r=0;for(const n of e)i[r++]=n.segment;return i}}return s=>[...s]})(),Ae.experimentalLetterSpacing=!1,Ae._fonts={},Ae._measurementCache=Bm(1e3);let Oe=Ae;const Jm=["serif","sans-serif","monospace","cursive","fantasy","system-ui"];function dn(s){const t=typeof s.fontSize=="number"?`${s.fontSize}px`:s.fontSize;let e=s.fontFamily;Array.isArray(s.fontFamily)||(e=s.fontFamily.split(","));for(let i=e.length-1;i>=0;i--){let r=e[i].trim();!/([\"\'])[^\'\"]+\1/.test(r)&&!Jm.includes(r)&&(r=`"${r}"`),e[i]=r}return`${s.fontStyle} ${s.fontVariant} ${s.fontWeight} ${t} ${e.join(",")}`}const ah=1e5;function Ds(s,t,e,i=0,r=0,n=0){if(s.texture===z.WHITE&&!s.fill)return ct.shared.setValue(s.color).setAlpha(s.alpha??1).toHexa();if(s.fill){if(s.fill instanceof is){const o=s.fill,a=t.createPattern(o.texture.source.resource,"repeat"),l=o.transform.copyTo(W.shared);return l.scale(o.texture.source.pixelWidth,o.texture.source.pixelHeight),a.setTransform(l),a}else if(s.fill instanceof de){const o=s.fill,a=o.type==="linear",l=o.textureSpace==="local";let h=1,c=1;l&&e&&(h=e.width+i,c=e.height+i);let u,m=!1;if(a){const{start:f,end:g}=o;u=t.createLinearGradient(f.x*h+r,f.y*c+n,g.x*h+r,g.y*c+n),m=Math.abs(g.x-f.x)<Math.abs((g.y-f.y)*.1)}else{const{center:f,innerRadius:g,outerCenter:y,outerRadius:x}=o;u=t.createRadialGradient(f.x*h+r,f.y*c+n,g*h,y.x*h+r,y.y*c+n,x*h)}if(m&&l&&e){const f=e.lineHeight/c;for(let g=0;g<e.lines.length;g++){const y=(g*e.lineHeight+i/2)/c;o.colorStops.forEach(x=>{let v=y+x.offset*f;v=Math.max(0,Math.min(1,v)),u.addColorStop(Math.floor(v*ah)/ah,ct.shared.setValue(x.color).toHex())})}}else o.colorStops.forEach(f=>{u.addColorStop(f.offset,ct.shared.setValue(f.color).toHex())});return u}}else{const o=t.createPattern(s.texture.source.resource,"repeat"),a=s.matrix.copyTo(W.shared);return a.scale(s.texture.source.pixelWidth,s.texture.source.pixelHeight),o.setTransform(a),o}return tt("FillStyle not recognised",s),"red"}const lh=new ut;function Ti(s){let t=0;for(let e=0;e<s.length;e++)s.charCodeAt(e)===32&&t++;return t}class Qm{getCanvasAndContext(t){const{text:e,style:i,resolution:r=1}=t,n=i._getFinalPadding(),o=Oe.measureText(e||" ",i),a=Math.ceil(Math.ceil(Math.max(1,o.width)+n*2)*r),l=Math.ceil(Math.ceil(Math.max(1,o.height)+n*2)*r),h=rs.getOptimalCanvasAndContext(a,l);this._renderTextToCanvas(i,n,r,h,o);const c=i.trim?Mm({canvas:h.canvas,width:a,height:l,resolution:1,output:lh}):lh.set(0,0,a,l);return{canvasAndContext:h,frame:c}}returnCanvasAndContext(t){rs.returnCanvasAndContext(t)}_renderTextToCanvas(t,e,i,r,n){var A,I,N;if(n.runsByLine&&n.runsByLine.length>0){this._renderTaggedTextToCanvas(n,t,e,i,r);return}const{canvas:o,context:a}=r,l=dn(t),h=n.lines,c=n.lineHeight,u=n.lineWidths,m=n.maxLineWidth,f=n.fontProperties,g=o.height;if(a.resetTransform(),a.scale(i,i),a.textBaseline=t.textBaseline,(A=t._stroke)!=null&&A.width){const B=t._stroke;a.lineWidth=B.width,a.miterLimit=B.miterLimit,a.lineJoin=B.join,a.lineCap=B.cap}a.font=l;let y,x;const v=t.dropShadow?2:1,E=t.wordWrap?Math.max(t.wordWrapWidth,m):m,C=(((I=t._stroke)==null?void 0:I.width)??0)/2;let R=(c-f.fontSize)/2;c-f.fontSize<0&&(R=0);for(let B=0;B<v;++B){const k=t.dropShadow&&B===0,O=k?Math.ceil(Math.max(1,g)+e*2):0,L=O*i;if(k)this._setupDropShadow(a,t,i,L);else{const F=t._gradientBounds,H=t._gradientOffset;if(F){const at={width:F.width,height:F.height,lineHeight:F.height,lines:n.lines};this._setFillAndStrokeStyles(a,t,at,e,C,(H==null?void 0:H.x)??0,(H==null?void 0:H.y)??0)}else H?this._setFillAndStrokeStyles(a,t,n,e,C,H.x,H.y):this._setFillAndStrokeStyles(a,t,n,e,C);a.shadowColor="rgba(0,0,0,0)"}for(let F=0;F<h.length;F++){y=C,x=C+F*c+f.ascent+R,y+=this._getAlignmentOffset(u[F],E,t.align);let H=0;if(t.align==="justify"&&t.wordWrap&&F<h.length-1){const at=Ti(h[F]);at>0&&(H=(E-u[F])/at)}(N=t._stroke)!=null&&N.width&&this._drawLetterSpacing(h[F],t,r,y+e,x+e-O,!0,H),t._fill!==void 0&&this._drawLetterSpacing(h[F],t,r,y+e,x+e-O,!1,H)}}}_renderTaggedTextToCanvas(t,e,i,r,n){var C,R,A;const{canvas:o,context:a}=n,{runsByLine:l,lineWidths:h,maxLineWidth:c,lineAscents:u,lineHeights:m,hasDropShadow:f}=t,g=o.height;a.resetTransform(),a.scale(r,r),a.textBaseline=e.textBaseline;const y=f?2:1,x=e.wordWrap?Math.max(e.wordWrapWidth,c):c;let v=((C=e._stroke)==null?void 0:C.width)??0;for(const I of l)for(const N of I){const B=((R=N.style._stroke)==null?void 0:R.width)??0;B>v&&(v=B)}const E=v/2,T=[];for(let I=0;I<l.length;I++){const N=l[I],B=[];for(const k of N){const O=dn(k.style);a.font=O,B.push({width:Oe._measureText(k.text,k.style.letterSpacing,a),font:O})}T.push(B)}for(let I=0;I<y;++I){const N=f&&I===0,B=N?Math.ceil(Math.max(1,g)+i*2):0,k=B*r;N||(a.shadowColor="rgba(0,0,0,0)");let O=E;for(let L=0;L<l.length;L++){const F=l[L],H=h[L],at=u[L],G=m[L],U=T[L];let X=E;X+=this._getAlignmentOffset(H,x,e.align);let D=0;if(e.align==="justify"&&e.wordWrap&&L<l.length-1){let j=0;for(const V of F)j+=Ti(V.text);j>0&&(D=(x-H)/j)}const $=O+at;let Y=X+i;for(let j=0;j<F.length;j++){const V=F[j],{width:ot,font:lt}=U[j];if(a.font=lt,a.textBaseline=V.style.textBaseline,(A=V.style._stroke)!=null&&A.width){const ht=V.style._stroke;if(a.lineWidth=ht.width,a.miterLimit=ht.miterLimit,a.lineJoin=ht.join,a.lineCap=ht.cap,N)if(V.style.dropShadow)this._setupDropShadow(a,V.style,r,k);else{const _t=Ti(V.text);Y+=ot+_t*D;continue}else{const _t=Oe.measureFont(lt),Z=V.style.lineHeight||_t.fontSize,Bt={width:ot,height:Z,lineHeight:Z,lines:[V.text]};a.strokeStyle=Ds(ht,a,Bt,i*2,Y-i,O)}this._drawLetterSpacing(V.text,V.style,n,Y,$+i-B,!0,D)}const gt=Ti(V.text);Y+=ot+gt*D}Y=X+i;for(let j=0;j<F.length;j++){const V=F[j],{width:ot,font:lt}=U[j];if(a.font=lt,a.textBaseline=V.style.textBaseline,V.style._fill!==void 0){if(N)if(V.style.dropShadow)this._setupDropShadow(a,V.style,r,k);else{const ht=Ti(V.text);Y+=ot+ht*D;continue}else{const ht=Oe.measureFont(lt),_t=V.style.lineHeight||ht.fontSize,Z={width:ot,height:_t,lineHeight:_t,lines:[V.text]};a.fillStyle=Ds(V.style._fill,a,Z,i*2,Y-i,O)}this._drawLetterSpacing(V.text,V.style,n,Y,$+i-B,!1,D)}const gt=Ti(V.text);Y+=ot+gt*D}O+=G}}}_setFillAndStrokeStyles(t,e,i,r,n,o=0,a=0){var l;if(t.fillStyle=e._fill?Ds(e._fill,t,i,r*2,o,a):null,(l=e._stroke)!=null&&l.width){const h=n+r*2;t.strokeStyle=Ds(e._stroke,t,i,h,o,a)}}_setupDropShadow(t,e,i,r){t.fillStyle="black",t.strokeStyle="black";const n=e.dropShadow,o=n.color,a=n.alpha;t.shadowColor=ct.shared.setValue(o).setAlpha(a).toRgbaString();const l=n.blur*i,h=n.distance*i;t.shadowBlur=l,t.shadowOffsetX=Math.cos(n.angle)*h,t.shadowOffsetY=Math.sin(n.angle)*h+r}_getAlignmentOffset(t,e,i){return i==="right"?e-t:i==="center"?(e-t)/2:0}_drawLetterSpacing(t,e,i,r,n,o=!1,a=0){const{context:l}=i,h=e.letterSpacing;let c=!1;if(Oe.experimentalLetterSpacingSupported&&(Oe.experimentalLetterSpacing?(l.letterSpacing=`${h}px`,l.textLetterSpacing=`${h}px`,c=!0):(l.letterSpacing="0px",l.textLetterSpacing="0px")),(h===0||c)&&a===0){o?l.strokeText(t,r,n):l.fillText(t,r,n);return}if(a!==0&&(h===0||c)){const y=t.split(" ");let x=r;const v=l.measureText(" ").width;for(let E=0;E<y.length;E++)o?l.strokeText(y[E],x,n):l.fillText(y[E],x,n),x+=l.measureText(y[E]).width+v+a;return}let u=r;const m=Oe.graphemeSegmenter(t);let f=l.measureText(t).width,g=0;for(let y=0;y<m.length;++y){const x=m[y];o?l.strokeText(x,u,n):l.fillText(x,u,n);let v="";for(let E=y+1;E<m.length;++E)v+=m[E];g=l.measureText(v).width,u+=f-g+h,x===" "&&(u+=a),f=g}}}const Si=new Qm,fn=class ni extends Jt{constructor(t={}){super(),this.uid=dt("textStyle"),this._tick=0,this._cachedFontString=null,tg(t),t instanceof ni&&(t=t._toObject());const r={...ni.defaultTextStyle,...t};for(const n in r){const o=n;this[o]=r[n]}this._tagStyles=t.tagStyles??void 0,this.update(),this._tick=0}get align(){return this._align}set align(t){this._align!==t&&(this._align=t,this.update())}get breakWords(){return this._breakWords}set breakWords(t){this._breakWords!==t&&(this._breakWords=t,this.update())}get dropShadow(){return this._dropShadow}set dropShadow(t){this._dropShadow!==t&&(t!==null&&typeof t=="object"?this._dropShadow=this._createProxy({...ni.defaultDropShadow,...t}):this._dropShadow=t?this._createProxy({...ni.defaultDropShadow}):null,this.update())}get fontFamily(){return this._fontFamily}set fontFamily(t){this._fontFamily!==t&&(this._fontFamily=t,this.update())}get fontSize(){return this._fontSize}set fontSize(t){this._fontSize!==t&&(typeof t=="string"?this._fontSize=parseInt(t,10):this._fontSize=t,this.update())}get fontStyle(){return this._fontStyle}set fontStyle(t){this._fontStyle!==t&&(this._fontStyle=t.toLowerCase(),this.update())}get fontVariant(){return this._fontVariant}set fontVariant(t){this._fontVariant!==t&&(this._fontVariant=t,this.update())}get fontWeight(){return this._fontWeight}set fontWeight(t){this._fontWeight!==t&&(this._fontWeight=t,this.update())}get leading(){return this._leading}set leading(t){this._leading!==t&&(this._leading=t,this.update())}get letterSpacing(){return this._letterSpacing}set letterSpacing(t){this._letterSpacing!==t&&(this._letterSpacing=t,this.update())}get lineHeight(){return this._lineHeight}set lineHeight(t){this._lineHeight!==t&&(this._lineHeight=t,this.update())}get padding(){return this._padding}set padding(t){this._padding!==t&&(this._padding=t,this.update())}get filters(){return this._filters}set filters(t){this._filters!==t&&(this._filters=Object.freeze(t),this.update())}get trim(){return this._trim}set trim(t){this._trim!==t&&(this._trim=t,this.update())}get textBaseline(){return this._textBaseline}set textBaseline(t){this._textBaseline!==t&&(this._textBaseline=t,this.update())}get whiteSpace(){return this._whiteSpace}set whiteSpace(t){this._whiteSpace!==t&&(this._whiteSpace=t,this.update())}get wordWrap(){return this._wordWrap}set wordWrap(t){this._wordWrap!==t&&(this._wordWrap=t,this.update())}get wordWrapWidth(){return this._wordWrapWidth}set wordWrapWidth(t){this._wordWrapWidth!==t&&(this._wordWrapWidth=t,this.update())}get fill(){return this._originalFill}set fill(t){t!==this._originalFill&&(this._originalFill=t,this._isFillStyle(t)&&(this._originalFill=this._createProxy({...se.defaultFillStyle,...t},()=>{this._fill=Qe({...this._originalFill},se.defaultFillStyle)})),this._fill=Qe(t===0?"black":t,se.defaultFillStyle),this.update())}get stroke(){return this._originalStroke}set stroke(t){t!==this._originalStroke&&(this._originalStroke=t,this._isFillStyle(t)&&(this._originalStroke=this._createProxy({...se.defaultStrokeStyle,...t},()=>{this._stroke=Ms({...this._originalStroke},se.defaultStrokeStyle)})),this._stroke=Ms(t,se.defaultStrokeStyle),this.update())}get tagStyles(){return this._tagStyles}set tagStyles(t){this._tagStyles!==t&&(this._tagStyles=t??void 0,this.update())}update(){this._tick++,this._cachedFontString=null,this.emit("update",this)}reset(){const t=ni.defaultTextStyle;for(const e in t)this[e]=t[e]}assign(t){for(const e in t){const i=e;this[i]=t[e]}return this}get styleKey(){return`${this.uid}-${this._tick}`}get _fontString(){return this._cachedFontString===null&&(this._cachedFontString=dn(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 ni(this._toObject())}_getFinalPadding(){let t=0;if(this._filters)for(let e=0;e<this._filters.length;e++)t+=this._filters[e].padding;return Math.max(this._padding,t)}destroy(t=!1){var i,r,n,o;if(this.removeAllListeners(),typeof t=="boolean"?t:t==null?void 0:t.texture){const a=typeof t=="boolean"?t:t==null?void 0:t.textureSource;(i=this._fill)!=null&&i.texture&&this._fill.texture.destroy(a),(r=this._originalFill)!=null&&r.texture&&this._originalFill.texture.destroy(a),(n=this._stroke)!=null&&n.texture&&this._stroke.texture.destroy(a),(o=this._originalStroke)!=null&&o.texture&&this._originalStroke.texture.destroy(a)}this._fill=null,this._stroke=null,this.dropShadow=null,this._originalStroke=null,this._originalFill=null}_createProxy(t,e){return new Proxy(t,{set:(i,r,n)=>(i[r]===n||(i[r]=n,e==null||e(r,n),this.update()),!0)})}_isFillStyle(t){return(t??null)!==null&&!(ct.isColorLike(t)||t instanceof de||t instanceof is)}};fn.defaultDropShadow={alpha:1,angle:Math.PI/6,blur:0,color:"black",distance:5},fn.defaultTextStyle={align:"left",breakWords:!1,dropShadow:null,fill:"black",fontFamily:"Arial",fontSize:26,fontStyle:"normal",fontVariant:"normal",fontWeight:"normal",leading:0,letterSpacing:0,lineHeight:0,padding:0,stroke:null,textBaseline:"alphabetic",trim:!1,whiteSpace:"pre",wordWrap:!1,wordWrapWidth:100};let Gs=fn;function tg(s){const t=s;if(typeof t.dropShadow=="boolean"&&t.dropShadow){const e=Gs.defaultDropShadow;s.dropShadow={alpha:t.dropShadowAlpha??e.alpha,angle:t.dropShadowAngle??e.angle,blur:t.dropShadowBlur??e.blur,color:t.dropShadowColor??e.color,distance:t.dropShadowDistance??e.distance}}if(t.strokeThickness!==void 0){K(vt,"strokeThickness is now a part of stroke");const e=t.stroke;let i={};if(ct.isColorLike(e))i.color=e;else if(e instanceof de||e instanceof is)i.fill=e;else if(Object.hasOwnProperty.call(e,"color")||Object.hasOwnProperty.call(e,"fill"))i=e;else throw new Error("Invalid stroke value.");s.stroke={...i,width:t.strokeThickness}}if(Array.isArray(t.fillGradientStops)){if(K(vt,"gradient fill is now a fill pattern: `new FillGradient(...)`"),!Array.isArray(t.fill)||t.fill.length===0)throw new Error("Invalid fill value. Expected an array of colors for gradient fill.");t.fill.length!==t.fillGradientStops.length&&tt("The number of fill colors must match the number of fill gradient stops.");const e=new de({start:{x:0,y:0},end:{x:0,y:1},textureSpace:"local"}),i=t.fillGradientStops.slice(),r=t.fill.map(n=>ct.shared.setValue(n).toNumber());i.forEach((n,o)=>{e.addColorStop(n,r[o])}),s.fill={fill:e}}}function eg(s,t){const{texture:e,bounds:i}=s,r=t._style._getFinalPadding();xo(i,t._anchor,e);const n=t._anchor._x*r*2,o=t._anchor._y*r*2;i.minX-=r-n,i.minY-=r-o,i.maxX-=r-n,i.maxY-=r-o}class pn{constructor(){this.batcherName="default",this.topology="triangle-list",this.attributeSize=4,this.indexSize=6,this.packAsQuad=!0,this.roundPixels=0,this._attributeStart=0,this._batcher=null,this._batch=null}get blendMode(){return this.renderable.groupBlendMode}get color(){return this.renderable.groupColorAlpha}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.bounds=null}destroy(){this.reset()}}class ig extends pn{}class hh{constructor(t){this._renderer=t,t.runners.resolutionChange.add(this),this._managedTexts=new ue({renderer:t,type:"renderable",onUnload:this.onTextUnload.bind(this),name:"canvasText"})}resolutionChange(){for(const t in this._managedTexts.items){const e=this._managedTexts.items[t];e!=null&&e._autoResolution&&e.onViewUpdate()}}validateRenderable(t){const e=this._getGpuText(t),i=t.styleKey;return e.currentKey!==i?!0:t._didTextUpdate}addRenderable(t,e){const i=this._getGpuText(t);if(t._didTextUpdate){const r=t._autoResolution?this._renderer.resolution:t.resolution;(i.currentKey!==t.styleKey||t._resolution!==r)&&this._updateGpuText(t),t._didTextUpdate=!1,eg(i,t)}this._renderer.renderPipes.batch.addToBatch(i,e)}updateRenderable(t){const e=this._getGpuText(t);e._batcher.updateElement(e)}_updateGpuText(t){const e=this._getGpuText(t);e.texture&&this._renderer.canvasText.decreaseReferenceCount(e.currentKey),t._resolution=t._autoResolution?this._renderer.resolution:t.resolution,e.texture=this._renderer.canvasText.getManagedTexture(t),e.currentKey=t.styleKey}_getGpuText(t){return t._gpuData[this._renderer.uid]||this.initGpuText(t)}initGpuText(t){const e=new ig;return e.currentKey="--",e.renderable=t,e.transform=t.groupTransform,e.bounds={minX:0,maxX:1,minY:0,maxY:0},e.roundPixels=this._renderer._roundPixels|t._roundPixels,t._gpuData[this._renderer.uid]=e,this._managedTexts.add(t),e}onTextUnload(t){const e=t._gpuData[this._renderer.uid];if(!e)return;const{canvasText:i}=this._renderer;i.getReferenceCount(e.currentKey)>0?i.decreaseReferenceCount(e.currentKey):e.texture&&i.returnTexture(e.texture)}destroy(){this._managedTexts.destroy(),this._renderer=null}}hh.extension={type:[w.WebGLPipes,w.WebGPUPipes,w.CanvasPipes],name:"text"};const sg=new Lt;function rg(s,t,e,i,r=!1){const n=sg;n.minX=0,n.minY=0,n.maxX=s.width/i|0,n.maxY=s.height/i|0;const o=Ft.getOptimalTexture(n.width,n.height,i,!1,r);return o.source.uploadMethodId="image",o.source.resource=s,o.source.alphaMode="premultiply-alpha-on-upload",o.frame.width=t/i,o.frame.height=e/i,o.source.emit("update",o.source),o.updateUvs(),o}class ch{constructor(t,e){this._activeTextures={},this._renderer=t,this._retainCanvasContext=e}getTexture(t,e,i,r){typeof t=="string"&&(K("8.0.0","CanvasTextSystem.getTexture: Use object TextOptions instead of separate arguments"),t={text:t,style:i,resolution:e}),t.style instanceof Gs||(t.style=new Gs(t.style)),t.textureStyle instanceof Xe||(t.textureStyle=new Xe(t.textureStyle)),typeof t.text!="string"&&(t.text=t.text.toString());const{text:n,style:o,textureStyle:a,autoGenerateMipmaps:l}=t,h=t.resolution??this._renderer.resolution,{frame:c,canvasAndContext:u}=Si.getCanvasAndContext({text:n,style:o,resolution:h}),m=rg(u.canvas,c.width,c.height,h,l);if(a&&(m.source.style=a),o.trim&&(c.pad(o.padding),m.frame.copyFrom(c),m.frame.scale(1/h),m.updateUvs()),o.filters){const f=this._applyFilters(m,o.filters);return this.returnTexture(m),Si.returnCanvasAndContext(u),f}return this._renderer.texture.initSource(m._source),this._retainCanvasContext||Si.returnCanvasAndContext(u),m}returnTexture(t){const e=t.source,i=e.resource;if(this._retainCanvasContext&&(i!=null&&i.getContext)){const r=i.getContext("2d");r&&Si.returnCanvasAndContext({canvas:i,context:r})}e.resource=null,e.uploadMethodId="unknown",e.alphaMode="no-premultiply-alpha",Ft.returnTexture(t,!0)}renderTextToCanvas(){K("8.10.0","CanvasTextSystem.renderTextToCanvas: no longer supported, use CanvasTextSystem.getTexture instead")}getManagedTexture(t){t._resolution=t._autoResolution?this._renderer.resolution:t.resolution;const e=t.styleKey;if(this._activeTextures[e])return this._increaseReferenceCount(e),this._activeTextures[e].texture;const i=this.getTexture({text:t.text,style:t.style,resolution:t._resolution,textureStyle:t.textureStyle,autoGenerateMipmaps:t.autoGenerateMipmaps});return this._activeTextures[e]={texture:i,usageCount:1},i}decreaseReferenceCount(t){const e=this._activeTextures[t];e&&(e.usageCount--,e.usageCount===0&&(this.returnTexture(e.texture),this._activeTextures[t]=null))}getReferenceCount(t){var e;return((e=this._activeTextures[t])==null?void 0:e.usageCount)??0}_increaseReferenceCount(t){this._activeTextures[t].usageCount++}_applyFilters(t,e){const i=this._renderer.renderTarget.renderTarget,r=this._renderer.filter.generateFilteredTexture({texture:t,filters:e});return this._renderer.renderTarget.bind(i,!1),r}destroy(){this._renderer=null;for(const t in this._activeTextures)this._activeTextures[t]&&this.returnTexture(this._activeTextures[t].texture);this._activeTextures=null}}class uh extends ch{constructor(t){super(t,!0)}}uh.extension={type:[w.CanvasSystem],name:"canvasText"};class dh extends ch{constructor(t){super(t,!1)}}dh.extension={type:[w.WebGLSystem,w.WebGPUSystem],name:"canvasText"},J.add(uh),J.add(dh),J.add(hh);class ng extends Am{constructor(...t){const e=Rm(t,"Text");super(e,Gs),this.renderPipeId="text",e.textureStyle&&(this.textureStyle=e.textureStyle instanceof Xe?e.textureStyle:new Xe(e.textureStyle)),this.autoGenerateMipmaps=e.autoGenerateMipmaps??At.defaultOptions.autoGenerateMipmaps}updateBounds(){const t=this._bounds,e=this._anchor;let i=0,r=0;if(this._style.trim){const{frame:n,canvasAndContext:o}=Si.getCanvasAndContext({text:this.text,style:this._style,resolution:1});Si.returnCanvasAndContext(o),i=n.width,r=n.height}else{const n=Oe.measureText(this._text,this._style);i=n.width,r=n.height}t.minX=-e._x*i,t.maxX=t.minX+i,t.minY=-e._y*r,t.maxY=t.minY+r}}function og(){const{userAgent:s}=rt.get().getNavigator();return/^((?!chrome|android).)*safari/i.test(s)}const mn=class oi{static _getPatternRepeat(t,e){const i=t&&t!=="clamp-to-edge",r=e&&e!=="clamp-to-edge";return i&&r?"repeat":i?"repeat-x":r?"repeat-y":"no-repeat"}start(t,e,i){}execute(t,e){var a,l,h,c;const i=e.elements;if(!i||!i.length)return;const r=t.renderer,n=r.canvasContext,o=n.activeContext;for(let u=0;u<i.length;u++){const m=i[u];if(!m.packAsQuad)continue;const f=m,g=f.texture,y=g?st.getCanvasSource(g):null;if(!y)continue;const x=g.source.style,v=n.smoothProperty,E=x.scaleMode!=="nearest";o[v]!==E&&(o[v]=E),n.setBlendMode(e.blendMode);const T=((a=r.globalUniforms.globalUniformData)==null?void 0:a.worldColor)??4294967295,C=f.color,R=(T>>>24&255)/255,A=(C>>>24&255)/255,I=((l=r.filter)==null?void 0:l.alphaMultiplier)??1,N=R*A*I;if(N<=0)continue;o.globalAlpha=N;const B=T&16777215,k=C&16777215,O=fi(di(k,B)),L=g.frame,F=x.addressModeU??x.addressMode,H=x.addressModeV??x.addressMode,at=oi._getPatternRepeat(F,H),G=g.source._resolution??g.source.resolution??1,U=(c=(h=f.renderable)==null?void 0:h.renderGroup)==null?void 0:c.isCachedAsTexture,X=L.x*G,D=L.y*G,$=L.width*G,Y=L.height*G,j=f.bounds,V=r.renderTarget.renderTarget.isRoot,ot=j.minX,lt=j.minY,gt=j.maxX-j.minX,ht=j.maxY-j.minY,_t=g.rotate,Z=g.uvs,Bt=Math.min(Z.x0,Z.x1,Z.x2,Z.x3,Z.y0,Z.y1,Z.y2,Z.y3),$t=Math.max(Z.x0,Z.x1,Z.x2,Z.x3,Z.y0,Z.y1,Z.y2,Z.y3),xt=at!=="no-repeat"&&(Bt<0||$t>1),Ut=_t&&!(!xt&&(O!==16777215||_t));Ut?(oi._tempPatternMatrix.copyFrom(f.transform),it.matrixAppendRotationInv(oi._tempPatternMatrix,_t,ot,lt,gt,ht),n.setContextTransform(oi._tempPatternMatrix,f.roundPixels===1,void 0,U&&V)):n.setContextTransform(f.transform,f.roundPixels===1,void 0,U&&V);const jt=Ut?0:ot,We=Ut?0:lt,pe=gt,ri=ht;if(xt){let Mi=y;const Ie=O!==16777215&&!_t,ne=L.width<=g.source.width&&L.height<=g.source.height;Ie&&ne&&(Mi=st.getTintedCanvas({texture:g},O));const Xt=o.createPattern(Mi,at);if(!Xt)continue;const ki=pe,Xs=ri;if(ki===0||Xs===0)continue;const oe=1/ki,Ys=1/Xs,_=(Z.x1-Z.x0)*oe,d=(Z.y1-Z.y0)*oe,p=(Z.x3-Z.x0)*Ys,b=(Z.y3-Z.y0)*Ys,S=Z.x0-_*jt-p*We,P=Z.y0-d*jt-b*We,M=g.source.pixelWidth,Q=g.source.pixelHeight;oi._tempPatternMatrix.set(_*M,d*Q,p*M,b*Q,S*M,P*Q),st.applyPatternTransform(Xt,oi._tempPatternMatrix),o.fillStyle=Xt,o.fillRect(jt,We,pe,ri)}else{const Ie=O!==16777215||_t?st.getTintedCanvas({texture:g},O):y,ne=Ie!==y;o.drawImage(Ie,ne?0:X,ne?0:D,ne?Ie.width:$,ne?Ie.height:Y,jt,We,pe,ri)}}}};mn._tempPatternMatrix=new W,mn.extension={type:[w.CanvasPipesAdaptor],name:"batch"};let ag=mn;class fh{constructor(){this._tempState=ve.for2d(),this._didUploadHash={}}init(t){t.renderer.runners.contextChange.add(this)}contextChange(){this._didUploadHash={}}start(t,e,i){const r=t.renderer,n=this._didUploadHash[i.uid];r.shader.bind(i,n),n||(this._didUploadHash[i.uid]=!0),r.shader.updateUniformGroup(r.globalUniforms.uniformGroup),r.geometry.bind(e,i.glProgram)}execute(t,e){const i=t.renderer;this._tempState.blendMode=e.blendMode,i.state.set(this._tempState);const r=e.textures.textures;for(let n=0;n<e.textures.count;n++)i.texture.bind(r[n],n);i.geometry.draw(e.topology,e.size,e.start)}}fh.extension={type:[w.WebGLPipesAdaptor],name:"batch"};const Us=ve.for2d();class ph{start(t,e,i){const r=t.renderer,n=r.encoder,o=i.gpuProgram;this._shader=i,this._geometry=e,n.setGeometry(e,o),Us.blendMode="normal",r.pipeline.getPipeline(e,o,Us);const a=r.globalUniforms.bindGroup;n.resetBindGroup(1),n.setBindGroup(0,a,o)}execute(t,e){const i=this._shader.gpuProgram,r=t.renderer,n=r.encoder;if(!e.bindGroup){const l=e.textures;e.bindGroup=Vr(l.textures,l.count,r.limits.maxBatchableTextures)}Us.blendMode=e.blendMode;const o=r.bindGroup.getBindGroup(e.bindGroup,i,1),a=r.pipeline.getPipeline(this._geometry,i,Us,e.topology);e.bindGroup._touch(r.gc.now,r.tick),n.setPipeline(a),n.renderPassEncoder.setBindGroup(1,o),n.renderPassEncoder.drawIndexed(e.size,1,e.start)}}ph.extension={type:[w.WebGPUPipesAdaptor],name:"batch"};const gn=class du{constructor(t,e){var i,r;this.state=ve.for2d(),this._batchersByInstructionSet=Object.create(null),this._activeBatches=Object.create(null),this.renderer=t,this._adaptor=e,(r=(i=this._adaptor).init)==null||r.call(i,this)}static getBatcher(t){return new this._availableBatchers[t]}buildStart(t){let e=this._batchersByInstructionSet[t.uid];e||(e=this._batchersByInstructionSet[t.uid]=Object.create(null),e.default||(e.default=new Qr({maxTextures:this.renderer.limits.maxBatchableTextures}))),this._activeBatches=e,this._activeBatch=this._activeBatches.default;for(const i in this._activeBatches)this._activeBatches[i].begin()}addToBatch(t,e){if(this._activeBatch.name!==t.batcherName){this._activeBatch.break(e);let i=this._activeBatches[t.batcherName];i||(i=this._activeBatches[t.batcherName]=du.getBatcher(t.batcherName),i.begin()),this._activeBatch=i}this._activeBatch.add(t)}break(t){this._activeBatch.break(t)}buildEnd(t){this._activeBatch.break(t);const e=this._activeBatches;for(const i in e){const r=e[i],n=r.geometry;n.indexBuffer.setDataWithSize(r.indexBuffer,r.indexSize,!0),n.buffers[0].setDataWithSize(r.attributeBuffer.float32View,r.attributeSize,!1)}}upload(t){const e=this._batchersByInstructionSet[t.uid];for(const i in e){const r=e[i],n=r.geometry;r.dirty&&(r.dirty=!1,n.buffers[0].update(r.attributeSize*4))}}execute(t){if(t.action==="startBatch"){const e=t.batcher,i=e.geometry,r=e.shader;this._adaptor.start(this,i,r)}this._adaptor.execute(this,t)}destroy(){this.state=null,this.renderer=null,this._adaptor=null;for(const t in this._activeBatches)this._activeBatches[t].destroy();this._activeBatches=null}};gn.extension={type:[w.WebGLPipes,w.WebGPUPipes,w.CanvasPipes],name:"batch"},gn._availableBatchers=Object.create(null);let _n=gn;J.handleByMap(w.Batcher,_n._availableBatchers),J.add(Qr);const lg={name:"texture-bit",vertex:{header:`
|
|
544
|
+
|
|
545
|
+
struct TextureUniforms {
|
|
546
|
+
uTextureMatrix:mat3x3<f32>,
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
@group(2) @binding(2) var<uniform> textureUniforms : TextureUniforms;
|
|
550
|
+
`,main:`
|
|
551
|
+
uv = (textureUniforms.uTextureMatrix * vec3(uv, 1.0)).xy;
|
|
552
|
+
`},fragment:{header:`
|
|
553
|
+
@group(2) @binding(0) var uTexture: texture_2d<f32>;
|
|
554
|
+
@group(2) @binding(1) var uSampler: sampler;
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
`,main:`
|
|
558
|
+
outColor = textureSample(uTexture, uSampler, vUV);
|
|
559
|
+
`}},hg={name:"texture-bit",vertex:{header:`
|
|
560
|
+
uniform mat3 uTextureMatrix;
|
|
561
|
+
`,main:`
|
|
562
|
+
uv = (uTextureMatrix * vec3(uv, 1.0)).xy;
|
|
563
|
+
`},fragment:{header:`
|
|
564
|
+
uniform sampler2D uTexture;
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
`,main:`
|
|
568
|
+
outColor = texture(uTexture, vUV);
|
|
569
|
+
`}},cg=new Lt;class ug extends ps{constructor(){super(),this.filters=[new vm({sprite:new ye(z.EMPTY),inverse:!1,resolution:"inherit",antialias:"inherit"})]}get sprite(){return this.filters[0].sprite}set sprite(t){this.filters[0].sprite=t}get inverse(){return this.filters[0].inverse}set inverse(t){this.filters[0].inverse=t}}class yn{constructor(t){this._activeMaskStage=[],this._renderer=t}push(t,e,i){const r=this._renderer;if(r.renderPipes.batch.break(i),i.add({renderPipeId:"alphaMask",action:"pushMaskBegin",mask:t,inverse:e._maskOptions.inverse,canBundle:!1,maskedContainer:e}),t.inverse=e._maskOptions.inverse,t.renderMaskToTexture){const n=t.mask;n.includeInBuild=!0,n.collectRenderables(i,r,null),n.includeInBuild=!1}r.renderPipes.batch.break(i),i.add({renderPipeId:"alphaMask",action:"pushMaskEnd",mask:t,maskedContainer:e,inverse:e._maskOptions.inverse,canBundle:!1})}pop(t,e,i){this._renderer.renderPipes.batch.break(i),i.add({renderPipeId:"alphaMask",action:"popMaskEnd",mask:t,inverse:e._maskOptions.inverse,canBundle:!1})}execute(t){const e=this._renderer,i=t.mask.renderMaskToTexture;if(t.action==="pushMaskBegin"){const r=Mt.get(ug);if(r.inverse=t.inverse,i){t.mask.mask.measurable=!0;const n=cr(t.mask.mask,!0,cg);t.mask.mask.measurable=!1,n.ceil();const o=e.renderTarget.renderTarget.colorTexture.source,a=Ft.getOptimalTexture(n.width,n.height,o._resolution,o.antialias);e.renderTarget.push(a,!0),e.globalUniforms.push({offset:n,worldColor:4294967295});const l=r.sprite;l.texture=a,l.worldTransform.tx=n.minX,l.worldTransform.ty=n.minY,this._activeMaskStage.push({filterEffect:r,maskedContainer:t.maskedContainer,filterTexture:a})}else r.sprite=t.mask.mask,this._activeMaskStage.push({filterEffect:r,maskedContainer:t.maskedContainer})}else if(t.action==="pushMaskEnd"){const r=this._activeMaskStage[this._activeMaskStage.length-1];i&&(e.type===ce.WEBGL&&e.renderTarget.finishRenderPass(),e.renderTarget.pop(),e.globalUniforms.pop()),e.filter.push({renderPipeId:"filter",action:"pushFilter",container:r.maskedContainer,filterEffect:r.filterEffect,canBundle:!1})}else if(t.action==="popMaskEnd"){e.filter.pop();const r=this._activeMaskStage.pop();i&&Ft.returnTexture(r.filterTexture),Mt.return(r.filterEffect)}}destroy(){this._renderer=null,this._activeMaskStage=null}}yn.extension={type:[w.WebGLPipes,w.WebGPUPipes,w.CanvasPipes],name:"alphaMask"};class mh{constructor(t){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=t}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(t,e,i){this._renderer.renderPipes.batch.break(i);const r=this._colorStack;r[this._colorStackIndex]=r[this._colorStackIndex-1]&t.mask;const n=this._colorStack[this._colorStackIndex];n!==this._currentColor&&(this._currentColor=n,i.add({renderPipeId:"colorMask",colorMask:n,canBundle:!1})),this._colorStackIndex++}pop(t,e,i){this._renderer.renderPipes.batch.break(i);const r=this._colorStack;this._colorStackIndex--;const n=r[this._colorStackIndex-1];n!==this._currentColor&&(this._currentColor=n,i.add({renderPipeId:"colorMask",colorMask:n,canBundle:!1}))}execute(t){}destroy(){this._renderer=null,this._colorStack=null}}mh.extension={type:[w.CanvasPipes],name:"colorMask"};class gh{constructor(t){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=t}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(t,e,i){this._renderer.renderPipes.batch.break(i);const n=this._colorStack;n[this._colorStackIndex]=n[this._colorStackIndex-1]&t.mask;const o=this._colorStack[this._colorStackIndex];o!==this._currentColor&&(this._currentColor=o,i.add({renderPipeId:"colorMask",colorMask:o,canBundle:!1})),this._colorStackIndex++}pop(t,e,i){this._renderer.renderPipes.batch.break(i);const n=this._colorStack;this._colorStackIndex--;const o=n[this._colorStackIndex-1];o!==this._currentColor&&(this._currentColor=o,i.add({renderPipeId:"colorMask",colorMask:o,canBundle:!1}))}execute(t){this._renderer.colorMask.setMask(t.colorMask)}destroy(){this._renderer=null,this._colorStack=null}}gh.extension={type:[w.WebGLPipes,w.WebGPUPipes],name:"colorMask"};function dg(s,t,e,i,r,n){n=Math.max(0,Math.min(n,Math.min(i,r)/2)),s.moveTo(t+n,e),s.lineTo(t+i-n,e),s.quadraticCurveTo(t+i,e,t+i,e+n),s.lineTo(t+i,e+r-n),s.quadraticCurveTo(t+i,e+r,t+i-n,e+r),s.lineTo(t+n,e+r),s.quadraticCurveTo(t,e+r,t,e+r-n),s.lineTo(t,e+n),s.quadraticCurveTo(t,e,t+n,e)}function _h(s,t){switch(t.type){case"rectangle":{const e=t;s.rect(e.x,e.y,e.width,e.height);break}case"roundedRectangle":{const e=t;dg(s,e.x,e.y,e.width,e.height,e.radius);break}case"circle":{const e=t;s.moveTo(e.x+e.radius,e.y),s.arc(e.x,e.y,e.radius,0,Math.PI*2);break}case"ellipse":{const e=t;s.ellipse?(s.moveTo(e.x+e.halfWidth,e.y),s.ellipse(e.x,e.y,e.halfWidth,e.halfHeight,0,0,Math.PI*2)):(s.save(),s.translate(e.x,e.y),s.scale(e.halfWidth,e.halfHeight),s.moveTo(1,0),s.arc(0,0,1,0,Math.PI*2),s.restore());break}case"triangle":{const e=t;s.moveTo(e.x,e.y),s.lineTo(e.x2,e.y2),s.lineTo(e.x3,e.y3),s.closePath();break}case"polygon":default:{const e=t,i=e.points;if(!(i!=null&&i.length))break;s.moveTo(i[0],i[1]);for(let r=2;r<i.length;r+=2)s.lineTo(i[r],i[r+1]);e.closePath&&s.closePath();break}}}function fg(s,t){if(!(t!=null&&t.length))return!1;for(let e=0;e<t.length;e++){const i=t[e];if(!(i!=null&&i.shape))continue;const r=i.transform,n=r&&!r.isIdentity();n&&(s.save(),s.transform(r.a,r.b,r.c,r.d,r.tx,r.ty)),_h(s,i.shape),n&&s.restore()}return!0}class yh{constructor(t){this._warnedMaskTypes=new Set,this._canvasMaskStack=[],this._renderer=t}push(t,e,i){this._renderer.renderPipes.batch.break(i),i.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:t,inverse:e._maskOptions.inverse,canBundle:!1})}pop(t,e,i){this._renderer.renderPipes.batch.break(i),i.add({renderPipeId:"stencilMask",action:"popMaskEnd",mask:t,inverse:e._maskOptions.inverse,canBundle:!1})}execute(t){var c,u,m;if(t.action!=="pushMaskBegin"&&t.action!=="popMaskEnd")return;const e=this._renderer,i=e.canvasContext,r=i==null?void 0:i.activeContext;if(!r)return;if(t.action==="popMaskEnd"){this._canvasMaskStack.pop()&&r.restore();return}t.inverse&&this._warnOnce("inverse","CanvasRenderer: inverse masks are not supported on Canvas2D; ignoring inverse flag.");const n=t.mask.mask;if(!(n instanceof Se)){this._warnOnce("nonGraphics","CanvasRenderer: only Graphics masks are supported in Canvas2D; skipping mask."),this._canvasMaskStack.push(!1);return}const o=n,a=(c=o.context)==null?void 0:c.instructions;if(!(a!=null&&a.length)){this._canvasMaskStack.push(!1);return}r.save(),i.setContextTransform(o.groupTransform,(e._roundPixels|o._roundPixels)===1),r.beginPath();let l=!1,h=!1;for(let f=0;f<a.length;f++){const g=a[f],y=g.action;if(y!=="fill"&&y!=="stroke")continue;const x=g.data,v=(u=x==null?void 0:x.path)==null?void 0:u.shapePath;if(!((m=v==null?void 0:v.shapePrimitives)!=null&&m.length))continue;const E=v.shapePrimitives;for(let T=0;T<E.length;T++){const C=E[T];if(!(C!=null&&C.shape))continue;const R=C.transform,A=R&&!R.isIdentity();A&&(r.save(),r.transform(R.a,R.b,R.c,R.d,R.tx,R.ty)),_h(r,C.shape),h=fg(r,C.holes)||h,l=!0,A&&r.restore()}}if(!l){r.restore(),this._canvasMaskStack.push(!1);return}h?r.clip("evenodd"):r.clip(),this._canvasMaskStack.push(!0)}destroy(){this._renderer=null,this._warnedMaskTypes=null,this._canvasMaskStack=null}_warnOnce(t,e){this._warnedMaskTypes.has(t)||(this._warnedMaskTypes.add(t),tt(e))}}yh.extension={type:[w.CanvasPipes],name:"stencilMask"};class xh{constructor(t){this._maskStackHash={},this._maskHash=new WeakMap,this._renderer=t}push(t,e,i){var r;const n=t,o=this._renderer;o.renderPipes.batch.break(i),o.renderPipes.blendMode.setBlendMode(n.mask,"none",i),i.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:t,inverse:e._maskOptions.inverse,canBundle:!1});const a=n.mask;a.includeInBuild=!0,this._maskHash.has(n)||this._maskHash.set(n,{instructionsStart:0,instructionsLength:0});const l=this._maskHash.get(n);l.instructionsStart=i.instructionSize,a.collectRenderables(i,o,null),a.includeInBuild=!1,o.renderPipes.batch.break(i),i.add({renderPipeId:"stencilMask",action:"pushMaskEnd",mask:t,inverse:e._maskOptions.inverse,canBundle:!1});const h=i.instructionSize-l.instructionsStart-1;l.instructionsLength=h;const c=o.renderTarget.renderTarget.uid;(r=this._maskStackHash)[c]??(r[c]=0)}pop(t,e,i){const r=t,n=this._renderer;n.renderPipes.batch.break(i),n.renderPipes.blendMode.setBlendMode(r.mask,"none",i),i.add({renderPipeId:"stencilMask",action:"popMaskBegin",inverse:e._maskOptions.inverse,canBundle:!1});const o=this._maskHash.get(t);for(let a=0;a<o.instructionsLength;a++)i.instructions[i.instructionSize++]=i.instructions[o.instructionsStart++];i.add({renderPipeId:"stencilMask",action:"popMaskEnd",canBundle:!1})}execute(t){var e;const i=this._renderer,r=i,n=i.renderTarget.renderTarget.uid;let o=(e=this._maskStackHash)[n]??(e[n]=0);t.action==="pushMaskBegin"?(r.renderTarget.ensureDepthStencil(),r.stencil.setStencilMode(wt.RENDERING_MASK_ADD,o),o++,r.colorMask.setMask(0)):t.action==="pushMaskEnd"?(t.inverse?r.stencil.setStencilMode(wt.INVERSE_MASK_ACTIVE,o):r.stencil.setStencilMode(wt.MASK_ACTIVE,o),r.colorMask.setMask(15)):t.action==="popMaskBegin"?(r.colorMask.setMask(0),o!==0?r.stencil.setStencilMode(wt.RENDERING_MASK_REMOVE,o):(r.renderTarget.clear(null,Yt.STENCIL),r.stencil.setStencilMode(wt.DISABLED,o)),o--):t.action==="popMaskEnd"&&(t.inverse?r.stencil.setStencilMode(wt.INVERSE_MASK_ACTIVE,o):r.stencil.setStencilMode(wt.MASK_ACTIVE,o),r.colorMask.setMask(15)),this._maskStackHash[n]=o}destroy(){this._renderer=null,this._maskStackHash=null,this._maskHash=null}}xh.extension={type:[w.WebGLPipes,w.WebGPUPipes],name:"stencilMask"};const ft="source-over";function pg(){const s=ql(),t=Object.create(null);return t.inherit=ft,t.none=ft,t.normal="source-over",t.add="lighter",t.multiply=s?"multiply":ft,t.screen=s?"screen":ft,t.overlay=s?"overlay":ft,t.darken=s?"darken":ft,t.lighten=s?"lighten":ft,t["color-dodge"]=s?"color-dodge":ft,t["color-burn"]=s?"color-burn":ft,t["hard-light"]=s?"hard-light":ft,t["soft-light"]=s?"soft-light":ft,t.difference=s?"difference":ft,t.exclusion=s?"exclusion":ft,t.saturation=s?"saturation":ft,t.color=s?"color":ft,t.luminosity=s?"luminosity":ft,t["linear-burn"]=s?"color-burn":ft,t["linear-dodge"]=s?"color-dodge":ft,t["linear-light"]=s?"hard-light":ft,t["pin-light"]=s?"hard-light":ft,t["vivid-light"]=s?"hard-light":ft,t["hard-mix"]=ft,t.negation=s?"difference":ft,t["normal-npm"]=t.normal,t["add-npm"]=t.add,t["screen-npm"]=t.screen,t.erase="destination-out",t.subtract=ft,t.divide=ft,t.min=ft,t.max=ft,t}const mg=new W;class bh{constructor(t){this.activeResolution=1,this.smoothProperty="imageSmoothingEnabled",this.blendModes=pg(),this._activeBlendMode="normal",this._projTransform=null,this._outerBlend=!1,this._warnedBlendModes=new Set,this._renderer=t}resolutionChange(t){this.activeResolution=t}init(){const t=this._renderer.background.alpha<1;if(this.rootContext=this._renderer.canvas.getContext("2d",{alpha:t}),this.activeContext=this.rootContext,this.activeResolution=this._renderer.resolution,!this.rootContext.imageSmoothingEnabled){const e=this.rootContext;e.webkitImageSmoothingEnabled?this.smoothProperty="webkitImageSmoothingEnabled":e.mozImageSmoothingEnabled?this.smoothProperty="mozImageSmoothingEnabled":e.oImageSmoothingEnabled?this.smoothProperty="oImageSmoothingEnabled":e.msImageSmoothingEnabled&&(this.smoothProperty="msImageSmoothingEnabled")}}setContextTransform(t,e,i,r){var h;const n=r?W.IDENTITY:((h=this._renderer.globalUniforms.globalUniformData)==null?void 0:h.worldTransformMatrix)||W.IDENTITY;let o=mg;o.copyFrom(n),o.append(t);const a=this._projTransform,l=this.activeResolution;if(i=i||l,a){const c=W.shared;c.copyFrom(o),c.prepend(a),o=c}e?this.activeContext.setTransform(o.a*i,o.b*i,o.c*i,o.d*i,o.tx*l|0,o.ty*l|0):this.activeContext.setTransform(o.a*i,o.b*i,o.c*i,o.d*i,o.tx*l,o.ty*l)}clear(t,e){const i=this.activeContext,r=this._renderer;if(i.clearRect(0,0,r.width,r.height),t){const n=ct.shared.setValue(t);i.globalAlpha=e??n.alpha,i.fillStyle=n.toHex(),i.fillRect(0,0,r.width,r.height),i.globalAlpha=1}}setBlendMode(t){if(this._activeBlendMode===t)return;this._activeBlendMode=t,this._outerBlend=!1;const e=this.blendModes[t];if(!e){this._warnedBlendModes.has(t)||(console.warn(`CanvasRenderer: blend mode "${t}" is not supported in Canvas2D; falling back to "source-over".`),this._warnedBlendModes.add(t)),this.activeContext.globalCompositeOperation="source-over";return}this.activeContext.globalCompositeOperation=e}destroy(){this.rootContext=null,this.activeContext=null,this._warnedBlendModes.clear()}}bh.extension={type:[w.CanvasSystem],name:"canvasContext"};class vh{constructor(){this.maxTextures=16,this.maxBatchableTextures=16,this.maxUniformBindings=0}init(){}}vh.extension={type:[w.CanvasSystem],name:"limits"};class xn{constructor(t){this._renderer=t}updateRenderable(){}destroyRenderable(){}validateRenderable(){return!1}addRenderable(t,e){this._renderer.renderPipes.batch.break(e),e.add(t)}execute(t){t.isRenderable&&t.render(this._renderer)}destroy(){this._renderer=null}}xn.extension={type:[w.WebGLPipes,w.WebGPUPipes,w.CanvasPipes],name:"customRender"};function bn(s,t){const e=s.instructionSet,i=e.instructions;for(let r=0;r<e.instructionSize;r++){const n=i[r];t[n.renderPipeId].execute(n)}}class vn{constructor(t){this._renderer=t}addRenderGroup(t,e){t.isCachedAsTexture?this._addRenderableCacheAsTexture(t,e):this._addRenderableDirect(t,e)}execute(t){t.isRenderable&&(t.isCachedAsTexture?this._executeCacheAsTexture(t):this._executeDirect(t))}destroy(){this._renderer=null}_addRenderableDirect(t,e){this._renderer.renderPipes.batch.break(e),t._batchableRenderGroup&&(Mt.return(t._batchableRenderGroup),t._batchableRenderGroup=null),e.add(t)}_addRenderableCacheAsTexture(t,e){const i=t._batchableRenderGroup??(t._batchableRenderGroup=Mt.get(pn));i.renderable=t.root,i.transform=t.root.relativeGroupTransform,i.texture=t.texture,i.bounds=t._textureBounds,e.add(t),this._renderer.renderPipes.blendMode.pushBlendMode(t,t.root.groupBlendMode,e),this._renderer.renderPipes.batch.addToBatch(i,e),this._renderer.renderPipes.blendMode.popBlendMode(e)}_executeCacheAsTexture(t){if(t.textureNeedsUpdate){t.textureNeedsUpdate=!1;const e=new W().translate(-t._textureBounds.x,-t._textureBounds.y);this._renderer.renderTarget.push(t.texture,!0,null,t.texture.frame),this._renderer.globalUniforms.push({worldTransformMatrix:e,worldColor:4294967295,offset:{x:0,y:0}}),bn(t,this._renderer.renderPipes),this._renderer.renderTarget.finishRenderPass(),this._renderer.renderTarget.pop(),this._renderer.globalUniforms.pop()}t._batchableRenderGroup._batcher.updateElement(t._batchableRenderGroup),t._batchableRenderGroup._batcher.geometry.buffers[0].update()}_executeDirect(t){this._renderer.globalUniforms.push({worldTransformMatrix:t.inverseParentTextureTransform,worldColor:t.worldColorAlpha}),bn(t,this._renderer.renderPipes),this._renderer.globalUniforms.pop()}}vn.extension={type:[w.WebGLPipes,w.WebGPUPipes,w.CanvasPipes],name:"renderGroup"};const gg="#808080",Ls=new W,_g=new W,yg=new W,En=new W;function xg(s,t,e){s.beginPath();for(let i=0;i<e.length;i+=3){const r=e[i]*2,n=e[i+1]*2,o=e[i+2]*2;s.moveTo(t[r],t[r+1]),s.lineTo(t[n],t[n+1]),s.lineTo(t[o],t[o+1]),s.closePath()}s.fill()}function bg(s){return`#${(s&16777215).toString(16).padStart(6,"0")}`}function vg(s,t,e,i,r,n){n=Math.max(0,Math.min(n,Math.min(i,r)/2)),s.moveTo(t+n,e),s.lineTo(t+i-n,e),s.quadraticCurveTo(t+i,e,t+i,e+n),s.lineTo(t+i,e+r-n),s.quadraticCurveTo(t+i,e+r,t+i-n,e+r),s.lineTo(t+n,e+r),s.quadraticCurveTo(t,e+r,t,e+r-n),s.lineTo(t,e+n),s.quadraticCurveTo(t,e,t+n,e)}function Fs(s,t){switch(t.type){case"rectangle":{const e=t;s.rect(e.x,e.y,e.width,e.height);break}case"roundedRectangle":{const e=t;vg(s,e.x,e.y,e.width,e.height,e.radius);break}case"circle":{const e=t;s.arc(e.x,e.y,e.radius,0,Math.PI*2);break}case"ellipse":{const e=t;s.ellipse?s.ellipse(e.x,e.y,e.halfWidth,e.halfHeight,0,0,Math.PI*2):(s.save(),s.translate(e.x,e.y),s.scale(e.halfWidth,e.halfHeight),s.arc(0,0,1,0,Math.PI*2),s.restore());break}case"triangle":{const e=t;s.moveTo(e.x,e.y),s.lineTo(e.x2,e.y2),s.lineTo(e.x3,e.y3),s.closePath();break}case"polygon":default:{const e=t,i=e.points;if(!(i!=null&&i.length))break;s.moveTo(i[0],i[1]);for(let r=2;r<i.length;r+=2)s.lineTo(i[r],i[r+1]);e.closePath&&s.closePath();break}}}function Eg(s,t){if(!(t!=null&&t.length))return!1;for(let e=0;e<t.length;e++){const i=t[e];if(!(i!=null&&i.shape))continue;const r=i.transform,n=r&&!r.isIdentity();n&&(s.save(),s.transform(r.a,r.b,r.c,r.d,r.tx,r.ty)),Fs(s,i.shape),n&&s.restore()}return!0}function Tg(s,t,e,i){const r=s.fill;if(r instanceof de){r.buildGradient();const o=r.texture;if(o){const a=st.getTintedPattern(o,t),l=e?En.copyFrom(e).scale(o.source.pixelWidth,o.source.pixelHeight):En.copyFrom(r.transform);return i&&!s.textureSpace&&l.append(i),st.applyPatternTransform(a,l),a}}if(r instanceof is){const o=st.getTintedPattern(r.texture,t);return st.applyPatternTransform(o,r.transform),o}const n=s.texture;if(n&&n!==z.WHITE){if(!n.source.resource)return gg;const o=st.getTintedPattern(n,t),a=e?En.copyFrom(e).scale(n.source.pixelWidth,n.source.pixelHeight):s.matrix;return st.applyPatternTransform(o,a),o}return bg(t)}class Eh{constructor(){this.shader=null}contextChange(t){}execute(t,e){var E,T,C,R,A,I,N;const i=t.renderer,r=i.canvasContext,n=r.activeContext,o=e.groupTransform,a=((E=i.globalUniforms.globalUniformData)==null?void 0:E.worldColor)??4294967295,l=e.groupColorAlpha,h=(a>>>24&255)/255,c=(l>>>24&255)/255,u=((T=i.filter)==null?void 0:T.alphaMultiplier)??1,m=h*c*u;if(m<=0)return;const f=a&16777215,g=l&16777215,y=fi(di(g,f)),x=i._roundPixels|e._roundPixels;n.save(),r.setContextTransform(o,x===1),r.setBlendMode(e.groupBlendMode);const v=e.context.instructions;for(let B=0;B<v.length;B++){const k=v[B];if(k.action==="texture"){const X=k.data,D=X.image,$=D?st.getCanvasSource(D):null;if(!$)continue;const Y=X.alpha*m;if(Y<=0)continue;const j=di(X.style,y);n.globalAlpha=Y;let V=$;j!==16777215&&(V=st.getTintedCanvas({texture:D},j));const ot=D.frame,lt=D.source._resolution??D.source.resolution??1;let gt=ot.x*lt,ht=ot.y*lt;const _t=ot.width*lt,Z=ot.height*lt;V!==$&&(gt=0,ht=0);const Bt=X.transform,$t=Bt&&!Bt.isIdentity(),xt=D.rotate;$t||xt?(Ls.copyFrom(o),$t&&Ls.append(Bt),xt&&it.matrixAppendRotationInv(Ls,xt,X.dx,X.dy,X.dw,X.dh),r.setContextTransform(Ls,x===1)):r.setContextTransform(o,x===1),n.drawImage(V,gt,ht,V===$?_t:V.width,V===$?Z:V.height,xt?0:X.dx,xt?0:X.dy,X.dw,X.dh),($t||xt)&&r.setContextTransform(o,x===1);continue}const O=k.data,L=(C=O==null?void 0:O.path)==null?void 0:C.shapePath;if(!((R=L==null?void 0:L.shapePrimitives)!=null&&R.length))continue;const F=O.style,H=di(F.color,y),at=F.alpha*m;if(at<=0)continue;const G=k.action==="stroke";if(n.globalAlpha=at,G){const X=F;n.lineWidth=X.width,n.lineCap=X.cap,n.lineJoin=X.join,n.miterLimit=X.miterLimit}const U=L.shapePrimitives;if(!G&&((N=(I=(A=O.hole)==null?void 0:A.shapePath)==null?void 0:I.shapePrimitives)!=null&&N.length)){const X=U[U.length-1];X.holes=O.hole.shapePath.shapePrimitives}for(let X=0;X<U.length;X++){const D=U[X];if(!(D!=null&&D.shape))continue;const $=D.transform,Y=$&&!$.isIdentity(),j=F.texture&&F.texture!==z.WHITE,V=F.textureSpace==="global"?$:null,ot=j?vl(_g,F,D.shape,V):null,lt=Y?yg.copyFrom(o).append($):o,gt=Tg(F,H,ot,lt);if(Y&&(n.save(),n.transform($.a,$.b,$.c,$.d,$.tx,$.ty)),G){const ht=F;if(ht.alignment!==.5&&!ht.pixelLine){const Z=[],Bt=[],$t=[],xt=Qi[D.shape.type];if(xt!=null&&xt.build(D.shape,Z)){const Gt=D.shape.closePath??!0;gl(Z,ht,!1,Gt,Bt,$t),n.fillStyle=gt,xg(n,Bt,$t)}else n.strokeStyle=gt,n.beginPath(),Fs(n,D.shape),n.stroke()}else n.strokeStyle=gt,n.beginPath(),Fs(n,D.shape),n.stroke()}else n.fillStyle=gt,n.beginPath(),Fs(n,D.shape),Eg(n,D.holes)?n.fill("evenodd"):n.fill();Y&&n.restore()}}n.restore()}destroy(){this.shader=null}}Eh.extension={type:[w.CanvasPipesAdaptor],name:"graphics"};class Tn{constructor(t){this._renderer=t}addRenderable(t,e){const i=this._getGpuSprite(t);t.didViewUpdate&&this._updateBatchableSprite(t,i),this._renderer.renderPipes.batch.addToBatch(i,e)}updateRenderable(t){const e=this._getGpuSprite(t);t.didViewUpdate&&this._updateBatchableSprite(t,e),e._batcher.updateElement(e)}validateRenderable(t){const e=this._getGpuSprite(t);return!e._batcher.checkAndUpdateTexture(e,t._texture)}_updateBatchableSprite(t,e){e.bounds=t.visualBounds,e.texture=t._texture}_getGpuSprite(t){return t._gpuData[this._renderer.uid]||this._initGPUSprite(t)}_initGPUSprite(t){const e=new pn;return e.renderable=t,e.transform=t.groupTransform,e.texture=t._texture,e.bounds=t.visualBounds,e.roundPixels=this._renderer._roundPixels|t._roundPixels,t._gpuData[this._renderer.uid]=e,e}destroy(){this._renderer=null}}Tn.extension={type:[w.WebGLPipes,w.WebGPUPipes,w.CanvasPipes],name:"sprite"};const ns={};J.handle(w.BlendMode,s=>{if(!s.name)throw new Error("BlendMode extension must have a name property");ns[s.name]=s.ref},s=>{delete ns[s.name]});class Sn{constructor(t){this._blendModeStack=[],this._isAdvanced=!1,this._filterHash=Object.create(null),this._renderer=t,this._renderer.runners.prerender.add(this)}prerender(){this._activeBlendMode="normal",this._isAdvanced=!1}pushBlendMode(t,e,i){this._blendModeStack.push(e),this.setBlendMode(t,e,i)}popBlendMode(t){this._blendModeStack.pop();const e=this._blendModeStack[this._activeBlendMode.length-1]??"normal";this.setBlendMode(null,e,t)}setBlendMode(t,e,i){var n;const r=t instanceof pr;if(this._activeBlendMode===e){this._isAdvanced&&t&&!r&&((n=this._renderableList)==null||n.push(t));return}this._isAdvanced&&this._endAdvancedBlendMode(i),this._activeBlendMode=e,t&&(this._isAdvanced=!!ns[e],this._isAdvanced&&this._beginAdvancedBlendMode(t,i))}_beginAdvancedBlendMode(t,e){this._renderer.renderPipes.batch.break(e);const i=this._activeBlendMode;if(!ns[i]){tt(`Unable to assign BlendMode: '${i}'. You may want to include: import 'pixi.js/advanced-blend-modes'`);return}const r=this._ensureFilterEffect(i),n=t instanceof pr,o={renderPipeId:"filter",action:"pushFilter",filterEffect:r,renderables:n?null:[t],container:n?t.root:null,canBundle:!1};this._renderableList=o.renderables,e.add(o)}_ensureFilterEffect(t){let e=this._filterHash[t];return e||(e=this._filterHash[t]=new ps,e.filters=[new ns[t]]),e}_endAdvancedBlendMode(t){this._isAdvanced=!1,this._renderableList=null,this._renderer.renderPipes.batch.break(t),t.add({renderPipeId:"filter",action:"popFilter",canBundle:!1})}buildStart(){this._isAdvanced=!1}buildEnd(t){this._isAdvanced&&this._endAdvancedBlendMode(t)}destroy(){this._renderer=null,this._renderableList=null;for(const t in this._filterHash)this._filterHash[t].destroy();this._filterHash=null}}Sn.extension={type:[w.WebGLPipes,w.WebGPUPipes,w.CanvasPipes],name:"blendMode"};function Cn(s,t){t||(t=0);for(let e=t;e<s.length&&s[e];e++)s[e]=null}const Sg=new kt,Th=Oi|ys|_r;function Sh(s,t=!1){Cg(s);const e=s.childrenToUpdate,i=s.updateTick++;for(const r in e){const n=Number(r),o=e[r],a=o.list,l=o.index;for(let h=0;h<l;h++){const c=a[h];c.parentRenderGroup===s&&c.relativeRenderGroupDepth===n&&Ch(c,i,0)}Cn(a,l),o.index=0}if(t)for(let r=0;r<s.renderGroupChildren.length;r++)Sh(s.renderGroupChildren[r],t)}function Cg(s){const t=s.root;let e;if(s.renderGroupParent){const i=s.renderGroupParent;s.worldTransform.appendFrom(t.relativeGroupTransform,i.worldTransform),s.worldColor=ms(t.groupColor,i.worldColor),e=t.groupAlpha*i.worldAlpha}else s.worldTransform.copyFrom(t.localTransform),s.worldColor=t.localColor,e=t.localAlpha;e=e<0?0:e>1?1:e,s.worldAlpha=e,s.worldColorAlpha=s.worldColor+((e*255|0)<<24)}function Ch(s,t,e){if(t===s.updateTick)return;s.updateTick=t,s.didChange=!1;const i=s.localTransform;s.updateLocalTransform();const r=s.parent;if(r&&!r.renderGroup?(e|=s._updateFlags,s.relativeGroupTransform.appendFrom(i,r.relativeGroupTransform),e&Th&&wh(s,r,e)):(e=s._updateFlags,s.relativeGroupTransform.copyFrom(i),e&Th&&wh(s,Sg,e)),!s.renderGroup){const n=s.children,o=n.length;for(let h=0;h<o;h++)Ch(n[h],t,e);const a=s.parentRenderGroup,l=s;l.renderPipeId&&!a.structureDidChange&&a.updateRenderable(l)}}function wh(s,t,e){if(e&ys){s.groupColor=ms(s.localColor,t.groupColor);let i=s.localAlpha*t.groupAlpha;i=i<0?0:i>1?1:i,s.groupAlpha=i,s.groupColorAlpha=s.groupColor+((i*255|0)<<24)}e&_r&&(s.groupBlendMode=s.localBlendMode==="inherit"?t.groupBlendMode:s.localBlendMode),e&Oi&&(s.globalDisplayStatus=s.localDisplayStatus&t.globalDisplayStatus),s._updateFlags=0}function wg(s,t){const{list:e}=s.childrenRenderablesToUpdate;let i=!1;for(let r=0;r<s.childrenRenderablesToUpdate.index;r++){const n=e[r];if(i=t[n.renderPipeId].validateRenderable(n),i)break}return s.structureDidChange=i,i}const Ag=new W;class Ah{constructor(t){this._renderer=t}render({container:t,transform:e}){const i=t.parent,r=t.renderGroup.renderGroupParent;t.parent=null,t.renderGroup.renderGroupParent=null;const n=this._renderer,o=Ag;e&&(o.copyFrom(t.renderGroup.localTransform),t.renderGroup.localTransform.copyFrom(e));const a=n.renderPipes;this._updateCachedRenderGroups(t.renderGroup,null),this._updateRenderGroups(t.renderGroup),n.globalUniforms.start({worldTransformMatrix:e?t.renderGroup.localTransform:t.renderGroup.worldTransform,worldColor:t.renderGroup.worldColorAlpha}),bn(t.renderGroup,a),a.uniformBatch&&a.uniformBatch.renderEnd(),e&&t.renderGroup.localTransform.copyFrom(o),t.parent=i,t.renderGroup.renderGroupParent=r}destroy(){this._renderer=null}_updateCachedRenderGroups(t,e){if(t._parentCacheAsTextureRenderGroup=e,t.isCachedAsTexture){if(!t.textureNeedsUpdate)return;e=t}for(let i=t.renderGroupChildren.length-1;i>=0;i--)this._updateCachedRenderGroups(t.renderGroupChildren[i],e);if(t.invalidateMatrices(),t.isCachedAsTexture){if(t.textureNeedsUpdate){const i=t.root.getLocalBounds(),r=this._renderer,n=t.textureOptions.resolution||r.view.resolution,o=t.textureOptions.antialias??r.view.antialias,a=t.textureOptions.scaleMode??"linear",l=t.texture;i.ceil(),t.texture&&Ft.returnTexture(t.texture,!0);const h=Ft.getOptimalTexture(i.width,i.height,n,o);h._source.style=new Xe({scaleMode:a}),t.texture=h,t._textureBounds||(t._textureBounds=new Lt),t._textureBounds.copyFrom(i),l!==t.texture&&t.renderGroupParent&&(t.renderGroupParent.structureDidChange=!0)}}else t.texture&&(Ft.returnTexture(t.texture,!0),t.texture=null)}_updateRenderGroups(t){const e=this._renderer,i=e.renderPipes;if(t.runOnRender(e),t.instructionSet.renderPipes=i,t.structureDidChange?Cn(t.childrenRenderablesToUpdate.list,0):wg(t,i),Sh(t),t.structureDidChange?(t.structureDidChange=!1,this._buildInstructions(t,e)):this._updateRenderables(t),t.childrenRenderablesToUpdate.index=0,e.renderPipes.batch.upload(t.instructionSet),!(t.isCachedAsTexture&&!t.textureNeedsUpdate))for(let r=0;r<t.renderGroupChildren.length;r++)this._updateRenderGroups(t.renderGroupChildren[r])}_updateRenderables(t){const{list:e,index:i}=t.childrenRenderablesToUpdate;for(let r=0;r<i;r++){const n=e[r];n.didViewUpdate&&t.updateRenderable(n)}Cn(e,i)}_buildInstructions(t,e){const i=t.root,r=t.instructionSet;r.reset();const n=e.renderPipes?e:e.batch.renderer,o=n.renderPipes;o.batch.buildStart(r),o.blendMode.buildStart(),o.colorMask.buildStart(),i.sortableChildren&&i.sortChildren(),i.collectRenderablesWithEffects(r,n,null),o.batch.buildEnd(r),o.blendMode.buildEnd(r)}}Ah.extension={type:[w.WebGLSystem,w.WebGPUSystem,w.CanvasSystem],name:"renderGroup"};const wn=class fu{constructor(){this.clearBeforeRender=!0,this._backgroundColor=new ct(0),this.color=this._backgroundColor,this.alpha=1}init(t){t={...fu.defaultOptions,...t},this.clearBeforeRender=t.clearBeforeRender,this.color=t.background||t.backgroundColor||this._backgroundColor,this.alpha=t.backgroundAlpha,this._backgroundColor.setAlpha(t.backgroundAlpha)}get color(){return this._backgroundColor}set color(t){ct.shared.setValue(t).alpha<1&&this._backgroundColor.alpha===1&&tt("Cannot set a transparent background on an opaque canvas. To enable transparency, set backgroundAlpha < 1 when initializing your Application."),this._backgroundColor.setValue(t)}get alpha(){return this._backgroundColor.alpha}set alpha(t){this._backgroundColor.setAlpha(t)}get colorRgba(){return this._backgroundColor.toArray()}destroy(){}};wn.extension={type:[w.WebGLSystem,w.WebGPUSystem,w.CanvasSystem],name:"background",priority:0},wn.defaultOptions={backgroundAlpha:1,backgroundColor:0,clearBeforeRender:!0};let Rg=wn;const An={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},Rn=class pu{constructor(t){this._renderer=t}_normalizeOptions(t,e={}){return t instanceof kt||t instanceof z?{target:t,...e}:{...e,...t}}async image(t){const e=rt.get().createImage();return e.src=await this.base64(t),e}async base64(t){t=this._normalizeOptions(t,pu.defaultImageOptions);const{format:e,quality:i}=t,r=this.canvas(t);if(r.toBlob!==void 0)return new Promise((n,o)=>{r.toBlob(a=>{if(!a){o(new Error("ICanvas.toBlob failed!"));return}const l=new FileReader;l.onload=()=>n(l.result),l.onerror=o,l.readAsDataURL(a)},An[e],i)});if(r.toDataURL!==void 0)return r.toDataURL(An[e],i);if(r.convertToBlob!==void 0){const n=await r.convertToBlob({type:An[e],quality:i});return new Promise((o,a)=>{const l=new FileReader;l.onload=()=>o(l.result),l.onerror=a,l.readAsDataURL(n)})}throw new Error("Extract.base64() requires ICanvas.toDataURL, ICanvas.toBlob, or ICanvas.convertToBlob to be implemented")}canvas(t){t=this._normalizeOptions(t);const e=t.target,i=this._renderer;if(e instanceof z)return i.texture.generateCanvas(e);const r=i.textureGenerator.generateTexture(t),n=i.texture.generateCanvas(r);return r.destroy(!0),n}pixels(t){t=this._normalizeOptions(t);const e=t.target,i=this._renderer,r=e instanceof z?e:i.textureGenerator.generateTexture(t),n=i.texture.getPixels(r);return e instanceof kt&&r.destroy(!0),n}texture(t){return t=this._normalizeOptions(t),t.target instanceof z?t.target:this._renderer.textureGenerator.generateTexture(t)}download(t){t=this._normalizeOptions(t);const e=this.canvas(t),i=document.createElement("a");i.download=t.filename??"image.png",i.href=e.toDataURL("image/png"),document.body.appendChild(i),i.click(),document.body.removeChild(i)}log(t){const e=t.width??200;t=this._normalizeOptions(t);const i=this.canvas(t),r=i.toDataURL();console.log(`[Pixi Texture] ${i.width}px ${i.height}px`);const n=["font-size: 1px;",`padding: ${e}px 300px;`,`background: url(${r}) no-repeat;`,"background-size: contain;"].join(" ");console.log("%c ",n)}destroy(){this._renderer=null}};Rn.extension={type:[w.WebGLSystem,w.WebGPUSystem,w.CanvasSystem],name:"extract"},Rn.defaultImageOptions={format:"png",quality:1};let Pg=Rn;class Pn extends z{static create(t){const{dynamic:e,...i}=t;return new Pn({source:new At(i),dynamic:e??!1})}resize(t,e,i){return this.source.resize(t,e,i),this}}const Ig=new ut,Mg=new Lt,kg=[0,0,0,0];class Rh{constructor(t){this._renderer=t}generateTexture(t){var h;t instanceof kt&&(t={target:t,frame:void 0,textureSourceOptions:{},resolution:void 0});const e=t.resolution||this._renderer.resolution,i=t.antialias||this._renderer.view.antialias,r=t.target;let n=t.clearColor;n?n=Array.isArray(n)&&n.length===4?n:ct.shared.setValue(n).toArray():n=kg;const o=((h=t.frame)==null?void 0:h.copyTo(Ig))||dr(r,Mg).rectangle;o.width=Math.max(o.width,1/e)|0,o.height=Math.max(o.height,1/e)|0;const a=Pn.create({...t.textureSourceOptions,width:o.width,height:o.height,resolution:e,antialias:i}),l=W.shared.translate(-o.x,-o.y);return this._renderer.render({container:r,transform:l,target:a,clearColor:n}),a.source.updateMipmaps(),a}destroy(){this._renderer=null}}Rh.extension={type:[w.WebGLSystem,w.WebGPUSystem,w.CanvasSystem],name:"textureGenerator"};function Bg(s){let t=!1;for(const i in s)if(s[i]==null){t=!0;break}if(!t)return s;const e=Object.create(null);for(const i in s){const r=s[i];r&&(e[i]=r)}return e}function Og(s){let t=0;for(let e=0;e<s.length;e++)s[e]==null?t++:s[e-t]=s[e];return s.length-=t,s}const In=class mu{constructor(t){this._managedResources=[],this._managedResourceHashes=[],this._managedCollections=[],this._ready=!1,this._renderer=t}init(t){t={...mu.defaultOptions,...t},this.maxUnusedTime=t.gcMaxUnusedTime,this._frequency=t.gcFrequency,this.enabled=t.gcActive,this.now=performance.now()}get enabled(){return!!this._handler}set enabled(t){this.enabled!==t&&(t?(this._handler=this._renderer.scheduler.repeat(()=>{this._ready=!0},this._frequency,!1),this._collectionsHandler=this._renderer.scheduler.repeat(()=>{for(const e of this._managedCollections){const{context:i,collection:r,type:n}=e;n==="hash"?i[r]=Bg(i[r]):i[r]=Og(i[r])}},this._frequency)):(this._renderer.scheduler.cancel(this._handler),this._renderer.scheduler.cancel(this._collectionsHandler),this._handler=0,this._collectionsHandler=0))}prerender({container:t}){this.now=performance.now(),t.renderGroup.gcTick=this._renderer.tick++,this._updateInstructionGCTick(t.renderGroup,t.renderGroup.gcTick)}postrender(){!this._ready||!this.enabled||(this.run(),this._ready=!1)}_updateInstructionGCTick(t,e){t.instructionSet.gcTick=e,t.gcTick=e;for(const i of t.renderGroupChildren)this._updateInstructionGCTick(i,e)}addCollection(t,e,i){this._managedCollections.push({context:t,collection:e,type:i})}addResource(t,e){var r,n;if(t._gcLastUsed!==-1){t._gcLastUsed=this.now,(r=t._onTouch)==null||r.call(t,this.now);return}const i=this._managedResources.length;t._gcData={index:i,type:e},t._gcLastUsed=this.now,(n=t._onTouch)==null||n.call(t,this.now),t.once("unload",this.removeResource,this),this._managedResources.push(t)}removeResource(t){const e=t._gcData;if(!e)return;const i=e.index,r=this._managedResources.length-1;if(i!==r){const n=this._managedResources[r];this._managedResources[i]=n,n._gcData.index=i}this._managedResources.length--,t._gcData=null,t._gcLastUsed=-1}addResourceHash(t,e,i,r=0){this._managedResourceHashes.push({context:t,hash:e,type:i,priority:r}),this._managedResourceHashes.sort((n,o)=>n.priority-o.priority)}run(){const t=performance.now(),e=this._managedResourceHashes;for(const r of e)this.runOnHash(r,t);let i=0;for(let r=0;r<this._managedResources.length;r++){const n=this._managedResources[r];i=this.runOnResource(n,t,i)}this._managedResources.length=i}updateRenderableGCTick(t,e){var n,o;const i=t.renderGroup??t.parentRenderGroup,r=((n=i==null?void 0:i.instructionSet)==null?void 0:n.gcTick)??-1;((i==null?void 0:i.gcTick)??0)===r&&(t._gcLastUsed=e,(o=t._onTouch)==null||o.call(t,e))}runOnResource(t,e,i){const r=t._gcData;return r.type==="renderable"&&this.updateRenderableGCTick(t,e),e-t._gcLastUsed<this.maxUnusedTime||!t.autoGarbageCollect?(this._managedResources[i]=t,r.index=i,i++):(t.unload(),t._gcData=null,t._gcLastUsed=-1,t.off("unload",this.removeResource,this)),i}_createHashClone(t,e){const i=Object.create(null);for(const r in t){if(r===e)break;t[r]!==null&&(i[r]=t[r])}return i}runOnHash(t,e){var h;const{context:i,hash:r,type:n}=t,o=i[r];let a=null,l=0;for(const c in o){const u=o[c];if(u===null){l++,l===1e4&&!a&&(a=this._createHashClone(o,c));continue}if(u._gcLastUsed===-1){u._gcLastUsed=e,(h=u._onTouch)==null||h.call(u,e),a&&(a[c]=u);continue}if(n==="renderable"&&this.updateRenderableGCTick(u,e),!(e-u._gcLastUsed<this.maxUnusedTime)&&u.autoGarbageCollect){if(a||(l+1!==1e4?(o[c]=null,l++):a=this._createHashClone(o,c)),n==="renderable"){const f=u,g=f.renderGroup??f.parentRenderGroup;g&&(g.structureDidChange=!0)}u.unload(),u._gcData=null,u._gcLastUsed=-1}else a&&(a[c]=u)}a&&(i[r]=a)}destroy(){this.enabled=!1,this._managedResources.forEach(t=>{t.off("unload",this.removeResource,this)}),this._managedResources.length=0,this._managedResourceHashes.length=0,this._managedCollections.length=0,this._renderer=null}};In.extension={type:[w.WebGLSystem,w.WebGPUSystem,w.CanvasSystem],name:"gc",priority:0},In.defaultOptions={gcActive:!0,gcMaxUnusedTime:6e4,gcFrequency:3e4};let Dg=In;class Ph{constructor(t){this._stackIndex=0,this._globalUniformDataStack=[],this._uniformsPool=[],this._activeUniforms=[],this._bindGroupPool=[],this._activeBindGroups=[],this._renderer=t}reset(){this._stackIndex=0;for(let t=0;t<this._activeUniforms.length;t++)this._uniformsPool.push(this._activeUniforms[t]);for(let t=0;t<this._activeBindGroups.length;t++)this._bindGroupPool.push(this._activeBindGroups[t]);this._activeUniforms.length=0,this._activeBindGroups.length=0}start(t){this.reset(),this.push(t)}bind({size:t,projectionMatrix:e,worldTransformMatrix:i,worldColor:r,offset:n}){const o=this._renderer.renderTarget.renderTarget,a=this._stackIndex?this._globalUniformDataStack[this._stackIndex-1]:{worldTransformMatrix:new W,worldColor:4294967295,offset:new mt},l={projectionMatrix:e||this._renderer.renderTarget.projectionMatrix,resolution:t||o.size,worldTransformMatrix:i||a.worldTransformMatrix,worldColor:r||a.worldColor,offset:n||a.offset,bindGroup:null},h=this._uniformsPool.pop()||this._createUniforms();this._activeUniforms.push(h);const c=h.uniforms;c.uProjectionMatrix=l.projectionMatrix,c.uResolution=l.resolution,c.uWorldTransformMatrix.copyFrom(l.worldTransformMatrix),c.uWorldTransformMatrix.tx-=l.offset.x,c.uWorldTransformMatrix.ty-=l.offset.y,jl(l.worldColor,c.uWorldColorAlpha,0),h.update();let u;this._renderer.renderPipes.uniformBatch?u=this._renderer.renderPipes.uniformBatch.getUniformBindGroup(h,!1):(u=this._bindGroupPool.pop()||new Me,this._activeBindGroups.push(u),u.setResource(h,0)),l.bindGroup=u,this._currentGlobalUniformData=l}push(t){this.bind(t),this._globalUniformDataStack[this._stackIndex++]=this._currentGlobalUniformData}pop(){this._currentGlobalUniformData=this._globalUniformDataStack[--this._stackIndex-1],this._renderer.type===ce.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 he({uProjectionMatrix:{value:new W,type:"mat3x3<f32>"},uWorldTransformMatrix:{value:new W,type:"mat3x3<f32>"},uWorldColorAlpha:{value:new Float32Array(4),type:"vec4<f32>"},uResolution:{value:[0,0],type:"vec2<f32>"}},{isStatic:!0})}destroy(){this._renderer=null,this._globalUniformDataStack.length=0,this._uniformsPool.length=0,this._activeUniforms.length=0,this._bindGroupPool.length=0,this._activeBindGroups.length=0,this._currentGlobalUniformData=null}}Ph.extension={type:[w.WebGLSystem,w.WebGPUSystem,w.CanvasSystem],name:"globalUniforms"};let Gg=1;class Ih{constructor(){this._tasks=[],this._offset=0}init(){te.system.add(this._update,this)}repeat(t,e,i=!0){const r=Gg++;let n=0;return i&&(this._offset+=1e3,n=this._offset),this._tasks.push({func:t,duration:e,start:performance.now(),offset:n,last:performance.now(),repeat:!0,id:r}),r}cancel(t){for(let e=0;e<this._tasks.length;e++)if(this._tasks[e].id===t){this._tasks.splice(e,1);return}}_update(){const t=performance.now();for(let e=0;e<this._tasks.length;e++){const i=this._tasks[e];if(t-i.offset-i.last>=i.duration){const r=t-i.start;i.func(r),i.last=t}}}destroy(){te.system.remove(this._update,this),this._tasks.length=0}}Ih.extension={type:[w.WebGLSystem,w.WebGPUSystem,w.CanvasSystem],name:"scheduler",priority:0};let Mh=!1;function Ug(s){if(!Mh){if(rt.get().getNavigator().userAgent.toLowerCase().indexOf("chrome")>-1){const t=[`%c %c %c %c %c PixiJS %c v${As} (${s}) http://www.pixijs.com/
|
|
570
|
+
|
|
571
|
+
`,"background: #E72264; padding:5px 0;","background: #6CA2EA; padding:5px 0;","background: #B5D33D; padding:5px 0;","background: #FED23F; padding:5px 0;","color: #FFFFFF; background: #E72264; padding:5px 0;","color: #E72264; background: #FFFFFF; padding:5px 0;"];globalThis.console.log(...t)}else globalThis.console&&globalThis.console.log(`PixiJS ${As} - ${s} - http://www.pixijs.com/`);Mh=!0}}class Mn{constructor(t){this._renderer=t}init(t){if(t.hello){let e=this._renderer.name;this._renderer.type===ce.WEBGL&&(e+=` ${this._renderer.context.webGLVersion}`),Ug(e)}}}Mn.extension={type:[w.WebGLSystem,w.WebGPUSystem,w.CanvasSystem],name:"hello",priority:-2},Mn.defaultOptions={hello:!1};const kn=class gu{constructor(t){this._renderer=t}init(t){t={...gu.defaultOptions,...t},this.maxUnusedTime=t.renderableGCMaxUnusedTime}get enabled(){return K("8.15.0","RenderableGCSystem.enabled is deprecated, please use the GCSystem.enabled instead."),this._renderer.gc.enabled}set enabled(t){K("8.15.0","RenderableGCSystem.enabled is deprecated, please use the GCSystem.enabled instead."),this._renderer.gc.enabled=t}addManagedHash(t,e){K("8.15.0","RenderableGCSystem.addManagedHash is deprecated, please use the GCSystem.addCollection instead."),this._renderer.gc.addCollection(t,e,"hash")}addManagedArray(t,e){K("8.15.0","RenderableGCSystem.addManagedArray is deprecated, please use the GCSystem.addCollection instead."),this._renderer.gc.addCollection(t,e,"array")}addRenderable(t){K("8.15.0","RenderableGCSystem.addRenderable is deprecated, please use the GCSystem instead."),this._renderer.gc.addResource(t,"renderable")}run(){K("8.15.0","RenderableGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.run()}destroy(){this._renderer=null}};kn.extension={type:[w.WebGLSystem,w.WebGPUSystem,w.CanvasSystem],name:"renderableGC",priority:0},kn.defaultOptions={renderableGCActive:!0,renderableGCMaxUnusedTime:6e4,renderableGCFrequency:3e4};let Lg=kn;const Bn=class qs{get count(){return this._renderer.tick}get checkCount(){return this._checkCount}set checkCount(t){K("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._checkCount=t}get maxIdle(){return this._renderer.gc.maxUnusedTime/1e3*60}set maxIdle(t){K("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.maxUnusedTime=t/60*1e3}get checkCountMax(){return Math.floor(this._renderer.gc._frequency/1e3)}set checkCountMax(t){K("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead.")}get active(){return this._renderer.gc.enabled}set active(t){K("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.enabled=t}constructor(t){this._renderer=t,this._checkCount=0}init(t){t.textureGCActive!==qs.defaultOptions.textureGCActive&&(this.active=t.textureGCActive),t.textureGCMaxIdle!==qs.defaultOptions.textureGCMaxIdle&&(this.maxIdle=t.textureGCMaxIdle),t.textureGCCheckCountMax!==qs.defaultOptions.textureGCCheckCountMax&&(this.checkCountMax=t.textureGCCheckCountMax)}run(){K("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.run()}destroy(){this._renderer=null}};Bn.extension={type:[w.WebGLSystem,w.WebGPUSystem],name:"textureGC"},Bn.defaultOptions={textureGCActive:!0,textureGCAMaxIdle:null,textureGCMaxIdle:3600,textureGCCheckCountMax:600};let Fg=Bn;const kh=class _u{constructor(t={}){if(this.uid=dt("renderTarget"),this.colorTextures=[],this.dirtyId=0,this.isRoot=!1,this._size=new Float32Array(2),this._managedColorTextures=!1,t={..._u.defaultOptions,...t},this.stencil=t.stencil,this.depth=t.depth,this.isRoot=t.isRoot,typeof t.colorTextures=="number"){this._managedColorTextures=!0;for(let e=0;e<t.colorTextures;e++)this.colorTextures.push(new At({width:t.width,height:t.height,resolution:t.resolution,antialias:t.antialias}))}else{this.colorTextures=[...t.colorTextures.map(i=>i.source)];const e=this.colorTexture.source;this.resize(e.width,e.height,e._resolution)}this.colorTexture.source.on("resize",this.onSourceResize,this),(t.depthStencilTexture||this.stencil)&&(t.depthStencilTexture instanceof z||t.depthStencilTexture instanceof At?this.depthStencilTexture=t.depthStencilTexture.source:this.ensureDepthStencilTexture())}get size(){const t=this._size;return t[0]=this.pixelWidth,t[1]=this.pixelHeight,t}get width(){return this.colorTexture.source.width}get height(){return this.colorTexture.source.height}get pixelWidth(){return this.colorTexture.source.pixelWidth}get pixelHeight(){return this.colorTexture.source.pixelHeight}get resolution(){return this.colorTexture.source._resolution}get colorTexture(){return this.colorTextures[0]}onSourceResize(t){this.resize(t.width,t.height,t._resolution,!0)}ensureDepthStencilTexture(){this.depthStencilTexture||(this.depthStencilTexture=new At({width:this.width,height:this.height,resolution:this.resolution,format:"depth24plus-stencil8",autoGenerateMipmaps:!1,antialias:!1,mipLevelCount:1}))}resize(t,e,i=this.resolution,r=!1){this.dirtyId++,this.colorTextures.forEach((n,o)=>{r&&o===0||n.source.resize(t,e,i)}),this.depthStencilTexture&&this.depthStencilTexture.source.resize(t,e,i)}destroy(){this.colorTexture.source.off("resize",this.onSourceResize,this),this._managedColorTextures&&this.colorTextures.forEach(t=>{t.destroy()}),this.depthStencilTexture&&(this.depthStencilTexture.destroy(),delete this.depthStencilTexture)}};kh.defaultOptions={width:0,height:0,resolution:1,colorTextures:1,stencil:!1,depth:!1,antialias:!1,isRoot:!1};let On=kh;const Ci=new Map;ui.register(Ci);function Bh(s,t){if(!Ci.has(s)){const e=new z({source:new le({resource:s,...t})}),i=()=>{Ci.get(s)===e&&Ci.delete(s)};e.once("destroy",i),e.source.once("destroy",i),Ci.set(s,e)}return Ci.get(s)}const Dn=class yu{get autoDensity(){return this.texture.source.autoDensity}set autoDensity(t){this.texture.source.autoDensity=t}get resolution(){return this.texture.source._resolution}set resolution(t){this.texture.source.resize(this.texture.source.width,this.texture.source.height,t)}init(t){t={...yu.defaultOptions,...t},t.view&&(K(vt,"ViewSystem.view has been renamed to ViewSystem.canvas"),t.canvas=t.view),this.screen=new ut(0,0,t.width,t.height),this.canvas=t.canvas||rt.get().createCanvas(),this.antialias=!!t.antialias,this.texture=Bh(this.canvas,t),this.renderTarget=new On({colorTextures:[this.texture],depth:!!t.depth,isRoot:!0}),this.texture.source.transparent=t.backgroundAlpha<1,this.resolution=t.resolution}resize(t,e,i){this.texture.source.resize(t,e,i),this.screen.width=this.texture.frame.width,this.screen.height=this.texture.frame.height}destroy(t=!1){(typeof t=="boolean"?t:!!(t!=null&&t.removeView))&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.texture.destroy()}};Dn.extension={type:[w.WebGLSystem,w.WebGPUSystem,w.CanvasSystem],name:"view",priority:0},Dn.defaultOptions={width:800,height:600,autoDensity:!1,antialias:!1};const Gn=[Rg,Ph,Mn,Dn,Ah,Dg,Fg,Rh,Pg,Ga,Lg,Ih],Oh=[Sn,_n,Tn,vn,yn,xh,gh,xn];function Ng(s,t,e,i,r,n){const o=n?1:-1;return s.identity(),s.a=1/i*2,s.d=o*(1/r*2),s.tx=-1-t*s.a,s.ty=-o-e*s.d,s}function Hg(s){const t=s.colorTexture.source.resource;return globalThis.HTMLCanvasElement&&t instanceof HTMLCanvasElement&&document.body.contains(t)}class Un{constructor(t){this.rootViewPort=new ut,this.viewport=new ut,this.mipLevel=0,this.layer=0,this.onRenderTargetChange=new ka("onRenderTargetChange"),this.projectionMatrix=new W,this.defaultClearColor=[0,0,0,0],this._renderSurfaceToRenderTargetHash=new Map,this._gpuRenderTargetHash=Object.create(null),this._renderTargetStack=[],this._renderer=t,t.gc.addCollection(this,"_gpuRenderTargetHash","hash")}finishRenderPass(){this.adaptor.finishRenderPass(this.renderTarget)}renderStart({target:t,clear:e,clearColor:i,frame:r,mipLevel:n,layer:o}){var a,l;this._renderTargetStack.length=0,this.push(t,e,i,r,n??0,o??0),this.rootViewPort.copyFrom(this.viewport),this.rootRenderTarget=this.renderTarget,this.renderingToScreen=Hg(this.rootRenderTarget),(l=(a=this.adaptor).prerender)==null||l.call(a,this.rootRenderTarget)}postrender(){var t,e;(e=(t=this.adaptor).postrender)==null||e.call(t,this.rootRenderTarget)}bind(t,e=!0,i,r,n=0,o=0){const a=this.getRenderTarget(t),l=this.renderTarget!==a;this.renderTarget=a,this.renderSurface=t;const h=this.getGpuRenderTarget(a);(a.pixelWidth!==h.width||a.pixelHeight!==h.height)&&(this.adaptor.resizeGpuRenderTarget(a),h.width=a.pixelWidth,h.height=a.pixelHeight);const c=a.colorTexture,u=this.viewport,m=c.arrayLayerCount||1;if((o|0)!==o&&(o|=0),o<0||o>=m)throw new Error(`[RenderTargetSystem] layer ${o} is out of bounds (arrayLayerCount=${m}).`);this.mipLevel=n|0,this.layer=o|0;const f=Math.max(c.pixelWidth>>n,1),g=Math.max(c.pixelHeight>>n,1);if(!r&&t instanceof z&&(r=t.frame),r){const y=c._resolution,x=1<<Math.max(n|0,0),v=r.x*y+.5|0,E=r.y*y+.5|0,T=r.width*y+.5|0,C=r.height*y+.5|0;let R=Math.floor(v/x),A=Math.floor(E/x),I=Math.ceil(T/x),N=Math.ceil(C/x);R=Math.min(Math.max(R,0),f-1),A=Math.min(Math.max(A,0),g-1),I=Math.min(Math.max(I,1),f-R),N=Math.min(Math.max(N,1),g-A),u.x=R,u.y=A,u.width=I,u.height=N}else u.x=0,u.y=0,u.width=f,u.height=g;return Ng(this.projectionMatrix,0,0,u.width/c.resolution,u.height/c.resolution,!a.isRoot),this.adaptor.startRenderPass(a,e,i,u,n,o),l&&this.onRenderTargetChange.emit(a),a}clear(t,e=Yt.ALL,i,r=this.mipLevel,n=this.layer){e&&(t&&(t=this.getRenderTarget(t)),this.adaptor.clear(t||this.renderTarget,e,i,this.viewport,r,n))}contextChange(){this._gpuRenderTargetHash=Object.create(null)}push(t,e=Yt.ALL,i,r,n=0,o=0){const a=this.bind(t,e,i,r,n,o);return this._renderTargetStack.push({renderTarget:a,frame:r,mipLevel:n,layer:o}),a}pop(){this._renderTargetStack.pop();const t=this._renderTargetStack[this._renderTargetStack.length-1];this.bind(t.renderTarget,!1,null,t.frame,t.mipLevel,t.layer)}getRenderTarget(t){return t.isTexture&&(t=t.source),this._renderSurfaceToRenderTargetHash.get(t)??this._initRenderTarget(t)}copyToTexture(t,e,i,r,n){i.x<0&&(r.width+=i.x,n.x-=i.x,i.x=0),i.y<0&&(r.height+=i.y,n.y-=i.y,i.y=0);const{pixelWidth:o,pixelHeight:a}=t;return r.width=Math.min(r.width,o-i.x),r.height=Math.min(r.height,a-i.y),this.adaptor.copyToTexture(t,e,i,r,n)}ensureDepthStencil(){this.renderTarget.stencil||(this.renderTarget.stencil=!0,this.adaptor.startRenderPass(this.renderTarget,!1,null,this.viewport,0,this.layer))}destroy(){this._renderer=null,this._renderSurfaceToRenderTargetHash.forEach((t,e)=>{t!==e&&t.destroy()}),this._renderSurfaceToRenderTargetHash.clear(),this._gpuRenderTargetHash=Object.create(null)}_initRenderTarget(t){let e=null;return le.test(t)&&(t=Bh(t).source),t instanceof On?e=t:t instanceof At&&(e=new On({colorTextures:[t]}),t.source instanceof le&&(e.isRoot=!0),t.once("destroy",()=>{e.destroy(),this._renderSurfaceToRenderTargetHash.delete(t);const i=this._gpuRenderTargetHash[e.uid];i&&(this._gpuRenderTargetHash[e.uid]=null,this.adaptor.destroyGpuRenderTarget(i))})),this._renderSurfaceToRenderTargetHash.set(t,e),e}getGpuRenderTarget(t){return this._gpuRenderTargetHash[t.uid]||(this._gpuRenderTargetHash[t.uid]=this.adaptor.initGpuRenderTarget(t))}resetState(){this.renderTarget=null,this.renderSurface=null}}class Wg{init(t,e){this._renderer=t,this._renderTargetSystem=e}initGpuRenderTarget(t){const e=t.colorTexture,{canvas:i,context:r}=this._ensureCanvas(e);return{canvas:i,context:r,width:i.width,height:i.height}}resizeGpuRenderTarget(t){const e=t.colorTexture,{canvas:i}=this._ensureCanvas(e);i.width=t.pixelWidth,i.height=t.pixelHeight}startRenderPass(t,e,i,r){const n=this._renderTargetSystem.getGpuRenderTarget(t);this._renderer.canvasContext.activeContext=n.context,this._renderer.canvasContext.activeResolution=t.resolution,e&&this.clear(t,e,i,r)}clear(t,e,i,r){const o=this._renderTargetSystem.getGpuRenderTarget(t).context,a=r||{x:0,y:0,width:t.pixelWidth,height:t.pixelHeight};if(o.setTransform(1,0,0,1,0,0),o.clearRect(a.x,a.y,a.width,a.height),i){const l=ct.shared.setValue(i);l.alpha>0&&(o.globalAlpha=l.alpha,o.fillStyle=l.toHex(),o.fillRect(a.x,a.y,a.width,a.height),o.globalAlpha=1)}}finishRenderPass(){}copyToTexture(t,e,i,r,n){const a=this._renderTargetSystem.getGpuRenderTarget(t).canvas,l=e.source,{context:h}=this._ensureCanvas(l),c=(n==null?void 0:n.x)??0,u=(n==null?void 0:n.y)??0;return h.drawImage(a,i.x,i.y,r.width,r.height,c,u,r.width,r.height),l.update(),e}destroyGpuRenderTarget(t){}_ensureCanvas(t){let e=t.resource;(!e||!le.test(e))&&(e=rt.get().createCanvas(t.pixelWidth,t.pixelHeight),t.resource=e),(e.width!==t.pixelWidth||e.height!==t.pixelHeight)&&(e.width=t.pixelWidth,e.height=t.pixelHeight);const i=e.getContext("2d");return{canvas:e,context:i}}}class Dh extends Un{constructor(t){super(t),this.adaptor=new Wg,this.adaptor.init(t,this)}}Dh.extension={type:[w.CanvasSystem],name:"renderTarget"};class Gh{constructor(t){}init(){}initSource(t){}generateCanvas(t){const e=rt.get().createCanvas(),i=e.getContext("2d"),r=st.getCanvasSource(t);if(!r)return e;const n=t.frame,o=t.source._resolution??t.source.resolution??1,a=n.x*o,l=n.y*o,h=n.width*o,c=n.height*o;return e.width=Math.ceil(h),e.height=Math.ceil(c),i.drawImage(r,a,l,h,c,0,0,h,c),e}getPixels(t){const e=this.generateCanvas(t);return{pixels:e.getContext("2d",{willReadFrequently:!0}).getImageData(0,0,e.width,e.height).data,width:e.width,height:e.height}}destroy(){}}Gh.extension={type:[w.CanvasSystem],name:"texture"};const Vg=[...Gn,bh,vh,Gh,Dh],zg=[Sn,_n,Tn,vn,yn,yh,mh,xn],$g=[ag,Eh],Uh=[],Lh=[],Fh=[];J.handleByNamedList(w.CanvasSystem,Uh),J.handleByNamedList(w.CanvasPipes,Lh),J.handleByNamedList(w.CanvasPipesAdaptor,Fh),J.add(...Vg,...zg,...$g);class jg extends Xi{constructor(){const t={name:"canvas",type:ce.CANVAS,systems:Uh,renderPipes:Lh,renderPipeAdaptors:Fh};super(t)}}const Xg=Object.freeze(Object.defineProperty({__proto__:null,CanvasRenderer:jg},Symbol.toStringTag,{value:"Module"}));var Ns=(s=>(s[s.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",s[s.ARRAY_BUFFER=34962]="ARRAY_BUFFER",s[s.UNIFORM_BUFFER=35345]="UNIFORM_BUFFER",s))(Ns||{});class Yg{constructor(t,e){this._lastBindBaseLocation=-1,this._lastBindCallId=-1,this.buffer=t||null,this.updateID=-1,this.byteLength=-1,this.type=e}destroy(){this.buffer=null,this.updateID=-1,this.byteLength=-1,this.type=-1,this._lastBindBaseLocation=-1,this._lastBindCallId=-1}}class Nh{constructor(t){this._boundBufferBases=Object.create(null),this._minBaseLocation=0,this._nextBindBaseIndex=this._minBaseLocation,this._bindCallId=0,this._renderer=t,this._managedBuffers=new ue({renderer:t,type:"resource",onUnload:this.onBufferUnload.bind(this),name:"glBuffer"})}destroy(){this._managedBuffers.destroy(),this._renderer=null,this._gl=null,this._boundBufferBases={}}contextChange(){this._gl=this._renderer.gl,this.destroyAll(!0),this._maxBindings=this._renderer.limits.maxUniformBindings}getGlBuffer(t){return t._gcLastUsed=this._renderer.gc.now,t._gpuData[this._renderer.uid]||this.createGLBuffer(t)}bind(t){const{_gl:e}=this,i=this.getGlBuffer(t);e.bindBuffer(i.type,i.buffer)}bindBufferBase(t,e){const{_gl:i}=this;this._boundBufferBases[e]!==t&&(this._boundBufferBases[e]=t,t._lastBindBaseLocation=e,i.bindBufferBase(i.UNIFORM_BUFFER,e,t.buffer))}nextBindBase(t){this._bindCallId++,this._minBaseLocation=0,t&&(this._boundBufferBases[0]=null,this._minBaseLocation=1,this._nextBindBaseIndex<1&&(this._nextBindBaseIndex=1))}freeLocationForBufferBase(t){let e=this.getLastBindBaseLocation(t);if(e>=this._minBaseLocation)return t._lastBindCallId=this._bindCallId,e;let i=0,r=this._nextBindBaseIndex;for(;i<2;){r>=this._maxBindings&&(r=this._minBaseLocation,i++);const n=this._boundBufferBases[r];if(n&&n._lastBindCallId===this._bindCallId){r++;continue}break}return e=r,this._nextBindBaseIndex=r+1,i>=2?-1:(t._lastBindCallId=this._bindCallId,this._boundBufferBases[e]=null,e)}getLastBindBaseLocation(t){const e=t._lastBindBaseLocation;return this._boundBufferBases[e]===t?e:-1}bindBufferRange(t,e,i,r){const{_gl:n}=this;i||(i=0),e||(e=0),this._boundBufferBases[e]=null,n.bindBufferRange(n.UNIFORM_BUFFER,e||0,t.buffer,i*256,r||256)}updateBuffer(t){const{_gl:e}=this,i=this.getGlBuffer(t);if(t._updateID===i.updateID)return i;i.updateID=t._updateID,e.bindBuffer(i.type,i.buffer);const r=t.data,n=t.descriptor.usage&yt.STATIC?e.STATIC_DRAW:e.DYNAMIC_DRAW;return r?i.byteLength>=r.byteLength?e.bufferSubData(i.type,0,r,0,t._updateSize/r.BYTES_PER_ELEMENT):(i.byteLength=r.byteLength,e.bufferData(i.type,r,n)):(i.byteLength=t.descriptor.size,e.bufferData(i.type,i.byteLength,n)),i}destroyAll(t=!1){this._managedBuffers.removeAll(t)}onBufferUnload(t,e=!1){const i=t._gpuData[this._renderer.uid];i&&(e||this._gl.deleteBuffer(i.buffer))}createGLBuffer(t){const{_gl:e}=this;let i=Ns.ARRAY_BUFFER;t.descriptor.usage&yt.INDEX?i=Ns.ELEMENT_ARRAY_BUFFER:t.descriptor.usage&yt.UNIFORM&&(i=Ns.UNIFORM_BUFFER);const r=new Yg(e.createBuffer(),i);return t._gpuData[this._renderer.uid]=r,this._managedBuffers.add(t),r}resetState(){this._boundBufferBases=Object.create(null)}}Nh.extension={type:[w.WebGLSystem],name:"buffer"};const Ln=class xu{constructor(t){this.supports={uint32Indices:!0,uniformBufferObject:!0,vertexArrayObject:!0,srgbTextures:!0,nonPowOf2wrapping:!0,msaa:!0,nonPowOf2mipmaps:!0},this._renderer=t,this.extensions=Object.create(null),this.handleContextLost=this.handleContextLost.bind(this),this.handleContextRestored=this.handleContextRestored.bind(this)}get isLost(){return!this.gl||this.gl.isContextLost()}contextChange(t){this.gl=t,this._renderer.gl=t}init(t){t={...xu.defaultOptions,...t};let e=this.multiView=t.multiView;if(t.context&&e&&(tt("Renderer created with both a context and multiview enabled. Disabling multiView as both cannot work together."),e=!1),e?this.canvas=rt.get().createCanvas(this._renderer.canvas.width,this._renderer.canvas.height):this.canvas=this._renderer.view.canvas,t.context)this.initFromContext(t.context);else{const i=this._renderer.background.alpha<1,r=t.premultipliedAlpha??!0,n=t.antialias&&!this._renderer.backBuffer.useBackBuffer;this.createContext(t.preferWebGLVersion,{alpha:i,premultipliedAlpha:r,antialias:n,stencil:!0,preserveDrawingBuffer:t.preserveDrawingBuffer,powerPreference:t.powerPreference??"default"})}}ensureCanvasSize(t){if(!this.multiView){t!==this.canvas&&tt("multiView is disabled, but targetCanvas is not the main canvas");return}const{canvas:e}=this;(e.width<t.width||e.height<t.height)&&(e.width=Math.max(t.width,t.width),e.height=Math.max(t.height,t.height))}initFromContext(t){this.gl=t,this.webGLVersion=t instanceof rt.get().getWebGLRenderingContext()?1:2,this.getExtensions(),this.validateContext(t),this._renderer.runners.contextChange.emit(t);const e=this._renderer.view.canvas;e.addEventListener("webglcontextlost",this.handleContextLost,!1),e.addEventListener("webglcontextrestored",this.handleContextRestored,!1)}createContext(t,e){let i;const r=this.canvas;if(t===2&&(i=r.getContext("webgl2",e)),!i&&(i=r.getContext("webgl",e),!i))throw new Error("This browser does not support WebGL. Try using the canvas renderer");this.gl=i,this.initFromContext(this.gl)}getExtensions(){const{gl:t}=this,e={anisotropicFiltering:t.getExtension("EXT_texture_filter_anisotropic"),floatTextureLinear:t.getExtension("OES_texture_float_linear"),s3tc:t.getExtension("WEBGL_compressed_texture_s3tc"),s3tc_sRGB:t.getExtension("WEBGL_compressed_texture_s3tc_srgb"),etc:t.getExtension("WEBGL_compressed_texture_etc"),etc1:t.getExtension("WEBGL_compressed_texture_etc1"),pvrtc:t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),atc:t.getExtension("WEBGL_compressed_texture_atc"),astc:t.getExtension("WEBGL_compressed_texture_astc"),bptc:t.getExtension("EXT_texture_compression_bptc"),rgtc:t.getExtension("EXT_texture_compression_rgtc"),loseContext:t.getExtension("WEBGL_lose_context")};if(this.webGLVersion===1)this.extensions={...e,drawBuffers:t.getExtension("WEBGL_draw_buffers"),depthTexture:t.getExtension("WEBGL_depth_texture"),vertexArrayObject:t.getExtension("OES_vertex_array_object")||t.getExtension("MOZ_OES_vertex_array_object")||t.getExtension("WEBKIT_OES_vertex_array_object"),uint32ElementIndex:t.getExtension("OES_element_index_uint"),floatTexture:t.getExtension("OES_texture_float"),floatTextureLinear:t.getExtension("OES_texture_float_linear"),textureHalfFloat:t.getExtension("OES_texture_half_float"),textureHalfFloatLinear:t.getExtension("OES_texture_half_float_linear"),vertexAttribDivisorANGLE:t.getExtension("ANGLE_instanced_arrays"),srgb:t.getExtension("EXT_sRGB")};else{this.extensions={...e,colorBufferFloat:t.getExtension("EXT_color_buffer_float")};const i=t.getExtension("WEBGL_provoking_vertex");i&&i.provokingVertexWEBGL(i.FIRST_VERTEX_CONVENTION_WEBGL)}}handleContextLost(t){t.preventDefault(),this._contextLossForced&&(this._contextLossForced=!1,setTimeout(()=>{var e;this.gl.isContextLost()&&((e=this.extensions.loseContext)==null||e.restoreContext())},0))}handleContextRestored(){this.getExtensions(),this._renderer.runners.contextChange.emit(this.gl)}destroy(){var e;const t=this._renderer.view.canvas;this._renderer=null,t.removeEventListener("webglcontextlost",this.handleContextLost),t.removeEventListener("webglcontextrestored",this.handleContextRestored),this.gl.useProgram(null),(e=this.extensions.loseContext)==null||e.loseContext()}forceContextLoss(){var t;(t=this.extensions.loseContext)==null||t.loseContext(),this._contextLossForced=!0}validateContext(t){const e=t.getContextAttributes();e&&!e.stencil&&tt("Provided WebGL context does not have a stencil buffer, masks may not render correctly");const i=this.supports,r=this.webGLVersion===2,n=this.extensions;i.uint32Indices=r||!!n.uint32ElementIndex,i.uniformBufferObject=r,i.vertexArrayObject=r||!!n.vertexArrayObject,i.srgbTextures=r||!!n.srgb,i.nonPowOf2wrapping=r,i.nonPowOf2mipmaps=r,i.msaa=r,i.uint32Indices||tt("Provided WebGL context does not support 32 index buffer, large scenes may not render correctly")}};Ln.extension={type:[w.WebGLSystem],name:"context"},Ln.defaultOptions={context:null,premultipliedAlpha:!0,preserveDrawingBuffer:!1,powerPreference:void 0,preferWebGLVersion:2,multiView:!1};let qg=Ln;function Hh(s,t){for(const e in s.attributes){const i=s.attributes[e],r=t[e];r?(i.format??(i.format=r.format),i.offset??(i.offset=r.offset),i.instance??(i.instance=r.instance)):tt(`Attribute ${e} is not present in the shader, but is present in the geometry. Unable to infer attribute details.`)}Kg(s)}function Kg(s){const{buffers:t,attributes:e}=s,i={},r={};for(const n in t){const o=t[n];i[o.uid]=0,r[o.uid]=0}for(const n in e){const o=e[n];i[o.buffer.uid]+=Ni(o.format).stride}for(const n in e){const o=e[n];o.stride??(o.stride=i[o.buffer.uid]),o.start??(o.start=r[o.buffer.uid]),r[o.buffer.uid]+=Ni(o.format).stride}}var Fn=(s=>(s[s.RGBA=6408]="RGBA",s[s.RGB=6407]="RGB",s[s.RG=33319]="RG",s[s.RED=6403]="RED",s[s.RGBA_INTEGER=36249]="RGBA_INTEGER",s[s.RGB_INTEGER=36248]="RGB_INTEGER",s[s.RG_INTEGER=33320]="RG_INTEGER",s[s.RED_INTEGER=36244]="RED_INTEGER",s[s.ALPHA=6406]="ALPHA",s[s.LUMINANCE=6409]="LUMINANCE",s[s.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA",s[s.DEPTH_COMPONENT=6402]="DEPTH_COMPONENT",s[s.DEPTH_STENCIL=34041]="DEPTH_STENCIL",s))(Fn||{}),Nn=(s=>(s[s.TEXTURE_2D=3553]="TEXTURE_2D",s[s.TEXTURE_CUBE_MAP=34067]="TEXTURE_CUBE_MAP",s[s.TEXTURE_2D_ARRAY=35866]="TEXTURE_2D_ARRAY",s[s.TEXTURE_CUBE_MAP_POSITIVE_X=34069]="TEXTURE_CUBE_MAP_POSITIVE_X",s[s.TEXTURE_CUBE_MAP_NEGATIVE_X=34070]="TEXTURE_CUBE_MAP_NEGATIVE_X",s[s.TEXTURE_CUBE_MAP_POSITIVE_Y=34071]="TEXTURE_CUBE_MAP_POSITIVE_Y",s[s.TEXTURE_CUBE_MAP_NEGATIVE_Y=34072]="TEXTURE_CUBE_MAP_NEGATIVE_Y",s[s.TEXTURE_CUBE_MAP_POSITIVE_Z=34073]="TEXTURE_CUBE_MAP_POSITIVE_Z",s[s.TEXTURE_CUBE_MAP_NEGATIVE_Z=34074]="TEXTURE_CUBE_MAP_NEGATIVE_Z",s))(Nn||{}),nt=(s=>(s[s.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",s[s.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",s[s.UNSIGNED_SHORT_5_6_5=33635]="UNSIGNED_SHORT_5_6_5",s[s.UNSIGNED_SHORT_4_4_4_4=32819]="UNSIGNED_SHORT_4_4_4_4",s[s.UNSIGNED_SHORT_5_5_5_1=32820]="UNSIGNED_SHORT_5_5_5_1",s[s.UNSIGNED_INT=5125]="UNSIGNED_INT",s[s.UNSIGNED_INT_10F_11F_11F_REV=35899]="UNSIGNED_INT_10F_11F_11F_REV",s[s.UNSIGNED_INT_2_10_10_10_REV=33640]="UNSIGNED_INT_2_10_10_10_REV",s[s.UNSIGNED_INT_24_8=34042]="UNSIGNED_INT_24_8",s[s.UNSIGNED_INT_5_9_9_9_REV=35902]="UNSIGNED_INT_5_9_9_9_REV",s[s.BYTE=5120]="BYTE",s[s.SHORT=5122]="SHORT",s[s.INT=5124]="INT",s[s.FLOAT=5126]="FLOAT",s[s.FLOAT_32_UNSIGNED_INT_24_8_REV=36269]="FLOAT_32_UNSIGNED_INT_24_8_REV",s[s.HALF_FLOAT=36193]="HALF_FLOAT",s))(nt||{});const Wh={uint8x2:nt.UNSIGNED_BYTE,uint8x4:nt.UNSIGNED_BYTE,sint8x2:nt.BYTE,sint8x4:nt.BYTE,unorm8x2:nt.UNSIGNED_BYTE,unorm8x4:nt.UNSIGNED_BYTE,snorm8x2:nt.BYTE,snorm8x4:nt.BYTE,uint16x2:nt.UNSIGNED_SHORT,uint16x4:nt.UNSIGNED_SHORT,sint16x2:nt.SHORT,sint16x4:nt.SHORT,unorm16x2:nt.UNSIGNED_SHORT,unorm16x4:nt.UNSIGNED_SHORT,snorm16x2:nt.SHORT,snorm16x4:nt.SHORT,float16x2:nt.HALF_FLOAT,float16x4:nt.HALF_FLOAT,float32:nt.FLOAT,float32x2:nt.FLOAT,float32x3:nt.FLOAT,float32x4:nt.FLOAT,uint32:nt.UNSIGNED_INT,uint32x2:nt.UNSIGNED_INT,uint32x3:nt.UNSIGNED_INT,uint32x4:nt.UNSIGNED_INT,sint32:nt.INT,sint32x2:nt.INT,sint32x3:nt.INT,sint32x4:nt.INT};function Zg(s){return Wh[s]??Wh.float32}const Jg={"point-list":0,"line-list":1,"line-strip":3,"triangle-list":4,"triangle-strip":5};class Qg{constructor(){this.vaoCache=Object.create(null)}destroy(){this.vaoCache=Object.create(null)}}class Vh{constructor(t){this._renderer=t,this._activeGeometry=null,this._activeVao=null,this.hasVao=!0,this.hasInstance=!0,this._managedGeometries=new ue({renderer:t,type:"resource",onUnload:this.onGeometryUnload.bind(this),name:"glGeometry"})}contextChange(){const t=this.gl=this._renderer.gl;if(!this._renderer.context.supports.vertexArrayObject)throw new Error("[PixiJS] Vertex Array Objects are not supported on this device");this.destroyAll(!0);const e=this._renderer.context.extensions.vertexArrayObject;e&&(t.createVertexArray=()=>e.createVertexArrayOES(),t.bindVertexArray=r=>e.bindVertexArrayOES(r),t.deleteVertexArray=r=>e.deleteVertexArrayOES(r));const i=this._renderer.context.extensions.vertexAttribDivisorANGLE;i&&(t.drawArraysInstanced=(r,n,o,a)=>{i.drawArraysInstancedANGLE(r,n,o,a)},t.drawElementsInstanced=(r,n,o,a,l)=>{i.drawElementsInstancedANGLE(r,n,o,a,l)},t.vertexAttribDivisor=(r,n)=>i.vertexAttribDivisorANGLE(r,n)),this._activeGeometry=null,this._activeVao=null}bind(t,e){const i=this.gl;this._activeGeometry=t;const r=this.getVao(t,e);this._activeVao!==r&&(this._activeVao=r,i.bindVertexArray(r)),this.updateBuffers()}resetState(){this.unbind()}updateBuffers(){const t=this._activeGeometry,e=this._renderer.buffer;for(let i=0;i<t.buffers.length;i++){const r=t.buffers[i];e.updateBuffer(r)}t._gcLastUsed=this._renderer.gc.now}checkCompatibility(t,e){const i=t.attributes,r=e._attributeData;for(const n in r)if(!i[n])throw new Error(`shader and geometry incompatible, geometry missing the "${n}" attribute`)}getSignature(t,e){const i=t.attributes,r=e._attributeData,n=["g",t.uid];for(const o in i)r[o]&&n.push(o,r[o].location);return n.join("-")}getVao(t,e){var i;return((i=t._gpuData[this._renderer.uid])==null?void 0:i.vaoCache[e._key])||this.initGeometryVao(t,e)}initGeometryVao(t,e,i=!0){const r=this._renderer.gl,n=this._renderer.buffer;this._renderer.shader._getProgramData(e),this.checkCompatibility(t,e);const o=this.getSignature(t,e);let a=t._gpuData[this._renderer.uid];a||(a=new Qg,t._gpuData[this._renderer.uid]=a,this._managedGeometries.add(t));const l=a.vaoCache;let h=l[o];if(h)return l[e._key]=h,h;Hh(t,e._attributeData);const c=t.buffers;h=r.createVertexArray(),r.bindVertexArray(h);for(let u=0;u<c.length;u++){const m=c[u];n.bind(m)}return this.activateVao(t,e),l[e._key]=h,l[o]=h,r.bindVertexArray(null),h}onGeometryUnload(t,e=!1){const i=t._gpuData[this._renderer.uid];if(!i)return;const r=i.vaoCache;if(!e)for(const n in r)this._activeVao!==r[n]&&this.resetState(),this.gl.deleteVertexArray(r[n])}destroyAll(t=!1){this._managedGeometries.removeAll(t)}activateVao(t,e){var a;const i=this._renderer.gl,r=this._renderer.buffer,n=t.attributes;t.indexBuffer&&r.bind(t.indexBuffer);let o=null;for(const l in n){const h=n[l],c=h.buffer,u=r.getGlBuffer(c),m=e._attributeData[l];if(m){o!==u&&(r.bind(c),o=u);const f=m.location;i.enableVertexAttribArray(f);const g=Ni(h.format),y=Zg(h.format);if(((a=m.format)==null?void 0:a.substring(1,4))==="int"?i.vertexAttribIPointer(f,g.size,y,h.stride,h.offset):i.vertexAttribPointer(f,g.size,y,g.normalised,h.stride,h.offset),h.instance)if(this.hasInstance){const x=h.divisor??1;i.vertexAttribDivisor(f,x)}else throw new Error("geometry error, GPU Instancing is not supported on this device")}}}draw(t,e,i,r){const{gl:n}=this._renderer,o=this._activeGeometry,a=Jg[t||o.topology];if(r??(r=o.instanceCount),o.indexBuffer){const l=o.indexBuffer.data.BYTES_PER_ELEMENT,h=l===2?n.UNSIGNED_SHORT:n.UNSIGNED_INT;r!==1?n.drawElementsInstanced(a,e||o.indexBuffer.data.length,h,(i||0)*l,r):n.drawElements(a,e||o.indexBuffer.data.length,h,(i||0)*l)}else r!==1?n.drawArraysInstanced(a,i||0,e||o.getSize(),r):n.drawArrays(a,i||0,e||o.getSize());return this}unbind(){this.gl.bindVertexArray(null),this._activeVao=null,this._activeGeometry=null}destroy(){this._managedGeometries.destroy(),this._renderer=null,this.gl=null,this._activeVao=null,this._activeGeometry=null}}Vh.extension={type:[w.WebGLSystem],name:"geometry"};const t_=new $r({attributes:{aPosition:[-1,-1,3,-1,-1,3]}}),Hn=class bu{constructor(t){this.useBackBuffer=!1,this._useBackBufferThisRender=!1,this._renderer=t}init(t={}){const{useBackBuffer:e,antialias:i}={...bu.defaultOptions,...t};this.useBackBuffer=e,this._antialias=i,this._renderer.context.supports.msaa||(tt("antialiasing, is not supported on when using the back buffer"),this._antialias=!1),this._state=ve.for2d();const r=new Ye({vertex:`
|
|
572
|
+
attribute vec2 aPosition;
|
|
573
|
+
out vec2 vUv;
|
|
574
|
+
|
|
575
|
+
void main() {
|
|
576
|
+
gl_Position = vec4(aPosition, 0.0, 1.0);
|
|
577
|
+
|
|
578
|
+
vUv = (aPosition + 1.0) / 2.0;
|
|
579
|
+
|
|
580
|
+
// flip dem UVs
|
|
581
|
+
vUv.y = 1.0 - vUv.y;
|
|
582
|
+
}`,fragment:`
|
|
583
|
+
in vec2 vUv;
|
|
584
|
+
out vec4 finalColor;
|
|
585
|
+
|
|
586
|
+
uniform sampler2D uTexture;
|
|
587
|
+
|
|
588
|
+
void main() {
|
|
589
|
+
finalColor = texture(uTexture, vUv);
|
|
590
|
+
}`,name:"big-triangle"});this._bigTriangleShader=new be({glProgram:r,resources:{uTexture:z.WHITE.source}})}renderStart(t){const e=this._renderer.renderTarget.getRenderTarget(t.target);if(this._useBackBufferThisRender=this.useBackBuffer&&!!e.isRoot,this._useBackBufferThisRender){const i=this._renderer.renderTarget.getRenderTarget(t.target);this._targetTexture=i.colorTexture,t.target=this._getBackBufferTexture(i.colorTexture)}}renderEnd(){this._presentBackBuffer()}_presentBackBuffer(){const t=this._renderer;t.renderTarget.finishRenderPass(),this._useBackBufferThisRender&&(t.renderTarget.bind(this._targetTexture,!1),this._bigTriangleShader.resources.uTexture=this._backBufferTexture.source,t.encoder.draw({geometry:t_,shader:this._bigTriangleShader,state:this._state}))}_getBackBufferTexture(t){return this._backBufferTexture=this._backBufferTexture||new z({source:new At({width:t.width,height:t.height,resolution:t._resolution,antialias:this._antialias})}),this._backBufferTexture.source.resize(t.width,t.height,t._resolution),this._backBufferTexture}destroy(){this._backBufferTexture&&(this._backBufferTexture.destroy(),this._backBufferTexture=null)}};Hn.extension={type:[w.WebGLSystem],name:"backBuffer",priority:1},Hn.defaultOptions={useBackBuffer:!1};let e_=Hn;class zh{constructor(t){this._colorMaskCache=15,this._renderer=t}setMask(t){this._colorMaskCache!==t&&(this._colorMaskCache=t,this._renderer.gl.colorMask(!!(t&8),!!(t&4),!!(t&2),!!(t&1)))}}zh.extension={type:[w.WebGLSystem],name:"colorMask"};class $h{constructor(t){this.commandFinished=Promise.resolve(),this._renderer=t}setGeometry(t,e){this._renderer.geometry.bind(t,e.glProgram)}finishRenderPass(){}draw(t){const e=this._renderer,{geometry:i,shader:r,state:n,skipSync:o,topology:a,size:l,start:h,instanceCount:c}=t;e.shader.bind(r,o),e.geometry.bind(i,e.shader._activeProgram),n&&e.state.set(n),e.geometry.draw(a,l,h,c??i.instanceCount)}destroy(){this._renderer=null}}$h.extension={type:[w.WebGLSystem],name:"encoder"};class jh{constructor(t){this._renderer=t}contextChange(){const t=this._renderer.gl;this.maxTextures=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),this.maxBatchableTextures=$a(this.maxTextures,t);const e=this._renderer.context.webGLVersion===2;this.maxUniformBindings=e?t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS):0}destroy(){}}jh.extension={type:[w.WebGLSystem],name:"limits"};class i_{constructor(){this.width=-1,this.height=-1,this.msaa=!1,this._attachedMipLevel=0,this._attachedLayer=0,this.msaaRenderBuffer=[]}}const De=[];De[wt.NONE]=void 0,De[wt.DISABLED]={stencilWriteMask:0,stencilReadMask:0},De[wt.RENDERING_MASK_ADD]={stencilFront:{compare:"equal",passOp:"increment-clamp"},stencilBack:{compare:"equal",passOp:"increment-clamp"}},De[wt.RENDERING_MASK_REMOVE]={stencilFront:{compare:"equal",passOp:"decrement-clamp"},stencilBack:{compare:"equal",passOp:"decrement-clamp"}},De[wt.MASK_ACTIVE]={stencilWriteMask:0,stencilFront:{compare:"equal",passOp:"keep"},stencilBack:{compare:"equal",passOp:"keep"}},De[wt.INVERSE_MASK_ACTIVE]={stencilWriteMask:0,stencilFront:{compare:"not-equal",passOp:"keep"},stencilBack:{compare:"not-equal",passOp:"keep"}};class Xh{constructor(t){this._stencilCache={enabled:!1,stencilReference:0,stencilMode:wt.NONE},this._renderTargetStencilState=Object.create(null),t.renderTarget.onRenderTargetChange.add(this)}contextChange(t){this._gl=t,this._comparisonFuncMapping={always:t.ALWAYS,never:t.NEVER,equal:t.EQUAL,"not-equal":t.NOTEQUAL,less:t.LESS,"less-equal":t.LEQUAL,greater:t.GREATER,"greater-equal":t.GEQUAL},this._stencilOpsMapping={keep:t.KEEP,zero:t.ZERO,replace:t.REPLACE,invert:t.INVERT,"increment-clamp":t.INCR,"decrement-clamp":t.DECR,"increment-wrap":t.INCR_WRAP,"decrement-wrap":t.DECR_WRAP},this.resetState()}onRenderTargetChange(t){if(this._activeRenderTarget===t)return;this._activeRenderTarget=t;let e=this._renderTargetStencilState[t.uid];e||(e=this._renderTargetStencilState[t.uid]={stencilMode:wt.DISABLED,stencilReference:0}),this.setStencilMode(e.stencilMode,e.stencilReference)}resetState(){this._stencilCache.enabled=!1,this._stencilCache.stencilMode=wt.NONE,this._stencilCache.stencilReference=0}setStencilMode(t,e){const i=this._renderTargetStencilState[this._activeRenderTarget.uid],r=this._gl,n=De[t],o=this._stencilCache;if(i.stencilMode=t,i.stencilReference=e,t===wt.DISABLED){this._stencilCache.enabled&&(this._stencilCache.enabled=!1,r.disable(r.STENCIL_TEST));return}this._stencilCache.enabled||(this._stencilCache.enabled=!0,r.enable(r.STENCIL_TEST)),(t!==o.stencilMode||o.stencilReference!==e)&&(o.stencilMode=t,o.stencilReference=e,r.stencilFunc(this._comparisonFuncMapping[n.stencilBack.compare],e,255),r.stencilOp(r.KEEP,r.KEEP,this._stencilOpsMapping[n.stencilBack.passOp]))}}Xh.extension={type:[w.WebGLSystem],name:"stencil"};class Yh{constructor(t){this._syncFunctionHash=Object.create(null),this._adaptor=t,this._systemCheck()}_systemCheck(){if(!Ca())throw new Error("Current environment does not allow unsafe-eval, please use pixi.js/unsafe-eval module to enable support.")}ensureUniformGroup(t){const e=this.getUniformGroupData(t);t.buffer||(t.buffer=new ke({data:new Float32Array(e.layout.size/4),usage:yt.UNIFORM|yt.COPY_DST}))}getUniformGroupData(t){return this._syncFunctionHash[t._signature]||this._initUniformGroup(t)}_initUniformGroup(t){const e=t._signature;let i=this._syncFunctionHash[e];if(!i){const r=Object.keys(t.uniformStructures).map(a=>t.uniformStructures[a]),n=this._adaptor.createUboElements(r),o=this._generateUboSync(n.uboElements);i=this._syncFunctionHash[e]={layout:n,syncFunction:o}}return this._syncFunctionHash[e]}_generateUboSync(t){return this._adaptor.generateUboSync(t)}syncUniformGroup(t,e,i){const r=this.getUniformGroupData(t);t.buffer||(t.buffer=new ke({data:new Float32Array(r.layout.size/4),usage:yt.UNIFORM|yt.COPY_DST}));let n=null;return e||(e=t.buffer.data,n=t.buffer.dataInt32),i||(i=0),r.syncFunction(t.uniforms,e,n,i),!0}updateUniformGroup(t){if(t.isStatic&&!t._dirtyId)return!1;t._dirtyId=0;const e=this.syncUniformGroup(t);return t.buffer.update(),e}destroy(){this._syncFunctionHash=null}}const qh={f32:4,i32:4,"vec2<f32>":8,"vec3<f32>":12,"vec4<f32>":16,"vec2<i32>":8,"vec3<i32>":12,"vec4<i32>":16,"mat2x2<f32>":32,"mat3x3<f32>":48,"mat4x4<f32>":64};function s_(s){const t=s.map(n=>({data:n,offset:0,size:0})),e=16;let i=0,r=0;for(let n=0;n<t.length;n++){const o=t[n];if(i=qh[o.data.type],!i)throw new Error(`Unknown type ${o.data.type}`);o.data.size>1&&(i=Math.max(i,e)*o.data.size);const a=i===12?16:i;o.size=i;const l=r%e;l>0&&e-l<a?r+=(e-l)%16:r+=(i-l%i)%i,o.offset=r,r+=i}return r=Math.ceil(r/16)*16,{uboElements:t,size:r}}const ei=[{type:"mat3x3<f32>",test:s=>s.value.a!==void 0,ubo:`
|
|
591
|
+
var matrix = uv[name].toArray(true);
|
|
592
|
+
data[offset] = matrix[0];
|
|
593
|
+
data[offset + 1] = matrix[1];
|
|
594
|
+
data[offset + 2] = matrix[2];
|
|
595
|
+
data[offset + 4] = matrix[3];
|
|
596
|
+
data[offset + 5] = matrix[4];
|
|
597
|
+
data[offset + 6] = matrix[5];
|
|
598
|
+
data[offset + 8] = matrix[6];
|
|
599
|
+
data[offset + 9] = matrix[7];
|
|
600
|
+
data[offset + 10] = matrix[8];
|
|
601
|
+
`,uniform:`
|
|
602
|
+
gl.uniformMatrix3fv(ud[name].location, false, uv[name].toArray(true));
|
|
603
|
+
`},{type:"vec4<f32>",test:s=>s.type==="vec4<f32>"&&s.size===1&&s.value.width!==void 0,ubo:`
|
|
604
|
+
v = uv[name];
|
|
605
|
+
data[offset] = v.x;
|
|
606
|
+
data[offset + 1] = v.y;
|
|
607
|
+
data[offset + 2] = v.width;
|
|
608
|
+
data[offset + 3] = v.height;
|
|
609
|
+
`,uniform:`
|
|
610
|
+
cv = ud[name].value;
|
|
611
|
+
v = uv[name];
|
|
612
|
+
if (cv[0] !== v.x || cv[1] !== v.y || cv[2] !== v.width || cv[3] !== v.height) {
|
|
613
|
+
cv[0] = v.x;
|
|
614
|
+
cv[1] = v.y;
|
|
615
|
+
cv[2] = v.width;
|
|
616
|
+
cv[3] = v.height;
|
|
617
|
+
gl.uniform4f(ud[name].location, v.x, v.y, v.width, v.height);
|
|
618
|
+
}
|
|
619
|
+
`},{type:"vec2<f32>",test:s=>s.type==="vec2<f32>"&&s.size===1&&s.value.x!==void 0,ubo:`
|
|
620
|
+
v = uv[name];
|
|
621
|
+
data[offset] = v.x;
|
|
622
|
+
data[offset + 1] = v.y;
|
|
623
|
+
`,uniform:`
|
|
624
|
+
cv = ud[name].value;
|
|
625
|
+
v = uv[name];
|
|
626
|
+
if (cv[0] !== v.x || cv[1] !== v.y) {
|
|
627
|
+
cv[0] = v.x;
|
|
628
|
+
cv[1] = v.y;
|
|
629
|
+
gl.uniform2f(ud[name].location, v.x, v.y);
|
|
630
|
+
}
|
|
631
|
+
`},{type:"vec4<f32>",test:s=>s.type==="vec4<f32>"&&s.size===1&&s.value.red!==void 0,ubo:`
|
|
632
|
+
v = uv[name];
|
|
633
|
+
data[offset] = v.red;
|
|
634
|
+
data[offset + 1] = v.green;
|
|
635
|
+
data[offset + 2] = v.blue;
|
|
636
|
+
data[offset + 3] = v.alpha;
|
|
637
|
+
`,uniform:`
|
|
638
|
+
cv = ud[name].value;
|
|
639
|
+
v = uv[name];
|
|
640
|
+
if (cv[0] !== v.red || cv[1] !== v.green || cv[2] !== v.blue || cv[3] !== v.alpha) {
|
|
641
|
+
cv[0] = v.red;
|
|
642
|
+
cv[1] = v.green;
|
|
643
|
+
cv[2] = v.blue;
|
|
644
|
+
cv[3] = v.alpha;
|
|
645
|
+
gl.uniform4f(ud[name].location, v.red, v.green, v.blue, v.alpha);
|
|
646
|
+
}
|
|
647
|
+
`},{type:"vec3<f32>",test:s=>s.type==="vec3<f32>"&&s.size===1&&s.value.red!==void 0,ubo:`
|
|
648
|
+
v = uv[name];
|
|
649
|
+
data[offset] = v.red;
|
|
650
|
+
data[offset + 1] = v.green;
|
|
651
|
+
data[offset + 2] = v.blue;
|
|
652
|
+
`,uniform:`
|
|
653
|
+
cv = ud[name].value;
|
|
654
|
+
v = uv[name];
|
|
655
|
+
if (cv[0] !== v.red || cv[1] !== v.green || cv[2] !== v.blue) {
|
|
656
|
+
cv[0] = v.red;
|
|
657
|
+
cv[1] = v.green;
|
|
658
|
+
cv[2] = v.blue;
|
|
659
|
+
gl.uniform3f(ud[name].location, v.red, v.green, v.blue);
|
|
660
|
+
}
|
|
661
|
+
`}];function Kh(s,t,e,i){const r=[`
|
|
662
|
+
var v = null;
|
|
663
|
+
var v2 = null;
|
|
664
|
+
var t = 0;
|
|
665
|
+
var index = 0;
|
|
666
|
+
var name = null;
|
|
667
|
+
var arrayOffset = null;
|
|
668
|
+
`];let n=0;for(let a=0;a<s.length;a++){const l=s[a],h=l.data.name;let c=!1,u=0;for(let m=0;m<ei.length;m++)if(ei[m].test(l.data)){u=l.offset/4,r.push(`name = "${h}";`,`offset += ${u-n};`,ei[m][t]||ei[m].ubo),c=!0;break}if(!c)if(l.data.size>1)u=l.offset/4,r.push(e(l,u-n));else{const m=i[l.data.type];u=l.offset/4,r.push(`
|
|
669
|
+
v = uv.${h};
|
|
670
|
+
offset += ${u-n};
|
|
671
|
+
${m};
|
|
672
|
+
`)}n=u}const o=r.join(`
|
|
673
|
+
`);return new Function("uv","data","dataInt32","offset",o)}function wi(s,t){return`
|
|
674
|
+
for (let i = 0; i < ${s*t}; i++) {
|
|
675
|
+
data[offset + (((i / ${s})|0) * 4) + (i % ${s})] = v[i];
|
|
676
|
+
}
|
|
677
|
+
`}const Zh={f32:`
|
|
678
|
+
data[offset] = v;`,i32:`
|
|
679
|
+
dataInt32[offset] = v;`,"vec2<f32>":`
|
|
680
|
+
data[offset] = v[0];
|
|
681
|
+
data[offset + 1] = v[1];`,"vec3<f32>":`
|
|
682
|
+
data[offset] = v[0];
|
|
683
|
+
data[offset + 1] = v[1];
|
|
684
|
+
data[offset + 2] = v[2];`,"vec4<f32>":`
|
|
685
|
+
data[offset] = v[0];
|
|
686
|
+
data[offset + 1] = v[1];
|
|
687
|
+
data[offset + 2] = v[2];
|
|
688
|
+
data[offset + 3] = v[3];`,"vec2<i32>":`
|
|
689
|
+
dataInt32[offset] = v[0];
|
|
690
|
+
dataInt32[offset + 1] = v[1];`,"vec3<i32>":`
|
|
691
|
+
dataInt32[offset] = v[0];
|
|
692
|
+
dataInt32[offset + 1] = v[1];
|
|
693
|
+
dataInt32[offset + 2] = v[2];`,"vec4<i32>":`
|
|
694
|
+
dataInt32[offset] = v[0];
|
|
695
|
+
dataInt32[offset + 1] = v[1];
|
|
696
|
+
dataInt32[offset + 2] = v[2];
|
|
697
|
+
dataInt32[offset + 3] = v[3];`,"mat2x2<f32>":`
|
|
698
|
+
data[offset] = v[0];
|
|
699
|
+
data[offset + 1] = v[1];
|
|
700
|
+
data[offset + 4] = v[2];
|
|
701
|
+
data[offset + 5] = v[3];`,"mat3x3<f32>":`
|
|
702
|
+
data[offset] = v[0];
|
|
703
|
+
data[offset + 1] = v[1];
|
|
704
|
+
data[offset + 2] = v[2];
|
|
705
|
+
data[offset + 4] = v[3];
|
|
706
|
+
data[offset + 5] = v[4];
|
|
707
|
+
data[offset + 6] = v[5];
|
|
708
|
+
data[offset + 8] = v[6];
|
|
709
|
+
data[offset + 9] = v[7];
|
|
710
|
+
data[offset + 10] = v[8];`,"mat4x4<f32>":`
|
|
711
|
+
for (let i = 0; i < 16; i++) {
|
|
712
|
+
data[offset + i] = v[i];
|
|
713
|
+
}`,"mat3x2<f32>":wi(3,2),"mat4x2<f32>":wi(4,2),"mat2x3<f32>":wi(2,3),"mat4x3<f32>":wi(4,3),"mat2x4<f32>":wi(2,4),"mat3x4<f32>":wi(3,4)},r_={...Zh,"mat2x2<f32>":`
|
|
714
|
+
data[offset] = v[0];
|
|
715
|
+
data[offset + 1] = v[1];
|
|
716
|
+
data[offset + 2] = v[2];
|
|
717
|
+
data[offset + 3] = v[3];
|
|
718
|
+
`};function n_(s,t){const e=Math.max(qh[s.data.type]/16,1),i=s.data.value.length/s.data.size,r=(4-i%4)%4,n=s.data.type.indexOf("i32")>=0?"dataInt32":"data";return`
|
|
719
|
+
v = uv.${s.data.name};
|
|
720
|
+
offset += ${t};
|
|
721
|
+
|
|
722
|
+
arrayOffset = offset;
|
|
723
|
+
|
|
724
|
+
t = 0;
|
|
725
|
+
|
|
726
|
+
for(var i=0; i < ${s.data.size*e}; i++)
|
|
727
|
+
{
|
|
728
|
+
for(var j = 0; j < ${i}; j++)
|
|
729
|
+
{
|
|
730
|
+
${n}[arrayOffset++] = v[t++];
|
|
731
|
+
}
|
|
732
|
+
${r!==0?`arrayOffset += ${r};`:""}
|
|
733
|
+
}
|
|
734
|
+
`}function o_(s){return Kh(s,"uboStd40",n_,Zh)}class Jh extends Yh{constructor(){super({createUboElements:s_,generateUboSync:o_})}}Jh.extension={type:[w.WebGLSystem],name:"ubo"};class a_{constructor(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new ut}init(t,e){this._renderer=t,this._renderTargetSystem=e,t.runners.contextChange.add(this)}contextChange(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new ut;const t=this._renderer.gl;this._drawBuffersCache=[];for(let e=1;e<=16;e++)this._drawBuffersCache[e]=Array.from({length:e},(i,r)=>t.COLOR_ATTACHMENT0+r)}copyToTexture(t,e,i,r,n){const o=this._renderTargetSystem,a=this._renderer,l=o.getGpuRenderTarget(t),h=a.gl;return this.finishRenderPass(t),h.bindFramebuffer(h.FRAMEBUFFER,l.resolveTargetFramebuffer),a.texture.bind(e,0),h.copyTexSubImage2D(h.TEXTURE_2D,0,n.x,n.y,i.x,i.y,r.width,r.height),e}startRenderPass(t,e=!0,i,r,n=0,o=0){const a=this._renderTargetSystem,l=t.colorTexture,h=a.getGpuRenderTarget(t);if(o!==0&&this._renderer.context.webGLVersion<2)throw new Error("[RenderTargetSystem] Rendering to array layers requires WebGL2.");if(n>0){if(h.msaa)throw new Error("[RenderTargetSystem] Rendering to mip levels is not supported with MSAA render targets.");if(this._renderer.context.webGLVersion<2)throw new Error("[RenderTargetSystem] Rendering to mip levels requires WebGL2.")}let c=r.y;t.isRoot&&(c=l.pixelHeight-r.height-r.y),t.colorTextures.forEach(f=>{this._renderer.texture.unbind(f)});const u=this._renderer.gl;u.bindFramebuffer(u.FRAMEBUFFER,h.framebuffer),!t.isRoot&&(h._attachedMipLevel!==n||h._attachedLayer!==o)&&(t.colorTextures.forEach((f,g)=>{const y=this._renderer.texture.getGlSource(f);if(y.target===u.TEXTURE_2D){if(o!==0)throw new Error("[RenderTargetSystem] layer must be 0 when rendering to 2D textures in WebGL.");u.framebufferTexture2D(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0+g,u.TEXTURE_2D,y.texture,n)}else if(y.target===u.TEXTURE_2D_ARRAY){if(this._renderer.context.webGLVersion<2)throw new Error("[RenderTargetSystem] Rendering to 2D array textures requires WebGL2.");u.framebufferTextureLayer(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0+g,y.texture,n,o)}else if(y.target===u.TEXTURE_CUBE_MAP){if(o<0||o>5)throw new Error("[RenderTargetSystem] Cube map layer must be between 0 and 5.");u.framebufferTexture2D(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0+g,u.TEXTURE_CUBE_MAP_POSITIVE_X+o,y.texture,n)}else throw new Error("[RenderTargetSystem] Unsupported texture target for render-to-layer in WebGL.")}),h._attachedMipLevel=n,h._attachedLayer=o),t.colorTextures.length>1&&this._setDrawBuffers(t,u);const m=this._viewPortCache;(m.x!==r.x||m.y!==c||m.width!==r.width||m.height!==r.height)&&(m.x=r.x,m.y=c,m.width=r.width,m.height=r.height,u.viewport(r.x,c,r.width,r.height)),!h.depthStencilRenderBuffer&&(t.stencil||t.depth)&&this._initStencil(h),this.clear(t,e,i)}finishRenderPass(t){const i=this._renderTargetSystem.getGpuRenderTarget(t);if(!i.msaa)return;const r=this._renderer.gl;r.bindFramebuffer(r.FRAMEBUFFER,i.resolveTargetFramebuffer),r.bindFramebuffer(r.READ_FRAMEBUFFER,i.framebuffer),r.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,r.COLOR_BUFFER_BIT,r.NEAREST),r.bindFramebuffer(r.FRAMEBUFFER,i.framebuffer)}initGpuRenderTarget(t){const i=this._renderer.gl,r=new i_;return r._attachedMipLevel=0,r._attachedLayer=0,t.colorTexture instanceof le?(this._renderer.context.ensureCanvasSize(t.colorTexture.resource),r.framebuffer=null,r):(this._initColor(t,r),i.bindFramebuffer(i.FRAMEBUFFER,null),r)}destroyGpuRenderTarget(t){const e=this._renderer.gl;t.framebuffer&&(e.deleteFramebuffer(t.framebuffer),t.framebuffer=null),t.resolveTargetFramebuffer&&(e.deleteFramebuffer(t.resolveTargetFramebuffer),t.resolveTargetFramebuffer=null),t.depthStencilRenderBuffer&&(e.deleteRenderbuffer(t.depthStencilRenderBuffer),t.depthStencilRenderBuffer=null),t.msaaRenderBuffer.forEach(i=>{e.deleteRenderbuffer(i)}),t.msaaRenderBuffer=null}clear(t,e,i,r,n=0,o=0){if(!e)return;if(o!==0)throw new Error("[RenderTargetSystem] Clearing array layers is not supported in WebGL renderer.");const a=this._renderTargetSystem;typeof e=="boolean"&&(e=e?Yt.ALL:Yt.NONE);const l=this._renderer.gl;if(e&Yt.COLOR){i??(i=a.defaultClearColor);const h=this._clearColorCache,c=i;(h[0]!==c[0]||h[1]!==c[1]||h[2]!==c[2]||h[3]!==c[3])&&(h[0]=c[0],h[1]=c[1],h[2]=c[2],h[3]=c[3],l.clearColor(c[0],c[1],c[2],c[3]))}l.clear(e)}resizeGpuRenderTarget(t){if(t.isRoot)return;const i=this._renderTargetSystem.getGpuRenderTarget(t);this._resizeColor(t,i),(t.stencil||t.depth)&&this._resizeStencil(i)}_initColor(t,e){const i=this._renderer,r=i.gl,n=r.createFramebuffer();if(e.resolveTargetFramebuffer=n,r.bindFramebuffer(r.FRAMEBUFFER,n),e.width=t.colorTexture.source.pixelWidth,e.height=t.colorTexture.source.pixelHeight,t.colorTextures.forEach((a,l)=>{const h=a.source;h.antialias&&(i.context.supports.msaa?e.msaa=!0:tt("[RenderTexture] Antialiasing on textures is not supported in WebGL1")),i.texture.bindSource(h,0);const c=i.texture.getGlSource(h),u=c.texture;if(c.target===r.TEXTURE_2D)r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+l,r.TEXTURE_2D,u,0);else if(c.target===r.TEXTURE_2D_ARRAY){if(i.context.webGLVersion<2)throw new Error("[RenderTargetSystem] TEXTURE_2D_ARRAY requires WebGL2.");r.framebufferTextureLayer(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+l,u,0,0)}else if(c.target===r.TEXTURE_CUBE_MAP)r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+l,r.TEXTURE_CUBE_MAP_POSITIVE_X,u,0);else throw new Error("[RenderTargetSystem] Unsupported texture target for framebuffer attachment.")}),e.msaa){const a=r.createFramebuffer();e.framebuffer=a,r.bindFramebuffer(r.FRAMEBUFFER,a),t.colorTextures.forEach((l,h)=>{const c=r.createRenderbuffer();e.msaaRenderBuffer[h]=c})}else e.framebuffer=n;this._resizeColor(t,e)}_resizeColor(t,e){const i=t.colorTexture.source;if(e.width=i.pixelWidth,e.height=i.pixelHeight,e._attachedMipLevel=0,e._attachedLayer=0,t.colorTextures.forEach((r,n)=>{n!==0&&r.source.resize(i.width,i.height,i._resolution)}),e.msaa){const r=this._renderer,n=r.gl,o=e.framebuffer;n.bindFramebuffer(n.FRAMEBUFFER,o),t.colorTextures.forEach((a,l)=>{const h=a.source;r.texture.bindSource(h,0);const u=r.texture.getGlSource(h).internalFormat,m=e.msaaRenderBuffer[l];n.bindRenderbuffer(n.RENDERBUFFER,m),n.renderbufferStorageMultisample(n.RENDERBUFFER,4,u,h.pixelWidth,h.pixelHeight),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+l,n.RENDERBUFFER,m)})}}_initStencil(t){if(t.framebuffer===null)return;const e=this._renderer.gl,i=e.createRenderbuffer();t.depthStencilRenderBuffer=i,e.bindRenderbuffer(e.RENDERBUFFER,i),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.RENDERBUFFER,i),this._resizeStencil(t)}_resizeStencil(t){const e=this._renderer.gl;e.bindRenderbuffer(e.RENDERBUFFER,t.depthStencilRenderBuffer),t.msaa?e.renderbufferStorageMultisample(e.RENDERBUFFER,4,e.DEPTH24_STENCIL8,t.width,t.height):e.renderbufferStorage(e.RENDERBUFFER,this._renderer.context.webGLVersion===2?e.DEPTH24_STENCIL8:e.DEPTH_STENCIL,t.width,t.height)}prerender(t){const e=t.colorTexture.resource;this._renderer.context.multiView&&le.test(e)&&this._renderer.context.ensureCanvasSize(e)}postrender(t){if(this._renderer.context.multiView&&le.test(t.colorTexture.resource)){const e=this._renderer.context.canvas,i=t.colorTexture;i.context2D.drawImage(e,0,i.pixelHeight-e.height)}}_setDrawBuffers(t,e){const i=t.colorTextures.length,r=this._drawBuffersCache[i];if(this._renderer.context.webGLVersion===1){const n=this._renderer.context.extensions.drawBuffers;n?n.drawBuffersWEBGL(r):tt("[RenderTexture] This WebGL1 context does not support rendering to multiple targets")}else e.drawBuffers(r)}}class Qh extends Un{constructor(t){super(t),this.adaptor=new a_,this.adaptor.init(t,this)}}Qh.extension={type:[w.WebGLSystem],name:"renderTarget"};class Wn extends Jt{constructor({buffer:t,offset:e,size:i}){super(),this.uid=dt("buffer"),this._resourceType="bufferResource",this._touched=0,this._resourceId=dt("resource"),this._bufferResource=!0,this.destroyed=!1,this.buffer=t,this.offset=e|0,this.size=i,this.buffer.on("change",this.onBufferChange,this)}onBufferChange(){this._resourceId=dt("resource"),this.emit("change",this)}destroy(t=!1){this.destroyed=!0,t&&this.buffer.destroy(),this.emit("change",this),this.buffer=null,this.removeAllListeners()}}function l_(s,t){const e=[],i=[`
|
|
735
|
+
var g = s.groups;
|
|
736
|
+
var sS = r.shader;
|
|
737
|
+
var p = s.glProgram;
|
|
738
|
+
var ugS = r.uniformGroup;
|
|
739
|
+
var resources;
|
|
740
|
+
`];let r=!1,n=0;const o=t._getProgramData(s.glProgram);for(const l in s.groups){const h=s.groups[l];e.push(`
|
|
741
|
+
resources = g[${l}].resources;
|
|
742
|
+
`);for(const c in h.resources){const u=h.resources[c];if(u instanceof he)if(u.ubo){const m=s._uniformBindMap[l][Number(c)];e.push(`
|
|
743
|
+
sS.bindUniformBlock(
|
|
744
|
+
resources[${c}],
|
|
745
|
+
'${m}',
|
|
746
|
+
${s.glProgram._uniformBlockData[m].index}
|
|
747
|
+
);
|
|
748
|
+
`)}else e.push(`
|
|
749
|
+
ugS.updateUniformGroup(resources[${c}], p, sD);
|
|
750
|
+
`);else if(u instanceof Wn){const m=s._uniformBindMap[l][Number(c)];e.push(`
|
|
751
|
+
sS.bindUniformBlock(
|
|
752
|
+
resources[${c}],
|
|
753
|
+
'${m}',
|
|
754
|
+
${s.glProgram._uniformBlockData[m].index}
|
|
755
|
+
);
|
|
756
|
+
`)}else if(u instanceof At){const m=s._uniformBindMap[l][c],f=o.uniformData[m];f&&(r||(r=!0,i.push(`
|
|
757
|
+
var tS = r.texture;
|
|
758
|
+
`)),t._gl.uniform1i(f.location,n),e.push(`
|
|
759
|
+
tS.bind(resources[${c}], ${n});
|
|
760
|
+
`),n++)}}}const a=[...i,...e].join(`
|
|
761
|
+
`);return new Function("r","s","sD",a)}class h_{constructor(t,e){this.program=t,this.uniformData=e,this.uniformGroups={},this.uniformDirtyGroups={},this.uniformBlockBindings={}}destroy(){this.uniformData=null,this.uniformGroups=null,this.uniformDirtyGroups=null,this.uniformBlockBindings=null,this.program=null}}function tc(s,t,e){const i=s.createShader(t);return s.shaderSource(i,e),s.compileShader(i),i}function Vn(s){const t=new Array(s);for(let e=0;e<t.length;e++)t[e]=!1;return t}function ec(s,t){switch(s){case"float":return 0;case"vec2":return new Float32Array(2*t);case"vec3":return new Float32Array(3*t);case"vec4":return new Float32Array(4*t);case"int":case"uint":case"sampler2D":case"sampler2DArray":return 0;case"ivec2":return new Int32Array(2*t);case"ivec3":return new Int32Array(3*t);case"ivec4":return new Int32Array(4*t);case"uvec2":return new Uint32Array(2*t);case"uvec3":return new Uint32Array(3*t);case"uvec4":return new Uint32Array(4*t);case"bool":return!1;case"bvec2":return Vn(2*t);case"bvec3":return Vn(3*t);case"bvec4":return Vn(4*t);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 Hs=null;const ic={FLOAT:"float",FLOAT_VEC2:"vec2",FLOAT_VEC3:"vec3",FLOAT_VEC4:"vec4",INT:"int",INT_VEC2:"ivec2",INT_VEC3:"ivec3",INT_VEC4:"ivec4",UNSIGNED_INT:"uint",UNSIGNED_INT_VEC2:"uvec2",UNSIGNED_INT_VEC3:"uvec3",UNSIGNED_INT_VEC4:"uvec4",BOOL:"bool",BOOL_VEC2:"bvec2",BOOL_VEC3:"bvec3",BOOL_VEC4:"bvec4",FLOAT_MAT2:"mat2",FLOAT_MAT3:"mat3",FLOAT_MAT4:"mat4",SAMPLER_2D:"sampler2D",INT_SAMPLER_2D:"sampler2D",UNSIGNED_INT_SAMPLER_2D:"sampler2D",SAMPLER_CUBE:"samplerCube",INT_SAMPLER_CUBE:"samplerCube",UNSIGNED_INT_SAMPLER_CUBE:"samplerCube",SAMPLER_2D_ARRAY:"sampler2DArray",INT_SAMPLER_2D_ARRAY:"sampler2DArray",UNSIGNED_INT_SAMPLER_2D_ARRAY:"sampler2DArray"},c_={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 sc(s,t){if(!Hs){const e=Object.keys(ic);Hs={};for(let i=0;i<e.length;++i){const r=e[i];Hs[s[r]]=ic[r]}}return Hs[t]}function u_(s,t){const e=sc(s,t);return c_[e]||"float32"}function d_(s,t,e=!1){const i={},r=t.getProgramParameter(s,t.ACTIVE_ATTRIBUTES);for(let o=0;o<r;o++){const a=t.getActiveAttrib(s,o);if(a.name.startsWith("gl_"))continue;const l=u_(t,a.type);i[a.name]={location:0,format:l,stride:Ni(l).stride,offset:0,instance:!1,start:0}}const n=Object.keys(i);if(e){n.sort((o,a)=>o>a?1:-1);for(let o=0;o<n.length;o++)i[n[o]].location=o,t.bindAttribLocation(s,o,n[o]);t.linkProgram(s)}else for(let o=0;o<n.length;o++)i[n[o]].location=t.getAttribLocation(s,n[o]);return i}function f_(s,t){if(!t.ACTIVE_UNIFORM_BLOCKS)return{};const e={},i=t.getProgramParameter(s,t.ACTIVE_UNIFORM_BLOCKS);for(let r=0;r<i;r++){const n=t.getActiveUniformBlockName(s,r),o=t.getUniformBlockIndex(s,n),a=t.getActiveUniformBlockParameter(s,r,t.UNIFORM_BLOCK_DATA_SIZE);e[n]={name:n,index:o,size:a}}return e}function p_(s,t){const e={},i=t.getProgramParameter(s,t.ACTIVE_UNIFORMS);for(let r=0;r<i;r++){const n=t.getActiveUniform(s,r),o=n.name.replace(/\[.*?\]$/,""),a=!!n.name.match(/\[.*?\]$/),l=sc(t,n.type);e[o]={name:o,index:r,type:l,size:n.size,isArray:a,value:ec(l,n.size)}}return e}function rc(s,t){const e=s.getShaderSource(t).split(`
|
|
762
|
+
`).map((h,c)=>`${c}: ${h}`),i=s.getShaderInfoLog(t),r=i.split(`
|
|
763
|
+
`),n={},o=r.map(h=>parseFloat(h.replace(/^ERROR\: 0\:([\d]+)\:.*$/,"$1"))).filter(h=>h&&!n[h]?(n[h]=!0,!0):!1),a=[""];o.forEach(h=>{e[h-1]=`%c${e[h-1]}%c`,a.push("background: #FF0000; color:#FFFFFF; font-size: 10px","font-size: 10px")});const l=e.join(`
|
|
764
|
+
`);a[0]=l,console.error(i),console.groupCollapsed("click to view full shader code"),console.warn(...a),console.groupEnd()}function m_(s,t,e,i){s.getProgramParameter(t,s.LINK_STATUS)||(s.getShaderParameter(e,s.COMPILE_STATUS)||rc(s,e),s.getShaderParameter(i,s.COMPILE_STATUS)||rc(s,i),console.error("PixiJS Error: Could not initialize shader."),s.getProgramInfoLog(t)!==""&&console.warn("PixiJS Warning: gl.getProgramInfoLog()",s.getProgramInfoLog(t)))}function g_(s,t){const e=tc(s,s.VERTEX_SHADER,t.vertex),i=tc(s,s.FRAGMENT_SHADER,t.fragment),r=s.createProgram();s.attachShader(r,e),s.attachShader(r,i);const n=t.transformFeedbackVaryings;n&&(typeof s.transformFeedbackVaryings!="function"?tt("TransformFeedback is not supported but TransformFeedbackVaryings are given."):s.transformFeedbackVaryings(r,n.names,n.bufferMode==="separate"?s.SEPARATE_ATTRIBS:s.INTERLEAVED_ATTRIBS)),s.linkProgram(r),s.getProgramParameter(r,s.LINK_STATUS)||m_(s,r,e,i),t._attributeData=d_(r,s,!/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m.test(t.vertex)),t._uniformData=p_(r,s),t._uniformBlockData=f_(r,s),s.deleteShader(e),s.deleteShader(i);const o={};for(const l in t._uniformData){const h=t._uniformData[l];o[l]={location:s.getUniformLocation(r,l),value:ec(h.type,h.size)}}return new h_(r,o)}const Ws={textureCount:0,blockIndex:0};class nc{constructor(t){this._activeProgram=null,this._programDataHash=Object.create(null),this._shaderSyncFunctions=Object.create(null),this._renderer=t}contextChange(t){this._gl=t,this._programDataHash=Object.create(null),this._shaderSyncFunctions=Object.create(null),this._activeProgram=null}bind(t,e){if(this._setProgram(t.glProgram),e)return;Ws.textureCount=0,Ws.blockIndex=0;let i=this._shaderSyncFunctions[t.glProgram._key];i||(i=this._shaderSyncFunctions[t.glProgram._key]=this._generateShaderSync(t,this)),this._renderer.buffer.nextBindBase(!!t.glProgram.transformFeedbackVaryings),i(this._renderer,t,Ws)}updateUniformGroup(t){this._renderer.uniformGroup.updateUniformGroup(t,this._activeProgram,Ws)}bindUniformBlock(t,e,i=0){const r=this._renderer.buffer,n=this._getProgramData(this._activeProgram),o=t._bufferResource;o||this._renderer.ubo.updateUniformGroup(t);const a=t.buffer,l=r.updateBuffer(a),h=r.freeLocationForBufferBase(l);if(o){const{offset:u,size:m}=t;u===0&&m===a.data.byteLength?r.bindBufferBase(l,h):r.bindBufferRange(l,h,u)}else r.getLastBindBaseLocation(l)!==h&&r.bindBufferBase(l,h);const c=this._activeProgram._uniformBlockData[e].index;n.uniformBlockBindings[i]!==h&&(n.uniformBlockBindings[i]=h,this._renderer.gl.uniformBlockBinding(n.program,c,h))}_setProgram(t){if(this._activeProgram===t)return;this._activeProgram=t;const e=this._getProgramData(t);this._gl.useProgram(e.program)}_getProgramData(t){return this._programDataHash[t._key]||this._createProgramData(t)}_createProgramData(t){const e=t._key;return this._programDataHash[e]=g_(this._gl,t),this._programDataHash[e]}destroy(){for(const t of Object.keys(this._programDataHash))this._programDataHash[t].destroy();this._programDataHash=null,this._shaderSyncFunctions=null,this._activeProgram=null,this._renderer=null,this._gl=null}_generateShaderSync(t,e){return l_(t,e)}resetState(){this._activeProgram=null}}nc.extension={type:[w.WebGLSystem],name:"shader"};const __={f32:`if (cv !== v) {
|
|
765
|
+
cu.value = v;
|
|
766
|
+
gl.uniform1f(location, v);
|
|
767
|
+
}`,"vec2<f32>":`if (cv[0] !== v[0] || cv[1] !== v[1]) {
|
|
768
|
+
cv[0] = v[0];
|
|
769
|
+
cv[1] = v[1];
|
|
770
|
+
gl.uniform2f(location, v[0], v[1]);
|
|
771
|
+
}`,"vec3<f32>":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) {
|
|
772
|
+
cv[0] = v[0];
|
|
773
|
+
cv[1] = v[1];
|
|
774
|
+
cv[2] = v[2];
|
|
775
|
+
gl.uniform3f(location, v[0], v[1], v[2]);
|
|
776
|
+
}`,"vec4<f32>":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) {
|
|
777
|
+
cv[0] = v[0];
|
|
778
|
+
cv[1] = v[1];
|
|
779
|
+
cv[2] = v[2];
|
|
780
|
+
cv[3] = v[3];
|
|
781
|
+
gl.uniform4f(location, v[0], v[1], v[2], v[3]);
|
|
782
|
+
}`,i32:`if (cv !== v) {
|
|
783
|
+
cu.value = v;
|
|
784
|
+
gl.uniform1i(location, v);
|
|
785
|
+
}`,"vec2<i32>":`if (cv[0] !== v[0] || cv[1] !== v[1]) {
|
|
786
|
+
cv[0] = v[0];
|
|
787
|
+
cv[1] = v[1];
|
|
788
|
+
gl.uniform2i(location, v[0], v[1]);
|
|
789
|
+
}`,"vec3<i32>":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) {
|
|
790
|
+
cv[0] = v[0];
|
|
791
|
+
cv[1] = v[1];
|
|
792
|
+
cv[2] = v[2];
|
|
793
|
+
gl.uniform3i(location, v[0], v[1], v[2]);
|
|
794
|
+
}`,"vec4<i32>":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) {
|
|
795
|
+
cv[0] = v[0];
|
|
796
|
+
cv[1] = v[1];
|
|
797
|
+
cv[2] = v[2];
|
|
798
|
+
cv[3] = v[3];
|
|
799
|
+
gl.uniform4i(location, v[0], v[1], v[2], v[3]);
|
|
800
|
+
}`,u32:`if (cv !== v) {
|
|
801
|
+
cu.value = v;
|
|
802
|
+
gl.uniform1ui(location, v);
|
|
803
|
+
}`,"vec2<u32>":`if (cv[0] !== v[0] || cv[1] !== v[1]) {
|
|
804
|
+
cv[0] = v[0];
|
|
805
|
+
cv[1] = v[1];
|
|
806
|
+
gl.uniform2ui(location, v[0], v[1]);
|
|
807
|
+
}`,"vec3<u32>":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) {
|
|
808
|
+
cv[0] = v[0];
|
|
809
|
+
cv[1] = v[1];
|
|
810
|
+
cv[2] = v[2];
|
|
811
|
+
gl.uniform3ui(location, v[0], v[1], v[2]);
|
|
812
|
+
}`,"vec4<u32>":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) {
|
|
813
|
+
cv[0] = v[0];
|
|
814
|
+
cv[1] = v[1];
|
|
815
|
+
cv[2] = v[2];
|
|
816
|
+
cv[3] = v[3];
|
|
817
|
+
gl.uniform4ui(location, v[0], v[1], v[2], v[3]);
|
|
818
|
+
}`,bool:`if (cv !== v) {
|
|
819
|
+
cu.value = v;
|
|
820
|
+
gl.uniform1i(location, v);
|
|
821
|
+
}`,"vec2<bool>":`if (cv[0] !== v[0] || cv[1] !== v[1]) {
|
|
822
|
+
cv[0] = v[0];
|
|
823
|
+
cv[1] = v[1];
|
|
824
|
+
gl.uniform2i(location, v[0], v[1]);
|
|
825
|
+
}`,"vec3<bool>":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) {
|
|
826
|
+
cv[0] = v[0];
|
|
827
|
+
cv[1] = v[1];
|
|
828
|
+
cv[2] = v[2];
|
|
829
|
+
gl.uniform3i(location, v[0], v[1], v[2]);
|
|
830
|
+
}`,"vec4<bool>":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) {
|
|
831
|
+
cv[0] = v[0];
|
|
832
|
+
cv[1] = v[1];
|
|
833
|
+
cv[2] = v[2];
|
|
834
|
+
cv[3] = v[3];
|
|
835
|
+
gl.uniform4i(location, v[0], v[1], v[2], v[3]);
|
|
836
|
+
}`,"mat2x2<f32>":"gl.uniformMatrix2fv(location, false, v);","mat3x3<f32>":"gl.uniformMatrix3fv(location, false, v);","mat4x4<f32>":"gl.uniformMatrix4fv(location, false, v);"},y_={f32:"gl.uniform1fv(location, v);","vec2<f32>":"gl.uniform2fv(location, v);","vec3<f32>":"gl.uniform3fv(location, v);","vec4<f32>":"gl.uniform4fv(location, v);","mat2x2<f32>":"gl.uniformMatrix2fv(location, false, v);","mat3x3<f32>":"gl.uniformMatrix3fv(location, false, v);","mat4x4<f32>":"gl.uniformMatrix4fv(location, false, v);",i32:"gl.uniform1iv(location, v);","vec2<i32>":"gl.uniform2iv(location, v);","vec3<i32>":"gl.uniform3iv(location, v);","vec4<i32>":"gl.uniform4iv(location, v);",u32:"gl.uniform1iv(location, v);","vec2<u32>":"gl.uniform2iv(location, v);","vec3<u32>":"gl.uniform3iv(location, v);","vec4<u32>":"gl.uniform4iv(location, v);",bool:"gl.uniform1iv(location, v);","vec2<bool>":"gl.uniform2iv(location, v);","vec3<bool>":"gl.uniform3iv(location, v);","vec4<bool>":"gl.uniform4iv(location, v);"};function x_(s,t){const e=[`
|
|
837
|
+
var v = null;
|
|
838
|
+
var cv = null;
|
|
839
|
+
var cu = null;
|
|
840
|
+
var t = 0;
|
|
841
|
+
var gl = renderer.gl;
|
|
842
|
+
var name = null;
|
|
843
|
+
`];for(const i in s.uniforms){if(!t[i]){s.uniforms[i]instanceof he?s.uniforms[i].ubo?e.push(`
|
|
844
|
+
renderer.shader.bindUniformBlock(uv.${i}, "${i}");
|
|
845
|
+
`):e.push(`
|
|
846
|
+
renderer.shader.updateUniformGroup(uv.${i});
|
|
847
|
+
`):s.uniforms[i]instanceof Wn&&e.push(`
|
|
848
|
+
renderer.shader.bindBufferResource(uv.${i}, "${i}");
|
|
849
|
+
`);continue}const r=s.uniformStructures[i];let n=!1;for(let o=0;o<ei.length;o++){const a=ei[o];if(r.type===a.type&&a.test(r)){e.push(`name = "${i}";`,ei[o].uniform),n=!0;break}}if(!n){const a=(r.size===1?__:y_)[r.type].replace("location",`ud["${i}"].location`);e.push(`
|
|
850
|
+
cu = ud["${i}"];
|
|
851
|
+
cv = cu.value;
|
|
852
|
+
v = uv["${i}"];
|
|
853
|
+
${a};`)}}return new Function("ud","uv","renderer","syncData",e.join(`
|
|
854
|
+
`))}class oc{constructor(t){this._cache={},this._uniformGroupSyncHash={},this._renderer=t,this.gl=null,this._cache={}}contextChange(t){this.gl=t}updateUniformGroup(t,e,i){const r=this._renderer.shader._getProgramData(e);(!t.isStatic||t._dirtyId!==r.uniformDirtyGroups[t.uid])&&(r.uniformDirtyGroups[t.uid]=t._dirtyId,this._getUniformSyncFunction(t,e)(r.uniformData,t.uniforms,this._renderer,i))}_getUniformSyncFunction(t,e){var i;return((i=this._uniformGroupSyncHash[t._signature])==null?void 0:i[e._key])||this._createUniformSyncFunction(t,e)}_createUniformSyncFunction(t,e){const i=this._uniformGroupSyncHash[t._signature]||(this._uniformGroupSyncHash[t._signature]={}),r=this._getSignature(t,e._uniformData,"u");return this._cache[r]||(this._cache[r]=this._generateUniformsSync(t,e._uniformData)),i[e._key]=this._cache[r],i[e._key]}_generateUniformsSync(t,e){return x_(t,e)}_getSignature(t,e,i){const r=t.uniforms,n=[`${i}-`];for(const o in r)n.push(o),e[o]&&n.push(e[o].type);return n.join("-")}destroy(){this._renderer=null,this._cache=null}}oc.extension={type:[w.WebGLSystem],name:"uniformGroup"};function b_(s){const t={};if(t.normal=[s.ONE,s.ONE_MINUS_SRC_ALPHA],t.add=[s.ONE,s.ONE],t.multiply=[s.DST_COLOR,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA],t.screen=[s.ONE,s.ONE_MINUS_SRC_COLOR,s.ONE,s.ONE_MINUS_SRC_ALPHA],t.none=[0,0],t["normal-npm"]=[s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA],t["add-npm"]=[s.SRC_ALPHA,s.ONE,s.ONE,s.ONE],t["screen-npm"]=[s.SRC_ALPHA,s.ONE_MINUS_SRC_COLOR,s.ONE,s.ONE_MINUS_SRC_ALPHA],t.erase=[s.ZERO,s.ONE_MINUS_SRC_ALPHA],!(s instanceof rt.get().getWebGLRenderingContext()))t.min=[s.ONE,s.ONE,s.ONE,s.ONE,s.MIN,s.MIN],t.max=[s.ONE,s.ONE,s.ONE,s.ONE,s.MAX,s.MAX];else{const i=s.getExtension("EXT_blend_minmax");i&&(t.min=[s.ONE,s.ONE,s.ONE,s.ONE,i.MIN_EXT,i.MIN_EXT],t.max=[s.ONE,s.ONE,s.ONE,s.ONE,i.MAX_EXT,i.MAX_EXT])}return t}const v_=0,E_=1,T_=2,S_=3,C_=4,w_=5,ac=class no{constructor(t){this._invertFrontFace=!1,this.gl=null,this.stateId=0,this.polygonOffset=0,this.blendMode="none",this._blendEq=!1,this.map=[],this.map[v_]=this.setBlend,this.map[E_]=this.setOffset,this.map[T_]=this.setCullFace,this.map[S_]=this.setDepthTest,this.map[C_]=this.setFrontFace,this.map[w_]=this.setDepthMask,this.checks=[],this.defaultState=ve.for2d(),t.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(t){this._invertFrontFace=!t.isRoot,this._cullFace?this.setFrontFace(this._frontFace):this._frontFaceDirty=!0}contextChange(t){this.gl=t,this.blendModesMap=b_(t),this.resetState()}set(t){if(t||(t=this.defaultState),this.stateId!==t.data){let e=this.stateId^t.data,i=0;for(;e;)e&1&&this.map[i].call(this,!!(t.data&1<<i)),e>>=1,i++;this.stateId=t.data}for(let e=0;e<this.checks.length;e++)this.checks[e](this,t)}forceState(t){t||(t=this.defaultState);for(let e=0;e<this.map.length;e++)this.map[e].call(this,!!(t.data&1<<e));for(let e=0;e<this.checks.length;e++)this.checks[e](this,t);this.stateId=t.data}setBlend(t){this._updateCheck(no._checkBlendMode,t),this.gl[t?"enable":"disable"](this.gl.BLEND)}setOffset(t){this._updateCheck(no._checkPolygonOffset,t),this.gl[t?"enable":"disable"](this.gl.POLYGON_OFFSET_FILL)}setDepthTest(t){this.gl[t?"enable":"disable"](this.gl.DEPTH_TEST)}setDepthMask(t){this.gl.depthMask(t)}setCullFace(t){this._cullFace=t,this.gl[t?"enable":"disable"](this.gl.CULL_FACE),this._cullFace&&this._frontFaceDirty&&this.setFrontFace(this._frontFace)}setFrontFace(t){this._frontFace=t,this._frontFaceDirty=!1;const e=this._invertFrontFace?!t:t;this._glFrontFace!==e&&(this._glFrontFace=e,this.gl.frontFace(this.gl[e?"CW":"CCW"]))}setBlendMode(t){if(this.blendModesMap[t]||(t="normal"),t===this.blendMode)return;this.blendMode=t;const e=this.blendModesMap[t],i=this.gl;e.length===2?i.blendFunc(e[0],e[1]):i.blendFuncSeparate(e[0],e[1],e[2],e[3]),e.length===6?(this._blendEq=!0,i.blendEquationSeparate(e[4],e[5])):this._blendEq&&(this._blendEq=!1,i.blendEquationSeparate(i.FUNC_ADD,i.FUNC_ADD))}setPolygonOffset(t,e){this.gl.polygonOffset(t,e)}resetState(){this._glFrontFace=!1,this._frontFace=!1,this._cullFace=!1,this._frontFaceDirty=!1,this._invertFrontFace=!1,this.gl.frontFace(this.gl.CCW),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.forceState(this.defaultState),this._blendEq=!0,this.blendMode="",this.setBlendMode("normal")}_updateCheck(t,e){const i=this.checks.indexOf(t);e&&i===-1?this.checks.push(t):!e&&i!==-1&&this.checks.splice(i,1)}static _checkBlendMode(t,e){t.setBlendMode(e.blendMode)}static _checkPolygonOffset(t,e){t.setPolygonOffset(1,e.polygonOffset)}destroy(){this.gl=null,this.checks.length=0}};ac.extension={type:[w.WebGLSystem],name:"state"};let A_=ac;class R_{constructor(t){this.target=Nn.TEXTURE_2D,this._layerInitMask=0,this.texture=t,this.width=-1,this.height=-1,this.type=nt.UNSIGNED_BYTE,this.internalFormat=Fn.RGBA,this.format=Fn.RGBA,this.samplerType=0}destroy(){}}const P_={id:"buffer",upload(s,t,e,i,r,n=!1){const o=r||t.target;!n&&t.width===s.width&&t.height===s.height?e.texSubImage2D(o,0,0,0,s.width,s.height,t.format,t.type,s.resource):e.texImage2D(o,0,t.internalFormat,s.width,s.height,0,t.format,t.type,s.resource),t.width=s.width,t.height=s.height}},I_={"bc1-rgba-unorm":!0,"bc1-rgba-unorm-srgb":!0,"bc2-rgba-unorm":!0,"bc2-rgba-unorm-srgb":!0,"bc3-rgba-unorm":!0,"bc3-rgba-unorm-srgb":!0,"bc4-r-unorm":!0,"bc4-r-snorm":!0,"bc5-rg-unorm":!0,"bc5-rg-snorm":!0,"bc6h-rgb-ufloat":!0,"bc6h-rgb-float":!0,"bc7-rgba-unorm":!0,"bc7-rgba-unorm-srgb":!0,"etc2-rgb8unorm":!0,"etc2-rgb8unorm-srgb":!0,"etc2-rgb8a1unorm":!0,"etc2-rgb8a1unorm-srgb":!0,"etc2-rgba8unorm":!0,"etc2-rgba8unorm-srgb":!0,"eac-r11unorm":!0,"eac-r11snorm":!0,"eac-rg11unorm":!0,"eac-rg11snorm":!0,"astc-4x4-unorm":!0,"astc-4x4-unorm-srgb":!0,"astc-5x4-unorm":!0,"astc-5x4-unorm-srgb":!0,"astc-5x5-unorm":!0,"astc-5x5-unorm-srgb":!0,"astc-6x5-unorm":!0,"astc-6x5-unorm-srgb":!0,"astc-6x6-unorm":!0,"astc-6x6-unorm-srgb":!0,"astc-8x5-unorm":!0,"astc-8x5-unorm-srgb":!0,"astc-8x6-unorm":!0,"astc-8x6-unorm-srgb":!0,"astc-8x8-unorm":!0,"astc-8x8-unorm-srgb":!0,"astc-10x5-unorm":!0,"astc-10x5-unorm-srgb":!0,"astc-10x6-unorm":!0,"astc-10x6-unorm-srgb":!0,"astc-10x8-unorm":!0,"astc-10x8-unorm-srgb":!0,"astc-10x10-unorm":!0,"astc-10x10-unorm-srgb":!0,"astc-12x10-unorm":!0,"astc-12x10-unorm-srgb":!0,"astc-12x12-unorm":!0,"astc-12x12-unorm-srgb":!0},M_={id:"compressed",upload(s,t,e,i,r,n){const o=r??t.target;e.pixelStorei(e.UNPACK_ALIGNMENT,4);let a=s.pixelWidth,l=s.pixelHeight;const h=!!I_[s.format];for(let c=0;c<s.resource.length;c++){const u=s.resource[c];h?e.compressedTexImage2D(o,c,t.internalFormat,a,l,0,u):e.texImage2D(o,c,t.internalFormat,a,l,0,t.format,t.type,u),a=Math.max(a>>1,1),l=Math.max(l>>1,1)}}},lc=["right","left","top","bottom","front","back"];function k_(s){return{id:"cube",upload(t,e,i,r){const n=t.faces;for(let o=0;o<lc.length;o++){const a=lc[o],l=n[a];(s[l.uploadMethodId]||s.image).upload(l,e,i,r,Nn.TEXTURE_CUBE_MAP_POSITIVE_X+o,(e._layerInitMask&1<<o)===0),e._layerInitMask|=1<<o}e.width=t.pixelWidth,e.height=t.pixelHeight}}}const hc={id:"image",upload(s,t,e,i,r,n=!1){const o=r||t.target,a=s.pixelWidth,l=s.pixelHeight,h=s.resourceWidth,c=s.resourceHeight,u=i===2,m=n||t.width!==a||t.height!==l,f=h>=a&&c>=l,g=s.resource;(u?B_:O_)(e,o,t,a,l,h,c,g,m,f),t.width=a,t.height=l}};function B_(s,t,e,i,r,n,o,a,l,h){if(!h){l&&s.texImage2D(t,0,e.internalFormat,i,r,0,e.format,e.type,null),s.texSubImage2D(t,0,0,0,n,o,e.format,e.type,a);return}if(!l){s.texSubImage2D(t,0,0,0,e.format,e.type,a);return}s.texImage2D(t,0,e.internalFormat,i,r,0,e.format,e.type,a)}function O_(s,t,e,i,r,n,o,a,l,h){if(!h){l&&s.texImage2D(t,0,e.internalFormat,i,r,0,e.format,e.type,null),s.texSubImage2D(t,0,0,0,e.format,e.type,a);return}if(!l){s.texSubImage2D(t,0,0,0,e.format,e.type,a);return}s.texImage2D(t,0,e.internalFormat,e.format,e.type,a)}const D_=og(),G_={id:"video",upload(s,t,e,i,r,n=D_){if(!s.isValid){const o=r??t.target;e.texImage2D(o,0,t.internalFormat,1,1,0,t.format,t.type,null);return}hc.upload(s,t,e,i,r,n)}},cc={linear:9729,nearest:9728},U_={linear:{linear:9987,nearest:9985},nearest:{linear:9986,nearest:9984}},zn={"clamp-to-edge":33071,repeat:10497,"mirror-repeat":33648},L_={never:512,less:513,equal:514,"less-equal":515,greater:516,"not-equal":517,"greater-equal":518,always:519};function uc(s,t,e,i,r,n,o,a){const l=n;if(!a||s.addressModeU!=="repeat"||s.addressModeV!=="repeat"||s.addressModeW!=="repeat"){const h=zn[o?"clamp-to-edge":s.addressModeU],c=zn[o?"clamp-to-edge":s.addressModeV],u=zn[o?"clamp-to-edge":s.addressModeW];t[r](l,t.TEXTURE_WRAP_S,h),t[r](l,t.TEXTURE_WRAP_T,c),t.TEXTURE_WRAP_R&&t[r](l,t.TEXTURE_WRAP_R,u)}if((!a||s.magFilter!=="linear")&&t[r](l,t.TEXTURE_MAG_FILTER,cc[s.magFilter]),e){if(!a||s.mipmapFilter!=="linear"){const h=U_[s.minFilter][s.mipmapFilter];t[r](l,t.TEXTURE_MIN_FILTER,h)}}else t[r](l,t.TEXTURE_MIN_FILTER,cc[s.minFilter]);if(i&&s.maxAnisotropy>1){const h=Math.min(s.maxAnisotropy,t.getParameter(i.MAX_TEXTURE_MAX_ANISOTROPY_EXT));t[r](l,i.TEXTURE_MAX_ANISOTROPY_EXT,h)}s.compare&&t[r](l,t.TEXTURE_COMPARE_FUNC,L_[s.compare])}function F_(s){return{r8unorm:s.RED,r8snorm:s.RED,r8uint:s.RED,r8sint:s.RED,r16uint:s.RED,r16sint:s.RED,r16float:s.RED,rg8unorm:s.RG,rg8snorm:s.RG,rg8uint:s.RG,rg8sint:s.RG,r32uint:s.RED,r32sint:s.RED,r32float:s.RED,rg16uint:s.RG,rg16sint:s.RG,rg16float:s.RG,rgba8unorm:s.RGBA,"rgba8unorm-srgb":s.RGBA,rgba8snorm:s.RGBA,rgba8uint:s.RGBA,rgba8sint:s.RGBA,bgra8unorm:s.RGBA,"bgra8unorm-srgb":s.RGBA,rgb9e5ufloat:s.RGB,rgb10a2unorm:s.RGBA,rg11b10ufloat:s.RGB,rg32uint:s.RG,rg32sint:s.RG,rg32float:s.RG,rgba16uint:s.RGBA,rgba16sint:s.RGBA,rgba16float:s.RGBA,rgba32uint:s.RGBA,rgba32sint:s.RGBA,rgba32float:s.RGBA,stencil8:s.STENCIL_INDEX8,depth16unorm:s.DEPTH_COMPONENT,depth24plus:s.DEPTH_COMPONENT,"depth24plus-stencil8":s.DEPTH_STENCIL,depth32float:s.DEPTH_COMPONENT,"depth32float-stencil8":s.DEPTH_STENCIL}}function N_(s,t){let e={},i=s.RGBA;return s instanceof rt.get().getWebGLRenderingContext()?t.srgb&&(e={"rgba8unorm-srgb":t.srgb.SRGB8_ALPHA8_EXT,"bgra8unorm-srgb":t.srgb.SRGB8_ALPHA8_EXT}):(e={"rgba8unorm-srgb":s.SRGB8_ALPHA8,"bgra8unorm-srgb":s.SRGB8_ALPHA8},i=s.RGBA8),{r8unorm:s.R8,r8snorm:s.R8_SNORM,r8uint:s.R8UI,r8sint:s.R8I,r16uint:s.R16UI,r16sint:s.R16I,r16float:s.R16F,rg8unorm:s.RG8,rg8snorm:s.RG8_SNORM,rg8uint:s.RG8UI,rg8sint:s.RG8I,r32uint:s.R32UI,r32sint:s.R32I,r32float:s.R32F,rg16uint:s.RG16UI,rg16sint:s.RG16I,rg16float:s.RG16F,rgba8unorm:s.RGBA,...e,rgba8snorm:s.RGBA8_SNORM,rgba8uint:s.RGBA8UI,rgba8sint:s.RGBA8I,bgra8unorm:i,rgb9e5ufloat:s.RGB9_E5,rgb10a2unorm:s.RGB10_A2,rg11b10ufloat:s.R11F_G11F_B10F,rg32uint:s.RG32UI,rg32sint:s.RG32I,rg32float:s.RG32F,rgba16uint:s.RGBA16UI,rgba16sint:s.RGBA16I,rgba16float:s.RGBA16F,rgba32uint:s.RGBA32UI,rgba32sint:s.RGBA32I,rgba32float:s.RGBA32F,stencil8:s.STENCIL_INDEX8,depth16unorm:s.DEPTH_COMPONENT16,depth24plus:s.DEPTH_COMPONENT24,"depth24plus-stencil8":s.DEPTH24_STENCIL8,depth32float:s.DEPTH_COMPONENT32F,"depth32float-stencil8":s.DEPTH32F_STENCIL8,...t.s3tc?{"bc1-rgba-unorm":t.s3tc.COMPRESSED_RGBA_S3TC_DXT1_EXT,"bc2-rgba-unorm":t.s3tc.COMPRESSED_RGBA_S3TC_DXT3_EXT,"bc3-rgba-unorm":t.s3tc.COMPRESSED_RGBA_S3TC_DXT5_EXT}:{},...t.s3tc_sRGB?{"bc1-rgba-unorm-srgb":t.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,"bc2-rgba-unorm-srgb":t.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT,"bc3-rgba-unorm-srgb":t.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}:{},...t.rgtc?{"bc4-r-unorm":t.rgtc.COMPRESSED_RED_RGTC1_EXT,"bc4-r-snorm":t.rgtc.COMPRESSED_SIGNED_RED_RGTC1_EXT,"bc5-rg-unorm":t.rgtc.COMPRESSED_RED_GREEN_RGTC2_EXT,"bc5-rg-snorm":t.rgtc.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}:{},...t.bptc?{"bc6h-rgb-float":t.bptc.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT,"bc6h-rgb-ufloat":t.bptc.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT,"bc7-rgba-unorm":t.bptc.COMPRESSED_RGBA_BPTC_UNORM_EXT,"bc7-rgba-unorm-srgb":t.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT}:{},...t.etc?{"etc2-rgb8unorm":t.etc.COMPRESSED_RGB8_ETC2,"etc2-rgb8unorm-srgb":t.etc.COMPRESSED_SRGB8_ETC2,"etc2-rgb8a1unorm":t.etc.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgb8a1unorm-srgb":t.etc.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgba8unorm":t.etc.COMPRESSED_RGBA8_ETC2_EAC,"etc2-rgba8unorm-srgb":t.etc.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC,"eac-r11unorm":t.etc.COMPRESSED_R11_EAC,"eac-rg11unorm":t.etc.COMPRESSED_SIGNED_RG11_EAC}:{},...t.astc?{"astc-4x4-unorm":t.astc.COMPRESSED_RGBA_ASTC_4x4_KHR,"astc-4x4-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,"astc-5x4-unorm":t.astc.COMPRESSED_RGBA_ASTC_5x4_KHR,"astc-5x4-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,"astc-5x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_5x5_KHR,"astc-5x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,"astc-6x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_6x5_KHR,"astc-6x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,"astc-6x6-unorm":t.astc.COMPRESSED_RGBA_ASTC_6x6_KHR,"astc-6x6-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,"astc-8x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_8x5_KHR,"astc-8x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,"astc-8x6-unorm":t.astc.COMPRESSED_RGBA_ASTC_8x6_KHR,"astc-8x6-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,"astc-8x8-unorm":t.astc.COMPRESSED_RGBA_ASTC_8x8_KHR,"astc-8x8-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,"astc-10x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x5_KHR,"astc-10x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,"astc-10x6-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x6_KHR,"astc-10x6-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,"astc-10x8-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x8_KHR,"astc-10x8-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,"astc-10x10-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x10_KHR,"astc-10x10-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,"astc-12x10-unorm":t.astc.COMPRESSED_RGBA_ASTC_12x10_KHR,"astc-12x10-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,"astc-12x12-unorm":t.astc.COMPRESSED_RGBA_ASTC_12x12_KHR,"astc-12x12-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR}:{}}}function H_(s){return{r8unorm:s.UNSIGNED_BYTE,r8snorm:s.BYTE,r8uint:s.UNSIGNED_BYTE,r8sint:s.BYTE,r16uint:s.UNSIGNED_SHORT,r16sint:s.SHORT,r16float:s.HALF_FLOAT,rg8unorm:s.UNSIGNED_BYTE,rg8snorm:s.BYTE,rg8uint:s.UNSIGNED_BYTE,rg8sint:s.BYTE,r32uint:s.UNSIGNED_INT,r32sint:s.INT,r32float:s.FLOAT,rg16uint:s.UNSIGNED_SHORT,rg16sint:s.SHORT,rg16float:s.HALF_FLOAT,rgba8unorm:s.UNSIGNED_BYTE,"rgba8unorm-srgb":s.UNSIGNED_BYTE,rgba8snorm:s.BYTE,rgba8uint:s.UNSIGNED_BYTE,rgba8sint:s.BYTE,bgra8unorm:s.UNSIGNED_BYTE,"bgra8unorm-srgb":s.UNSIGNED_BYTE,rgb9e5ufloat:s.UNSIGNED_INT_5_9_9_9_REV,rgb10a2unorm:s.UNSIGNED_INT_2_10_10_10_REV,rg11b10ufloat:s.UNSIGNED_INT_10F_11F_11F_REV,rg32uint:s.UNSIGNED_INT,rg32sint:s.INT,rg32float:s.FLOAT,rgba16uint:s.UNSIGNED_SHORT,rgba16sint:s.SHORT,rgba16float:s.HALF_FLOAT,rgba32uint:s.UNSIGNED_INT,rgba32sint:s.INT,rgba32float:s.FLOAT,stencil8:s.UNSIGNED_BYTE,depth16unorm:s.UNSIGNED_SHORT,depth24plus:s.UNSIGNED_INT,"depth24plus-stencil8":s.UNSIGNED_INT_24_8,depth32float:s.FLOAT,"depth32float-stencil8":s.FLOAT_32_UNSIGNED_INT_24_8_REV}}function W_(s){return{"2d":s.TEXTURE_2D,cube:s.TEXTURE_CUBE_MAP,"1d":null,"3d":(s==null?void 0:s.TEXTURE_3D)||null,"2d-array":(s==null?void 0:s.TEXTURE_2D_ARRAY)||null,"cube-array":(s==null?void 0:s.TEXTURE_CUBE_MAP_ARRAY)||null}}const V_=4;class dc{constructor(t){this._glSamplers=Object.create(null),this._boundTextures=[],this._activeTextureLocation=-1,this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1,this._useSeparateSamplers=!1,this._renderer=t,this._managedTextures=new ue({renderer:t,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"glTexture"});const e={image:hc,buffer:P_,video:G_,compressed:M_};this._uploads={...e,cube:k_(e)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(t){this._gl=t,this._mapFormatToInternalFormat||(this._mapFormatToInternalFormat=N_(t,this._renderer.context.extensions),this._mapFormatToType=H_(t),this._mapFormatToFormat=F_(t),this._mapViewDimensionToGlTarget=W_(t)),this._managedTextures.removeAll(!0),this._glSamplers=Object.create(null),this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1;for(let e=0;e<16;e++)this.bind(z.EMPTY,e)}initSource(t){this.bind(t)}bind(t,e=0){const i=t.source;t?(this.bindSource(i,e),this._useSeparateSamplers&&this._bindSampler(i.style,e)):(this.bindSource(null,e),this._useSeparateSamplers&&this._bindSampler(null,e))}bindSource(t,e=0){const i=this._gl;if(t._gcLastUsed=this._renderer.gc.now,this._boundTextures[e]!==t){this._boundTextures[e]=t,this._activateLocation(e),t||(t=z.EMPTY.source);const r=this.getGlSource(t);i.bindTexture(r.target,r.texture)}}_bindSampler(t,e=0){const i=this._gl;if(!t){this._boundSamplers[e]=null,i.bindSampler(e,null);return}const r=this._getGlSampler(t);this._boundSamplers[e]!==r&&(this._boundSamplers[e]=r,i.bindSampler(e,r))}unbind(t){const e=t.source,i=this._boundTextures,r=this._gl;for(let n=0;n<i.length;n++)if(i[n]===e){this._activateLocation(n);const o=this.getGlSource(e);r.bindTexture(o.target,null),i[n]=null}}_activateLocation(t){this._activeTextureLocation!==t&&(this._activeTextureLocation=t,this._gl.activeTexture(this._gl.TEXTURE0+t))}_initSource(t){const e=this._gl,i=new R_(e.createTexture());if(i.type=this._mapFormatToType[t.format],i.internalFormat=this._mapFormatToInternalFormat[t.format],i.format=this._mapFormatToFormat[t.format],i.target=this._mapViewDimensionToGlTarget[t.viewDimension],i.target===null)throw new Error(`Unsupported view dimension: ${t.viewDimension} with this webgl version: ${this._renderer.context.webGLVersion}`);if(t.uploadMethodId==="cube"&&(i.target=e.TEXTURE_CUBE_MAP),t.autoGenerateMipmaps&&(this._renderer.context.supports.nonPowOf2mipmaps||t.isPowerOfTwo)){const n=Math.max(t.width,t.height);t.mipLevelCount=Math.floor(Math.log2(n))+1}return t._gpuData[this._renderer.uid]=i,this._managedTextures.add(t)&&(t.on("update",this.onSourceUpdate,this),t.on("resize",this.onSourceUpdate,this),t.on("styleChange",this.onStyleChange,this),t.on("updateMipmaps",this.onUpdateMipmaps,this)),this.onSourceUpdate(t),this.updateStyle(t,!1),i}onStyleChange(t){this.updateStyle(t,!1)}updateStyle(t,e){const i=this._gl,r=this.getGlSource(t);i.bindTexture(r.target,r.texture),this._boundTextures[this._activeTextureLocation]=t,uc(t.style,i,t.mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"texParameteri",r.target,!this._renderer.context.supports.nonPowOf2wrapping&&!t.isPowerOfTwo,e)}onSourceUnload(t,e=!1){const i=t._gpuData[this._renderer.uid];i&&(e||(this.unbind(t),this._gl.deleteTexture(i.texture)),t.off("update",this.onSourceUpdate,this),t.off("resize",this.onSourceUpdate,this),t.off("styleChange",this.onStyleChange,this),t.off("updateMipmaps",this.onUpdateMipmaps,this))}onSourceUpdate(t){const e=this._gl,i=this.getGlSource(t);e.bindTexture(i.target,i.texture),this._boundTextures[this._activeTextureLocation]=t;const r=t.alphaMode==="premultiply-alpha-on-upload";if(this._premultiplyAlpha!==r&&(this._premultiplyAlpha=r,e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,r)),this._uploads[t.uploadMethodId])this._uploads[t.uploadMethodId].upload(t,i,e,this._renderer.context.webGLVersion);else if(i.target===e.TEXTURE_2D)this._initEmptyTexture2D(i,t);else if(i.target===e.TEXTURE_2D_ARRAY)this._initEmptyTexture2DArray(i,t);else if(i.target===e.TEXTURE_CUBE_MAP)this._initEmptyTextureCube(i,t);else throw new Error("[GlTextureSystem] Unsupported texture target for empty allocation.");this._applyMipRange(i,t),t.autoGenerateMipmaps&&t.mipLevelCount>1&&this.onUpdateMipmaps(t,!1)}onUpdateMipmaps(t,e=!0){e&&this.bindSource(t,0);const i=this.getGlSource(t);this._gl.generateMipmap(i.target)}_initEmptyTexture2D(t,e){const i=this._gl;i.texImage2D(i.TEXTURE_2D,0,t.internalFormat,e.pixelWidth,e.pixelHeight,0,t.format,t.type,null);let r=Math.max(e.pixelWidth>>1,1),n=Math.max(e.pixelHeight>>1,1);for(let o=1;o<e.mipLevelCount;o++)i.texImage2D(i.TEXTURE_2D,o,t.internalFormat,r,n,0,t.format,t.type,null),r=Math.max(r>>1,1),n=Math.max(n>>1,1)}_initEmptyTexture2DArray(t,e){if(this._renderer.context.webGLVersion!==2)throw new Error("[GlTextureSystem] TEXTURE_2D_ARRAY requires WebGL2.");const i=this._gl,r=Math.max(e.arrayLayerCount|0,1);i.texImage3D(i.TEXTURE_2D_ARRAY,0,t.internalFormat,e.pixelWidth,e.pixelHeight,r,0,t.format,t.type,null);let n=Math.max(e.pixelWidth>>1,1),o=Math.max(e.pixelHeight>>1,1);for(let a=1;a<e.mipLevelCount;a++)i.texImage3D(i.TEXTURE_2D_ARRAY,a,t.internalFormat,n,o,r,0,t.format,t.type,null),n=Math.max(n>>1,1),o=Math.max(o>>1,1)}_initEmptyTextureCube(t,e){const i=this._gl,r=6;for(let a=0;a<r;a++)i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+a,0,t.internalFormat,e.pixelWidth,e.pixelHeight,0,t.format,t.type,null);let n=Math.max(e.pixelWidth>>1,1),o=Math.max(e.pixelHeight>>1,1);for(let a=1;a<e.mipLevelCount;a++){for(let l=0;l<r;l++)i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+l,a,t.internalFormat,n,o,0,t.format,t.type,null);n=Math.max(n>>1,1),o=Math.max(o>>1,1)}}_applyMipRange(t,e){if(this._renderer.context.webGLVersion!==2)return;const i=this._gl,r=Math.max((e.mipLevelCount|0)-1,0);i.texParameteri(t.target,i.TEXTURE_BASE_LEVEL,0),i.texParameteri(t.target,i.TEXTURE_MAX_LEVEL,r)}_initSampler(t){const e=this._gl,i=this._gl.createSampler();return this._glSamplers[t._resourceId]=i,uc(t,e,this._boundTextures[this._activeTextureLocation].mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"samplerParameteri",i,!1,!0),this._glSamplers[t._resourceId]}_getGlSampler(t){return this._glSamplers[t._resourceId]||this._initSampler(t)}getGlSource(t){return t._gcLastUsed=this._renderer.gc.now,t._gpuData[this._renderer.uid]||this._initSource(t)}generateCanvas(t){const{pixels:e,width:i,height:r}=this.getPixels(t),n=rt.get().createCanvas();n.width=i,n.height=r;const o=n.getContext("2d");if(o){const a=o.createImageData(i,r);a.data.set(e),o.putImageData(a,0,0)}return n}getPixels(t){const e=t.source.resolution,i=t.frame,r=Math.max(Math.round(i.width*e),1),n=Math.max(Math.round(i.height*e),1),o=new Uint8Array(V_*r*n),a=this._renderer,l=a.renderTarget.getRenderTarget(t),h=a.renderTarget.getGpuRenderTarget(l),c=a.gl;return c.bindFramebuffer(c.FRAMEBUFFER,h.resolveTargetFramebuffer),c.readPixels(Math.round(i.x*e),Math.round(i.y*e),r,n,c.RGBA,c.UNSIGNED_BYTE,o),{pixels:new Uint8ClampedArray(o.buffer),width:r,height:n}}destroy(){this._managedTextures.destroy(),this._glSamplers=null,this._boundTextures=null,this._boundSamplers=null,this._mapFormatToInternalFormat=null,this._mapFormatToType=null,this._mapFormatToFormat=null,this._uploads=null,this._renderer=null}resetState(){this._activeTextureLocation=-1,this._boundTextures.fill(z.EMPTY.source),this._boundSamplers=Object.create(null);const t=this._gl;this._premultiplyAlpha=!1,t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this._premultiplyAlpha)}}dc.extension={type:[w.WebGLSystem],name:"texture"};class fc{contextChange(t){const e=new he({uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uTransformMatrix:{value:new W,type:"mat3x3<f32>"},uRound:{value:0,type:"f32"}}),i=t.limits.maxBatchableTextures,r=Yr({name:"graphics",bits:[nl,al(i),Kl,Jr]});this.shader=new be({glProgram:r,resources:{localUniforms:e,batchSamplers:hl(i)}})}execute(t,e){const i=e.context,r=i.customShader||this.shader,n=t.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(i);r.groups[0]=n.globalUniforms.bindGroup,n.state.set(t.state),n.shader.bind(r),n.geometry.bind(a.geometry,r.glProgram);const h=l.instructions;for(let c=0;c<l.instructionSize;c++){const u=h[c];if(u.size){for(let m=0;m<u.textures.count;m++)n.texture.bind(u.textures.textures[m],m);n.geometry.draw(u.topology,u.size,u.start)}}}destroy(){this.shader.destroy(!0),this.shader=null}}fc.extension={type:[w.WebGLPipesAdaptor],name:"graphics"};class pc{init(){const t=Yr({name:"mesh",bits:[Kl,hg,Jr]});this._shader=new be({glProgram:t,resources:{uTexture:z.EMPTY.source,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new W}}}})}execute(t,e){const i=t.renderer;let r=e._shader;if(r){if(!r.glProgram){tt("Mesh shader has no glProgram",e.shader);return}}else{r=this._shader;const n=e.texture,o=n.source;r.resources.uTexture=o,r.resources.uSampler=o.style,r.resources.textureUniforms.uniforms.uTextureMatrix=n.textureMatrix.mapCoord}r.groups[100]=i.globalUniforms.bindGroup,r.groups[101]=t.localUniformsBindGroup,i.encoder.draw({geometry:e._geometry,shader:r,state:e.state})}destroy(){this._shader.destroy(!0),this._shader=null}}pc.extension={type:[w.WebGLPipesAdaptor],name:"mesh"};const z_=[...Gn,Jh,e_,qg,jh,Nh,dc,Qh,Vh,oc,nc,$h,A_,Xh,zh],$_=[...Oh],j_=[fh,pc,fc],mc=[],gc=[],_c=[];J.handleByNamedList(w.WebGLSystem,mc),J.handleByNamedList(w.WebGLPipes,gc),J.handleByNamedList(w.WebGLPipesAdaptor,_c),J.add(...z_,...$_,...j_);class X_ extends Xi{constructor(){const t={name:"webgl",type:ce.WEBGL,systems:mc,renderPipes:gc,renderPipeAdaptors:_c};super(t)}}const Y_=Object.freeze(Object.defineProperty({__proto__:null,WebGLRenderer:X_},Symbol.toStringTag,{value:"Module"}));class yc{constructor(t){this._hash=Object.create(null),this._renderer=t}contextChange(t){this._gpu=t}getBindGroup(t,e,i){return t._updateKey(),this._hash[t._key]||this._createBindGroup(t,e,i)}_createBindGroup(t,e,i){const r=this._gpu.device,n=e.layout[i],o=[],a=this._renderer;for(const c in n){const u=t.resources[c]??t.resources[n[c]];let m;if(u._resourceType==="uniformGroup"){const f=u;a.ubo.updateUniformGroup(f);const g=f.buffer;m={buffer:a.buffer.getGPUBuffer(g),offset:0,size:g.descriptor.size}}else if(u._resourceType==="buffer"){const f=u;m={buffer:a.buffer.getGPUBuffer(f),offset:0,size:f.descriptor.size}}else if(u._resourceType==="bufferResource"){const f=u;m={buffer:a.buffer.getGPUBuffer(f.buffer),offset:f.offset,size:f.size}}else if(u._resourceType==="textureSampler"){const f=u;m=a.texture.getGpuSampler(f)}else if(u._resourceType==="textureSource"){const f=u;m=a.texture.getTextureView(f)}o.push({binding:n[c],resource:m})}const l=a.shader.getProgramData(e).bindGroups[i],h=r.createBindGroup({layout:l,entries:o});return this._hash[t._key]=h,h}destroy(){this._hash=null,this._renderer=null}}yc.extension={type:[w.WebGPUSystem],name:"bindGroup"};class q_{constructor(t){this.gpuBuffer=t}destroy(){this.gpuBuffer.destroy(),this.gpuBuffer=null}}class xc{constructor(t){this._renderer=t,this._managedBuffers=new ue({renderer:t,type:"resource",onUnload:this.onBufferUnload.bind(this),name:"gpuBuffer"})}contextChange(t){this._gpu=t}getGPUBuffer(t){var e;return t._gcLastUsed=this._renderer.gc.now,((e=t._gpuData[this._renderer.uid])==null?void 0:e.gpuBuffer)||this.createGPUBuffer(t)}updateBuffer(t){const e=this.getGPUBuffer(t),i=t.data;return t._updateID&&i&&(t._updateID=0,this._gpu.device.queue.writeBuffer(e,0,i.buffer,0,(t._updateSize||i.byteLength)+3&-4)),e}destroyAll(){this._managedBuffers.removeAll()}onBufferUnload(t){t.off("update",this.updateBuffer,this),t.off("change",this.onBufferChange,this)}createGPUBuffer(t){const e=this._gpu.device.createBuffer(t.descriptor);return t._updateID=0,t._resourceId=dt("resource"),t.data&&(zr(t.data.buffer,e.getMappedRange(),t.data.byteOffset,t.data.byteLength),e.unmap()),t._gpuData[this._renderer.uid]=new q_(e),this._managedBuffers.add(t)&&(t.on("update",this.updateBuffer,this),t.on("change",this.onBufferChange,this)),e}onBufferChange(t){this._managedBuffers.remove(t),t._updateID=0,this.createGPUBuffer(t)}destroy(){this._managedBuffers.destroy(),this._renderer=null,this._gpu=null}}xc.extension={type:[w.WebGPUSystem],name:"buffer"};class K_{constructor({minUniformOffsetAlignment:t}){this._minUniformOffsetAlignment=256,this.byteIndex=0,this._minUniformOffsetAlignment=t,this.data=new Float32Array(65535)}clear(){this.byteIndex=0}addEmptyGroup(t){if(t>this._minUniformOffsetAlignment/4)throw new Error(`UniformBufferBatch: array is too large: ${t*4}`);const e=this.byteIndex;let i=e+t*4;if(i=Math.ceil(i/this._minUniformOffsetAlignment)*this._minUniformOffsetAlignment,i>this.data.length*4)throw new Error("UniformBufferBatch: ubo batch got too big");return this.byteIndex=i,e}addGroup(t){const e=this.addEmptyGroup(t.length);for(let i=0;i<t.length;i++)this.data[e/4+i]=t[i];return e}destroy(){this.data=null}}class bc{constructor(t){this._colorMaskCache=15,this._renderer=t}setMask(t){this._colorMaskCache!==t&&(this._colorMaskCache=t,this._renderer.pipeline.setColorMask(t))}destroy(){this._renderer=null,this._colorMaskCache=null}}bc.extension={type:[w.WebGPUSystem],name:"colorMask"};class $n{constructor(t){this._renderer=t}async init(t){return this._initPromise?this._initPromise:(this._initPromise=(t.gpu?Promise.resolve(t.gpu):this._createDeviceAndAdaptor(t)).then(e=>{this.gpu=e,this._renderer.runners.contextChange.emit(this.gpu)}),this._initPromise)}contextChange(t){this._renderer.gpu=t}async _createDeviceAndAdaptor(t){const e=await rt.get().getNavigator().gpu.requestAdapter({powerPreference:t.powerPreference,forceFallbackAdapter:t.forceFallbackAdapter}),i=["texture-compression-bc","texture-compression-astc","texture-compression-etc2"].filter(n=>e.features.has(n)),r=await e.requestDevice({requiredFeatures:i});return{adapter:e,device:r}}destroy(){this.gpu=null,this._renderer=null}}$n.extension={type:[w.WebGPUSystem],name:"device"},$n.defaultOptions={powerPreference:void 0,forceFallbackAdapter:!1};class vc{constructor(t){this._boundBindGroup=Object.create(null),this._boundVertexBuffer=Object.create(null),this._renderer=t}renderStart(){this.commandFinished=new Promise(t=>{this._resolveCommandFinished=t}),this.commandEncoder=this._renderer.gpu.device.createCommandEncoder()}beginRenderPass(t){this.endRenderPass(),this._clearCache(),this.renderPassEncoder=this.commandEncoder.beginRenderPass(t.descriptor)}endRenderPass(){this.renderPassEncoder&&this.renderPassEncoder.end(),this.renderPassEncoder=null}setViewport(t){this.renderPassEncoder.setViewport(t.x,t.y,t.width,t.height,0,1)}setPipelineFromGeometryProgramAndState(t,e,i,r){const n=this._renderer.pipeline.getPipeline(t,e,i,r);this.setPipeline(n)}setPipeline(t){this._boundPipeline!==t&&(this._boundPipeline=t,this.renderPassEncoder.setPipeline(t))}_setVertexBuffer(t,e){this._boundVertexBuffer[t]!==e&&(this._boundVertexBuffer[t]=e,this.renderPassEncoder.setVertexBuffer(t,this._renderer.buffer.updateBuffer(e)))}_setIndexBuffer(t){if(this._boundIndexBuffer===t)return;this._boundIndexBuffer=t;const e=t.data.BYTES_PER_ELEMENT===2?"uint16":"uint32";this.renderPassEncoder.setIndexBuffer(this._renderer.buffer.updateBuffer(t),e)}resetBindGroup(t){this._boundBindGroup[t]=null}setBindGroup(t,e,i){if(this._boundBindGroup[t]===e)return;this._boundBindGroup[t]=e,e._touch(this._renderer.gc.now,this._renderer.tick);const r=this._renderer.bindGroup.getBindGroup(e,i,t);this.renderPassEncoder.setBindGroup(t,r)}setGeometry(t,e){const i=this._renderer.pipeline.getBufferNamesToBind(t,e);for(const r in i)this._setVertexBuffer(parseInt(r,10),t.attributes[i[r]].buffer);t.indexBuffer&&this._setIndexBuffer(t.indexBuffer)}_setShaderBindGroups(t,e){for(const i in t.groups){const r=t.groups[i];e||this._syncBindGroup(r),this.setBindGroup(i,r,t.gpuProgram)}}_syncBindGroup(t){for(const e in t.resources){const i=t.resources[e];i.isUniformGroup&&this._renderer.ubo.updateUniformGroup(i)}}draw(t){const{geometry:e,shader:i,state:r,topology:n,size:o,start:a,instanceCount:l,skipSync:h}=t;this.setPipelineFromGeometryProgramAndState(e,i.gpuProgram,r,n),this.setGeometry(e,i.gpuProgram),this._setShaderBindGroups(i,h),e.indexBuffer?this.renderPassEncoder.drawIndexed(o||e.indexBuffer.data.length,l??e.instanceCount,a||0):this.renderPassEncoder.draw(o||e.getSize(),l??e.instanceCount,a||0)}finishRenderPass(){this.renderPassEncoder&&(this.renderPassEncoder.end(),this.renderPassEncoder=null)}postrender(){this.finishRenderPass(),this._gpu.device.queue.submit([this.commandEncoder.finish()]),this._resolveCommandFinished(),this.commandEncoder=null}restoreRenderPass(){const t=this._renderer.renderTarget.adaptor.getDescriptor(this._renderer.renderTarget.renderTarget,!1,[0,0,0,1],this._renderer.renderTarget.mipLevel,this._renderer.renderTarget.layer);this.renderPassEncoder=this.commandEncoder.beginRenderPass(t);const e=this._boundPipeline,i={...this._boundVertexBuffer},r=this._boundIndexBuffer,n={...this._boundBindGroup};this._clearCache();const o=this._renderer.renderTarget.viewport;this.renderPassEncoder.setViewport(o.x,o.y,o.width,o.height,0,1),this.setPipeline(e);for(const a in i)this._setVertexBuffer(a,i[a]);for(const a in n)this.setBindGroup(a,n[a],null);this._setIndexBuffer(r)}_clearCache(){for(let t=0;t<16;t++)this._boundBindGroup[t]=null,this._boundVertexBuffer[t]=null;this._boundIndexBuffer=null,this._boundPipeline=null}destroy(){this._renderer=null,this._gpu=null,this._boundBindGroup=null,this._boundVertexBuffer=null,this._boundIndexBuffer=null,this._boundPipeline=null}contextChange(t){this._gpu=t}}vc.extension={type:[w.WebGPUSystem],name:"encoder",priority:1};class Ec{constructor(t){this._renderer=t}contextChange(){this.maxTextures=this._renderer.device.gpu.device.limits.maxSampledTexturesPerShaderStage,this.maxBatchableTextures=this.maxTextures}destroy(){}}Ec.extension={type:[w.WebGPUSystem],name:"limits"};class Tc{constructor(t){this._renderTargetStencilState=Object.create(null),this._renderer=t,t.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(t){let e=this._renderTargetStencilState[t.uid];e||(e=this._renderTargetStencilState[t.uid]={stencilMode:wt.DISABLED,stencilReference:0}),this._activeRenderTarget=t,this.setStencilMode(e.stencilMode,e.stencilReference)}setStencilMode(t,e){const i=this._renderTargetStencilState[this._activeRenderTarget.uid];i.stencilMode=t,i.stencilReference=e;const r=this._renderer;r.pipeline.setStencilMode(t),r.encoder.renderPassEncoder.setStencilReference(e)}destroy(){this._renderer.renderTarget.onRenderTargetChange.remove(this),this._renderer=null,this._activeRenderTarget=null,this._renderTargetStencilState=null}}Tc.extension={type:[w.WebGPUSystem],name:"stencil"};const Vs={i32:{align:4,size:4},u32:{align:4,size:4},f32:{align:4,size:4},f16:{align:2,size:2},"vec2<i32>":{align:8,size:8},"vec2<u32>":{align:8,size:8},"vec2<f32>":{align:8,size:8},"vec2<f16>":{align:4,size:4},"vec3<i32>":{align:16,size:12},"vec3<u32>":{align:16,size:12},"vec3<f32>":{align:16,size:12},"vec3<f16>":{align:8,size:6},"vec4<i32>":{align:16,size:16},"vec4<u32>":{align:16,size:16},"vec4<f32>":{align:16,size:16},"vec4<f16>":{align:8,size:8},"mat2x2<f32>":{align:8,size:16},"mat2x2<f16>":{align:4,size:8},"mat3x2<f32>":{align:8,size:24},"mat3x2<f16>":{align:4,size:12},"mat4x2<f32>":{align:8,size:32},"mat4x2<f16>":{align:4,size:16},"mat2x3<f32>":{align:16,size:32},"mat2x3<f16>":{align:8,size:16},"mat3x3<f32>":{align:16,size:48},"mat3x3<f16>":{align:8,size:24},"mat4x3<f32>":{align:16,size:64},"mat4x3<f16>":{align:8,size:32},"mat2x4<f32>":{align:16,size:32},"mat2x4<f16>":{align:8,size:16},"mat3x4<f32>":{align:16,size:48},"mat3x4<f16>":{align:8,size:24},"mat4x4<f32>":{align:16,size:64},"mat4x4<f16>":{align:8,size:32}};function Z_(s){const t=s.map(i=>({data:i,offset:0,size:0}));let e=0;for(let i=0;i<t.length;i++){const r=t[i];let n=Vs[r.data.type].size;const o=Vs[r.data.type].align;if(!Vs[r.data.type])throw new Error(`[Pixi.js] WebGPU UniformBuffer: Unknown type ${r.data.type}`);r.data.size>1&&(n=Math.max(n,o)*r.data.size),e=Math.ceil(e/o)*o,r.size=n,r.offset=e,e+=n}return e=Math.ceil(e/16)*16,{uboElements:t,size:e}}function J_(s,t){const{size:e,align:i}=Vs[s.data.type],r=(i-e)/4,n=s.data.type.indexOf("i32")>=0?"dataInt32":"data";return`
|
|
855
|
+
v = uv.${s.data.name};
|
|
856
|
+
${t!==0?`offset += ${t};`:""}
|
|
857
|
+
|
|
858
|
+
arrayOffset = offset;
|
|
859
|
+
|
|
860
|
+
t = 0;
|
|
861
|
+
|
|
862
|
+
for(var i=0; i < ${s.data.size*(e/4)}; i++)
|
|
863
|
+
{
|
|
864
|
+
for(var j = 0; j < ${e/4}; j++)
|
|
865
|
+
{
|
|
866
|
+
${n}[arrayOffset++] = v[t++];
|
|
867
|
+
}
|
|
868
|
+
${r!==0?`arrayOffset += ${r};`:""}
|
|
869
|
+
}
|
|
870
|
+
`}function Q_(s){return Kh(s,"uboWgsl",J_,r_)}class Sc extends Yh{constructor(){super({createUboElements:Z_,generateUboSync:Q_})}}Sc.extension={type:[w.WebGPUSystem],name:"ubo"};const Ge=128;class Cc{constructor(t){this._bindGroupHash=Object.create(null),this._buffers=[],this._bindGroups=[],this._bufferResources=[],this._renderer=t,this._batchBuffer=new K_({minUniformOffsetAlignment:Ge});const e=256/Ge;for(let i=0;i<e;i++){let r=yt.UNIFORM|yt.COPY_DST;i===0&&(r|=yt.COPY_SRC),this._buffers.push(new ke({data:this._batchBuffer.data,usage:r}))}}renderEnd(){this._uploadBindGroups(),this._resetBindGroups()}_resetBindGroups(){this._bindGroupHash=Object.create(null),this._batchBuffer.clear()}getUniformBindGroup(t,e){if(!e&&this._bindGroupHash[t.uid])return this._bindGroupHash[t.uid];this._renderer.ubo.ensureUniformGroup(t);const i=t.buffer.data,r=this._batchBuffer.addEmptyGroup(i.length);return this._renderer.ubo.syncUniformGroup(t,this._batchBuffer.data,r/4),this._bindGroupHash[t.uid]=this._getBindGroup(r/Ge),this._bindGroupHash[t.uid]}getUboResource(t){this._renderer.ubo.updateUniformGroup(t);const e=t.buffer.data,i=this._batchBuffer.addGroup(e);return this._getBufferResource(i/Ge)}getArrayBindGroup(t){const e=this._batchBuffer.addGroup(t);return this._getBindGroup(e/Ge)}getArrayBufferResource(t){const i=this._batchBuffer.addGroup(t)/Ge;return this._getBufferResource(i)}_getBufferResource(t){if(!this._bufferResources[t]){const e=this._buffers[t%2];this._bufferResources[t]=new Wn({buffer:e,offset:(t/2|0)*256,size:Ge})}return this._bufferResources[t]}_getBindGroup(t){if(!this._bindGroups[t]){const e=new Me({0:this._getBufferResource(t)});this._bindGroups[t]=e}return this._bindGroups[t]}_uploadBindGroups(){const t=this._renderer.buffer,e=this._buffers[0];e.update(this._batchBuffer.byteIndex),t.updateBuffer(e);const i=this._renderer.gpu.device.createCommandEncoder();for(let r=1;r<this._buffers.length;r++){const n=this._buffers[r];i.copyBufferToBuffer(t.getGPUBuffer(e),Ge,t.getGPUBuffer(n),0,this._batchBuffer.byteIndex)}this._renderer.gpu.device.queue.submit([i.finish()])}destroy(){var t;for(let e=0;e<this._bindGroups.length;e++)(t=this._bindGroups[e])==null||t.destroy();this._bindGroups=null,this._bindGroupHash=null;for(let e=0;e<this._buffers.length;e++)this._buffers[e].destroy();this._buffers=null;for(let e=0;e<this._bufferResources.length;e++)this._bufferResources[e].destroy();this._bufferResources=null,this._batchBuffer.destroy(),this._renderer=null}}Cc.extension={type:[w.WebGPUPipes],name:"uniformBatch"};const ty={"point-list":0,"line-list":1,"line-strip":2,"triangle-list":3,"triangle-strip":4};function ey(s,t,e,i,r){return s<<24|t<<16|e<<10|i<<5|r}function iy(s,t,e,i,r){return e<<8|s<<5|i<<3|r<<1|t}class wc{constructor(t){this._moduleCache=Object.create(null),this._bufferLayoutsCache=Object.create(null),this._bindingNamesCache=Object.create(null),this._pipeCache=Object.create(null),this._pipeStateCaches=Object.create(null),this._colorMask=15,this._multisampleCount=1,this._colorTargetCount=1,this._renderer=t}contextChange(t){this._gpu=t,this.setStencilMode(wt.DISABLED),this._updatePipeHash()}setMultisampleCount(t){this._multisampleCount!==t&&(this._multisampleCount=t,this._updatePipeHash())}setRenderTarget(t){this._multisampleCount=t.msaaSamples,this._depthStencilAttachment=t.descriptor.depthStencilAttachment?1:0,this._colorTargetCount=t.colorTargetCount,this._updatePipeHash()}setColorMask(t){this._colorMask!==t&&(this._colorMask=t,this._updatePipeHash())}setStencilMode(t){this._stencilMode!==t&&(this._stencilMode=t,this._stencilState=De[t],this._updatePipeHash())}setPipeline(t,e,i,r){const n=this.getPipeline(t,e,i);r.setPipeline(n)}getPipeline(t,e,i,r){t._layoutKey||(Hh(t,e.attributeData),this._generateBufferKey(t)),r||(r=t.topology);const n=ey(t._layoutKey,e._layoutKey,i.data,i._blendModeId,ty[r]);return this._pipeCache[n]?this._pipeCache[n]:(this._pipeCache[n]=this._createPipeline(t,e,i,r),this._pipeCache[n])}_createPipeline(t,e,i,r){const n=this._gpu.device,o=this._createVertexBufferLayouts(t,e),a=this._renderer.state.getColorTargets(i,this._colorTargetCount),l=this._stencilMode===wt.RENDERING_MASK_ADD?0:this._colorMask;for(let m=0;m<a.length;m++)a[m].writeMask=l;const h=this._renderer.shader.getProgramData(e).pipeline,c={vertex:{module:this._getModule(e.vertex.source),entryPoint:e.vertex.entryPoint,buffers:o},fragment:{module:this._getModule(e.fragment.source),entryPoint:e.fragment.entryPoint,targets:a},primitive:{topology:r,cullMode:i.cullMode},layout:h,multisample:{count:this._multisampleCount},label:"PIXI Pipeline"};return this._depthStencilAttachment&&(c.depthStencil={...this._stencilState,format:"depth24plus-stencil8",depthWriteEnabled:i.depthTest,depthCompare:i.depthTest?"less":"always"}),n.createRenderPipeline(c)}_getModule(t){return this._moduleCache[t]||this._createModule(t)}_createModule(t){const e=this._gpu.device;return this._moduleCache[t]=e.createShaderModule({code:t}),this._moduleCache[t]}_generateBufferKey(t){const e=[];let i=0;const r=Object.keys(t.attributes).sort();for(let o=0;o<r.length;o++){const a=t.attributes[r[o]];e[i++]=a.offset,e[i++]=a.format,e[i++]=a.stride,e[i++]=a.instance}const n=e.join("|");return t._layoutKey=Li(n,"geometry"),t._layoutKey}_generateAttributeLocationsKey(t){const e=[];let i=0;const r=Object.keys(t.attributeData).sort();for(let o=0;o<r.length;o++){const a=t.attributeData[r[o]];e[i++]=a.location}const n=e.join("|");return t._attributeLocationsKey=Li(n,"programAttributes"),t._attributeLocationsKey}getBufferNamesToBind(t,e){const i=t._layoutKey<<16|e._attributeLocationsKey;if(this._bindingNamesCache[i])return this._bindingNamesCache[i];const r=this._createVertexBufferLayouts(t,e),n=Object.create(null),o=e.attributeData;for(let a=0;a<r.length;a++){const h=Object.values(r[a].attributes)[0].shaderLocation;for(const c in o)if(o[c].location===h){n[a]=c;break}}return this._bindingNamesCache[i]=n,n}_createVertexBufferLayouts(t,e){e._attributeLocationsKey||this._generateAttributeLocationsKey(e);const i=t._layoutKey<<16|e._attributeLocationsKey;if(this._bufferLayoutsCache[i])return this._bufferLayoutsCache[i];const r=[];return t.buffers.forEach(n=>{const o={arrayStride:0,stepMode:"vertex",attributes:[]},a=o.attributes;for(const l in e.attributeData){const h=t.attributes[l];(h.divisor??1)!==1&&tt(`Attribute ${l} has an invalid divisor value of '${h.divisor}'. WebGPU only supports a divisor value of 1`),h.buffer===n&&(o.arrayStride=h.stride,o.stepMode=h.instance?"instance":"vertex",a.push({shaderLocation:e.attributeData[l].location,offset:h.offset,format:h.format}))}a.length&&r.push(o)}),this._bufferLayoutsCache[i]=r,r}_updatePipeHash(){const t=iy(this._stencilMode,this._multisampleCount,this._colorMask,this._depthStencilAttachment,this._colorTargetCount);this._pipeStateCaches[t]||(this._pipeStateCaches[t]=Object.create(null)),this._pipeCache=this._pipeStateCaches[t]}destroy(){this._renderer=null,this._bufferLayoutsCache=null}}wc.extension={type:[w.WebGPUSystem],name:"pipeline"};class sy{constructor(){this.contexts=[],this.msaaTextures=[],this.msaaSamples=1}}class ry{init(t,e){this._renderer=t,this._renderTargetSystem=e}copyToTexture(t,e,i,r,n){const o=this._renderer,a=this._getGpuColorTexture(t),l=o.texture.getGpuSource(e.source);return o.encoder.commandEncoder.copyTextureToTexture({texture:a,origin:i},{texture:l,origin:n},r),e}startRenderPass(t,e=!0,i,r,n=0,o=0){var c,u;const l=this._renderTargetSystem.getGpuRenderTarget(t);if(o!==0&&((c=l.msaaTextures)!=null&&c.length))throw new Error("[RenderTargetSystem] Rendering to array layers is not supported with MSAA render targets.");if(n>0&&((u=l.msaaTextures)!=null&&u.length))throw new Error("[RenderTargetSystem] Rendering to mip levels is not supported with MSAA render targets.");const h=this.getDescriptor(t,e,i,n,o);l.descriptor=h,this._renderer.pipeline.setRenderTarget(l),this._renderer.encoder.beginRenderPass(l),this._renderer.encoder.setViewport(r)}finishRenderPass(){this._renderer.encoder.endRenderPass()}_getGpuColorTexture(t){const e=this._renderTargetSystem.getGpuRenderTarget(t);return e.contexts[0]?e.contexts[0].getCurrentTexture():this._renderer.texture.getGpuSource(t.colorTextures[0].source)}getDescriptor(t,e,i,r=0,n=0){typeof e=="boolean"&&(e=e?Yt.ALL:Yt.NONE);const o=this._renderTargetSystem,a=o.getGpuRenderTarget(t),l=t.colorTextures.map((u,m)=>{const f=a.contexts[m];let g,y;if(f){if(n!==0)throw new Error("[RenderTargetSystem] Rendering to array layers is not supported for canvas targets.");g=f.getCurrentTexture().createView()}else g=this._renderer.texture.getGpuSource(u).createView({dimension:"2d",baseMipLevel:r,mipLevelCount:1,baseArrayLayer:n,arrayLayerCount:1});a.msaaTextures[m]&&(y=g,g=this._renderer.texture.getTextureView(a.msaaTextures[m]));const x=e&Yt.COLOR?"clear":"load";return i??(i=o.defaultClearColor),{view:g,resolveTarget:y,clearValue:i,storeOp:"store",loadOp:x}});let h;if((t.stencil||t.depth)&&!t.depthStencilTexture&&(t.ensureDepthStencilTexture(),t.depthStencilTexture.source.sampleCount=a.msaa?4:1),t.depthStencilTexture){const u=e&Yt.STENCIL?"clear":"load",m=e&Yt.DEPTH?"clear":"load";h={view:this._renderer.texture.getGpuSource(t.depthStencilTexture.source).createView({dimension:"2d",baseMipLevel:r,mipLevelCount:1,baseArrayLayer:n,arrayLayerCount:1}),stencilStoreOp:"store",stencilLoadOp:u,depthClearValue:1,depthLoadOp:m,depthStoreOp:"store"}}return{colorAttachments:l,depthStencilAttachment:h}}clear(t,e=!0,i,r,n=0,o=0){if(!e)return;const{gpu:a,encoder:l}=this._renderer,h=a.device;if(l.commandEncoder===null){const u=h.createCommandEncoder(),m=this.getDescriptor(t,e,i,n,o),f=u.beginRenderPass(m);f.setViewport(r.x,r.y,r.width,r.height,0,1),f.end();const g=u.finish();h.queue.submit([g])}else this.startRenderPass(t,e,i,r,n,o)}initGpuRenderTarget(t){t.isRoot=!0;const e=new sy;return e.colorTargetCount=t.colorTextures.length,t.colorTextures.forEach((i,r)=>{if(i instanceof le){const n=i.resource.getContext("webgpu"),o=i.transparent?"premultiplied":"opaque";try{n.configure({device:this._renderer.gpu.device,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,format:"bgra8unorm",alphaMode:o})}catch(a){console.error(a)}e.contexts[r]=n}if(e.msaa=i.source.antialias,i.source.antialias){const n=new At({width:0,height:0,sampleCount:4,arrayLayerCount:i.source.arrayLayerCount});e.msaaTextures[r]=n}}),e.msaa&&(e.msaaSamples=4,t.depthStencilTexture&&(t.depthStencilTexture.source.sampleCount=4)),e}destroyGpuRenderTarget(t){t.contexts.forEach(e=>{e.unconfigure()}),t.msaaTextures.forEach(e=>{e.destroy()}),t.msaaTextures.length=0,t.contexts.length=0}ensureDepthStencilTexture(t){const e=this._renderTargetSystem.getGpuRenderTarget(t);t.depthStencilTexture&&e.msaa&&(t.depthStencilTexture.source.sampleCount=4)}resizeGpuRenderTarget(t){const e=this._renderTargetSystem.getGpuRenderTarget(t);e.width=t.width,e.height=t.height,e.msaa&&t.colorTextures.forEach((i,r)=>{const n=e.msaaTextures[r];n==null||n.resize(i.source.width,i.source.height,i.source._resolution)})}}class Ac extends Un{constructor(t){super(t),this.adaptor=new ry,this.adaptor.init(t,this)}}Ac.extension={type:[w.WebGPUSystem],name:"renderTarget"};class Rc{constructor(){this._gpuProgramData=Object.create(null)}contextChange(t){this._gpu=t}getProgramData(t){return this._gpuProgramData[t._layoutKey]||this._createGPUProgramData(t)}_createGPUProgramData(t){const e=this._gpu.device,i=t.gpuLayout.map(n=>e.createBindGroupLayout({entries:n})),r={bindGroupLayouts:i};return this._gpuProgramData[t._layoutKey]={bindGroups:i,pipeline:e.createPipelineLayout(r)},this._gpuProgramData[t._layoutKey]}destroy(){this._gpu=null,this._gpuProgramData=null}}Rc.extension={type:[w.WebGPUSystem],name:"shader"};const Vt={};Vt.normal={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}},Vt.add={alpha:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one",operation:"add"}},Vt.multiply={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"dst",dstFactor:"one-minus-src-alpha",operation:"add"}},Vt.screen={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}},Vt.overlay={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}},Vt.none={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"zero",operation:"add"}},Vt["normal-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"}},Vt["add-npm"]={alpha:{srcFactor:"one",dstFactor:"one",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"}},Vt["screen-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src",operation:"add"}},Vt.erase={alpha:{srcFactor:"zero",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"one-minus-src",operation:"add"}},Vt.min={alpha:{srcFactor:"one",dstFactor:"one",operation:"min"},color:{srcFactor:"one",dstFactor:"one",operation:"min"}},Vt.max={alpha:{srcFactor:"one",dstFactor:"one",operation:"max"},color:{srcFactor:"one",dstFactor:"one",operation:"max"}};class Pc{constructor(){this.defaultState=new ve,this.defaultState.blend=!0}contextChange(t){this.gpu=t}getColorTargets(t,e){const i=Vt[t.blendMode]||Vt.normal,r=[],n={format:"bgra8unorm",writeMask:0,blend:i};for(let o=0;o<e;o++)r[o]=n;return r}destroy(){this.gpu=null}}Pc.extension={type:[w.WebGPUSystem],name:"state"};const ny={type:"image",upload(s,t,e,i=0){const r=s.resource,n=(s.pixelWidth|0)*(s.pixelHeight|0),o=r.byteLength/n;e.device.queue.writeTexture({texture:t,origin:{x:0,y:0,z:i}},r,{offset:0,rowsPerImage:s.pixelHeight,bytesPerRow:s.pixelWidth*o},{width:s.pixelWidth,height:s.pixelHeight,depthOrArrayLayers:1})}},Ic={"bc1-rgba-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"bc2-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc3-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc7-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"etc1-rgb-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"etc2-rgba8unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"astc-4x4-unorm":{blockBytes:16,blockWidth:4,blockHeight:4}},oy={blockBytes:4,blockWidth:1,blockHeight:1},ay={type:"compressed",upload(s,t,e,i=0){let r=s.pixelWidth,n=s.pixelHeight;const o=Ic[s.format]||oy;for(let a=0;a<s.resource.length;a++){const l=s.resource[a],h=Math.ceil(r/o.blockWidth)*o.blockBytes;e.device.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:i}},l,{offset:0,bytesPerRow:h},{width:Math.ceil(r/o.blockWidth)*o.blockWidth,height:Math.ceil(n/o.blockHeight)*o.blockHeight,depthOrArrayLayers:1}),r=Math.max(r>>1,1),n=Math.max(n>>1,1)}}},Mc=["right","left","top","bottom","front","back"];function ly(s){return{type:"cube",upload(t,e,i){const r=t.faces;for(let n=0;n<Mc.length;n++){const o=Mc[n],a=r[o];(s[a.uploadMethodId]||s.image).upload(a,e,i,n)}}}}const kc={type:"image",upload(s,t,e,i=0){const r=s.resource;if(!r)return;if(globalThis.HTMLImageElement&&r instanceof HTMLImageElement){const l=rt.get().createCanvas(r.width,r.height);l.getContext("2d").drawImage(r,0,0,r.width,r.height),s.resource=l,tt("ImageSource: Image element passed, converting to canvas and replacing resource.")}const n=Math.min(t.width,s.resourceWidth||s.pixelWidth),o=Math.min(t.height,s.resourceHeight||s.pixelHeight),a=s.alphaMode==="premultiply-alpha-on-upload";e.device.queue.copyExternalImageToTexture({source:r},{texture:t,origin:{x:0,y:0,z:i},premultipliedAlpha:a},{width:n,height:o})}},hy={type:"video",upload(s,t,e,i){kc.upload(s,t,e,i)}};class cy{constructor(t){this.device=t,this.sampler=t.createSampler({minFilter:"linear"}),this.pipelines={}}_getMipmapPipeline(t){let e=this.pipelines[t];return e||(this.mipmapShaderModule||(this.mipmapShaderModule=this.device.createShaderModule({code:`
|
|
871
|
+
var<private> pos : array<vec2<f32>, 3> = array<vec2<f32>, 3>(
|
|
872
|
+
vec2<f32>(-1.0, -1.0), vec2<f32>(-1.0, 3.0), vec2<f32>(3.0, -1.0));
|
|
873
|
+
|
|
874
|
+
struct VertexOutput {
|
|
875
|
+
@builtin(position) position : vec4<f32>,
|
|
876
|
+
@location(0) texCoord : vec2<f32>,
|
|
877
|
+
};
|
|
878
|
+
|
|
879
|
+
@vertex
|
|
880
|
+
fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> VertexOutput {
|
|
881
|
+
var output : VertexOutput;
|
|
882
|
+
output.texCoord = pos[vertexIndex] * vec2<f32>(0.5, -0.5) + vec2<f32>(0.5);
|
|
883
|
+
output.position = vec4<f32>(pos[vertexIndex], 0.0, 1.0);
|
|
884
|
+
return output;
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
@group(0) @binding(0) var imgSampler : sampler;
|
|
888
|
+
@group(0) @binding(1) var img : texture_2d<f32>;
|
|
889
|
+
|
|
890
|
+
@fragment
|
|
891
|
+
fn fragmentMain(@location(0) texCoord : vec2<f32>) -> @location(0) vec4<f32> {
|
|
892
|
+
return textureSample(img, imgSampler, texCoord);
|
|
893
|
+
}
|
|
894
|
+
`})),e=this.device.createRenderPipeline({layout:"auto",vertex:{module:this.mipmapShaderModule,entryPoint:"vertexMain"},fragment:{module:this.mipmapShaderModule,entryPoint:"fragmentMain",targets:[{format:t}]}}),this.pipelines[t]=e),e}generateMipmap(t){const e=this._getMipmapPipeline(t.format);if(t.dimension==="3d"||t.dimension==="1d")throw new Error("Generating mipmaps for non-2d textures is currently unsupported!");let i=t;const r=t.depthOrArrayLayers||1,n=t.usage&GPUTextureUsage.RENDER_ATTACHMENT;if(!n){const l={size:{width:Math.ceil(t.width/2),height:Math.ceil(t.height/2),depthOrArrayLayers:r},format:t.format,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:t.mipLevelCount-1};i=this.device.createTexture(l)}const o=this.device.createCommandEncoder({}),a=e.getBindGroupLayout(0);for(let l=0;l<r;++l){let h=t.createView({baseMipLevel:0,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),c=n?1:0;for(let u=1;u<t.mipLevelCount;++u){const m=i.createView({baseMipLevel:c++,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),f=o.beginRenderPass({colorAttachments:[{view:m,storeOp:"store",loadOp:"clear",clearValue:{r:0,g:0,b:0,a:0}}]}),g=this.device.createBindGroup({layout:a,entries:[{binding:0,resource:this.sampler},{binding:1,resource:h}]});f.setPipeline(e),f.setBindGroup(0,g),f.draw(3,1,0,0),f.end(),h=m}}if(!n){const l={width:Math.ceil(t.width/2),height:Math.ceil(t.height/2),depthOrArrayLayers:r};for(let h=1;h<t.mipLevelCount;++h)o.copyTextureToTexture({texture:i,mipLevel:h-1},{texture:t,mipLevel:h},l),l.width=Math.ceil(l.width/2),l.height=Math.ceil(l.height/2)}return this.device.queue.submit([o.finish()]),n||i.destroy(),t}}class uy{constructor(t){this.textureView=null,this.gpuTexture=t}destroy(){this.gpuTexture.destroy(),this.textureView=null,this.gpuTexture=null}}class Bc{constructor(t){this._gpuSamplers=Object.create(null),this._bindGroupHash=Object.create(null),this._renderer=t,t.gc.addCollection(this,"_bindGroupHash","hash"),this._managedTextures=new ue({renderer:t,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"gpuTextureSource"});const e={image:kc,buffer:ny,video:hy,compressed:ay};this._uploads={...e,cube:ly(e)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(t){this._gpu=t}initSource(t){var e;return((e=t._gpuData[this._renderer.uid])==null?void 0:e.gpuTexture)||this._initSource(t)}_initSource(t){if(t.autoGenerateMipmaps){const h=Math.max(t.pixelWidth,t.pixelHeight);t.mipLevelCount=Math.floor(Math.log2(h))+1}let e=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST;t.uploadMethodId!=="compressed"&&(e|=GPUTextureUsage.RENDER_ATTACHMENT,e|=GPUTextureUsage.COPY_SRC);const i=Ic[t.format]||{blockWidth:1,blockHeight:1},r=Math.ceil(t.pixelWidth/i.blockWidth)*i.blockWidth,n=Math.ceil(t.pixelHeight/i.blockHeight)*i.blockHeight,o={label:t.label,size:{width:r,height:n,depthOrArrayLayers:t.arrayLayerCount},format:t.format,sampleCount:t.sampleCount,mipLevelCount:t.mipLevelCount,dimension:t.dimension,usage:e},a=this._gpu.device.createTexture(o);return t._gpuData[this._renderer.uid]=new uy(a),this._managedTextures.add(t)&&(t.on("update",this.onSourceUpdate,this),t.on("resize",this.onSourceResize,this),t.on("updateMipmaps",this.onUpdateMipmaps,this)),this.onSourceUpdate(t),a}onSourceUpdate(t){const e=this.getGpuSource(t);e&&(this._uploads[t.uploadMethodId]&&this._uploads[t.uploadMethodId].upload(t,e,this._gpu),t.autoGenerateMipmaps&&t.mipLevelCount>1&&this.onUpdateMipmaps(t))}onUpdateMipmaps(t){this._mipmapGenerator||(this._mipmapGenerator=new cy(this._gpu.device));const e=this.getGpuSource(t);this._mipmapGenerator.generateMipmap(e)}onSourceUnload(t){t.off("update",this.onSourceUpdate,this),t.off("resize",this.onSourceResize,this),t.off("updateMipmaps",this.onUpdateMipmaps,this)}onSourceResize(t){t._gcLastUsed=this._renderer.gc.now;const e=t._gpuData[this._renderer.uid],i=e==null?void 0:e.gpuTexture;i?(i.width!==t.pixelWidth||i.height!==t.pixelHeight)&&(e.destroy(),this._bindGroupHash[t.uid]=null,t._gpuData[this._renderer.uid]=null,this.initSource(t)):this.initSource(t)}_initSampler(t){return this._gpuSamplers[t._resourceId]=this._gpu.device.createSampler(t),this._gpuSamplers[t._resourceId]}getGpuSampler(t){return this._gpuSamplers[t._resourceId]||this._initSampler(t)}getGpuSource(t){var e;return t._gcLastUsed=this._renderer.gc.now,((e=t._gpuData[this._renderer.uid])==null?void 0:e.gpuTexture)||this.initSource(t)}getTextureBindGroup(t){return this._bindGroupHash[t.uid]||this._createTextureBindGroup(t)}_createTextureBindGroup(t){const e=t.source;return this._bindGroupHash[t.uid]=new Me({0:e,1:e.style,2:new he({uTextureMatrix:{type:"mat3x3<f32>",value:t.textureMatrix.mapCoord}})}),this._bindGroupHash[t.uid]}getTextureView(t){const e=t.source;e._gcLastUsed=this._renderer.gc.now;let i=e._gpuData[this._renderer.uid];return i||(this.initSource(e),i=e._gpuData[this._renderer.uid]),i.textureView||(i.textureView=i.gpuTexture.createView({dimension:e.viewDimension})),i.textureView}generateCanvas(t){const e=this._renderer,i=e.gpu.device.createCommandEncoder(),r=rt.get().createCanvas();r.width=t.source.pixelWidth,r.height=t.source.pixelHeight;const n=r.getContext("webgpu");return n.configure({device:e.gpu.device,usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,format:rt.get().getNavigator().gpu.getPreferredCanvasFormat(),alphaMode:"premultiplied"}),i.copyTextureToTexture({texture:e.texture.getGpuSource(t.source),origin:{x:0,y:0}},{texture:n.getCurrentTexture()},{width:r.width,height:r.height}),e.gpu.device.queue.submit([i.finish()]),r}getPixels(t){const e=this.generateCanvas(t),i=rs.getOptimalCanvasAndContext(e.width,e.height),r=i.context;r.drawImage(e,0,0);const{width:n,height:o}=e,a=r.getImageData(0,0,n,o),l=new Uint8ClampedArray(a.data.buffer);return rs.returnCanvasAndContext(i),{pixels:l,width:n,height:o}}destroy(){this._managedTextures.destroy();for(const t of Object.keys(this._bindGroupHash)){const e=Number(t),i=this._bindGroupHash[e];i==null||i.destroy()}this._renderer=null,this._gpu=null,this._mipmapGenerator=null,this._gpuSamplers=null,this._bindGroupHash=null}}Bc.extension={type:[w.WebGPUSystem],name:"texture"};class Oc{constructor(){this._maxTextures=0}contextChange(t){const e=new he({uTransformMatrix:{value:new W,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}});this._maxTextures=t.limits.maxBatchableTextures;const i=Xr({name:"graphics",bits:[rl,ol(this._maxTextures),wm,Zr]});this.shader=new be({gpuProgram:i,resources:{localUniforms:e}})}execute(t,e){const i=e.context,r=i.customShader||this.shader,n=t.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(i),h=n.encoder;h.setGeometry(a.geometry,r.gpuProgram);const c=n.globalUniforms.bindGroup;h.setBindGroup(0,c,r.gpuProgram);const u=n.renderPipes.uniformBatch.getUniformBindGroup(r.resources.localUniforms,!0);h.setBindGroup(2,u,r.gpuProgram);const m=l.instructions;let f=null;for(let g=0;g<l.instructionSize;g++){const y=m[g];if(y.topology!==f&&(f=y.topology,h.setPipelineFromGeometryProgramAndState(a.geometry,r.gpuProgram,t.state,y.topology)),r.groups[1]=y.bindGroup,!y.gpuBindGroup){const x=y.textures;y.bindGroup=Vr(x.textures,x.count,this._maxTextures),y.gpuBindGroup=n.bindGroup.getBindGroup(y.bindGroup,r.gpuProgram,1)}h.setBindGroup(1,y.bindGroup,r.gpuProgram),h.renderPassEncoder.drawIndexed(y.size,1,y.start)}}destroy(){this.shader.destroy(!0),this.shader=null}}Oc.extension={type:[w.WebGPUPipesAdaptor],name:"graphics"};class Dc{init(){const t=Xr({name:"mesh",bits:[Bs,lg,Zr]});this._shader=new be({gpuProgram:t,resources:{uTexture:z.EMPTY._source,uSampler:z.EMPTY._source.style,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new W}}}})}execute(t,e){const i=t.renderer;let r=e._shader;if(!r)r=this._shader,r.groups[2]=i.texture.getTextureBindGroup(e.texture);else if(!r.gpuProgram){tt("Mesh shader has no gpuProgram",e.shader);return}const n=r.gpuProgram;if(n.autoAssignGlobalUniforms&&(r.groups[0]=i.globalUniforms.bindGroup),n.autoAssignLocalUniforms){const o=t.localUniforms;r.groups[1]=i.renderPipes.uniformBatch.getUniformBindGroup(o,!0)}i.encoder.draw({geometry:e._geometry,shader:r,state:e.state})}destroy(){this._shader.destroy(!0),this._shader=null}}Dc.extension={type:[w.WebGPUPipesAdaptor],name:"mesh"};const dy=[...Gn,Sc,vc,$n,Ec,xc,Bc,Ac,Rc,Pc,wc,bc,Tc,yc],fy=[...Oh,Cc],py=[ph,Dc,Oc],Gc=[],Uc=[],Lc=[];J.handleByNamedList(w.WebGPUSystem,Gc),J.handleByNamedList(w.WebGPUPipes,Uc),J.handleByNamedList(w.WebGPUPipesAdaptor,Lc),J.add(...dy,...fy,...py);class my extends Xi{constructor(){const t={name:"webgpu",type:ce.WEBGPU,systems:Gc,renderPipes:Uc,renderPipeAdaptors:Lc};super(t)}}const gy=Object.freeze(Object.defineProperty({__proto__:null,WebGPURenderer:my},Symbol.toStringTag,{value:"Module"}));J.add(Pu,Iu);const Ai=480,os=480;class _y{constructor(){this.container=null,this.resizeObserver=null,this.app=new Na}async init(){await this.app.init({width:Ai,height:os,backgroundAlpha:0,antialias:!0,resolution:window.devicePixelRatio||1,autoDensity:!0}),this.container=document.createElement("div"),this.container.id="holostaff-widget-root",Object.assign(this.container.style,{position:"fixed",bottom:"0",left:"50%",transform:"translateX(-50%)",width:`${Ai}px`,height:`${os}px`,zIndex:"2147483646",pointerEvents:"none",overflow:"visible"});const t=this.app.canvas;return Object.assign(t.style,{width:"100%",height:"100%",display:"block",pointerEvents:"auto"}),this.container.appendChild(t),document.body.appendChild(this.container),this.setupResize(),t}setupResize(){const t=()=>{const e=window.innerWidth,i=Math.min(Ai,e),r=i/Ai,n=os*r;this.container&&(this.container.style.width=`${i}px`,this.container.style.height=`${n}px`),this.app.renderer.resize(Ai,os)};window.addEventListener("resize",t),t()}get stageWidth(){return Ai}get stageHeight(){return os}destroy(){var t,e;window.removeEventListener("resize",this.setupResize),(t=this.resizeObserver)==null||t.disconnect(),(e=this.container)==null||e.remove(),this.app.destroy(!0)}}function Fc(){var s,t;return((t=(s=globalThis.matchMedia)==null?void 0:s.call(globalThis,"(prefers-reduced-motion: reduce)"))==null?void 0:t.matches)??!1}const ii={easeOutCubic:s=>1-Math.pow(1-s,3),easeInCubic:s=>s*s*s,easeOutBack:s=>1+2.70158*Math.pow(s-1,3)+1.70158*Math.pow(s-1,2),easeInOutSine:s=>-(Math.cos(Math.PI*s)-1)/2};function Ri(s){const{target:t,props:e,duration:i,easing:r=ii.easeOutCubic,delay:n=0,onComplete:o,ticker:a}=s;if(Fc()){for(const m of Object.keys(e))t[m]=e[m];return o==null||o(),()=>{}}const l={};for(const m of Object.keys(e))l[m]=t[m];let h=-n,c=!1;const u=m=>{if(c||(h+=m.deltaMS,h<0))return;const f=Math.min(h/i,1),g=r(f);for(const y of Object.keys(e))t[y]=l[y]+(e[y]-l[y])*g;f>=1&&(a.remove(u),o==null||o())};return a.add(u),()=>{c=!0,a.remove(u)}}function Nc(s,t,e=.3,i=.7,r=2e3){if(Fc())return s.alpha=(e+i)/2,()=>{};let n=0,o=!1;const a=l=>{if(o)return;n+=l.deltaMS;const h=(Math.sin(n/r*Math.PI*2)+1)/2;s.alpha=e+(i-e)*h};return t.add(a),()=>{o=!0,t.remove(a)}}const yy=`
|
|
895
|
+
in vec2 aPosition;
|
|
896
|
+
out vec2 vTextureCoord;
|
|
897
|
+
|
|
898
|
+
uniform vec4 uInputSize;
|
|
899
|
+
uniform vec4 uOutputFrame;
|
|
900
|
+
uniform vec4 uOutputTexture;
|
|
901
|
+
|
|
902
|
+
vec4 filterVertexPosition(void) {
|
|
903
|
+
vec2 position = aPosition * uOutputFrame.zw + uOutputFrame.xy;
|
|
904
|
+
position.x = position.x * (2.0 / uOutputTexture.x) - 1.0;
|
|
905
|
+
position.y = position.y * (2.0 * uOutputTexture.z / uOutputTexture.y) - uOutputTexture.z;
|
|
906
|
+
return vec4(position, 0.0, 1.0);
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
vec2 filterTextureCoord(void) {
|
|
910
|
+
return aPosition * (uOutputFrame.zw * uInputSize.zw);
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
void main(void) {
|
|
914
|
+
gl_Position = filterVertexPosition();
|
|
915
|
+
vTextureCoord = filterTextureCoord();
|
|
916
|
+
}
|
|
917
|
+
`,xy=`
|
|
918
|
+
in vec2 vTextureCoord;
|
|
919
|
+
out vec4 finalColor;
|
|
920
|
+
|
|
921
|
+
uniform sampler2D uTexture;
|
|
922
|
+
uniform float uSimilarity;
|
|
923
|
+
uniform float uSmoothness;
|
|
924
|
+
|
|
925
|
+
void main(void) {
|
|
926
|
+
vec4 color = texture(uTexture, vTextureCoord);
|
|
927
|
+
|
|
928
|
+
// Target: pure green (#00FF00)
|
|
929
|
+
vec3 keyColor = vec3(0.0, 1.0, 0.0);
|
|
930
|
+
|
|
931
|
+
// Distance from the key color in RGB space
|
|
932
|
+
float diff = distance(color.rgb, keyColor);
|
|
933
|
+
|
|
934
|
+
// Create alpha mask: green areas become transparent
|
|
935
|
+
float alpha = smoothstep(uSimilarity, uSimilarity + uSmoothness, diff);
|
|
936
|
+
|
|
937
|
+
// Despill: reduce green contamination on edges
|
|
938
|
+
color.g = min(color.g, max(color.r, color.b));
|
|
939
|
+
|
|
940
|
+
finalColor = vec4(color.rgb * alpha, alpha);
|
|
941
|
+
}
|
|
942
|
+
`;class by extends Dr{constructor(t=.35,e=.12){const i=Ye.from({vertex:yy,fragment:xy});super({glProgram:i,resources:{chromaKeyUniforms:{uSimilarity:{value:t,type:"f32"},uSmoothness:{value:e,type:"f32"}}}})}get similarity(){return this.resources.chromaKeyUniforms.uniforms.uSimilarity}set similarity(t){this.resources.chromaKeyUniforms.uniforms.uSimilarity=t}get smoothness(){return this.resources.chromaKeyUniforms.uniforms.uSmoothness}set smoothness(t){this.resources.chromaKeyUniforms.uniforms.uSmoothness=t}}const Re=140,zt=Re*(16/9),Hc=220;class vy{constructor(t,e){this.idleSprite=null,this.idleGroup=null,this.liveSprite=null,this.glowGraphic=null,this.videoElement=null,this.liveVideoElement=null,this.cancelGlow=null,this.cancelEntrance=null,this.visible=!1,this.stageWidth=t,this.stageHeight=e,this.container=new kt,this.container.visible=!1,this.container.y=e+zt}async loadIdleVideo(t){this.videoElement=document.createElement("video"),this.videoElement.src=t,this.videoElement.loop=!0,this.videoElement.muted=!0,this.videoElement.playsInline=!0,this.videoElement.crossOrigin="anonymous",this.videoElement.style.display="none",document.body.appendChild(this.videoElement),await this.videoElement.play();const e=z.from(this.videoElement);this.idleSprite=new ye(e),this.idleSprite.width=Re,this.idleSprite.height=zt,this.idleSprite.anchor.set(.5,1),this.idleSprite.filters=[new by];const i=5,r=new kt,n=new Se;n.roundRect(-Re/2+i,-zt+i,Re-i*2,zt-i,6),n.fill({color:16777215}),r.addChild(this.idleSprite),r.addChild(n),r.mask=n,this.glowGraphic=new Se;const o=Re*1.15,a=zt*.92,l=20;this.glowGraphic.roundRect(-o/2-2,-a-1,o+4,a+4,l+2),this.glowGraphic.fill({color:0,alpha:.06}),this.glowGraphic.roundRect(-o/2,-a,o,a,l),this.glowGraphic.fill({color:15659767,alpha:.55}),this.idleGroup=new kt,this.idleGroup.addChild(this.glowGraphic),this.idleGroup.addChild(r),this.container.addChild(this.idleGroup),this.container.x=this.stageWidth/2,this.container.y=this.stageHeight+zt}async loadIdleImage(t){var n,o;await((o=(n=z.from(t).baseTexture)==null?void 0:n.resource)==null?void 0:o.load().catch(()=>null)),this.idleSprite=new ye(z.from(t)),this.idleSprite.width=Re,this.idleSprite.height=zt,this.idleSprite.anchor.set(.5,1),this.glowGraphic=new Se;const e=Re*1.15,i=zt*.92,r=20;this.glowGraphic.roundRect(-e/2-2,-i-1,e+4,i+4,r+2),this.glowGraphic.fill({color:0,alpha:.06}),this.glowGraphic.roundRect(-e/2,-i,e,i,r),this.glowGraphic.fill({color:15659767,alpha:.55}),this.container.addChild(this.glowGraphic),this.container.addChild(this.idleSprite),this.container.x=this.stageWidth/2,this.container.y=this.stageHeight+zt}slideIn(t){if(this.visible)return;this.visible=!0;const e=this.stageHeight-10;this.container.alpha=1,this.container.visible=!0,this.container.y=this.stageHeight+zt,this.cancelEntrance=Ri({target:this.container,props:{y:e},duration:700,easing:ii.easeOutBack,ticker:t}),this.glowGraphic&&(this.glowGraphic.alpha=0,setTimeout(()=>{this.glowGraphic&&(this.cancelGlow=Nc(this.glowGraphic,t,.15,.5,2500))},700))}slideOut(t){var e;this.visible&&(this.visible=!1,(e=this.cancelGlow)==null||e.call(this),this.cancelGlow=null,Ri({target:this.container,props:{y:this.stageHeight+zt},duration:450,easing:ii.easeInCubic,ticker:t,onComplete:()=>{this.container.visible=!1}}))}get isVisible(){return this.visible}setInteractive(t){this.container.eventMode="static",this.container.cursor="pointer";const e=new Se;e.roundRect(-Re/2,-zt,Re,zt,12),e.fill({color:16777215,alpha:.001}),this.container.addChildAt(e,0),this.container.on("pointertap",t),this.container.on("pointerenter",()=>{this.container&&this.container.scale.set(1.04)}),this.container.on("pointerleave",()=>{this.container&&this.container.scale.set(1)})}setLiveVideo(t,e){this.liveVideoElement=t;const i=()=>{var l;const r=z.from(t);this.liveSprite=new ye(r);const n=t.videoWidth||1,o=t.videoHeight||1,a=Hc/n;this.liveSprite.width=Hc,this.liveSprite.height=o*a,this.liveSprite.anchor.set(.5,1),this.liveSprite.alpha=0,this.container.addChild(this.liveSprite),this.idleGroup&&(this.idleGroup.visible=!1),(l=this.cancelGlow)==null||l.call(this),this.cancelGlow=null,Ri({target:this.liveSprite,props:{alpha:1},duration:500,easing:ii.easeInOutSine,ticker:e})};if(t.videoWidth>0&&t.videoHeight>0)i();else{const r=()=>{t.removeEventListener("loadeddata",r),t.removeEventListener("resize",r),i()};t.addEventListener("loadeddata",r),t.addEventListener("resize",r)}}clearLiveVideo(t){this.liveSprite&&Ri({target:this.liveSprite,props:{alpha:0},duration:400,easing:ii.easeInCubic,ticker:t,onComplete:()=>{var e;(e=this.liveSprite)==null||e.destroy(),this.liveSprite=null,this.liveVideoElement=null}}),this.idleGroup&&(this.idleGroup.visible=!0,this.idleSprite&&(this.idleSprite.alpha=1)),this.glowGraphic&&(this.cancelGlow=Nc(this.glowGraphic,t,.15,.5,2500))}destroy(){var t,e;(t=this.cancelGlow)==null||t.call(this),(e=this.cancelEntrance)==null||e.call(this),this.videoElement&&(this.videoElement.pause(),this.videoElement.remove()),this.container.destroy({children:!0})}}const jn=18,Wc=12,Ey=20,Ty=240,zs=14,Sy=35,Cy=2500,Vc=300,wy=16777215,Ay=13160666,Ry=1.5,Py=3820124,Iy=.1,My=["Got questions? Click me!","I can guide you through this page","Need help? Let’s chat!"];class ky{constructor(t,e){this.promptIndex=0,this.charIndex=0,this.phase="idle",this.phaseElapsed=0,this.cancelFade=null,this.tickCb=null,this.running=!1,this.ticker=t,this.prompts=e!=null&&e.length?e:My,this.container=new kt,this.container.alpha=0,this.container.visible=!1,this.bg=new Se,this.container.addChild(this.bg),this.label=new ng({text:"",style:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:13,fontWeight:"500",fill:2763326,wordWrap:!0,wordWrapWidth:Ty-jn*2,lineHeight:19}}),this.label.x=jn,this.label.y=Wc,this.container.addChild(this.label),this.container.eventMode="static",this.container.cursor="pointer"}start(){this.running||(this.running=!0,this.container.visible=!0,this.promptIndex=0,this.beginTyping(),this.tickCb=t=>this.update(t.deltaMS),this.ticker.add(this.tickCb))}stop(){var t;this.running&&(this.running=!1,this.phase="idle",this.tickCb&&this.ticker.remove(this.tickCb),this.tickCb=null,(t=this.cancelFade)==null||t.call(this),this.cancelFade=null,this.container.visible=!1,this.container.alpha=0)}beginTyping(){this.charIndex=0,this.phaseElapsed=0,this.phase="typing",this.label.text="",this.drawBubble(),this.container.alpha=0,this.cancelFade=Ri({target:this.container,props:{alpha:1},duration:Vc,easing:ii.easeOutCubic,ticker:this.ticker})}update(t){var e;if(this.phase==="typing"){this.phaseElapsed+=t;const i=this.prompts[this.promptIndex],r=Math.min(Math.floor(this.phaseElapsed/Sy),i.length);r!==this.charIndex&&(this.charIndex=r,this.label.text=i.substring(0,this.charIndex),this.drawBubble()),this.charIndex>=i.length&&(this.phase="holding",this.phaseElapsed=0)}else this.phase==="holding"&&(this.phaseElapsed+=t,this.phaseElapsed>=Cy&&(this.phase="fading",this.phaseElapsed=0,(e=this.cancelFade)==null||e.call(this),this.cancelFade=Ri({target:this.container,props:{alpha:0},duration:Vc,easing:ii.easeInCubic,ticker:this.ticker,onComplete:()=>{this.promptIndex=(this.promptIndex+1)%this.prompts.length,this.beginTyping()}})))}drawBubble(){const t=Math.max(this.label.width,50),e=Math.max(this.label.height,18),i=t+jn*2,r=e+Wc*2,n=Ey,o=14,a=i*.5-o/2,l=i*.5+o/2,h=i*.48,c=r+zs;this.bg.clear(),this.bg.roundRect(2,3,i,r+2,n),this.bg.fill({color:Py,alpha:Iy}),this.bg.moveTo(n,0),this.bg.lineTo(i-n,0),this.bg.quadraticCurveTo(i,0,i,n),this.bg.lineTo(i,r-n),this.bg.quadraticCurveTo(i,r,i-n,r),this.bg.lineTo(l,r),this.bg.quadraticCurveTo(l-2,r+zs*.35,h,c),this.bg.quadraticCurveTo(a+2,r+zs*.55,a,r),this.bg.lineTo(n,r),this.bg.quadraticCurveTo(0,r,0,r-n),this.bg.lineTo(0,n),this.bg.quadraticCurveTo(0,0,n,0),this.bg.closePath(),this.bg.fill({color:wy,alpha:.97}),this.bg.stroke({color:Ay,width:Ry,alpha:.6}),this.container.pivot.x=i/2,this.container.pivot.y=r+zs}onClick(t){this.container.on("pointertap",t)}destroy(){this.stop(),this.container.destroy({children:!0})}}const By=[{urls:"stun:stun.l.google.com:19302"}],Oy=3e3,Dy="oai-events";class Gy{constructor(t){this.onConnected=null,this.onDisconnected=null,this.onRemoteTrack=null,this.onDataMessage=null,this.onError=null,this.pc=null,this.dc=null,this.micStream=null,this._remoteAudioStream=null,this._connected=!1,this.opts={model:"gpt-4o-realtime-preview",voice:"verse",instructions:"",tools:[],...t}}get isConnected(){return this._connected}get dataChannel(){return this.dc}get remoteAudioStream(){return this._remoteAudioStream}async connect(){var t,e;try{console.log("[RealtimeSession] Requesting microphone..."),this.micStream=await navigator.mediaDevices.getUserMedia({audio:!0}),console.log("[RealtimeSession] Microphone granted"),this.pc=new RTCPeerConnection({iceServers:By}),this.setupPeerConnectionHandlers();for(const o of this.micStream.getAudioTracks())this.pc.addTrack(o,this.micStream);this.dc=this.pc.createDataChannel(Dy),this.setupDataChannelHandlers();const i=await this.pc.createOffer();await this.pc.setLocalDescription(i),await this.waitForIceGathering();const r=(t=this.pc.localDescription)==null?void 0:t.sdp;if(!r)throw new Error("No local SDP after ICE gathering");console.log("[RealtimeSession] Exchanging SDP...");const n=await this.exchangeSDP(r);await this.pc.setRemoteDescription({type:"answer",sdp:n}),console.log("[RealtimeSession] Remote description set")}catch(i){const r=i instanceof Error?i:new Error(String(i));throw console.error("[RealtimeSession] Connection failed:",r.message),(e=this.onError)==null||e.call(this,r),this.close(),r}}sendJSON(t){if(!this.dc||this.dc.readyState!=="open"){console.warn("[RealtimeSession] Data channel not open, cannot send:",t);return}this.dc.send(JSON.stringify(t))}close(){var t;if(console.log("[RealtimeSession] Closing..."),this.dc){try{this.dc.close()}catch{}this.dc=null}if(this.pc){try{this.pc.close()}catch{}this.pc=null}if(this.micStream){for(const e of this.micStream.getTracks())e.stop();this.micStream=null}this._remoteAudioStream=null,this._connected&&(this._connected=!1,(t=this.onDisconnected)==null||t.call(this))}setupPeerConnectionHandlers(){this.pc&&(this.pc.ontrack=t=>{var e;console.log("[RealtimeSession] Remote audio track received"),this._remoteAudioStream=t.streams[0]??new MediaStream([t.track]),(e=this.onRemoteTrack)==null||e.call(this,this._remoteAudioStream)},this.pc.onconnectionstatechange=()=>{var e,i,r,n;const t=(e=this.pc)==null?void 0:e.connectionState;console.log("[RealtimeSession] Connection state:",t),t==="connected"?(this._connected=!0,(i=this.onConnected)==null||i.call(this)):(t==="failed"||t==="closed"||t==="disconnected")&&(this._connected&&(this._connected=!1,(r=this.onDisconnected)==null||r.call(this)),t==="failed"&&((n=this.onError)==null||n.call(this,new Error("WebRTC connection failed"))))})}waitForIceGathering(){return!this.pc||this.pc.iceGatheringState==="complete"?Promise.resolve():new Promise(t=>{const e=this.pc;let i;const r=()=>{clearTimeout(i);try{e.removeEventListener("icegatheringstatechange",n)}catch{}t()},n=()=>{e.iceGatheringState==="complete"&&r()};e.addEventListener("icegatheringstatechange",n),i=setTimeout(r,Oy)})}async exchangeSDP(t){const{webrtcUrl:e,ephemeralKey:i,model:r,voice:n}=this.opts,o=`${e}?model=${encodeURIComponent(r)}&voice=${encodeURIComponent(n)}`,a=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/sdp",Accept:"application/sdp"},body:t});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`SDP exchange failed (${a.status}): ${l}`)}return a.text()}setupDataChannelHandlers(){this.dc&&(this.dc.onopen=()=>{console.log("[RealtimeSession] Data channel open"),this.sendSessionUpdate(),this.sendJSON({type:"response.create"})},this.dc.onmessage=t=>{var e;try{const i=JSON.parse(t.data);(e=this.onDataMessage)==null||e.call(this,i)}catch(i){console.warn("[RealtimeSession] Failed to parse data channel message:",i)}},this.dc.onclose=()=>{console.log("[RealtimeSession] Data channel closed")},this.dc.onerror=t=>{console.error("[RealtimeSession] Data channel error:",t)})}sendSessionUpdate(){const t={instructions:this.opts.instructions,modalities:["audio","text"],input_audio_transcription:{model:"whisper-1"},turn_detection:{type:"server_vad",threshold:.5,prefix_padding_ms:300,silence_duration_ms:700,create_response:!0}};this.opts.tools&&this.opts.tools.length>0&&(t.tools=this.opts.tools),this.sendJSON({type:"session.update",session:t})}}const Uy=24e3,Ly=`
|
|
943
|
+
class PcmBufferProcessor extends AudioWorkletProcessor {
|
|
944
|
+
constructor() {
|
|
945
|
+
super()
|
|
946
|
+
this._buffer = new Float32Array(0)
|
|
947
|
+
this._paused = false
|
|
948
|
+
this._chunkSize = 24000
|
|
949
|
+
|
|
950
|
+
this.port.onmessage = (e) => {
|
|
951
|
+
if (e.data.type === 'pause') this._paused = true
|
|
952
|
+
if (e.data.type === 'resume') this._paused = false
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
process(inputs) {
|
|
957
|
+
const input = inputs[0]
|
|
958
|
+
if (!input || !input[0] || this._paused) return true
|
|
959
|
+
|
|
960
|
+
const samples = input[0] // Float32 mono channel
|
|
961
|
+
|
|
962
|
+
// Append to buffer
|
|
963
|
+
const newBuf = new Float32Array(this._buffer.length + samples.length)
|
|
964
|
+
newBuf.set(this._buffer)
|
|
965
|
+
newBuf.set(samples, this._buffer.length)
|
|
966
|
+
this._buffer = newBuf
|
|
967
|
+
|
|
968
|
+
// Emit chunks when we have enough samples
|
|
969
|
+
while (this._buffer.length >= this._chunkSize) {
|
|
970
|
+
const chunk = this._buffer.slice(0, this._chunkSize)
|
|
971
|
+
this._buffer = this._buffer.slice(this._chunkSize)
|
|
972
|
+
this.port.postMessage({ type: 'chunk', samples: chunk })
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
return true
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
registerProcessor('pcm-buffer-processor', PcmBufferProcessor)
|
|
980
|
+
`;function Fy(s){const t=new Int16Array(s.length);for(let e=0;e<s.length;e++){const i=Math.max(-1,Math.min(1,s[e]));t[e]=i<0?i*32768:i*32767}return t}class Ny{constructor(){this.onAudioChunk=null,this.audioCtx=null,this.sourceNode=null,this.workletNode=null,this._started=!1,this._paused=!1}get isStarted(){return this._started}get isPaused(){return this._paused}async start(t){if(this._started)return;this.audioCtx=new AudioContext({sampleRate:Uy});const e=new Blob([Ly],{type:"application/javascript"}),i=URL.createObjectURL(e);await this.audioCtx.audioWorklet.addModule(i),URL.revokeObjectURL(i),this.sourceNode=this.audioCtx.createMediaStreamSource(t),this.workletNode=new AudioWorkletNode(this.audioCtx,"pcm-buffer-processor"),this.workletNode.port.onmessage=n=>{var o;if(n.data.type==="chunk"){const a=n.data.samples,l=Fy(a);(o=this.onAudioChunk)==null||o.call(this,new Uint8Array(l.buffer))}},this.sourceNode.connect(this.workletNode);const r=this.audioCtx.createGain();r.gain.value=0,r.connect(this.audioCtx.destination),this.workletNode.connect(r),this._started=!0,this._paused=!1,console.log("[AudioForwarder] Started capturing remote audio at 24kHz")}pause(){var t;!this._started||this._paused||(this._paused=!0,(t=this.workletNode)==null||t.port.postMessage({type:"pause"}),console.log("[AudioForwarder] Paused"))}resume(){var t;!this._started||!this._paused||(this._paused=!1,(t=this.workletNode)==null||t.port.postMessage({type:"resume"}),console.log("[AudioForwarder] Resumed"))}stop(){var t,e,i;if(this._started){try{(t=this.workletNode)==null||t.disconnect()}catch{}try{(e=this.sourceNode)==null||e.disconnect()}catch{}try{(i=this.audioCtx)==null||i.close()}catch{}this.workletNode=null,this.sourceNode=null,this.audioCtx=null,this._started=!1,this._paused=!1,console.log("[AudioForwarder] Stopped")}}}var Xn={},as={},zc;function Hy(){if(zc)return as;zc=1,as.byteLength=a,as.toByteArray=h,as.fromByteArray=m;for(var s=[],t=[],e=typeof Uint8Array<"u"?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r=0,n=i.length;r<n;++r)s[r]=i[r],t[i.charCodeAt(r)]=r;t[45]=62,t[95]=63;function o(f){var g=f.length;if(g%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var y=f.indexOf("=");y===-1&&(y=g);var x=y===g?0:4-y%4;return[y,x]}function a(f){var g=o(f),y=g[0],x=g[1];return(y+x)*3/4-x}function l(f,g,y){return(g+y)*3/4-y}function h(f){var g,y=o(f),x=y[0],v=y[1],E=new e(l(f,x,v)),T=0,C=v>0?x-4:x,R;for(R=0;R<C;R+=4)g=t[f.charCodeAt(R)]<<18|t[f.charCodeAt(R+1)]<<12|t[f.charCodeAt(R+2)]<<6|t[f.charCodeAt(R+3)],E[T++]=g>>16&255,E[T++]=g>>8&255,E[T++]=g&255;return v===2&&(g=t[f.charCodeAt(R)]<<2|t[f.charCodeAt(R+1)]>>4,E[T++]=g&255),v===1&&(g=t[f.charCodeAt(R)]<<10|t[f.charCodeAt(R+1)]<<4|t[f.charCodeAt(R+2)]>>2,E[T++]=g>>8&255,E[T++]=g&255),E}function c(f){return s[f>>18&63]+s[f>>12&63]+s[f>>6&63]+s[f&63]}function u(f,g,y){for(var x,v=[],E=g;E<y;E+=3)x=(f[E]<<16&16711680)+(f[E+1]<<8&65280)+(f[E+2]&255),v.push(c(x));return v.join("")}function m(f){for(var g,y=f.length,x=y%3,v=[],E=16383,T=0,C=y-x;T<C;T+=E)v.push(u(f,T,T+E>C?C:T+E));return x===1?(g=f[y-1],v.push(s[g>>2]+s[g<<4&63]+"==")):x===2&&(g=(f[y-2]<<8)+f[y-1],v.push(s[g>>10]+s[g>>4&63]+s[g<<2&63]+"=")),v.join("")}return as}var $s={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */var $c;function Wy(){return $c||($c=1,$s.read=function(s,t,e,i,r){var n,o,a=r*8-i-1,l=(1<<a)-1,h=l>>1,c=-7,u=e?r-1:0,m=e?-1:1,f=s[t+u];for(u+=m,n=f&(1<<-c)-1,f>>=-c,c+=a;c>0;n=n*256+s[t+u],u+=m,c-=8);for(o=n&(1<<-c)-1,n>>=-c,c+=i;c>0;o=o*256+s[t+u],u+=m,c-=8);if(n===0)n=1-h;else{if(n===l)return o?NaN:(f?-1:1)*(1/0);o=o+Math.pow(2,i),n=n-h}return(f?-1:1)*o*Math.pow(2,n-i)},$s.write=function(s,t,e,i,r,n){var o,a,l,h=n*8-r-1,c=(1<<h)-1,u=c>>1,m=r===23?Math.pow(2,-24)-Math.pow(2,-77):0,f=i?0:n-1,g=i?1:-1,y=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=c):(o=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-o))<1&&(o--,l*=2),o+u>=1?t+=m/l:t+=m*Math.pow(2,1-u),t*l>=2&&(o++,l/=2),o+u>=c?(a=0,o=c):o+u>=1?(a=(t*l-1)*Math.pow(2,r),o=o+u):(a=t*Math.pow(2,u-1)*Math.pow(2,r),o=0));r>=8;s[e+f]=a&255,f+=g,a/=256,r-=8);for(o=o<<r|a,h+=r;h>0;s[e+f]=o&255,f+=g,o/=256,h-=8);s[e+f-g]|=y*128}),$s}/*!
|
|
981
|
+
* The buffer module from node.js, for the browser.
|
|
982
|
+
*
|
|
983
|
+
* @author Feross Aboukhadijeh <https://feross.org>
|
|
984
|
+
* @license MIT
|
|
985
|
+
*/var jc;function Vy(){return jc||(jc=1,(function(s){const t=Hy(),e=Wy(),i=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;s.Buffer=a,s.SlowBuffer=E,s.INSPECT_MAX_BYTES=50;const r=2147483647;s.kMaxLength=r,a.TYPED_ARRAY_SUPPORT=n(),!a.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function n(){try{const _=new Uint8Array(1),d={foo:function(){return 42}};return Object.setPrototypeOf(d,Uint8Array.prototype),Object.setPrototypeOf(_,d),_.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function o(_){if(_>r)throw new RangeError('The value "'+_+'" is invalid for option "size"');const d=new Uint8Array(_);return Object.setPrototypeOf(d,a.prototype),d}function a(_,d,p){if(typeof _=="number"){if(typeof d=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(_)}return l(_,d,p)}a.poolSize=8192;function l(_,d,p){if(typeof _=="string")return m(_,d);if(ArrayBuffer.isView(_))return g(_);if(_==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof _);if(Xt(_,ArrayBuffer)||_&&Xt(_.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Xt(_,SharedArrayBuffer)||_&&Xt(_.buffer,SharedArrayBuffer)))return y(_,d,p);if(typeof _=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const b=_.valueOf&&_.valueOf();if(b!=null&&b!==_)return a.from(b,d,p);const S=x(_);if(S)return S;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof _[Symbol.toPrimitive]=="function")return a.from(_[Symbol.toPrimitive]("string"),d,p);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof _)}a.from=function(_,d,p){return l(_,d,p)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function h(_){if(typeof _!="number")throw new TypeError('"size" argument must be of type number');if(_<0)throw new RangeError('The value "'+_+'" is invalid for option "size"')}function c(_,d,p){return h(_),_<=0?o(_):d!==void 0?typeof p=="string"?o(_).fill(d,p):o(_).fill(d):o(_)}a.alloc=function(_,d,p){return c(_,d,p)};function u(_){return h(_),o(_<0?0:v(_)|0)}a.allocUnsafe=function(_){return u(_)},a.allocUnsafeSlow=function(_){return u(_)};function m(_,d){if((typeof d!="string"||d==="")&&(d="utf8"),!a.isEncoding(d))throw new TypeError("Unknown encoding: "+d);const p=T(_,d)|0;let b=o(p);const S=b.write(_,d);return S!==p&&(b=b.slice(0,S)),b}function f(_){const d=_.length<0?0:v(_.length)|0,p=o(d);for(let b=0;b<d;b+=1)p[b]=_[b]&255;return p}function g(_){if(Xt(_,Uint8Array)){const d=new Uint8Array(_);return y(d.buffer,d.byteOffset,d.byteLength)}return f(_)}function y(_,d,p){if(d<0||_.byteLength<d)throw new RangeError('"offset" is outside of buffer bounds');if(_.byteLength<d+(p||0))throw new RangeError('"length" is outside of buffer bounds');let b;return d===void 0&&p===void 0?b=new Uint8Array(_):p===void 0?b=new Uint8Array(_,d):b=new Uint8Array(_,d,p),Object.setPrototypeOf(b,a.prototype),b}function x(_){if(a.isBuffer(_)){const d=v(_.length)|0,p=o(d);return p.length===0||_.copy(p,0,0,d),p}if(_.length!==void 0)return typeof _.length!="number"||ki(_.length)?o(0):f(_);if(_.type==="Buffer"&&Array.isArray(_.data))return f(_.data)}function v(_){if(_>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return _|0}function E(_){return+_!=_&&(_=0),a.alloc(+_)}a.isBuffer=function(d){return d!=null&&d._isBuffer===!0&&d!==a.prototype},a.compare=function(d,p){if(Xt(d,Uint8Array)&&(d=a.from(d,d.offset,d.byteLength)),Xt(p,Uint8Array)&&(p=a.from(p,p.offset,p.byteLength)),!a.isBuffer(d)||!a.isBuffer(p))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(d===p)return 0;let b=d.length,S=p.length;for(let P=0,M=Math.min(b,S);P<M;++P)if(d[P]!==p[P]){b=d[P],S=p[P];break}return b<S?-1:S<b?1:0},a.isEncoding=function(d){switch(String(d).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(d,p){if(!Array.isArray(d))throw new TypeError('"list" argument must be an Array of Buffers');if(d.length===0)return a.alloc(0);let b;if(p===void 0)for(p=0,b=0;b<d.length;++b)p+=d[b].length;const S=a.allocUnsafe(p);let P=0;for(b=0;b<d.length;++b){let M=d[b];if(Xt(M,Uint8Array))P+M.length>S.length?(a.isBuffer(M)||(M=a.from(M)),M.copy(S,P)):Uint8Array.prototype.set.call(S,M,P);else if(a.isBuffer(M))M.copy(S,P);else throw new TypeError('"list" argument must be an Array of Buffers');P+=M.length}return S};function T(_,d){if(a.isBuffer(_))return _.length;if(ArrayBuffer.isView(_)||Xt(_,ArrayBuffer))return _.byteLength;if(typeof _!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof _);const p=_.length,b=arguments.length>2&&arguments[2]===!0;if(!b&&p===0)return 0;let S=!1;for(;;)switch(d){case"ascii":case"latin1":case"binary":return p;case"utf8":case"utf-8":return pe(_).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return p*2;case"hex":return p>>>1;case"base64":return Ie(_).length;default:if(S)return b?-1:pe(_).length;d=(""+d).toLowerCase(),S=!0}}a.byteLength=T;function C(_,d,p){let b=!1;if((d===void 0||d<0)&&(d=0),d>this.length||((p===void 0||p>this.length)&&(p=this.length),p<=0)||(p>>>=0,d>>>=0,p<=d))return"";for(_||(_="utf8");;)switch(_){case"hex":return D(this,d,p);case"utf8":case"utf-8":return H(this,d,p);case"ascii":return U(this,d,p);case"latin1":case"binary":return X(this,d,p);case"base64":return F(this,d,p);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return $(this,d,p);default:if(b)throw new TypeError("Unknown encoding: "+_);_=(_+"").toLowerCase(),b=!0}}a.prototype._isBuffer=!0;function R(_,d,p){const b=_[d];_[d]=_[p],_[p]=b}a.prototype.swap16=function(){const d=this.length;if(d%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let p=0;p<d;p+=2)R(this,p,p+1);return this},a.prototype.swap32=function(){const d=this.length;if(d%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let p=0;p<d;p+=4)R(this,p,p+3),R(this,p+1,p+2);return this},a.prototype.swap64=function(){const d=this.length;if(d%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let p=0;p<d;p+=8)R(this,p,p+7),R(this,p+1,p+6),R(this,p+2,p+5),R(this,p+3,p+4);return this},a.prototype.toString=function(){const d=this.length;return d===0?"":arguments.length===0?H(this,0,d):C.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(d){if(!a.isBuffer(d))throw new TypeError("Argument must be a Buffer");return this===d?!0:a.compare(this,d)===0},a.prototype.inspect=function(){let d="";const p=s.INSPECT_MAX_BYTES;return d=this.toString("hex",0,p).replace(/(.{2})/g,"$1 ").trim(),this.length>p&&(d+=" ... "),"<Buffer "+d+">"},i&&(a.prototype[i]=a.prototype.inspect),a.prototype.compare=function(d,p,b,S,P){if(Xt(d,Uint8Array)&&(d=a.from(d,d.offset,d.byteLength)),!a.isBuffer(d))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof d);if(p===void 0&&(p=0),b===void 0&&(b=d?d.length:0),S===void 0&&(S=0),P===void 0&&(P=this.length),p<0||b>d.length||S<0||P>this.length)throw new RangeError("out of range index");if(S>=P&&p>=b)return 0;if(S>=P)return-1;if(p>=b)return 1;if(p>>>=0,b>>>=0,S>>>=0,P>>>=0,this===d)return 0;let M=P-S,Q=b-p;const St=Math.min(M,Q),bt=this.slice(S,P),Ct=d.slice(p,b);for(let pt=0;pt<St;++pt)if(bt[pt]!==Ct[pt]){M=bt[pt],Q=Ct[pt];break}return M<Q?-1:Q<M?1:0};function A(_,d,p,b,S){if(_.length===0)return-1;if(typeof p=="string"?(b=p,p=0):p>2147483647?p=2147483647:p<-2147483648&&(p=-2147483648),p=+p,ki(p)&&(p=S?0:_.length-1),p<0&&(p=_.length+p),p>=_.length){if(S)return-1;p=_.length-1}else if(p<0)if(S)p=0;else return-1;if(typeof d=="string"&&(d=a.from(d,b)),a.isBuffer(d))return d.length===0?-1:I(_,d,p,b,S);if(typeof d=="number")return d=d&255,typeof Uint8Array.prototype.indexOf=="function"?S?Uint8Array.prototype.indexOf.call(_,d,p):Uint8Array.prototype.lastIndexOf.call(_,d,p):I(_,[d],p,b,S);throw new TypeError("val must be string, number or Buffer")}function I(_,d,p,b,S){let P=1,M=_.length,Q=d.length;if(b!==void 0&&(b=String(b).toLowerCase(),b==="ucs2"||b==="ucs-2"||b==="utf16le"||b==="utf-16le")){if(_.length<2||d.length<2)return-1;P=2,M/=2,Q/=2,p/=2}function St(Ct,pt){return P===1?Ct[pt]:Ct.readUInt16BE(pt*P)}let bt;if(S){let Ct=-1;for(bt=p;bt<M;bt++)if(St(_,bt)===St(d,Ct===-1?0:bt-Ct)){if(Ct===-1&&(Ct=bt),bt-Ct+1===Q)return Ct*P}else Ct!==-1&&(bt-=bt-Ct),Ct=-1}else for(p+Q>M&&(p=M-Q),bt=p;bt>=0;bt--){let Ct=!0;for(let pt=0;pt<Q;pt++)if(St(_,bt+pt)!==St(d,pt)){Ct=!1;break}if(Ct)return bt}return-1}a.prototype.includes=function(d,p,b){return this.indexOf(d,p,b)!==-1},a.prototype.indexOf=function(d,p,b){return A(this,d,p,b,!0)},a.prototype.lastIndexOf=function(d,p,b){return A(this,d,p,b,!1)};function N(_,d,p,b){p=Number(p)||0;const S=_.length-p;b?(b=Number(b),b>S&&(b=S)):b=S;const P=d.length;b>P/2&&(b=P/2);let M;for(M=0;M<b;++M){const Q=parseInt(d.substr(M*2,2),16);if(ki(Q))return M;_[p+M]=Q}return M}function B(_,d,p,b){return ne(pe(d,_.length-p),_,p,b)}function k(_,d,p,b){return ne(ri(d),_,p,b)}function O(_,d,p,b){return ne(Ie(d),_,p,b)}function L(_,d,p,b){return ne(Mi(d,_.length-p),_,p,b)}a.prototype.write=function(d,p,b,S){if(p===void 0)S="utf8",b=this.length,p=0;else if(b===void 0&&typeof p=="string")S=p,b=this.length,p=0;else if(isFinite(p))p=p>>>0,isFinite(b)?(b=b>>>0,S===void 0&&(S="utf8")):(S=b,b=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const P=this.length-p;if((b===void 0||b>P)&&(b=P),d.length>0&&(b<0||p<0)||p>this.length)throw new RangeError("Attempt to write outside buffer bounds");S||(S="utf8");let M=!1;for(;;)switch(S){case"hex":return N(this,d,p,b);case"utf8":case"utf-8":return B(this,d,p,b);case"ascii":case"latin1":case"binary":return k(this,d,p,b);case"base64":return O(this,d,p,b);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L(this,d,p,b);default:if(M)throw new TypeError("Unknown encoding: "+S);S=(""+S).toLowerCase(),M=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function F(_,d,p){return d===0&&p===_.length?t.fromByteArray(_):t.fromByteArray(_.slice(d,p))}function H(_,d,p){p=Math.min(_.length,p);const b=[];let S=d;for(;S<p;){const P=_[S];let M=null,Q=P>239?4:P>223?3:P>191?2:1;if(S+Q<=p){let St,bt,Ct,pt;switch(Q){case 1:P<128&&(M=P);break;case 2:St=_[S+1],(St&192)===128&&(pt=(P&31)<<6|St&63,pt>127&&(M=pt));break;case 3:St=_[S+1],bt=_[S+2],(St&192)===128&&(bt&192)===128&&(pt=(P&15)<<12|(St&63)<<6|bt&63,pt>2047&&(pt<55296||pt>57343)&&(M=pt));break;case 4:St=_[S+1],bt=_[S+2],Ct=_[S+3],(St&192)===128&&(bt&192)===128&&(Ct&192)===128&&(pt=(P&15)<<18|(St&63)<<12|(bt&63)<<6|Ct&63,pt>65535&&pt<1114112&&(M=pt))}}M===null?(M=65533,Q=1):M>65535&&(M-=65536,b.push(M>>>10&1023|55296),M=56320|M&1023),b.push(M),S+=Q}return G(b)}const at=4096;function G(_){const d=_.length;if(d<=at)return String.fromCharCode.apply(String,_);let p="",b=0;for(;b<d;)p+=String.fromCharCode.apply(String,_.slice(b,b+=at));return p}function U(_,d,p){let b="";p=Math.min(_.length,p);for(let S=d;S<p;++S)b+=String.fromCharCode(_[S]&127);return b}function X(_,d,p){let b="";p=Math.min(_.length,p);for(let S=d;S<p;++S)b+=String.fromCharCode(_[S]);return b}function D(_,d,p){const b=_.length;(!d||d<0)&&(d=0),(!p||p<0||p>b)&&(p=b);let S="";for(let P=d;P<p;++P)S+=Xs[_[P]];return S}function $(_,d,p){const b=_.slice(d,p);let S="";for(let P=0;P<b.length-1;P+=2)S+=String.fromCharCode(b[P]+b[P+1]*256);return S}a.prototype.slice=function(d,p){const b=this.length;d=~~d,p=p===void 0?b:~~p,d<0?(d+=b,d<0&&(d=0)):d>b&&(d=b),p<0?(p+=b,p<0&&(p=0)):p>b&&(p=b),p<d&&(p=d);const S=this.subarray(d,p);return Object.setPrototypeOf(S,a.prototype),S};function Y(_,d,p){if(_%1!==0||_<0)throw new RangeError("offset is not uint");if(_+d>p)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(d,p,b){d=d>>>0,p=p>>>0,b||Y(d,p,this.length);let S=this[d],P=1,M=0;for(;++M<p&&(P*=256);)S+=this[d+M]*P;return S},a.prototype.readUintBE=a.prototype.readUIntBE=function(d,p,b){d=d>>>0,p=p>>>0,b||Y(d,p,this.length);let S=this[d+--p],P=1;for(;p>0&&(P*=256);)S+=this[d+--p]*P;return S},a.prototype.readUint8=a.prototype.readUInt8=function(d,p){return d=d>>>0,p||Y(d,1,this.length),this[d]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(d,p){return d=d>>>0,p||Y(d,2,this.length),this[d]|this[d+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(d,p){return d=d>>>0,p||Y(d,2,this.length),this[d]<<8|this[d+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(d,p){return d=d>>>0,p||Y(d,4,this.length),(this[d]|this[d+1]<<8|this[d+2]<<16)+this[d+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(d,p){return d=d>>>0,p||Y(d,4,this.length),this[d]*16777216+(this[d+1]<<16|this[d+2]<<8|this[d+3])},a.prototype.readBigUInt64LE=oe(function(d){d=d>>>0,Gt(d,"offset");const p=this[d],b=this[d+7];(p===void 0||b===void 0)&&Ut(d,this.length-8);const S=p+this[++d]*2**8+this[++d]*2**16+this[++d]*2**24,P=this[++d]+this[++d]*2**8+this[++d]*2**16+b*2**24;return BigInt(S)+(BigInt(P)<<BigInt(32))}),a.prototype.readBigUInt64BE=oe(function(d){d=d>>>0,Gt(d,"offset");const p=this[d],b=this[d+7];(p===void 0||b===void 0)&&Ut(d,this.length-8);const S=p*2**24+this[++d]*2**16+this[++d]*2**8+this[++d],P=this[++d]*2**24+this[++d]*2**16+this[++d]*2**8+b;return(BigInt(S)<<BigInt(32))+BigInt(P)}),a.prototype.readIntLE=function(d,p,b){d=d>>>0,p=p>>>0,b||Y(d,p,this.length);let S=this[d],P=1,M=0;for(;++M<p&&(P*=256);)S+=this[d+M]*P;return P*=128,S>=P&&(S-=Math.pow(2,8*p)),S},a.prototype.readIntBE=function(d,p,b){d=d>>>0,p=p>>>0,b||Y(d,p,this.length);let S=p,P=1,M=this[d+--S];for(;S>0&&(P*=256);)M+=this[d+--S]*P;return P*=128,M>=P&&(M-=Math.pow(2,8*p)),M},a.prototype.readInt8=function(d,p){return d=d>>>0,p||Y(d,1,this.length),this[d]&128?(255-this[d]+1)*-1:this[d]},a.prototype.readInt16LE=function(d,p){d=d>>>0,p||Y(d,2,this.length);const b=this[d]|this[d+1]<<8;return b&32768?b|4294901760:b},a.prototype.readInt16BE=function(d,p){d=d>>>0,p||Y(d,2,this.length);const b=this[d+1]|this[d]<<8;return b&32768?b|4294901760:b},a.prototype.readInt32LE=function(d,p){return d=d>>>0,p||Y(d,4,this.length),this[d]|this[d+1]<<8|this[d+2]<<16|this[d+3]<<24},a.prototype.readInt32BE=function(d,p){return d=d>>>0,p||Y(d,4,this.length),this[d]<<24|this[d+1]<<16|this[d+2]<<8|this[d+3]},a.prototype.readBigInt64LE=oe(function(d){d=d>>>0,Gt(d,"offset");const p=this[d],b=this[d+7];(p===void 0||b===void 0)&&Ut(d,this.length-8);const S=this[d+4]+this[d+5]*2**8+this[d+6]*2**16+(b<<24);return(BigInt(S)<<BigInt(32))+BigInt(p+this[++d]*2**8+this[++d]*2**16+this[++d]*2**24)}),a.prototype.readBigInt64BE=oe(function(d){d=d>>>0,Gt(d,"offset");const p=this[d],b=this[d+7];(p===void 0||b===void 0)&&Ut(d,this.length-8);const S=(p<<24)+this[++d]*2**16+this[++d]*2**8+this[++d];return(BigInt(S)<<BigInt(32))+BigInt(this[++d]*2**24+this[++d]*2**16+this[++d]*2**8+b)}),a.prototype.readFloatLE=function(d,p){return d=d>>>0,p||Y(d,4,this.length),e.read(this,d,!0,23,4)},a.prototype.readFloatBE=function(d,p){return d=d>>>0,p||Y(d,4,this.length),e.read(this,d,!1,23,4)},a.prototype.readDoubleLE=function(d,p){return d=d>>>0,p||Y(d,8,this.length),e.read(this,d,!0,52,8)},a.prototype.readDoubleBE=function(d,p){return d=d>>>0,p||Y(d,8,this.length),e.read(this,d,!1,52,8)};function j(_,d,p,b,S,P){if(!a.isBuffer(_))throw new TypeError('"buffer" argument must be a Buffer instance');if(d>S||d<P)throw new RangeError('"value" argument is out of bounds');if(p+b>_.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(d,p,b,S){if(d=+d,p=p>>>0,b=b>>>0,!S){const Q=Math.pow(2,8*b)-1;j(this,d,p,b,Q,0)}let P=1,M=0;for(this[p]=d&255;++M<b&&(P*=256);)this[p+M]=d/P&255;return p+b},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(d,p,b,S){if(d=+d,p=p>>>0,b=b>>>0,!S){const Q=Math.pow(2,8*b)-1;j(this,d,p,b,Q,0)}let P=b-1,M=1;for(this[p+P]=d&255;--P>=0&&(M*=256);)this[p+P]=d/M&255;return p+b},a.prototype.writeUint8=a.prototype.writeUInt8=function(d,p,b){return d=+d,p=p>>>0,b||j(this,d,p,1,255,0),this[p]=d&255,p+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(d,p,b){return d=+d,p=p>>>0,b||j(this,d,p,2,65535,0),this[p]=d&255,this[p+1]=d>>>8,p+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(d,p,b){return d=+d,p=p>>>0,b||j(this,d,p,2,65535,0),this[p]=d>>>8,this[p+1]=d&255,p+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(d,p,b){return d=+d,p=p>>>0,b||j(this,d,p,4,4294967295,0),this[p+3]=d>>>24,this[p+2]=d>>>16,this[p+1]=d>>>8,this[p]=d&255,p+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(d,p,b){return d=+d,p=p>>>0,b||j(this,d,p,4,4294967295,0),this[p]=d>>>24,this[p+1]=d>>>16,this[p+2]=d>>>8,this[p+3]=d&255,p+4};function V(_,d,p,b,S){xt(d,b,S,_,p,7);let P=Number(d&BigInt(4294967295));_[p++]=P,P=P>>8,_[p++]=P,P=P>>8,_[p++]=P,P=P>>8,_[p++]=P;let M=Number(d>>BigInt(32)&BigInt(4294967295));return _[p++]=M,M=M>>8,_[p++]=M,M=M>>8,_[p++]=M,M=M>>8,_[p++]=M,p}function ot(_,d,p,b,S){xt(d,b,S,_,p,7);let P=Number(d&BigInt(4294967295));_[p+7]=P,P=P>>8,_[p+6]=P,P=P>>8,_[p+5]=P,P=P>>8,_[p+4]=P;let M=Number(d>>BigInt(32)&BigInt(4294967295));return _[p+3]=M,M=M>>8,_[p+2]=M,M=M>>8,_[p+1]=M,M=M>>8,_[p]=M,p+8}a.prototype.writeBigUInt64LE=oe(function(d,p=0){return V(this,d,p,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=oe(function(d,p=0){return ot(this,d,p,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(d,p,b,S){if(d=+d,p=p>>>0,!S){const St=Math.pow(2,8*b-1);j(this,d,p,b,St-1,-St)}let P=0,M=1,Q=0;for(this[p]=d&255;++P<b&&(M*=256);)d<0&&Q===0&&this[p+P-1]!==0&&(Q=1),this[p+P]=(d/M>>0)-Q&255;return p+b},a.prototype.writeIntBE=function(d,p,b,S){if(d=+d,p=p>>>0,!S){const St=Math.pow(2,8*b-1);j(this,d,p,b,St-1,-St)}let P=b-1,M=1,Q=0;for(this[p+P]=d&255;--P>=0&&(M*=256);)d<0&&Q===0&&this[p+P+1]!==0&&(Q=1),this[p+P]=(d/M>>0)-Q&255;return p+b},a.prototype.writeInt8=function(d,p,b){return d=+d,p=p>>>0,b||j(this,d,p,1,127,-128),d<0&&(d=255+d+1),this[p]=d&255,p+1},a.prototype.writeInt16LE=function(d,p,b){return d=+d,p=p>>>0,b||j(this,d,p,2,32767,-32768),this[p]=d&255,this[p+1]=d>>>8,p+2},a.prototype.writeInt16BE=function(d,p,b){return d=+d,p=p>>>0,b||j(this,d,p,2,32767,-32768),this[p]=d>>>8,this[p+1]=d&255,p+2},a.prototype.writeInt32LE=function(d,p,b){return d=+d,p=p>>>0,b||j(this,d,p,4,2147483647,-2147483648),this[p]=d&255,this[p+1]=d>>>8,this[p+2]=d>>>16,this[p+3]=d>>>24,p+4},a.prototype.writeInt32BE=function(d,p,b){return d=+d,p=p>>>0,b||j(this,d,p,4,2147483647,-2147483648),d<0&&(d=4294967295+d+1),this[p]=d>>>24,this[p+1]=d>>>16,this[p+2]=d>>>8,this[p+3]=d&255,p+4},a.prototype.writeBigInt64LE=oe(function(d,p=0){return V(this,d,p,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=oe(function(d,p=0){return ot(this,d,p,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function lt(_,d,p,b,S,P){if(p+b>_.length)throw new RangeError("Index out of range");if(p<0)throw new RangeError("Index out of range")}function gt(_,d,p,b,S){return d=+d,p=p>>>0,S||lt(_,d,p,4),e.write(_,d,p,b,23,4),p+4}a.prototype.writeFloatLE=function(d,p,b){return gt(this,d,p,!0,b)},a.prototype.writeFloatBE=function(d,p,b){return gt(this,d,p,!1,b)};function ht(_,d,p,b,S){return d=+d,p=p>>>0,S||lt(_,d,p,8),e.write(_,d,p,b,52,8),p+8}a.prototype.writeDoubleLE=function(d,p,b){return ht(this,d,p,!0,b)},a.prototype.writeDoubleBE=function(d,p,b){return ht(this,d,p,!1,b)},a.prototype.copy=function(d,p,b,S){if(!a.isBuffer(d))throw new TypeError("argument should be a Buffer");if(b||(b=0),!S&&S!==0&&(S=this.length),p>=d.length&&(p=d.length),p||(p=0),S>0&&S<b&&(S=b),S===b||d.length===0||this.length===0)return 0;if(p<0)throw new RangeError("targetStart out of bounds");if(b<0||b>=this.length)throw new RangeError("Index out of range");if(S<0)throw new RangeError("sourceEnd out of bounds");S>this.length&&(S=this.length),d.length-p<S-b&&(S=d.length-p+b);const P=S-b;return this===d&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(p,b,S):Uint8Array.prototype.set.call(d,this.subarray(b,S),p),P},a.prototype.fill=function(d,p,b,S){if(typeof d=="string"){if(typeof p=="string"?(S=p,p=0,b=this.length):typeof b=="string"&&(S=b,b=this.length),S!==void 0&&typeof S!="string")throw new TypeError("encoding must be a string");if(typeof S=="string"&&!a.isEncoding(S))throw new TypeError("Unknown encoding: "+S);if(d.length===1){const M=d.charCodeAt(0);(S==="utf8"&&M<128||S==="latin1")&&(d=M)}}else typeof d=="number"?d=d&255:typeof d=="boolean"&&(d=Number(d));if(p<0||this.length<p||this.length<b)throw new RangeError("Out of range index");if(b<=p)return this;p=p>>>0,b=b===void 0?this.length:b>>>0,d||(d=0);let P;if(typeof d=="number")for(P=p;P<b;++P)this[P]=d;else{const M=a.isBuffer(d)?d:a.from(d,S),Q=M.length;if(Q===0)throw new TypeError('The value "'+d+'" is invalid for argument "value"');for(P=0;P<b-p;++P)this[P+p]=M[P%Q]}return this};const _t={};function Z(_,d,p){_t[_]=class extends p{constructor(){super(),Object.defineProperty(this,"message",{value:d.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${_}]`,this.stack,delete this.name}get code(){return _}set code(S){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:S,writable:!0})}toString(){return`${this.name} [${_}]: ${this.message}`}}}Z("ERR_BUFFER_OUT_OF_BOUNDS",function(_){return _?`${_} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),Z("ERR_INVALID_ARG_TYPE",function(_,d){return`The "${_}" argument must be of type number. Received type ${typeof d}`},TypeError),Z("ERR_OUT_OF_RANGE",function(_,d,p){let b=`The value of "${_}" is out of range.`,S=p;return Number.isInteger(p)&&Math.abs(p)>2**32?S=Bt(String(p)):typeof p=="bigint"&&(S=String(p),(p>BigInt(2)**BigInt(32)||p<-(BigInt(2)**BigInt(32)))&&(S=Bt(S)),S+="n"),b+=` It must be ${d}. Received ${S}`,b},RangeError);function Bt(_){let d="",p=_.length;const b=_[0]==="-"?1:0;for(;p>=b+4;p-=3)d=`_${_.slice(p-3,p)}${d}`;return`${_.slice(0,p)}${d}`}function $t(_,d,p){Gt(d,"offset"),(_[d]===void 0||_[d+p]===void 0)&&Ut(d,_.length-(p+1))}function xt(_,d,p,b,S,P){if(_>p||_<d){const M=typeof d=="bigint"?"n":"";let Q;throw d===0||d===BigInt(0)?Q=`>= 0${M} and < 2${M} ** ${(P+1)*8}${M}`:Q=`>= -(2${M} ** ${(P+1)*8-1}${M}) and < 2 ** ${(P+1)*8-1}${M}`,new _t.ERR_OUT_OF_RANGE("value",Q,_)}$t(b,S,P)}function Gt(_,d){if(typeof _!="number")throw new _t.ERR_INVALID_ARG_TYPE(d,"number",_)}function Ut(_,d,p){throw Math.floor(_)!==_?(Gt(_,p),new _t.ERR_OUT_OF_RANGE("offset","an integer",_)):d<0?new _t.ERR_BUFFER_OUT_OF_BOUNDS:new _t.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${d}`,_)}const jt=/[^+/0-9A-Za-z-_]/g;function We(_){if(_=_.split("=")[0],_=_.trim().replace(jt,""),_.length<2)return"";for(;_.length%4!==0;)_=_+"=";return _}function pe(_,d){d=d||1/0;let p;const b=_.length;let S=null;const P=[];for(let M=0;M<b;++M){if(p=_.charCodeAt(M),p>55295&&p<57344){if(!S){if(p>56319){(d-=3)>-1&&P.push(239,191,189);continue}else if(M+1===b){(d-=3)>-1&&P.push(239,191,189);continue}S=p;continue}if(p<56320){(d-=3)>-1&&P.push(239,191,189),S=p;continue}p=(S-55296<<10|p-56320)+65536}else S&&(d-=3)>-1&&P.push(239,191,189);if(S=null,p<128){if((d-=1)<0)break;P.push(p)}else if(p<2048){if((d-=2)<0)break;P.push(p>>6|192,p&63|128)}else if(p<65536){if((d-=3)<0)break;P.push(p>>12|224,p>>6&63|128,p&63|128)}else if(p<1114112){if((d-=4)<0)break;P.push(p>>18|240,p>>12&63|128,p>>6&63|128,p&63|128)}else throw new Error("Invalid code point")}return P}function ri(_){const d=[];for(let p=0;p<_.length;++p)d.push(_.charCodeAt(p)&255);return d}function Mi(_,d){let p,b,S;const P=[];for(let M=0;M<_.length&&!((d-=2)<0);++M)p=_.charCodeAt(M),b=p>>8,S=p%256,P.push(S),P.push(b);return P}function Ie(_){return t.toByteArray(We(_))}function ne(_,d,p,b){let S;for(S=0;S<b&&!(S+p>=d.length||S>=_.length);++S)d[S+p]=_[S];return S}function Xt(_,d){return _ instanceof d||_!=null&&_.constructor!=null&&_.constructor.name!=null&&_.constructor.name===d.name}function ki(_){return _!==_}const Xs=(function(){const _="0123456789abcdef",d=new Array(256);for(let p=0;p<16;++p){const b=p*16;for(let S=0;S<16;++S)d[b+S]=_[p]+_[S]}return d})();function oe(_){return typeof BigInt>"u"?Ys:_}function Ys(){throw new Error("BigInt not supported")}})(Xn)),Xn}var zy=Vy();const $y="https://api.anam.ai",jy="/v1",Xc={client:"js-sdk",version:"4.12.0"};var Xy=function(s,t,e,i){function r(n){return n instanceof e?n:new e(function(o){o(n)})}return new(e||(e=Promise))(function(n,o){function a(c){try{h(i.next(c))}catch(u){o(u)}}function l(c){try{h(i.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):r(c.value).then(a,l)}h((i=i.apply(s,t||[])).next())})};const Yc="https://api.anam.ai",Yn="/v1";var Pe;(function(s){s.CLIENT_METRIC_MEASUREMENT_ERROR="client_error",s.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED="client_connection_closed",s.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED="client_connection_established",s.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT="client_session_attempt",s.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS="client_session_success"})(Pe||(Pe={}));let qn=Yc,qc=Yn,Ue,Kc=!1;const Yy=(s,t=Yn)=>{qn=s,qc=t},qy=s=>{Ue=s},Ky=s=>{Kc=s};let Le={sessionId:null,organizationId:null,attemptCorrelationId:null};const Pi=s=>{Le=Object.assign(Object.assign({},Le),s)},si=(s,t,e)=>Xy(void 0,void 0,void 0,function*(){if(!Kc)try{const i=Object.assign(Object.assign({},Xc),e);Le.sessionId&&(i.sessionId=Le.sessionId),Le.organizationId&&(i.organizationId=Le.organizationId),Le.attemptCorrelationId&&(i.attemptCorrelationId=Le.attemptCorrelationId);const r=`${qc}/metrics/client`;let n,o={"Content-Type":"application/json"};Ue!=null&&Ue.enabled&&(Ue!=null&&Ue.baseUrl)?(n=`${Ue.baseUrl}${r}`,o["X-Anam-Target-Url"]=`${qn}${r}`):n=`${qn}${r}`,yield fetch(n,{method:"POST",headers:o,body:JSON.stringify({name:s,value:t,tags:i})})}catch(i){console.error("Failed to send error metric:",i)}}),Zy=(s,t="console")=>{var e,i,r;const n={};s.forEach(u=>{n[u.type]||(n[u.type]=[]),n[u.type].push(u)});const o={issues:[]},a=((e=n["inbound-rtp"])===null||e===void 0?void 0:e.filter(u=>u.kind==="video"))||[];a.length>0&&(o.personaVideoStream=[],a.forEach(u=>{var m,f,g,y,x;const v={framesReceived:(m=u.framesReceived)!==null&&m!==void 0?m:"unknown",framesDropped:(f=u.framesDropped)!==null&&f!==void 0?f:"unknown",framesPerSecond:(g=u.framesPerSecond)!==null&&g!==void 0?g:"unknown",packetsReceived:(y=u.packetsReceived)!==null&&y!==void 0?y:"unknown",packetsLost:(x=u.packetsLost)!==null&&x!==void 0?x:"unknown",resolution:u.frameWidth&&u.frameHeight?`${u.frameWidth}x${u.frameHeight}`:void 0,jitter:u.jitter!==void 0?u.jitter:void 0};o.personaVideoStream.push(v)}));const l=((i=n["inbound-rtp"])===null||i===void 0?void 0:i.filter(u=>u.kind==="audio"))||[];l.length>0&&(o.personaAudioStream=[],l.forEach(u=>{var m,f,g;const y={packetsReceived:(m=u.packetsReceived)!==null&&m!==void 0?m:"unknown",packetsLost:(f=u.packetsLost)!==null&&f!==void 0?f:"unknown",audioLevel:(g=u.audioLevel)!==null&&g!==void 0?g:"unknown",jitter:u.jitter!==void 0?u.jitter:void 0,totalAudioEnergy:u.totalAudioEnergy!==void 0?u.totalAudioEnergy:void 0};o.personaAudioStream.push(y)}));const h=((r=n["outbound-rtp"])===null||r===void 0?void 0:r.filter(u=>u.kind==="audio"))||[];h.length>0&&(o.userAudioInput=[],h.forEach(u=>{var m,f;const g={packetsSent:(m=u.packetsSent)!==null&&m!==void 0?m:"unknown",retransmittedPackets:(f=u.retransmittedPacketsSent)!==null&&f!==void 0?f:void 0,avgPacketSendDelay:u.totalPacketSendDelay!==void 0?u.totalPacketSendDelay/(u.packetsSent||1)*1e3:void 0};o.userAudioInput.push(g)})),n.codec&&(o.codecs=[],n.codec.forEach(u=>{const m={status:u.payloadType?"Active":"Available",mimeType:u.mimeType||"Unknown",payloadType:u.payloadType||"N/A",clockRate:u.clockRate||void 0,channels:u.channels||void 0};o.codecs.push(m)})),n.transport&&(o.transportLayer=[],n.transport.forEach(u=>{const m={dtlsState:u.dtlsState||"unknown",iceState:u.iceState||"unknown",bytesSent:u.bytesSent||void 0,bytesReceived:u.bytesReceived||void 0};o.transportLayer.push(m)}));const c=[];if(a.forEach(u=>{typeof u.framesDropped=="number"&&u.framesDropped>0&&c.push(`Video: ${u.framesDropped} frames dropped`),typeof u.packetsLost=="number"&&u.packetsLost>0&&c.push(`Video: ${u.packetsLost} packets lost`),typeof u.framesPerSecond=="number"&&u.framesPerSecond<23&&c.push(`Video: Low frame rate (${u.framesPerSecond} fps)`)}),l.forEach(u=>{typeof u.packetsLost=="number"&&u.packetsLost>0&&c.push(`Audio: ${u.packetsLost} packets lost`),typeof u.jitter=="number"&&u.jitter>.1&&c.push(`Audio: High jitter (${(u.jitter*1e3).toFixed(1)}ms)`)}),o.issues=c,t==="json")return o;console.group("📊 WebRTC Session Statistics Report"),o.personaVideoStream&&o.personaVideoStream.length>0&&(console.group("📹 Persona Video Stream (Inbound)"),o.personaVideoStream.forEach(u=>{console.log(`Frames Received: ${u.framesReceived}`),console.log(`Frames Dropped: ${u.framesDropped}`),console.log(`Frames Per Second: ${u.framesPerSecond}`),console.log(`Packets Received: ${typeof u.packetsReceived=="number"?u.packetsReceived.toLocaleString():u.packetsReceived}`),console.log(`Packets Lost: ${u.packetsLost}`),u.resolution&&console.log(`Resolution: ${u.resolution}`),u.jitter!==void 0&&console.log(`Jitter: ${u.jitter.toFixed(5)}ms`)}),console.groupEnd()),o.personaAudioStream&&o.personaAudioStream.length>0&&(console.group("🔊 Persona Audio Stream (Inbound)"),o.personaAudioStream.forEach(u=>{console.log(`Packets Received: ${typeof u.packetsReceived=="number"?u.packetsReceived.toLocaleString():u.packetsReceived}`),console.log(`Packets Lost: ${u.packetsLost}`),console.log(`Audio Level: ${u.audioLevel}`),u.jitter!==void 0&&console.log(`Jitter: ${u.jitter.toFixed(5)}ms`),u.totalAudioEnergy!==void 0&&console.log(`Total Audio Energy: ${u.totalAudioEnergy.toFixed(6)}`)}),console.groupEnd()),o.userAudioInput&&o.userAudioInput.length>0&&(console.group("🎤 User Audio Input (Outbound)"),o.userAudioInput.forEach(u=>{console.log(`Packets Sent: ${typeof u.packetsSent=="number"?u.packetsSent.toLocaleString():u.packetsSent}`),u.retransmittedPackets&&console.log(`Retransmitted Packets: ${u.retransmittedPackets}`),u.avgPacketSendDelay!==void 0&&console.log(`Avg Packet Send Delay: ${u.avgPacketSendDelay.toFixed(5)}ms`)}),console.groupEnd()),o.codecs&&o.codecs.length>0&&(console.group("🔧 Codecs Used"),o.codecs.forEach(u=>{console.log(`${u.status} ${u.mimeType} - Payload Type: ${u.payloadType}`),u.clockRate&&console.log(` Clock Rate: ${u.clockRate}Hz`),u.channels&&console.log(` Channels: ${u.channels}`)}),console.groupEnd()),o.transportLayer&&o.transportLayer.length>0&&(console.group("🚚 Transport Layer"),o.transportLayer.forEach(u=>{console.log(`DTLS State: ${u.dtlsState}`),console.log(`ICE State: ${u.iceState}`),(u.bytesReceived||u.bytesSent)&&console.log(`Data Transfer (bytes) - Sent: ${(u.bytesSent||0).toLocaleString()}, Received: ${(u.bytesReceived||0).toLocaleString()}`)}),console.groupEnd()),o.issues.length>0?(console.group("⚠️ Potential Issues Detected"),o.issues.forEach(u=>console.warn(u)),console.groupEnd()):console.log("✅ No significant issues detected"),console.groupEnd()};var Dt;(function(s){s.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED="CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED",s.CLIENT_ERROR_CODE_SPEND_CAP_REACHED="CLIENT_ERROR_CODE_SPEND_CAP_REACHED",s.CLIENT_ERROR_CODE_VALIDATION_ERROR="CLIENT_ERROR_CODE_VALIDATION_ERROR",s.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR="CLIENT_ERROR_CODE_AUTHENTICATION_ERROR",s.CLIENT_ERROR_CODE_SERVER_ERROR="CLIENT_ERROR_CODE_SERVER_ERROR",s.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED="CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED",s.CLIENT_ERROR_CODE_SERVICE_BUSY="CLIENT_ERROR_CODE_SERVICE_BUSY",s.CLIENT_ERROR_CODE_NO_PLAN_FOUND="CLIENT_ERROR_CODE_NO_PLAN_FOUND",s.CLIENT_ERROR_CODE_UNKNOWN_ERROR="CLIENT_ERROR_CODE_UNKNOWN_ERROR",s.CLIENT_ERROR_CODE_CONFIGURATION_ERROR="CLIENT_ERROR_CODE_CONFIGURATION_ERROR"})(Dt||(Dt={}));class Rt extends Error{constructor(t,e,i=500,r){super(t),this.name="ClientError",this.code=e,this.statusCode=i,this.details=r,Object.setPrototypeOf(this,Rt.prototype),si(Pe.CLIENT_METRIC_MEASUREMENT_ERROR,e,{details:r,statusCode:i})}}function Zc(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substr(2,9)}function Jy(s){if(!(!s||!s.enabled)){if(!s.baseUrl)return"API Gateway baseUrl is required when enabled";try{const t=new URL(s.baseUrl);if(!["http:","https:","ws:","wss:"].includes(t.protocol))return`Invalid API Gateway baseUrl protocol: ${t.protocol}. Must be http:, https:, ws:, or wss:`}catch{return`Invalid API Gateway baseUrl: ${s.baseUrl}`}if(s.wsPath&&!s.wsPath.startsWith("/"))return"API Gateway wsPath must start with /"}}var Nt;(function(s){s.OFFER="offer",s.ANSWER="answer",s.ICE_CANDIDATE="icecandidate",s.END_SESSION="endsession",s.HEARTBEAT="heartbeat",s.WARNING="warning",s.TALK_STREAM_INTERRUPTED="talkinputstreaminterrupted",s.TALK_STREAM_INPUT="talkstream",s.SESSION_READY="sessionready",s.AGENT_AUDIO_INPUT="agentaudioinput",s.AGENT_AUDIO_INPUT_END="agentaudioinputend"})(Nt||(Nt={}));var fe;(function(s){s.SPEECH_TEXT="speechText",s.CLIENT_TOOL_EVENT="clientToolEvent",s.TOOL_CALL_STARTED_EVENT="toolCallStarted",s.TOOL_CALL_COMPLETED_EVENT="toolCallCompleted",s.TOOL_CALL_FAILED_EVENT="toolCallFailed",s.REASONING_TEXT="reasoningText",s.USER_SPEECH_STARTED="userSpeechStarted",s.USER_SPEECH_ENDED="userSpeechEnded"})(fe||(fe={}));var Fe;(function(s){s.PENDING="pending",s.GRANTED="granted",s.DENIED="denied",s.NOT_REQUESTED="not_requested"})(Fe||(Fe={}));var js;(function(s){s.USER="user",s.PERSONA="persona"})(js||(js={}));var et;(function(s){s.MESSAGE_HISTORY_UPDATED="MESSAGE_HISTORY_UPDATED",s.MESSAGE_STREAM_EVENT_RECEIVED="MESSAGE_STREAM_EVENT_RECEIVED",s.CONNECTION_ESTABLISHED="CONNECTION_ESTABLISHED",s.CONNECTION_CLOSED="CONNECTION_CLOSED",s.INPUT_AUDIO_STREAM_STARTED="INPUT_AUDIO_STREAM_STARTED",s.VIDEO_STREAM_STARTED="VIDEO_STREAM_STARTED",s.VIDEO_PLAY_STARTED="VIDEO_PLAY_STARTED",s.AUDIO_STREAM_STARTED="AUDIO_STREAM_STARTED",s.TALK_STREAM_INTERRUPTED="TALK_STREAM_INTERRUPTED",s.SESSION_READY="SESSION_READY",s.SERVER_WARNING="SERVER_WARNING",s.MIC_PERMISSION_PENDING="MIC_PERMISSION_PENDING",s.MIC_PERMISSION_GRANTED="MIC_PERMISSION_GRANTED",s.MIC_PERMISSION_DENIED="MIC_PERMISSION_DENIED",s.INPUT_AUDIO_DEVICE_CHANGED="INPUT_AUDIO_DEVICE_CHANGED",s.CLIENT_TOOL_EVENT_RECEIVED="CLIENT_TOOL_EVENT_RECEIVED",s.TOOL_CALL_STARTED="TOOL_CALL_STARTED",s.TOOL_CALL_COMPLETED="TOOL_CALL_COMPLETED",s.TOOL_CALL_FAILED="TOOL_CALL_FAILED",s.REASONING_HISTORY_UPDATED="REASONING_HISTORY_UPDATED",s.REASONING_STREAM_EVENT_RECEIVED="REASONING_STREAM_EVENT_RECEIVED",s.USER_SPEECH_STARTED="USER_SPEECH_STARTED",s.USER_SPEECH_ENDED="USER_SPEECH_ENDED"})(et||(et={}));var Pt;(function(s){s.WEB_SOCKET_OPEN="WEB_SOCKET_OPEN",s.SIGNAL_MESSAGE_RECEIVED="SIGNAL_MESSAGE_RECEIVED",s.WEBRTC_CHAT_MESSAGE_RECEIVED="WEBRTC_CHAT_MESSAGE_RECEIVED",s.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED="WEBRTC_CLIENT_TOOL_EVENT_RECEIVED",s.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED",s.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED",s.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED",s.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED="WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED"})(Pt||(Pt={}));var Ne;(function(s){s.NORMAL="CONNECTION_CLOSED_CODE_NORMAL",s.MICROPHONE_PERMISSION_DENIED="CONNECTION_CLOSED_CODE_MICROPHONE_PERMISSION_DENIED",s.SIGNALLING_CLIENT_CONNECTION_FAILURE="CONNECTION_CLOSED_CODE_SIGNALLING_CLIENT_CONNECTION_FAILURE",s.WEBRTC_FAILURE="CONNECTION_CLOSED_CODE_WEBRTC_FAILURE",s.SERVER_CLOSED_CONNECTION="CONNECTION_CLOSED_CODE_SERVER_CLOSED_CONNECTION"})(Ne||(Ne={}));class Qy{constructor(t,e){this.sequenceNumber=0,this.config=t,this.signallingClient=e}sendAudioChunk(t){const i={audioData:typeof t=="string"?t:this.arrayBufferToBase64(t),encoding:this.config.encoding,sampleRate:this.config.sampleRate,channels:this.config.channels,sequenceNumber:this.sequenceNumber++};this.signallingClient.sendAgentAudioInput(i)}endSequence(){this.signallingClient.sendAgentAudioInputEnd(),this.sequenceNumber=0}getSequenceNumber(){return this.sequenceNumber}getConfig(){return this.config}arrayBufferToBase64(t){const e=t instanceof Uint8Array?t:new Uint8Array(t),i=Array.from(e,r=>String.fromCharCode(r)).join("");return btoa(i)}}var Ii=function(s,t,e,i){function r(n){return n instanceof e?n:new e(function(o){o(n)})}return new(e||(e=Promise))(function(n,o){function a(c){try{h(i.next(c))}catch(u){o(u)}}function l(c){try{h(i.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):r(c.value).then(a,l)}h((i=i.apply(s,t||[])).next())})};const tx=5,ex=5;class ix{constructor(t,e,i,r,n){var o,a,l,h,c;if(this.stopSignal=!1,this.sendingBuffer=[],this.wsConnectionAttempts=0,this.socket=null,this.heartBeatIntervalRef=null,this.publicEventEmitter=i,this.internalEventEmitter=r,this.apiGatewayConfig=n,!t)throw new Error("Signalling Client: sessionId is required");this.sessionId=t;const{heartbeatIntervalSeconds:u,maxWsReconnectionAttempts:m,url:f}=e;if(this.heartbeatIntervalSeconds=u||tx,this.maxWsReconnectionAttempts=m||ex,!f.baseUrl)throw new Error("Signalling Client: baseUrl is required");if(!((o=this.apiGatewayConfig)===null||o===void 0)&&o.enabled&&(!((a=this.apiGatewayConfig)===null||a===void 0)&&a.baseUrl)){const g=new URL(this.apiGatewayConfig.baseUrl),y=(l=this.apiGatewayConfig.wsPath)!==null&&l!==void 0?l:"/ws";g.protocol=g.protocol.replace("http","ws"),g.pathname=y,this.url=g;const x=f.protocol||"https",v=x==="http"?"ws":"wss",E=`${x}://${f.baseUrl}`,T=(h=f.signallingPath)!==null&&h!==void 0?h:"/ws",C=new URL(E);C.protocol=v==="ws"?"ws:":"wss:",f.port&&(C.port=f.port),C.pathname=T,C.searchParams.append("session_id",t),this.url.searchParams.append("target_url",C.href)}else{const y=`${f.protocol||"https"}://${f.baseUrl}`;this.url=new URL(y),this.url.protocol=f.protocol==="http"?"ws:":"wss:",f.port&&(this.url.port=f.port),this.url.pathname=(c=f.signallingPath)!==null&&c!==void 0?c:"/ws",this.url.searchParams.append("session_id",t)}}stop(){this.stopSignal=!0,this.closeSocket()}connect(){return this.socket=new WebSocket(this.url.href),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.socket.onerror=this.onError.bind(this),this.socket}sendOffer(t){return Ii(this,void 0,void 0,function*(){const e={connectionDescription:t,userUid:this.sessionId},i={actionType:Nt.OFFER,sessionId:this.sessionId,payload:e};this.sendSignalMessage(i)})}sendIceCandidate(t){return Ii(this,void 0,void 0,function*(){const e={actionType:Nt.ICE_CANDIDATE,sessionId:this.sessionId,payload:t.toJSON()};this.sendSignalMessage(e)})}sendSignalMessage(t){var e;if(((e=this.socket)===null||e===void 0?void 0:e.readyState)===WebSocket.OPEN)try{this.socket.send(JSON.stringify(t))}catch(i){console.error("SignallingClient - sendSignalMessage: error sending message",i)}else this.sendingBuffer.push(t)}sendTalkMessage(t){return Ii(this,void 0,void 0,function*(){const e={actionType:Nt.TALK_STREAM_INPUT,sessionId:this.sessionId,payload:t};this.sendSignalMessage(e)})}sendAgentAudioInput(t){const e={actionType:Nt.AGENT_AUDIO_INPUT,sessionId:this.sessionId,payload:t};this.sendSignalMessage(e)}sendAgentAudioInputEnd(){const t={actionType:Nt.AGENT_AUDIO_INPUT_END,sessionId:this.sessionId,payload:{}};this.sendSignalMessage(t)}closeSocket(){this.socket&&(this.socket.close(),this.socket=null),this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null)}onOpen(){return Ii(this,void 0,void 0,function*(){if(!this.socket)throw new Error("SignallingClient - onOpen: socket is null");try{this.wsConnectionAttempts=0,this.flushSendingBuffer(),this.socket.onmessage=this.onMessage.bind(this),this.startSendingHeartBeats(),this.internalEventEmitter.emit(Pt.WEB_SOCKET_OPEN)}catch(t){console.error("SignallingClient - onOpen: error in onOpen",t),this.publicEventEmitter.emit(et.CONNECTION_CLOSED,Ne.SIGNALLING_CLIENT_CONNECTION_FAILURE)}})}onClose(){return Ii(this,void 0,void 0,function*(){this.wsConnectionAttempts+=1,!this.stopSignal&&(this.wsConnectionAttempts<=this.maxWsReconnectionAttempts?(this.socket=null,setTimeout(()=>{this.connect()},100*this.wsConnectionAttempts)):(this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null),this.publicEventEmitter.emit(et.CONNECTION_CLOSED,Ne.SIGNALLING_CLIENT_CONNECTION_FAILURE)))})}onError(t){this.stopSignal||console.error("SignallingClient - onError: ",t)}flushSendingBuffer(){const t=[];this.sendingBuffer.length>0&&this.sendingBuffer.forEach(e=>{var i;((i=this.socket)===null||i===void 0?void 0:i.readyState)===WebSocket.OPEN?this.socket.send(JSON.stringify(e)):t.push(e)}),this.sendingBuffer=t}onMessage(t){return Ii(this,void 0,void 0,function*(){const e=JSON.parse(t.data);this.internalEventEmitter.emit(Pt.SIGNAL_MESSAGE_RECEIVED,e)})}startSendingHeartBeats(){if(!this.socket)throw new Error("SignallingClient - startSendingHeartBeats: socket is null");this.heartBeatIntervalRef&&console.warn("SignallingClient - startSendingHeartBeats: heartbeat interval already set");const t=this.heartbeatIntervalSeconds*1e3,e={actionType:Nt.HEARTBEAT,sessionId:this.sessionId,payload:""},i=JSON.stringify(e);this.heartBeatIntervalRef=setInterval(()=>{var r;this.stopSignal||((r=this.socket)===null||r===void 0?void 0:r.readyState)===WebSocket.OPEN&&this.socket.send(i)},t)}}function sx(s){return"brainType"in s||"llmId"in s}var Jc=function(s,t,e,i){function r(n){return n instanceof e?n:new e(function(o){o(n)})}return new(e||(e=Promise))(function(n,o){function a(c){try{h(i.next(c))}catch(u){o(u)}}function l(c){try{h(i.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):r(c.value).then(a,l)}h((i=i.apply(s,t||[])).next())})};class rx{constructor(t,e,i){if(!t&&!e)throw new Error("Either sessionToken or apiKey must be provided");this.sessionToken=t||null,this.apiKey=e||null,this.baseUrl=(i==null?void 0:i.baseUrl)||$y,this.apiVersion=(i==null?void 0:i.apiVersion)||jy,this.apiGatewayConfig=(i==null?void 0:i.apiGateway)||void 0}buildGatewayUrlAndHeaders(t,e){var i,r;if(!((i=this.apiGatewayConfig)===null||i===void 0)&&i.enabled&&(!((r=this.apiGatewayConfig)===null||r===void 0)&&r.baseUrl)){const n=`${this.apiGatewayConfig.baseUrl}${t}`,o=new URL(`${this.baseUrl}${t}`),a=Object.assign(Object.assign({},e),{"X-Anam-Target-Url":o.href});return{url:n,headers:a}}else return{url:`${this.baseUrl}${t}`,headers:e}}startSession(t,e){return Jc(this,void 0,void 0,function*(){if(!this.sessionToken){if(!t)throw new Rt("Persona configuration must be provided when using apiKey",Dt.CLIENT_ERROR_CODE_VALIDATION_ERROR,400);this.sessionToken=yield this.unsafe_getSessionToken(t)}t&&"brainType"in t&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");try{const i=`${this.apiVersion}/engine/session`,{url:r,headers:n}=this.buildGatewayUrlAndHeaders(i,{"Content-Type":"application/json",Authorization:`Bearer ${this.sessionToken}`}),o=yield fetch(r,{method:"POST",headers:n,body:JSON.stringify({personaConfig:t,sessionOptions:e,clientMetadata:Xc})}),a=yield o.json(),l=a.error;switch(o.status){case 200:case 201:return a;case 400:throw new Rt("Invalid request to start session",Dt.CLIENT_ERROR_CODE_VALIDATION_ERROR,400,{cause:a.message});case 401:throw new Rt("Authentication failed when starting session",Dt.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,401,{cause:a.message});case 402:throw new Rt("Please sign up for a plan to start a session",Dt.CLIENT_ERROR_CODE_NO_PLAN_FOUND,402,{cause:a.message});case 403:throw new Rt("Authentication failed when starting session",Dt.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,403,{cause:a.message});case 429:throw l==="Concurrent session limit reached"?new Rt("Concurrency limit reached, please upgrade your plan",Dt.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED,429,{cause:a.message}):l==="Spend cap reached"?new Rt("Spend cap reached, please upgrade your plan",Dt.CLIENT_ERROR_CODE_SPEND_CAP_REACHED,429,{cause:a.message}):new Rt("Usage limit reached, please upgrade your plan",Dt.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED,429,{cause:a.message});case 503:throw new Rt("There are no available personas, please try again later",Dt.CLIENT_ERROR_CODE_SERVICE_BUSY,503,{cause:a.message});default:throw new Rt("Unknown error when starting session",Dt.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:a.message})}}catch(i){throw i instanceof Rt?i:new Rt("Failed to start session",Dt.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:i instanceof Error?i.message:String(i)})}})}unsafe_getSessionToken(t){return Jc(this,void 0,void 0,function*(){if(console.warn("Using unsecure method. This method should not be used in production."),!this.apiKey)throw new Error("No apiKey provided");t&&"brainType"in t&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");let e={clientLabel:"js-sdk-api-key"};sx(t)&&(e=Object.assign(Object.assign({},e),{personaConfig:t}));try{const i=`${this.apiVersion}/auth/session-token`,{url:r,headers:n}=this.buildGatewayUrlAndHeaders(i,{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`});return(yield(yield fetch(r,{method:"POST",headers:n,body:JSON.stringify(e)})).json()).sessionToken}catch{throw new Error("Failed to get session token")}})}getApiUrl(){return`${this.baseUrl}${this.apiVersion}`}}var nx=function(s,t,e,i){function r(n){return n instanceof e?n:new e(function(o){o(n)})}return new(e||(e=Promise))(function(n,o){function a(c){try{h(i.next(c))}catch(u){o(u)}}function l(c){try{h(i.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):r(c.value).then(a,l)}h((i=i.apply(s,t||[])).next())})};class ox{constructor(t,e,i){this.baseUrl=t,this.sessionId=e,this.apiGatewayConfig=i}sendTalkCommand(t){return nx(this,void 0,void 0,function*(){var e,i;try{let r,n={"Content-Type":"application/json"};const o="/talk",a=`?session_id=${this.sessionId}`;if(!((e=this.apiGatewayConfig)===null||e===void 0)&&e.enabled&&(!((i=this.apiGatewayConfig)===null||i===void 0)&&i.baseUrl)){r=`${this.apiGatewayConfig.baseUrl}${o}${a}`;const h=new URL(`${this.baseUrl}${o}${a}`);n["X-Anam-Target-Url"]=h.href}else r=`${this.baseUrl}${o}${a}`;const l=yield fetch(r,{method:"POST",headers:n,body:JSON.stringify({content:t})});if(!l.ok)throw new Error(`Failed to send talk command: ${l.status} ${l.statusText}`)}catch(r){throw console.error(r),new Error("EngineApiRestClient - sendTalkCommand: Failed to send talk command")}})}}class ax{constructor(){this.listeners={}}addListener(t,e){this.listeners[t]||(this.listeners[t]=new Set),this.listeners[t].add(e)}removeListener(t,e){this.listeners[t]&&this.listeners[t].delete(e)}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach(i=>{i(...e)})}}class lx{constructor(t,e){this.messages=[],this.publicEventEmitter=t,this.internalEventEmitter=e,this.internalEventEmitter.addListener(Pt.WEBRTC_CHAT_MESSAGE_RECEIVED,this.processWebRtcTextMessageEvent.bind(this))}webRtcTextMessageEventToMessageStreamEvent(t){return{id:`${t.role}::${t.message_id}`,content:t.content,role:t.role,endOfSpeech:t.end_of_speech,interrupted:t.interrupted}}processUserMessage(t){const e={id:t.id,content:t.content,role:t.role};this.messages.push(e)}processPersonaMessage(t){const e={id:t.id,content:t.content,role:t.role,interrupted:t.interrupted},i=this.messages.findIndex(r=>r.id===e.id);if(i!==-1){const r=this.messages[i];this.messages[i]=Object.assign(Object.assign({},r),{content:r.content+e.content,interrupted:r.interrupted||e.interrupted})}else this.messages.push(e)}processWebRtcTextMessageEvent(t){const e=this.webRtcTextMessageEventToMessageStreamEvent(t);switch(this.publicEventEmitter.emit(et.MESSAGE_STREAM_EVENT_RECEIVED,e),e.role){case js.USER:this.processUserMessage(e);break;case js.PERSONA:this.processPersonaMessage(e);break}e.endOfSpeech&&this.publicEventEmitter.emit(et.MESSAGE_HISTORY_UPDATED,this.messages)}}class hx{constructor(){this.listeners={}}addListener(t,e){this.listeners[t]||(this.listeners[t]=new Set),this.listeners[t].add(e)}removeListener(t,e){this.listeners[t]&&this.listeners[t].delete(e)}emit(t,...e){if(t===et.CONNECTION_ESTABLISHED&&si(Pe.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED,"1"),t===et.CONNECTION_CLOSED){const[i,r]=e;si(Pe.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED,i,r?{details:r}:void 0)}this.listeners[t]&&this.listeners[t].forEach(i=>{i(...e)})}}var Wt;(function(s){s[s.UNSTARTED=0]="UNSTARTED",s[s.STREAMING=1]="STREAMING",s[s.INTERRUPTED=2]="INTERRUPTED",s[s.ENDED=3]="ENDED"})(Wt||(Wt={}));var Kn=function(s,t,e,i){function r(n){return n instanceof e?n:new e(function(o){o(n)})}return new(e||(e=Promise))(function(n,o){function a(c){try{h(i.next(c))}catch(u){o(u)}}function l(c){try{h(i.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):r(c.value).then(a,l)}h((i=i.apply(s,t||[])).next())})};class cx{constructor(t,e,i){this.state=Wt.UNSTARTED,this.correlationId=t,this.internalEventEmitter=e,this.signallingClient=i,this.internalEventEmitter.addListener(Pt.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onDeactivate(){this.internalEventEmitter.removeListener(Pt.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onSignalMessage(t){return Kn(this,void 0,void 0,function*(){t.actionType===Nt.TALK_STREAM_INTERRUPTED&&t.payload.correlationId===this.correlationId&&(this.state=Wt.INTERRUPTED,this.onDeactivate())})}endMessage(){return Kn(this,void 0,void 0,function*(){if(this.state===Wt.ENDED){console.warn("Talk stream is already ended via end of speech. No need to call endMessage.");return}if(this.state!==Wt.STREAMING){console.warn("Talk stream is not active state: "+this.state);return}const t={content:"",startOfSpeech:!1,endOfSpeech:!0,correlationId:this.correlationId};yield this.signallingClient.sendTalkMessage(t),this.state=Wt.ENDED,this.onDeactivate()})}streamMessageChunk(t,e){return Kn(this,void 0,void 0,function*(){if(this.state!==Wt.STREAMING&&this.state!==Wt.UNSTARTED)throw new Error("Talk stream is not in an active state: "+this.state);const i={content:t,startOfSpeech:this.state===Wt.UNSTARTED,endOfSpeech:e,correlationId:this.correlationId};this.state=e?Wt.ENDED:Wt.STREAMING,this.state===Wt.ENDED&&this.onDeactivate(),yield this.signallingClient.sendTalkMessage(i)})}getCorrelationId(){return this.correlationId}isActive(){return this.state===Wt.STREAMING||this.state===Wt.UNSTARTED}getState(){return this.state}}var Zn=function(s,t,e,i){function r(n){return n instanceof e?n:new e(function(o){o(n)})}return new(e||(e=Promise))(function(n,o){function a(c){try{h(i.next(c))}catch(u){o(u)}}function l(c){try{h(i.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):r(c.value).then(a,l)}h((i=i.apply(s,t||[])).next())})};const Qc=(s,t)=>{if(isNaN(s)||isNaN(t))return 0;const e=t-s;return e>0?e:0};class tu{constructor(t){this.handlers=Object.create(null),this.pendingCalls=Object.create(null),this.publicEventEmitter=t}clearPendingCalls(){this.pendingCalls=Object.create(null)}registerHandler(t,e){return this.handlers[t]=e,()=>{delete this.handlers[t]}}processToolCallStartedEvent(t){return Zn(this,void 0,void 0,function*(){const{tool_name:e,timestamp:i}=t,r=this.WebRTCToolCallStartedEventToToolCallStartedPayload(t),n=new Date(i);if(this.pendingCalls[t.tool_call_id]={payload:r,timestamp:n.getTime()},!(e in this.handlers))return;const o=this.handlers[e];if(o.onStart)try{let a=yield o.onStart(r);if(t.tool_type==="client"){yield this.processToolCallCompletedEvent(Object.assign(Object.assign({},t),{result:a,timestamp:new Date().toISOString()}));return}}catch(a){a instanceof Error?yield this.processToolCallFailedEvent(Object.assign(Object.assign({},t),{error_message:`Error in onStart handler: ${a.message}`,timestamp:new Date().toISOString()})):yield this.processToolCallFailedEvent(Object.assign(Object.assign({},t),{error_message:`Error in onStart handler: ${String(a)}`,timestamp:new Date().toISOString()}));return}})}processToolCallCompletedEvent(t){return Zn(this,void 0,void 0,function*(){const{tool_name:e,tool_call_id:i,timestamp:r}=t,n=this.webRTCToolCallCompletedEventToToolCallCompletedPayload(t);if(i in this.pendingCalls&&delete this.pendingCalls[i],!(e in this.handlers))return;const o=this.handlers[e];if(o.onComplete){t.tool_type==="client"&&this.publicEventEmitter.emit(et.TOOL_CALL_COMPLETED,n);try{yield o.onComplete(n)}catch(a){console.error(`Error in onComplete handler for tool ${e}:`,a);return}}})}processToolCallFailedEvent(t){return Zn(this,void 0,void 0,function*(){const{tool_name:e,tool_call_id:i,timestamp:r}=t,n=this.webRTCToolCallFailedEventToToolCallFailedPayload(t);if(i in this.pendingCalls&&delete this.pendingCalls[i],!(e in this.handlers))return;const o=this.handlers[e];if(o.onFail){t.tool_type==="client"&&this.publicEventEmitter.emit(et.TOOL_CALL_FAILED,n);try{yield o.onFail(n)}catch(a){console.error(`Error in onFail handler for tool ${e}:`,a);return}}})}static WebRTCClientToolEventToClientToolEvent(t){return{eventUid:t.event_uid,sessionId:t.session_id,eventName:t.event_name,eventData:t.event_data,timestamp:t.timestamp,timestampUserAction:t.timestamp_user_action,userActionCorrelationId:t.user_action_correlation_id}}static WebRTCToolCallStartedEventToClientToolEvent(t){return{eventUid:t.event_uid,sessionId:t.session_id,eventName:t.tool_name,eventData:t.arguments,timestamp:t.timestamp,timestampUserAction:t.timestamp_user_action,userActionCorrelationId:t.user_action_correlation_id}}WebRTCToolCallStartedEventToToolCallStartedPayload(t){return{eventUid:t.event_uid,toolCallId:t.tool_call_id,toolName:t.tool_name,toolType:t.tool_type,toolSubtype:t.tool_subtype,arguments:t.arguments,timestamp:t.timestamp,timestampUserAction:t.timestamp_user_action,userActionCorrelationId:t.user_action_correlation_id}}webRTCToolCallCompletedEventToToolCallCompletedPayload(t){const e=new Date(t.timestamp),i=this.pendingCalls[t.tool_call_id],r=i?Qc(i.timestamp,e.getTime()):0;return{eventUid:t.event_uid,toolCallId:t.tool_call_id,toolName:t.tool_name,toolType:t.tool_type,toolSubtype:t.tool_subtype,result:t.result,executionTime:r>0?r:0,timestamp:t.timestamp,documentsAccessed:t.documents_accessed,timestampUserAction:t.timestamp_user_action,userActionCorrelationId:t.user_action_correlation_id}}webRTCToolCallFailedEventToToolCallFailedPayload(t){const e=new Date(t.timestamp),i=this.pendingCalls[t.tool_call_id],r=i?Qc(i.timestamp,e.getTime()):0;return{eventUid:t.event_uid,toolCallId:t.tool_call_id,toolName:t.tool_name,toolType:t.tool_type,toolSubtype:t.tool_subtype,errorMessage:t.error_message,executionTime:r>0?r:0,timestamp:t.timestamp,timestampUserAction:t.timestamp_user_action,userActionCorrelationId:t.user_action_correlation_id}}}var qt=function(s,t,e,i){function r(n){return n instanceof e?n:new e(function(o){o(n)})}return new(e||(e=Promise))(function(n,o){function a(c){try{h(i.next(c))}catch(u){o(u)}}function l(c){try{h(i.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):r(c.value).then(a,l)}h((i=i.apply(s,t||[])).next())})};const ux=15e3,dx=5e3,fx=2;class px{constructor(t,e,i,r,n){var o,a,l,h;this.peerConnection=null,this.connectionReceivedAnswer=!1,this.remoteIceCandidateBuffer=[],this.inputAudioStream=null,this.dataChannel=null,this.videoElement=null,this.videoStream=null,this.audioStream=null,this.inputAudioState={isMuted:!1,permissionState:Fe.NOT_REQUESTED},this.successMetricPoller=null,this.successMetricFired=!1,this.showPeerConnectionStatsReport=!1,this.peerConnectionStatsReportOutputFormat="console",this.statsCollectionInterval=null,this.agentAudioInputStream=null,this.publicEventEmitter=i,this.internalEventEmitter=r,this.toolCallManager=n,this.apiGatewayConfig=e.apiGateway;const{inputAudio:c}=e;this.inputAudioState=c.inputAudioState,e.inputAudio.userProvidedMediaStream&&(this.inputAudioStream=e.inputAudio.userProvidedMediaStream),this.disableInputAudio=e.inputAudio.disableInputAudio===!0,this.internalEventEmitter.addListener(Pt.WEB_SOCKET_OPEN,this.onSignallingClientConnected.bind(this)),this.internalEventEmitter.addListener(Pt.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this)),this.internalEventEmitter.addListener(Pt.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,this.toolCallManager.processToolCallStartedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(Pt.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,this.toolCallManager.processToolCallCompletedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(Pt.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,this.toolCallManager.processToolCallFailedEvent.bind(this.toolCallManager)),this.iceServers=e.iceServers,this.signallingClient=new ix(t,e.signalling,this.publicEventEmitter,this.internalEventEmitter,this.apiGatewayConfig),this.engineApiRestClient=new ox(e.engine.baseUrl,t,this.apiGatewayConfig),this.audioDeviceId=e.inputAudio.audioDeviceId,this.showPeerConnectionStatsReport=(a=(o=e.metrics)===null||o===void 0?void 0:o.showPeerConnectionStatsReport)!==null&&a!==void 0?a:!1,this.peerConnectionStatsReportOutputFormat=(h=(l=e.metrics)===null||l===void 0?void 0:l.peerConnectionStatsReportOutputFormat)!==null&&h!==void 0?h:"console"}onInputAudioStateChange(t,e){t.isMuted!==e.isMuted&&(e.isMuted?this.muteAllAudioTracks():this.unmuteAllAudioTracks())}muteAllAudioTracks(){var t;(t=this.inputAudioStream)===null||t===void 0||t.getAudioTracks().forEach(e=>{e.enabled=!1})}unmuteAllAudioTracks(){var t;(t=this.inputAudioStream)===null||t===void 0||t.getAudioTracks().forEach(e=>{e.enabled=!0})}startStatsCollection(){this.statsCollectionInterval||(this.statsCollectionInterval=setInterval(()=>qt(this,void 0,void 0,function*(){if(!(!this.peerConnection||!this.dataChannel||this.dataChannel.readyState!=="open"))try{const t=yield this.peerConnection.getStats();this.sendClientSideMetrics(t)}catch(t){console.error("Failed to collect and send stats:",t)}}),dx))}sendClientSideMetrics(t){t.forEach(e=>{if(e.type==="inbound-rtp"){const i={message_type:"remote_rtp_stats",data:e};this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(JSON.stringify(i))}})}startSuccessMetricPolling(){if(this.successMetricPoller||this.successMetricFired)return;const t=setTimeout(()=>{this.successMetricPoller&&(console.warn("No video frames received, there is a problem with the connection."),clearInterval(this.successMetricPoller),this.successMetricPoller=null)},ux);this.successMetricPoller=setInterval(()=>qt(this,void 0,void 0,function*(){if(!this.peerConnection||this.successMetricFired){this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(t);return}try{const e=yield this.peerConnection.getStats();let i=!1,r=null;e.forEach(n=>{n.type==="inbound-rtp"&&n.kind==="video"&&(n.framesDecoded!==void 0&&n.framesDecoded>0?(i=!0,r="framesDecoded"):n.framesReceived!==void 0&&n.framesReceived>0?(i=!0,r="framesReceived"):n.bytesReceived>0&&n.packetsReceived>0&&n.bytesReceived>1e5&&(i=!0,r="bytesReceived"))}),i&&!this.successMetricFired&&(this.successMetricFired=!0,si(Pe.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",r?{detectionMethod:r}:void 0),this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(t),this.successMetricPoller=null)}catch{}}),500)}muteInputAudio(){const t=this.inputAudioState,e=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0});return this.inputAudioState=e,this.onInputAudioStateChange(t,e),this.inputAudioState}unmuteInputAudio(){const t=this.inputAudioState,e=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1});return this.inputAudioState=e,this.onInputAudioStateChange(t,e),this.inputAudioState}getInputAudioState(){return this.inputAudioState}getPeerConnection(){return this.peerConnection}changeAudioInputDevice(t){return qt(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - changeAudioInputDevice: peer connection is not initialized. Start streaming first.");if(t==null)throw new Error("StreamingClient - changeAudioInputDevice: deviceId is required");const e=this.inputAudioState.isMuted;try{this.inputAudioStream&&this.inputAudioStream.getAudioTracks().forEach(r=>{r.stop()});const i={echoCancellation:!0,deviceId:{exact:t}};this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:i}),this.audioDeviceId=t,yield this.setupAudioTrack(),e&&this.muteAllAudioTracks(),this.publicEventEmitter.emit(et.INPUT_AUDIO_DEVICE_CHANGED,t)}catch(i){throw console.error("Failed to change audio input device:",i),new Error(`StreamingClient - changeAudioInputDevice: ${i instanceof Error?i.message:String(i)}`)}})}getInputAudioStream(){return this.inputAudioStream}getVideoStream(){return this.videoStream}getAudioStream(){return this.audioStream}sendDataMessage(t){this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(t)}setMediaStreamTargetById(t){if(t){const e=document.getElementById(t);if(!e)throw new Error(`StreamingClient: video element with id ${t} not found`);this.videoElement=e}}startConnection(){try{if(this.peerConnection){console.error("StreamingClient - startConnection: peer connection already exists");return}this.signallingClient.connect()}catch(t){console.error("StreamingClient - startConnection: error",t),this.handleWebrtcFailure(t)}}stopConnection(){return qt(this,void 0,void 0,function*(){yield this.shutdown()})}sendTalkCommand(t){return qt(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - sendTalkCommand: peer connection is null");yield this.engineApiRestClient.sendTalkCommand(t)})}startTalkMessageStream(t){return t||(t=Math.random().toString(36).substring(2,15)),new cx(t,this.internalEventEmitter,this.signallingClient)}createAgentAudioInputStream(t){return this.agentAudioInputStream=new Qy(t,this.signallingClient),this.agentAudioInputStream}getAgentAudioInputStream(){return this.agentAudioInputStream}initPeerConnection(){return qt(this,void 0,void 0,function*(){this.peerConnection=new RTCPeerConnection({iceServers:this.iceServers,iceCandidatePoolSize:fx}),this.peerConnection.onicecandidate=this.onIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onIceConnectionStateChange.bind(this),this.peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this.peerConnection.addEventListener("track",this.onTrackEventHandler.bind(this)),yield this.setupDataChannels(),this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.disableInputAudio?this.peerConnection.addTransceiver("audio",{direction:"recvonly"}):(this.peerConnection.addTransceiver("audio",{direction:"sendrecv"}),this.inputAudioStream?yield this.setupAudioTrack():this.requestMicrophonePermissionAsync().catch(t=>{console.error("Async microphone permission request failed:",t)}))})}onSignalMessage(t){return qt(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - onSignalMessage: peerConnection is not initialized");return}switch(t.actionType){case Nt.ANSWER:const e=t.payload;yield this.peerConnection.setRemoteDescription(e),this.connectionReceivedAnswer=!0,this.flushRemoteIceCandidateBuffer();break;case Nt.ICE_CANDIDATE:const i=t.payload,r=new RTCIceCandidate(i);this.connectionReceivedAnswer?yield this.peerConnection.addIceCandidate(r):this.remoteIceCandidateBuffer.push(r);break;case Nt.END_SESSION:const n=t.payload;this.publicEventEmitter.emit(et.CONNECTION_CLOSED,Ne.SERVER_CLOSED_CONNECTION,n),this.shutdown();break;case Nt.WARNING:const o=t.payload;console.warn("Warning received from server: "+o),this.publicEventEmitter.emit(et.SERVER_WARNING,o);break;case Nt.TALK_STREAM_INTERRUPTED:const a=t.payload;this.publicEventEmitter.emit(et.TALK_STREAM_INTERRUPTED,a.correlationId);break;case Nt.SESSION_READY:const l=t.sessionId;this.publicEventEmitter.emit(et.SESSION_READY,l);break;case Nt.HEARTBEAT:break;default:console.warn("StreamingClient - onSignalMessage: unknown signal message action type. Is your anam-sdk version up to date?",t)}})}onSignallingClientConnected(){return qt(this,void 0,void 0,function*(){if(!this.peerConnection)try{yield this.initPeerConnectionAndSendOffer()}catch(t){console.error("StreamingClient - onSignallingClientConnected: Error initializing peer connection",t),this.handleWebrtcFailure(t)}})}flushRemoteIceCandidateBuffer(){this.remoteIceCandidateBuffer.forEach(t=>{var e;(e=this.peerConnection)===null||e===void 0||e.addIceCandidate(t)}),this.remoteIceCandidateBuffer=[]}onIceCandidate(t){t.candidate&&this.signallingClient.sendIceCandidate(t.candidate)}onIceConnectionStateChange(){var t,e;(((t=this.peerConnection)===null||t===void 0?void 0:t.iceConnectionState)==="connected"||((e=this.peerConnection)===null||e===void 0?void 0:e.iceConnectionState)==="completed")&&(this.publicEventEmitter.emit(et.CONNECTION_ESTABLISHED),this.startStatsCollection())}onConnectionStateChange(){var t;((t=this.peerConnection)===null||t===void 0?void 0:t.connectionState)==="closed"&&(console.error("StreamingClient - onConnectionStateChange: Connection closed"),this.handleWebrtcFailure("The connection to our servers was lost. Please try again."))}handleWebrtcFailure(t){console.error({message:"StreamingClient - handleWebrtcFailure: ",err:t}),t.name==="NotAllowedError"&&t.message==="Permission denied"?this.publicEventEmitter.emit(et.CONNECTION_CLOSED,Ne.MICROPHONE_PERMISSION_DENIED):this.publicEventEmitter.emit(et.CONNECTION_CLOSED,Ne.WEBRTC_FAILURE);try{this.stopConnection()}catch(e){console.error("StreamingClient - handleWebrtcFailure: error stopping connection",e)}}onTrackEventHandler(t){if(t.track.kind==="video"){if(this.startSuccessMetricPolling(),this.videoStream=t.streams[0],this.publicEventEmitter.emit(et.VIDEO_STREAM_STARTED,this.videoStream),this.videoElement){this.videoElement.srcObject=this.videoStream;const e=this.videoElement.requestVideoFrameCallback(()=>{var i;(i=this.videoElement)===null||i===void 0||i.cancelVideoFrameCallback(e),this.publicEventEmitter.emit(et.VIDEO_PLAY_STARTED),this.successMetricFired||(this.successMetricFired=!0,si(Pe.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",{detectionMethod:"videoElement"}))})}}else t.track.kind==="audio"&&(this.audioStream=t.streams[0],this.publicEventEmitter.emit(et.AUDIO_STREAM_STARTED,this.audioStream))}setupDataChannels(){return qt(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - setupDataChannels: peer connection is not initialized");return}if(!this.disableInputAudio&&this.inputAudioStream&&!this.inputAudioStream.getAudioTracks().length)throw new Error("StreamingClient - setupDataChannels: user provided stream does not have audio tracks");const t=this.peerConnection.createDataChannel("session",{ordered:!0});t.onopen=()=>{this.dataChannel=t??null},t.onclose=()=>{},t.onmessage=e=>{var i,r,n,o;try{const a=JSON.parse(e.data);switch(a.messageType){case fe.SPEECH_TEXT:this.internalEventEmitter.emit(Pt.WEBRTC_CHAT_MESSAGE_RECEIVED,a.data);break;case fe.CLIENT_TOOL_EVENT:const l=a.data;this.internalEventEmitter.emit(Pt.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED,l);const h=tu.WebRTCClientToolEventToClientToolEvent(l);this.publicEventEmitter.emit(et.CLIENT_TOOL_EVENT_RECEIVED,h);break;case fe.TOOL_CALL_STARTED_EVENT:const c=a.data;this.publicEventEmitter.emit(et.TOOL_CALL_STARTED,this.toolCallManager.WebRTCToolCallStartedEventToToolCallStartedPayload(c)),this.internalEventEmitter.emit(Pt.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,c);break;case fe.TOOL_CALL_COMPLETED_EVENT:const u=a.data;this.publicEventEmitter.emit(et.TOOL_CALL_COMPLETED,this.toolCallManager.webRTCToolCallCompletedEventToToolCallCompletedPayload(u)),this.internalEventEmitter.emit(Pt.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,u);break;case fe.TOOL_CALL_FAILED_EVENT:const m=a.data;this.publicEventEmitter.emit(et.TOOL_CALL_FAILED,this.toolCallManager.webRTCToolCallFailedEventToToolCallFailedPayload(m)),this.internalEventEmitter.emit(Pt.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,m);break;case fe.REASONING_TEXT:this.internalEventEmitter.emit(Pt.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,a.data);break;case fe.USER_SPEECH_STARTED:this.publicEventEmitter.emit(et.USER_SPEECH_STARTED,(r=(i=a.data)===null||i===void 0?void 0:i.user_action_correlation_id)!==null&&r!==void 0?r:"unknown");break;case fe.USER_SPEECH_ENDED:this.publicEventEmitter.emit(et.USER_SPEECH_ENDED,(o=(n=a.data)===null||n===void 0?void 0:n.user_action_correlation_id)!==null&&o!==void 0?o:"unknown");break;default:break}}catch(a){console.error("Failed to parse data channel message:",a)}}})}requestMicrophonePermissionAsync(){return qt(this,void 0,void 0,function*(){if(this.inputAudioState.permissionState!==Fe.PENDING){this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:Fe.PENDING}),this.publicEventEmitter.emit(et.MIC_PERMISSION_PENDING);try{const t={echoCancellation:!0};this.audioDeviceId&&(t.deviceId={exact:this.audioDeviceId}),this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:t}),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:Fe.GRANTED}),this.publicEventEmitter.emit(et.MIC_PERMISSION_GRANTED),yield this.setupAudioTrack()}catch(t){console.error("Failed to get microphone permission:",t),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:Fe.DENIED});const e=t instanceof Error?t.message:String(t);this.publicEventEmitter.emit(et.MIC_PERMISSION_DENIED,e)}}})}setupAudioTrack(){return qt(this,void 0,void 0,function*(){if(!this.peerConnection||!this.inputAudioStream)return;if(!this.inputAudioStream.getAudioTracks().length){console.error("StreamingClient - setupAudioTrack: stream does not have audio tracks");return}this.inputAudioState.isMuted&&this.muteAllAudioTracks();const t=this.inputAudioStream.getAudioTracks()[0],i=this.peerConnection.getSenders().find(r=>{var n;return((n=r.track)===null||n===void 0?void 0:n.kind)==="audio"||r.track===null&&r.dtmf!==null});if(i)try{yield i.replaceTrack(t)}catch(r){console.error("Failed to replace audio track:",r),this.peerConnection.addTrack(t,this.inputAudioStream)}else this.peerConnection.addTrack(t,this.inputAudioStream);this.publicEventEmitter.emit(et.INPUT_AUDIO_STREAM_STARTED,this.inputAudioStream)})}initPeerConnectionAndSendOffer(){return qt(this,void 0,void 0,function*(){if(yield this.initPeerConnection(),!this.peerConnection){console.error("StreamingClient - initPeerConnectionAndSendOffer: peer connection is not initialized");return}try{const t=yield this.peerConnection.createOffer();yield this.peerConnection.setLocalDescription(t)}catch(t){console.error("StreamingClient - initPeerConnectionAndSendOffer: error creating offer",t)}if(!this.peerConnection.localDescription)throw new Error("StreamingClient - initPeerConnectionAndSendOffer: local description is null");yield this.signallingClient.sendOffer(this.peerConnection.localDescription)})}shutdown(){return qt(this,void 0,void 0,function*(){var t;if(this.showPeerConnectionStatsReport){const e=yield(t=this.peerConnection)===null||t===void 0?void 0:t.getStats();if(e){const i=Zy(e,this.peerConnectionStatsReportOutputFormat);i&&console.log(i,void 0,2)}}this.statsCollectionInterval&&(clearInterval(this.statsCollectionInterval),this.statsCollectionInterval=null),this.successMetricPoller&&(clearInterval(this.successMetricPoller),this.successMetricPoller=null),this.successMetricFired=!1;try{this.inputAudioStream&&this.inputAudioStream.getTracks().forEach(e=>{e.stop()}),this.inputAudioStream=null}catch(e){console.error("StreamingClient - shutdown: error stopping input audio stream",e)}try{this.signallingClient.stop()}catch(e){console.error("StreamingClient - shutdown: error stopping signallilng",e)}this.toolCallManager.clearPendingCalls();try{this.peerConnection&&this.peerConnection.connectionState!=="closed"&&(this.peerConnection.onconnectionstatechange=null,this.peerConnection.close(),this.peerConnection=null)}catch(e){console.error("StreamingClient - shutdown: error closing peer connection",e)}})}}class mx{constructor(t,e){this.reasoning_messages=[],this.publicEventEmitter=t,this.internalEventEmitter=e,this.internalEventEmitter.addListener(Pt.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,this.processWebRtcReasoningTextMessageEvent.bind(this))}webRtcTextMessageEventToReasoningStreamEvent(t){return{id:`${t.role}::${t.message_id}`,content:t.content,endOfThought:t.end_of_thought,role:t.role}}processWebRtcReasoningTextMessageEvent(t){const e=this.webRtcTextMessageEventToReasoningStreamEvent(t);this.publicEventEmitter.emit(et.REASONING_STREAM_EVENT_RECEIVED,e);const i={id:e.id,content:e.content,role:e.role},r=this.reasoning_messages.findIndex(n=>n.id===i.id);if(r!==-1){const n=this.reasoning_messages[r];n.content+=i.content,this.reasoning_messages[r]=n}else this.reasoning_messages.push(i);e.endOfThought&&this.publicEventEmitter.emit(et.REASONING_HISTORY_UPDATED,this.reasoning_messages)}}var He=function(s,t,e,i){function r(n){return n instanceof e?n:new e(function(o){o(n)})}return new(e||(e=Promise))(function(n,o){function a(c){try{h(i.next(c))}catch(u){o(u)}}function l(c){try{h(i.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):r(c.value).then(a,l)}h((i=i.apply(s,t||[])).next())})};class gx{constructor(t,e,i){var r,n,o,a,l;this.inputAudioState={isMuted:!1,permissionState:Fe.NOT_REQUESTED},this.sessionId=null,this.organizationId=null,this.streamingClient=null,this._isStreaming=!1;const h=this.validateClientConfig(t,e,i);if(h)throw new Rt(h,Dt.CLIENT_ERROR_CODE_CONFIGURATION_ERROR,400);this.personaConfig=e,this.clientOptions=i,(!((r=i==null?void 0:i.api)===null||r===void 0)&&r.baseUrl||!((n=i==null?void 0:i.api)===null||n===void 0)&&n.apiVersion)&&Yy(i.api.baseUrl||Yc,i.api.apiVersion||Yn),!((a=(o=i==null?void 0:i.api)===null||o===void 0?void 0:o.apiGateway)===null||a===void 0)&&a.enabled&&qy(i.api.apiGateway),!((l=i==null?void 0:i.metrics)===null||l===void 0)&&l.disableClientMetrics&&Ky(!0),this.publicEventEmitter=new hx,this.internalEventEmitter=new ax,this.toolCallManager=new tu(this.publicEventEmitter),this.apiClient=new rx(t,i==null?void 0:i.apiKey,i==null?void 0:i.api),this.messageHistoryClient=new lx(this.publicEventEmitter,this.internalEventEmitter),this.reasoningHistoryClient=new mx(this.publicEventEmitter,this.internalEventEmitter)}decodeJwt(t){try{const e=t.split(".")[1],i=zy.Buffer.from(e,"base64").toString("utf8");return JSON.parse(i)}catch{throw new Error("Invalid session token format")}}validateClientConfig(t,e,i){var r,n;if(!t&&!(i!=null&&i.apiKey))return"Either sessionToken or apiKey must be provided";if(i!=null&&i.apiKey&&t)return"Only one of sessionToken or apiKey should be used";const o=Jy((r=i==null?void 0:i.api)===null||r===void 0?void 0:r.apiGateway);if(o)return o;if(t){const a=this.decodeJwt(t);this.organizationId=a.accountId,Pi({organizationId:this.organizationId});const l=(n=a.type)===null||n===void 0?void 0:n.toLowerCase();if(l==="legacy")return"Legacy session tokens are no longer supported. Please define your persona when creating your session token. See https://docs.anam.ai/resources/migrating-legacy for more information.";if((l==="ephemeral"||l==="stateful")&&e)return"This session token already contains a persona configuration. Please remove the personaConfig parameter."}else if(!e)return"Missing persona config. Persona configuration must be provided when using apiKey";if(i!=null&&i.voiceDetection){if(i.disableInputAudio)return"Voice detection is disabled because input audio is disabled. Please set disableInputAudio to false to enable voice detection.";if(i.voiceDetection.endOfSpeechSensitivity!==void 0){if(typeof i.voiceDetection.endOfSpeechSensitivity!="number")return"End of speech sensitivity must be a number";if(i.voiceDetection.endOfSpeechSensitivity<0||i.voiceDetection.endOfSpeechSensitivity>1)return"End of speech sensitivity must be between 0 and 1"}}}buildStartSessionOptionsForClient(){var t;const e={};if(!((t=this.clientOptions)===null||t===void 0)&&t.voiceDetection&&(e.voiceDetection=this.clientOptions.voiceDetection),Object.keys(e).length!==0)return e}startSession(t){return He(this,void 0,void 0,function*(){var e,i,r,n,o,a,l,h,c,u,m,f;const g=this.personaConfig,y=this.buildStartSessionOptionsForClient(),x=yield this.apiClient.startSession(g,y),{sessionId:v,clientConfig:E,engineHost:T,engineProtocol:C,signallingEndpoint:R}=x,{heartbeatIntervalSeconds:A,maxWsReconnectionAttempts:I,iceServers:N}=E;this.sessionId=v,Pi({sessionId:this.sessionId});const B=!((e=this.clientOptions)===null||e===void 0)&&e.iceServers?this.clientOptions.iceServers:N;try{this.streamingClient=new px(v,{engine:{baseUrl:`${C}://${T}`},signalling:{heartbeatIntervalSeconds:A,maxWsReconnectionAttempts:I,url:{baseUrl:T,protocol:C,signallingPath:R}},iceServers:B,inputAudio:{inputAudioState:this.inputAudioState,userProvidedMediaStream:!((i=this.clientOptions)===null||i===void 0)&&i.disableInputAudio?void 0:t,audioDeviceId:(r=this.clientOptions)===null||r===void 0?void 0:r.audioDeviceId,disableInputAudio:(n=this.clientOptions)===null||n===void 0?void 0:n.disableInputAudio},apiGateway:(a=(o=this.clientOptions)===null||o===void 0?void 0:o.api)===null||a===void 0?void 0:a.apiGateway,metrics:{showPeerConnectionStatsReport:(c=(h=(l=this.clientOptions)===null||l===void 0?void 0:l.metrics)===null||h===void 0?void 0:h.showPeerConnectionStatsReport)!==null&&c!==void 0?c:!1,peerConnectionStatsReportOutputFormat:(f=(m=(u=this.clientOptions)===null||u===void 0?void 0:u.metrics)===null||m===void 0?void 0:m.peerConnectionStatsReportOutputFormat)!==null&&f!==void 0?f:"console"}},this.publicEventEmitter,this.internalEventEmitter,this.toolCallManager)}catch(k){throw Pi({sessionId:null}),new Rt("Failed to initialize streaming client",Dt.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:k instanceof Error?k.message:String(k),sessionId:v})}return v})}startSessionIfNeeded(t){return He(this,void 0,void 0,function*(){if((!this.sessionId||!this.streamingClient)&&(yield this.startSession(t),!this.sessionId||!this.streamingClient))throw new Rt("Session ID or streaming client is not available after starting session",Dt.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:"Failed to initialize session properly"})})}stream(t){return He(this,void 0,void 0,function*(){var e;if(this._isStreaming)throw new Error("Already streaming");const i=Zc();return Pi({attemptCorrelationId:i,sessionId:null}),si(Pe.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&t&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored."),yield this.startSessionIfNeeded(t),this._isStreaming=!0,new Promise(r=>{var n;const o=[];let a=!1,l=!1;this.publicEventEmitter.addListener(et.VIDEO_STREAM_STARTED,h=>{o.push(h),a=!0,l&&r(o)}),this.publicEventEmitter.addListener(et.AUDIO_STREAM_STARTED,h=>{o.push(h),l=!0,a&&r(o)}),(n=this.streamingClient)===null||n===void 0||n.startConnection()})})}streamToVideoAndAudioElements(t,e,i){return He(this,void 0,void 0,function*(){console.warn("AnamClient: streamToVideoAndAudioElements is deprecated. To avoid possible audio issues, please use streamToVideoElement instead."),yield this.streamToVideoElement(t,i)})}streamToVideoElement(t,e){return He(this,void 0,void 0,function*(){var i;const r=Zc();Pi({attemptCorrelationId:r,sessionId:null}),si(Pe.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((i=this.clientOptions)===null||i===void 0)&&i.disableInputAudio&&e&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(e)}catch(n){throw n instanceof Rt?n:new Rt("Failed to start session",Dt.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:n instanceof Error?n.message:String(n),sessionId:this.sessionId})}if(this._isStreaming)throw new Error("Already streaming");if(this._isStreaming=!0,!this.streamingClient)throw new Error("Failed to stream: streaming client is not available");this.streamingClient.setMediaStreamTargetById(t),this.streamingClient.startConnection()})}talk(t){return He(this,void 0,void 0,function*(){if(!this.streamingClient)throw new Error("Failed to send talk command: session is not started. Have you called startSession?");if(!this._isStreaming)throw new Error("Failed to send talk command: not currently streaming. Have you called stream?");yield this.streamingClient.sendTalkCommand(t)})}sendDataMessage(t){if(this.streamingClient)this.streamingClient.sendDataMessage(t);else throw new Error("Failed to send message: session is not started.")}sendUserMessage(t){if(!this._isStreaming)throw console.warn("AnamClient: Not currently streaming. User message will not be sent."),new Error("Failed to send user message: not currently streaming");const e=this.getActiveSessionId();if(!e)throw new Error("Failed to send user message: no active session");const i=new Date().toISOString().replace("Z",""),r=JSON.stringify({content:t,timestamp:i,session_id:e,message_type:"speech"});this.sendDataMessage(r)}interruptPersona(){if(!this._isStreaming)throw new Error("Failed to send interrupt command: not currently streaming");const t=this.getActiveSessionId();if(!t)throw new Error("Failed to send interrupt command: no active session");const e=JSON.stringify({message_type:"interrupt",session_id:t,timestamp:new Date().toISOString()});this.sendDataMessage(e)}addContext(t){if(!this._isStreaming)throw new Error("Failed to add context: not currently streaming");const e=this.getActiveSessionId();if(!e)throw new Error("Failed to add context: no active session");const i=JSON.stringify({message_type:"context",session_id:e,content:t});this.sendDataMessage(i)}stopStreaming(){return He(this,void 0,void 0,function*(){this.streamingClient&&(this.publicEventEmitter.emit(et.CONNECTION_CLOSED,Ne.NORMAL),yield this.streamingClient.stopConnection(),this.streamingClient=null,this.sessionId=null,Pi({attemptCorrelationId:null,sessionId:null,organizationId:this.organizationId}),this._isStreaming=!1)})}isStreaming(){return this._isStreaming}setPersonaConfig(t){this.personaConfig=t}getPersonaConfig(){return this.personaConfig}getInputAudioState(){var t;return!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio&&console.warn("AnamClient: Audio state will not be used because input audio is disabled."),this.streamingClient&&(this.inputAudioState=this.streamingClient.getInputAudioState()),this.inputAudioState}muteInputAudio(){var t,e;return!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Muting input audio will have no effect."),this.streamingClient&&!(!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio)?this.inputAudioState=this.streamingClient.muteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0}),this.inputAudioState}unmuteInputAudio(){var t,e;return!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Unmuting input audio will have no effect."),this.streamingClient&&!(!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio)?this.inputAudioState=this.streamingClient.unmuteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1}),this.inputAudioState}changeAudioInputDevice(t){return He(this,void 0,void 0,function*(){var e;if(!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio)throw new Error("AnamClient: Cannot change audio input device because input audio is disabled.");if(!this._isStreaming)throw new Error("AnamClient: Cannot change audio input device while not streaming. Start streaming first.");if(!this.streamingClient)throw new Error("AnamClient: Cannot change audio input device because streaming client is not available. Start streaming first.");yield this.streamingClient.changeAudioInputDevice(t)})}createTalkMessageStream(t){if(!this.streamingClient)throw new Error("Failed to start talk message stream: session is not started.");if(t&&t.trim()==="")throw new Error("Failed to start talk message stream: correlationId is empty");return this.streamingClient.startTalkMessageStream(t)}createAgentAudioInputStream(t){if(!this.streamingClient)throw new Error("Failed to create agent audio input stream: session is not started.");return this.streamingClient.createAgentAudioInputStream(t)}addListener(t,e){this.publicEventEmitter.addListener(t,e)}removeListener(t,e){this.publicEventEmitter.removeListener(t,e)}getActiveSessionId(){return this.sessionId}registerToolCallHandler(t,e){return this.toolCallManager.registerHandler(t,e)}}const _x=(s,t)=>new gx(s,void 0,t);let yx=0;class xx{constructor(t){this.onVideoReady=null,this.onConnected=null,this.onDisconnected=null,this.onTalkStreamInterrupted=null,this.onError=null,this.audioInputStream=null,this.videoElement=null,this._connected=!1,this._closing=!1,this.client=_x(t.sessionToken,{disableInputAudio:!0,metrics:{disableClientMetrics:!0}})}get isConnected(){return this._connected}get videoEl(){return this.videoElement}async connect(){var t;try{const e=`anam-avatar-video-${++yx}`;this.videoElement=document.createElement("video"),this.videoElement.id=e,this.videoElement.autoplay=!0,this.videoElement.playsInline=!0,this.videoElement.style.display="none",document.body.appendChild(this.videoElement),this.client.addListener(et.CONNECTION_ESTABLISHED,()=>{var i;console.log("[AnamSession] Connection established"),this._connected=!0,(i=this.onConnected)==null||i.call(this)}),this.client.addListener(et.VIDEO_PLAY_STARTED,()=>{var i;console.log("[AnamSession] Video playing"),this.videoElement&&((i=this.onVideoReady)==null||i.call(this,this.videoElement))}),this.client.addListener(et.TALK_STREAM_INTERRUPTED,()=>{var i;console.log("[AnamSession] Talk stream interrupted"),(i=this.onTalkStreamInterrupted)==null||i.call(this)}),this.client.addListener(et.CONNECTION_CLOSED,i=>{var r;console.log("[AnamSession] Connection closed:",i),this._connected=!1,(r=this.onDisconnected)==null||r.call(this,String(i))}),await this.client.streamToVideoElement(e),this.audioInputStream=this.client.createAgentAudioInputStream({encoding:"pcm_s16le",sampleRate:24e3,channels:1}),console.log("[AnamSession] BYO audio input stream ready")}catch(e){const i=e instanceof Error?e:new Error(String(e));throw console.error("[AnamSession] Connection failed:",i.message),(t=this.onError)==null||t.call(this,i),this.close(),i}}sendAudioChunk(t){var e;(e=this.audioInputStream)==null||e.sendAudioChunk(t)}endSequence(){var t;(t=this.audioInputStream)==null||t.endSequence()}interrupt(){this.client.interruptPersona()}close(){if(!this._closing){this._closing=!0,console.log("[AnamSession] Closing...");try{this.client.stopStreaming()}catch{}this.videoElement&&(this.videoElement.pause(),this.videoElement.srcObject=null,this.videoElement.remove(),this.videoElement=null),this.audioInputStream=null,this._connected=!1}}}const bx=new Set(["a","button","input","select","textarea","details","summary","label","option"]),vx=new Set(["button","link","menuitem","menuitemcheckbox","menuitemradio","tab","switch","slider","combobox","listbox","option","radio","checkbox","textbox","searchbox","scrollbar"]),Ex=new Set(["h1","h2","h3","h4","h5","h6"]),Tx=["type","role","aria-label","placeholder","value","href","alt","title","name","checked","aria-expanded"];class Sx{constructor(){this.elementMap=new Map}analyze(){this.elementMap.clear();let t=0;const e=[];e.push(`Page: ${document.title}`),e.push(`URL: ${location.href}`),e.push("");const i=r=>{if(r.nodeType===Node.TEXT_NODE){const h=(r.textContent??"").trim();h&&h.length>1&&e.push(h);return}if(r.nodeType!==Node.ELEMENT_NODE)return;const n=r,o=n.tagName.toLowerCase();if(!this.isVisible(n)||["script","style","svg","noscript","link","meta"].includes(o)||n.id==="holostaff-widget-root"||n.closest("#holostaff-widget-root"))return;const a=this.isInteractive(n),l=Ex.has(o);if(a||l){const h=t++;this.elementMap.set(h,n);const c=this.getUsefulAttrs(n),u=c?" "+c:"",m=this.getDirectText(n).slice(0,200);if(l){const f=parseInt(o[1]),g="#".repeat(f);e.push(""),e.push(`${g} [${h}]${m}`)}else e.push(`[${h}]<${o}${u}>${m}</${o}>`);return}for(const h of n.childNodes)i(h)};return i(document.body),{text:e.join(`
|
|
986
|
+
`),elementMap:this.elementMap}}getElementByIndex(t){return this.elementMap.get(t)??null}isVisible(t){if(t.offsetWidth===0&&t.offsetHeight===0){const i=t.getBoundingClientRect();if(i.width===0&&i.height===0)return!1}const e=getComputedStyle(t);return!(e.display==="none"||e.visibility==="hidden"||e.opacity==="0")}isInteractive(t){const e=t.tagName.toLowerCase();if(bx.has(e))return!t.disabled;const i=t.getAttribute("role");if(i&&vx.has(i))return!0;try{if(getComputedStyle(t).cursor==="pointer")return!0}catch{}return!!(t.hasAttribute("tabindex")&&t.getAttribute("tabindex")!=="-1"||t.isContentEditable&&t.getAttribute("contenteditable")!=="false")}getDirectText(t){return(t.textContent??"").replace(/\s+/g," ").trim()}getUsefulAttrs(t){const e=[];for(const i of Tx){const r=t.getAttribute(i);r&&r.length>0&&r.length<100&&e.push(`${i}="${r}"`)}return e.join(" ")}}const Cx=new Set(["scroll_to","click","highlight"]);class wx{constructor(t){this.onToolCall=null,this.fnArgBufs=new Map,this.fnNames=new Map,this.fnCallIds=new Map,this.realtimeSession=t.realtimeSession,this.domAnalyzer=t.domAnalyzer,this.pageActions=t.pageActions,this.overlayActions=t.overlayActions,this.confirmationPrompt=t.confirmationPrompt,this.staffId=t.staffId,this.backendUrl=t.backendUrl}handleMessage(t){var i;switch(t.type){case"response.output_item.added":if(((i=t.item)==null?void 0:i.type)==="function_call"){const r=t.item.id,n=t.item.name,o=t.item.call_id||t.item.id;return this.fnNames.set(r,n),this.fnCallIds.set(r,o),this.fnArgBufs.set(r,""),console.log(`[ToolHandler] Function call started: ${n} (${r})`),!0}return!1;case"response.function_call_arguments.delta":if(t.item_id&&this.fnArgBufs.has(t.item_id)){const r=this.fnArgBufs.get(t.item_id)??"";return this.fnArgBufs.set(t.item_id,r+(t.delta??"")),!0}return!1;case"response.function_call_arguments.done":return t.item_id&&this.fnArgBufs.has(t.item_id)?(this.handleFunctionCallDone(t.item_id),!0):!1;default:return!1}}async handleFunctionCallDone(t){var a;const e=this.fnNames.get(t)??"unknown",i=this.fnCallIds.get(t)??t,r=this.fnArgBufs.get(t)??"{}";this.fnArgBufs.delete(t),this.fnNames.delete(t),this.fnCallIds.delete(t);let n;try{n=JSON.parse(r)}catch{console.warn(`[ToolHandler] Failed to parse args for ${e}:`,r),this.sendToolResult(i,{error:"Malformed JSON in function call arguments"});return}console.log(`[ToolHandler] Executing: ${e}`,n),(a=this.onToolCall)==null||a.call(this,e,n);let o=null;switch(e){case"page_action":await this.handlePageAction(i,n.instruction??"");return;case"show_text_card":o=this.overlayActions.showTextCard(n.title??"",n.body??"");break;case"show_image_card":o=this.overlayActions.showImageCard(n.image_url??"",n.caption);break;case"show_bullet_list":o=this.overlayActions.showBulletList(n.title??"",n.items??[]);break;case"dismiss_overlays":o=this.overlayActions.dismissAll();break;default:console.warn(`[ToolHandler] Unknown tool: ${e}`),o={error:`Unknown tool: ${e}`}}this.sendToolResult(i,o)}async handlePageAction(t,e){try{const{text:i}=this.domAnalyzer.analyze();console.log(`[ToolHandler] DOM snapshot: ${i.length} chars, instruction: "${e}"`);const n=(await Ru(this.staffId,i,e,this.backendUrl)).actions??[];console.log(`[ToolHandler] Page agent returned ${n.length} actions:`,n);const o=[];for(const a of n){if(a.action==="describe"){o.push({action:"describe",status:"ok",description:a.description});continue}if(Cx.has(a.action)&&!await this.confirmationPrompt.ask(`${a.description}?`)){o.push({action:a.action,status:"declined",description:"Visitor declined"});continue}let l;switch(a.action){case"scroll_to":l=this.pageActions.scrollTo(a.index);break;case"highlight":l=this.pageActions.highlight(a.index);break;case"click":l=this.pageActions.click(a.index);break;case"fill":l=this.pageActions.fill(a.index,a.value??"");break;default:l={status:"error",description:`Unknown action: ${a.action}`}}o.push({action:a.action,...l})}this.sendToolResult(t,{results:o})}catch(i){const r=i instanceof Error?i.message:String(i);console.error("[ToolHandler] Page action failed:",r),this.sendToolResult(t,{error:r})}}sendToolResult(t,e){this.realtimeSession.sendJSON({type:"conversation.item.create",item:{type:"function_call_output",call_id:t,output:JSON.stringify(e)}}),this.realtimeSession.sendJSON({type:"response.create"})}}class Ax{constructor(t,e){this.analyzer=t,this.highlightRenderer=e}scrollTo(t){const e=this.analyzer.getElementByIndex(t);if(!e)return{status:"error",description:`Element [${t}] not found`};e.scrollIntoView({behavior:"smooth",block:"center"});const i=this.describeElement(e);return console.log(`[PageActions] Scrolled to [${t}] ${i}`),{status:"scrolled",description:i}}highlight(t,e=3e3){const i=this.analyzer.getElementByIndex(t);if(!i)return{status:"error",description:`Element [${t}] not found`};this.highlightRenderer.highlight(i,e);const r=this.describeElement(i);return console.log(`[PageActions] Highlighting [${t}] ${r} for ${e}ms`),{status:"highlighted",description:r}}click(t){const e=this.analyzer.getElementByIndex(t);if(!e)return{status:"error",description:`Element [${t}] not found`};e.click();const i=this.describeElement(e);return console.log(`[PageActions] Clicked [${t}] ${i}`),{status:"clicked",description:i}}fill(t,e){var a,l;const i=this.analyzer.getElementByIndex(t);if(!i)return{status:"error",description:`Element [${t}] not found`};const r=i.tagName.toLowerCase(),n=(a=i.type)==null?void 0:a.toLowerCase();if(r==="select"){const h=i,c=Array.from(h.options).find(u=>u.text.toLowerCase().includes(e.toLowerCase())||u.value.toLowerCase()===e.toLowerCase());if(c)h.value=c.value,h.dispatchEvent(new Event("change",{bubbles:!0}));else return{status:"error",description:`No option matching "${e}"`}}else if(n==="checkbox"||n==="radio"){const h=i;h.checked=e==="true"||e==="1",h.dispatchEvent(new Event("change",{bubbles:!0}))}else{const h=(l=Object.getOwnPropertyDescriptor(r==="textarea"?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value"))==null?void 0:l.set;h?h.call(i,e):i.value=e,i.dispatchEvent(new Event("input",{bubbles:!0})),i.dispatchEvent(new Event("change",{bubbles:!0}))}const o=this.describeElement(i);return console.log(`[PageActions] Filled [${t}] ${o} with "${e}"`),{status:"filled",description:`${o} = "${e}"`}}describeElement(t){const e=t.tagName.toLowerCase(),i=(t.textContent??"").trim().slice(0,50),r=t.getAttribute("aria-label")||t.getAttribute("placeholder")||i;return`<${e}>${r}</${e}>`}}class Rx{constructor(t){this.renderer=t}showTextCard(t,e){return this.renderer.showTextCard(t,e),console.log(`[OverlayActions] Showing text card: "${t}"`),{status:"shown"}}showImageCard(t,e){return this.renderer.showImageCard(t,e),console.log(`[OverlayActions] Showing image card: "${e??t}"`),{status:"shown"}}showBulletList(t,e){return this.renderer.showBulletList(t,e),console.log(`[OverlayActions] Showing bullet list: "${t}" (${e.length} items)`),{status:"shown"}}dismissAll(){return this.renderer.dismissAll(),console.log("[OverlayActions] Dismissed all overlays"),{status:"dismissed"}}}class Px{constructor(){this.activeHighlights=[]}highlight(t,e=3e3){const i=t.getBoundingClientRect(),r=document.createElement("div");Object.assign(r.style,{position:"fixed",left:`${i.left-4}px`,top:`${i.top-4}px`,width:`${i.width+8}px`,height:`${i.height+8}px`,border:"3px solid #4a6fa5",borderRadius:"8px",boxShadow:"0 0 12px rgba(74, 111, 165, 0.5)",pointerEvents:"none",zIndex:"2147483645",animation:"hs-highlight-pulse 1.2s ease-in-out infinite",transition:"opacity 0.3s ease"}),this.ensureKeyframes(),document.body.appendChild(r),this.activeHighlights.push(r);const n=()=>{const o=t.getBoundingClientRect();r.style.left=`${o.left-4}px`,r.style.top=`${o.top-4}px`,r.style.width=`${o.width+8}px`,r.style.height=`${o.height+8}px`};window.addEventListener("scroll",n,{passive:!0}),setTimeout(()=>{r.style.opacity="0",setTimeout(()=>{r.remove(),window.removeEventListener("scroll",n),this.activeHighlights=this.activeHighlights.filter(o=>o!==r)},300)},e)}clearAll(){for(const t of this.activeHighlights)t.remove();this.activeHighlights=[]}ensureKeyframes(){if(document.getElementById("hs-highlight-keyframes"))return;const t=document.createElement("style");t.id="hs-highlight-keyframes",t.textContent=`
|
|
987
|
+
@keyframes hs-highlight-pulse {
|
|
988
|
+
0%, 100% { box-shadow: 0 0 8px rgba(74, 111, 165, 0.4); border-color: #4a6fa5; }
|
|
989
|
+
50% { box-shadow: 0 0 20px rgba(74, 111, 165, 0.8); border-color: #6b8fc5; }
|
|
990
|
+
}
|
|
991
|
+
`,document.head.appendChild(t)}}const Ix=1e4;class Mx{constructor(){this.container=null}ask(t){return new Promise(e=>{this.dismiss(),this.container=document.createElement("div"),Object.assign(this.container.style,{position:"fixed",bottom:"300px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483647",background:"rgba(255, 255, 255, 0.97)",border:"1.5px solid #c8d0da",borderRadius:"16px",padding:"14px 18px",boxShadow:"0 4px 20px rgba(0, 0, 0, 0.12)",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:"13px",color:"#2a2a3e",display:"flex",flexDirection:"column",alignItems:"center",gap:"10px",maxWidth:"280px",textAlign:"center",animation:"hs-confirm-in 0.25s ease-out"}),this.ensureKeyframes(),this.container.setAttribute("role","alertdialog"),this.container.setAttribute("aria-label","Confirm action");const i=document.createElement("div");i.textContent=t,i.style.lineHeight="1.4",this.container.appendChild(i);const r=document.createElement("div");Object.assign(r.style,{display:"flex",gap:"8px",width:"100%"});const n=this.createButton("Yes","#4a6fa5","#ffffff"),o=this.createButton("No","#e8ecf0","#2a2a3e");r.appendChild(n),r.appendChild(o),this.container.appendChild(r),document.body.appendChild(this.container);let a=!1;const l=c=>{a||(a=!0,clearTimeout(h),this.dismiss(),e(c))};n.addEventListener("click",()=>l(!0)),o.addEventListener("click",()=>l(!1));const h=setTimeout(()=>l(!1),Ix)})}dismiss(){this.container&&(this.container.remove(),this.container=null)}createButton(t,e,i){const r=document.createElement("button");return r.textContent=t,Object.assign(r.style,{flex:"1",padding:"8px 0",border:"none",borderRadius:"10px",background:e,color:i,fontSize:"13px",fontWeight:"600",cursor:"pointer",transition:"opacity 0.15s"}),r.addEventListener("mouseenter",()=>{r.style.opacity="0.85"}),r.addEventListener("mouseleave",()=>{r.style.opacity="1"}),r}ensureKeyframes(){if(document.getElementById("hs-confirm-keyframes"))return;const t=document.createElement("style");t.id="hs-confirm-keyframes",t.textContent=`
|
|
992
|
+
@keyframes hs-confirm-in {
|
|
993
|
+
from { opacity: 0; transform: translateX(-50%) translateY(8px); }
|
|
994
|
+
to { opacity: 1; transform: translateX(-50%) translateY(0); }
|
|
995
|
+
}
|
|
996
|
+
`,document.head.appendChild(t)}}const kx=15e3,Bx=320;function Ox(){return Math.min(300,window.innerWidth-32)}class Dx{constructor(){this.cards=[]}showTextCard(t,e){const i=this.createCard();if(t){const r=document.createElement("div");r.textContent=t,Object.assign(r.style,{fontWeight:"700",fontSize:"14px",marginBottom:"6px",color:"#1a1a2e"}),i.appendChild(r)}if(e){const r=document.createElement("div");r.textContent=e,Object.assign(r.style,{fontSize:"13px",lineHeight:"1.5",color:"#3a3a4e",whiteSpace:"pre-wrap"}),i.appendChild(r)}this.mount(i)}showImageCard(t,e){const i=this.createCard(),r=document.createElement("img");if(r.src=t,r.alt=e??"",Object.assign(r.style,{width:"100%",borderRadius:"8px",marginBottom:e?"8px":"0",display:"block"}),i.appendChild(r),e){const n=document.createElement("div");n.textContent=e,Object.assign(n.style,{fontSize:"12px",color:"#6a6a7e",textAlign:"center"}),i.appendChild(n)}this.mount(i)}showBulletList(t,e){const i=this.createCard();if(t){const n=document.createElement("div");n.textContent=t,Object.assign(n.style,{fontWeight:"700",fontSize:"14px",marginBottom:"8px",color:"#1a1a2e"}),i.appendChild(n)}const r=document.createElement("ul");Object.assign(r.style,{margin:"0",paddingLeft:"18px",fontSize:"13px",lineHeight:"1.6",color:"#3a3a4e"});for(const n of e){const o=document.createElement("li");o.textContent=n,o.style.marginBottom="4px",r.appendChild(o)}i.appendChild(r),this.mount(i)}dismissAll(){for(const t of[...this.cards])this.removeCard(t)}createCard(){var i,r;const t=document.createElement("div");Object.assign(t.style,{position:"fixed",maxWidth:`${Ox()}px`,padding:"14px 16px",background:"rgba(255, 255, 255, 0.92)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(200, 208, 218, 0.6)",borderRadius:"16px",boxShadow:"0 4px 24px rgba(0, 0, 0, 0.10)",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',zIndex:"2147483645",opacity:"0",transform:"translateY(12px)",transition:(r=(i=globalThis.matchMedia)==null?void 0:i.call(globalThis,"(prefers-reduced-motion: reduce)"))!=null&&r.matches?"none":"opacity 0.3s ease, transform 0.3s ease",pointerEvents:"auto"});const e=document.createElement("button");return e.textContent="×",Object.assign(e.style,{position:"absolute",top:"6px",right:"8px",background:"none",border:"none",fontSize:"18px",color:"#9a9ab0",cursor:"pointer",lineHeight:"1",padding:"2px 4px"}),e.addEventListener("click",()=>this.removeCard(t)),t.appendChild(e),t}mount(t){const e=this.cards.length,i=Bx+e*10;t.style.bottom=`${i}px`,t.style.left="50%",t.style.transform="translateX(-50%) translateY(12px)",document.body.appendChild(t),this.cards.push(t),requestAnimationFrame(()=>{t.style.opacity="1",t.style.transform="translateX(-50%) translateY(0)"});const r=setTimeout(()=>this.removeCard(t),kx);t._dismissTimer=r}removeCard(t){clearTimeout(t._dismissTimer),t.style.opacity="0",t.style.transform="translateX(-50%) translateY(12px)",setTimeout(()=>{t.remove(),this.cards=this.cards.filter(e=>e!==t)},300)}}class Gx{constructor(){this.container=null,this.minimizeBtn=null,this.closeBtn=null,this.onMinimize=null,this.onRestore=null,this.onClose=null,this.minimized=!1}show(){this.container||(this.container=document.createElement("div"),Object.assign(this.container.style,{position:"fixed",bottom:"8px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483647",display:"flex",gap:"6px",opacity:"0",transition:"opacity 0.3s ease"}),this.minimizeBtn=this.createButton("–","Minimize conversation"),this.closeBtn=this.createButton("×","Close conversation"),this.minimizeBtn.addEventListener("click",()=>{var t,e;this.minimized?(this.minimized=!1,this.minimizeBtn.textContent="–",this.minimizeBtn.title="Minimize",(t=this.onRestore)==null||t.call(this)):(this.minimized=!0,this.minimizeBtn.textContent="□",this.minimizeBtn.title="Restore",(e=this.onMinimize)==null||e.call(this))}),this.closeBtn.addEventListener("click",()=>{var t;(t=this.onClose)==null||t.call(this)}),this.container.appendChild(this.minimizeBtn),this.container.appendChild(this.closeBtn),document.body.appendChild(this.container),requestAnimationFrame(()=>{this.container&&(this.container.style.opacity="1")}))}hide(){this.container&&(this.container.remove(),this.container=null,this.minimizeBtn=null,this.closeBtn=null,this.minimized=!1)}createButton(t,e){const i=document.createElement("button");return i.textContent=t,i.title=e,i.setAttribute("aria-label",e),Object.assign(i.style,{width:"28px",height:"28px",borderRadius:"50%",border:"1px solid rgba(200, 208, 218, 0.6)",background:"rgba(255, 255, 255, 0.85)",backdropFilter:"blur(8px)",WebkitBackdropFilter:"blur(8px)",color:"#4a4a6a",fontSize:"14px",fontWeight:"700",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",padding:"0",lineHeight:"1",transition:"background 0.15s, transform 0.15s",boxShadow:"0 2px 8px rgba(0,0,0,0.08)"}),i.addEventListener("mouseenter",()=>{i.style.background="rgba(240, 242, 245, 0.95)",i.style.transform="scale(1.1)"}),i.addEventListener("mouseleave",()=>{i.style.background="rgba(255, 255, 255, 0.85)",i.style.transform="scale(1)"}),i}}const Ux="https://us-central1-holostaff-ai.cloudfunctions.net";class Lx{constructor(t){this.messages={},this.actions=[],this.msgCounter=0,this.staffId=t.staffId,this.staffName=t.staffName,this.backendUrl=t.backendUrl??Ux,this.startTime=new Date().toISOString(),this.userId=`visitor_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`}addUserMessage(t){if(!t.trim())return;const e=`msg_${this.msgCounter++}`;this.messages[e]={sender:"user",text:t.trim(),timestamp:new Date().toISOString()}}addStaffMessage(t){if(!t.trim())return;const e=`msg_${this.msgCounter++}`;this.messages[e]={sender:"staff",text:t.trim(),timestamp:new Date().toISOString()}}addAction(t,e){this.actions.push({tool:t,args:e,timestamp:new Date().toISOString()})}async flush(){if(Object.keys(this.messages).length===0){console.log("[Logger] No messages to log, skipping");return}const t=Object.values(this.messages).pop(),e={staffId:this.staffId,staffName:this.staffName,userId:this.userId,startTime:this.startTime,lastMessageAt:(t==null?void 0:t.timestamp)??this.startTime,messages:this.messages,actions:this.actions,source:"widget_v2"};console.log("[Logger] Flushing conversation log:",{messages:Object.keys(this.messages).length,actions:this.actions.length});try{const i=await fetch(`${this.backendUrl}/logConversation`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(i.ok){const r=await i.json();console.log("[Logger] Conversation logged:",r.id)}else console.warn("[Logger] Failed to log conversation:",i.status)}catch(i){console.warn("[Logger] Error logging conversation:",i)}}}const Fx=8,Nx=800,Hx=600*1e3,Wx=540*1e3,eu=60*1e3,Vx=90*1e3,zx=[{type:"function",name:"page_action",description:"Interact with the webpage the visitor is viewing. You can scroll to elements, highlight elements, click buttons/links, fill form fields, or read the page content. Describe what you want to do in natural language. Call this to understand the page, guide the visitor, or take actions on their behalf.",parameters:{type:"object",properties:{instruction:{type:"string",description:"What to do on the page, e.g. 'scroll to pricing section', 'highlight the sign-up button', 'fill the email field with test@example.com', 'read the page to understand what it contains'"}},required:["instruction"]}},{type:"function",name:"show_text_card",description:"Display a floating text card overlay near the avatar with additional information for the visitor. Use for key points, explanations, or summaries that benefit from visual display.",parameters:{type:"object",properties:{title:{type:"string",description:"Card title"},body:{type:"string",description:"Card body text"}},required:["title","body"]}},{type:"function",name:"show_image_card",description:"Display a floating image card overlay with an optional caption.",parameters:{type:"object",properties:{image_url:{type:"string",description:"URL of the image to display"},caption:{type:"string",description:"Optional caption below the image"}},required:["image_url"]}},{type:"function",name:"show_bullet_list",description:"Display a styled list of key points as a floating overlay card.",parameters:{type:"object",properties:{title:{type:"string",description:"List title"},items:{type:"array",items:{type:"string"},description:"List items"}},required:["title","items"]}},{type:"function",name:"dismiss_overlays",description:"Dismiss all currently visible overlay cards.",parameters:{type:"object",properties:{},required:[]}}];class iu{constructor(t,e){this.stage=null,this.avatar=null,this.bubble=null,this.state="idle",this.avatarState="idle",this.scrollHandler=null,this.idleVideoUrl=null,this.bubbleTimer=null,this.realtimeSession=null,this.audioForwarder=null,this.anamSession=null,this.sessionResponse=null,this.domAnalyzer=null,this.toolHandler=null,this.highlightRenderer=null,this.confirmationPrompt=null,this.overlayRenderer=null,this.controls=null,this.maxDurationTimer=null,this.maxDurationWarnTimer=null,this.inactivityTimer=null,this.inactivityCloseTimer=null,this.sessionStartTime=0,this.logger=null,this.config=t,this.widgetPrompts=e??null}async init(){this.stage=new _y,await this.stage.init(),this.avatar=new vy(this.stage.stageWidth,this.stage.stageHeight),this.stage.app.stage.addChild(this.avatar.container),await this.loadIdleAsset(),this.bubble=new ky(this.stage.app.ticker,this.widgetPrompts??void 0),this.bubble.container.x=0,this.bubble.container.y=-zt-Fx,this.avatar.container.addChild(this.bubble.container),this.avatar.setInteractive(()=>this.onAvatarClick()),this.bubble.onClick(()=>this.onAvatarClick()),this.setupTrigger(),console.log("[HolostaffWidget] Initialized",{staffId:this.config.staffId,trigger:this.config.trigger})}async loadIdleAsset(){if(this.avatar)if(this.idleVideoUrl)await this.avatar.loadIdleVideo(this.idleVideoUrl);else try{await this.avatar.loadIdleVideo("/assets/idle-loop-green-8.mp4")}catch{console.warn("[HolostaffWidget] No idle video found, using static fallback"),await this.avatar.loadIdleImage("/assets/avatar-placeholder.png")}}setIdleVideo(t){this.idleVideoUrl=t}setupTrigger(){switch(this.config.trigger){case"scroll":this.setupScrollTrigger();break;case"delay":setTimeout(()=>this.showTeaser(),this.config.delayMs);break;case"immediate":this.showTeaser();break}}setupScrollTrigger(){this.scrollHandler=()=>{const t=window.scrollY,e=document.documentElement.scrollHeight-window.innerHeight,i=e>0?t/e:0;i>=this.config.scrollThreshold&&this.state==="idle"?this.showTeaser():i<this.config.scrollThreshold*.5&&this.state==="teasing"&&this.hideTeaser()},window.addEventListener("scroll",this.scrollHandler,{passive:!0})}showTeaser(){this.state!=="idle"||!this.avatar||!this.stage||(this.state="teasing",this.avatar.slideIn(this.stage.app.ticker),this.bubbleTimer=setTimeout(()=>{var t;return(t=this.bubble)==null?void 0:t.start()},Nx))}hideTeaser(){var t;this.state!=="teasing"||!this.avatar||!this.stage||(this.state="idle",this.bubbleTimer&&(clearTimeout(this.bubbleTimer),this.bubbleTimer=null),(t=this.bubble)==null||t.stop(),this.avatar.slideOut(this.stage.app.ticker))}async onAvatarClick(){var t;if(this.state==="teasing"){this.state="connecting",(t=this.bubble)==null||t.stop(),console.log("[HolostaffWidget] Starting conversation...");try{this.sessionResponse=await wu(this.config.staffId,this.config.backendUrl),console.log("[HolostaffWidget] Session tokens received"),this.logger=new Lx({staffId:this.config.staffId,staffName:this.sessionResponse.staff.name,backendUrl:this.config.backendUrl}),await this.connectAnam(),await this.connectRealtimeApi(),this.state="active",this.setAvatarState("listening"),this.sessionStartTime=Date.now(),this.showControls(),this.startSessionTimers(),console.log("[HolostaffWidget] Conversation active")}catch(e){console.error("[HolostaffWidget] Failed to start conversation:",e),this.endConversation()}}}async connectAnam(){this.sessionResponse&&(this.anamSession=new xx({sessionToken:this.sessionResponse.anamSessionToken}),this.anamSession.onConnected=()=>{console.log("[HolostaffWidget] Anam connected")},this.anamSession.onVideoReady=t=>{console.log("[HolostaffWidget] Anam avatar video ready"),this.avatar&&this.stage&&this.avatar.setLiveVideo(t,this.stage.app.ticker)},this.anamSession.onTalkStreamInterrupted=()=>{console.log("[HolostaffWidget] Anam talk stream interrupted")},this.anamSession.onDisconnected=t=>{console.log("[HolostaffWidget] Anam disconnected:",t),this.endConversation()},this.anamSession.onError=t=>{console.error("[HolostaffWidget] Anam error:",t.message)},await this.anamSession.connect(),console.log("[HolostaffWidget] Anam session ready"))}async connectRealtimeApi(){if(!this.sessionResponse)return;const t=(this.sessionResponse.staff.instructions??"")+`
|
|
997
|
+
|
|
998
|
+
## Page Interaction
|
|
999
|
+
You can interact with the webpage the visitor is viewing by calling the page_action tool.
|
|
1000
|
+
Call it with instruction "read the page content" first to understand what is on the page.
|
|
1001
|
+
Then you can scroll to elements, highlight them, click links/buttons, or fill form fields.
|
|
1002
|
+
All actions except form filling require the visitor to confirm before executing.`;this.realtimeSession=new Gy({ephemeralKey:this.sessionResponse.realtimeEphemeralKey,webrtcUrl:this.sessionResponse.realtimeWebrtcUrl,voice:this.sessionResponse.staff.voiceId,instructions:t,tools:zx}),this.domAnalyzer=new Sx,this.highlightRenderer=new Px,this.confirmationPrompt=new Mx,this.realtimeSession.onConnected=()=>{var i,r,n,o;console.log("[HolostaffWidget] Realtime API connected");const e=(i=this.sessionResponse)==null?void 0:i.staff.openingText;e!=null&&e.trim()&&((r=this.realtimeSession)==null||r.sendJSON({type:"conversation.item.create",item:{type:"message",role:"user",content:[{type:"input_text",text:"(conversation started — greet the visitor now)"}]}}),(n=this.realtimeSession)==null||n.sendJSON({type:"conversation.item.create",item:{type:"message",role:"assistant",content:[{type:"text",text:e}]}}),(o=this.realtimeSession)==null||o.sendJSON({type:"response.create"}))},this.realtimeSession.onDisconnected=()=>{console.log("[HolostaffWidget] Realtime API disconnected"),(this.state==="active"||this.state==="connecting")&&this.endConversation()},this.realtimeSession.onRemoteTrack=async e=>{console.log("[HolostaffWidget] Remote audio track → starting audio forwarder"),this.audioForwarder=new Ny,this.audioForwarder.onAudioChunk=i=>{var r;(r=this.anamSession)==null||r.sendAudioChunk(i)},await this.audioForwarder.start(e)},this.overlayRenderer=new Dx,this.toolHandler=new wx({realtimeSession:this.realtimeSession,domAnalyzer:this.domAnalyzer,pageActions:new Ax(this.domAnalyzer,this.highlightRenderer),overlayActions:new Rx(this.overlayRenderer),confirmationPrompt:this.confirmationPrompt,staffId:this.config.staffId,backendUrl:this.config.backendUrl}),this.toolHandler.onToolCall=(e,i)=>{var r;(r=this.logger)==null||r.addAction(e,i)},this.realtimeSession.onDataMessage=e=>{this.handleDataChannelMessage(e)},this.realtimeSession.onError=e=>{console.error("[HolostaffWidget] Realtime error:",e.message),this.endConversation()},await this.realtimeSession.connect()}handleDataChannelMessage(t){var i,r,n,o,a,l,h,c;if((i=this.toolHandler)!=null&&i.handleMessage(t))return;const e=t.type;switch(e){case"session.created":case"session.updated":console.log("[HolostaffWidget] Data:",e);break;case"input_audio_buffer.speech_started":console.log("[HolostaffWidget] User started speaking"),(r=this.anamSession)==null||r.interrupt(),(n=this.audioForwarder)==null||n.pause(),this.setAvatarState("listening"),this.resetInactivityTimer();break;case"input_audio_buffer.speech_stopped":console.log("[HolostaffWidget] User stopped speaking"),this.setAvatarState("thinking");break;case"response.created":console.log("[HolostaffWidget] AI response started"),(o=this.audioForwarder)==null||o.resume(),this.setAvatarState("speaking");break;case"response.done":console.log("[HolostaffWidget] AI response done"),(a=this.anamSession)==null||a.endSequence(),this.setAvatarState("listening"),this.resetInactivityTimer(),this.extractAiTranscript(t.response);break;case"conversation.item.input_audio_transcription.completed":console.log("[HolostaffWidget] User said:",t.transcript),(l=this.logger)==null||l.addUserMessage(t.transcript??"");break;case"error":console.error("[HolostaffWidget] Realtime error event:",t.error);break;case"response.cancelled":case"response.canceled":case"response.failed":console.warn("[HolostaffWidget] Response ended:",e),(h=this.anamSession)==null||h.endSequence(),(c=this.audioForwarder)==null||c.pause(),this.setAvatarState("listening");break}}extractAiTranscript(t){if(!(!(t!=null&&t.output)||!this.logger)){for(const e of t.output)if(e.type==="message"&&e.content)for(const i of e.content)i.transcript?this.logger.addStaffMessage(i.transcript):i.text&&this.logger.addStaffMessage(i.text)}}setAvatarState(t){if(this.avatarState===t)return;const e=this.avatarState;this.avatarState=t,console.log(`[HolostaffWidget] Avatar: ${e} → ${t}`)}showControls(){this.controls=new Gx,this.controls.onMinimize=()=>{var t;this.state="minimized",this.avatar&&this.stage&&this.avatar.slideOut(this.stage.app.ticker),(t=this.overlayRenderer)==null||t.dismissAll(),console.log("[HolostaffWidget] Minimized")},this.controls.onRestore=()=>{this.state="active",this.avatar&&this.stage&&this.avatar.slideIn(this.stage.app.ticker),console.log("[HolostaffWidget] Restored")},this.controls.onClose=()=>{console.log("[HolostaffWidget] Close button clicked"),this.endConversation()},this.controls.show()}startSessionTimers(){this.maxDurationWarnTimer=setTimeout(()=>{var t,e;console.log("[HolostaffWidget] Session approaching max duration"),(t=this.realtimeSession)==null||t.sendJSON({type:"conversation.item.create",item:{type:"message",role:"system",content:[{type:"input_text",text:"The session will end in about one minute. Please wrap up the conversation gracefully."}]}}),(e=this.realtimeSession)==null||e.sendJSON({type:"response.create"})},Wx),this.maxDurationTimer=setTimeout(()=>{console.log("[HolostaffWidget] Max session duration reached"),this.endConversation()},Hx),this.resetInactivityTimer()}resetInactivityTimer(){this.inactivityTimer&&clearTimeout(this.inactivityTimer),this.inactivityCloseTimer&&clearTimeout(this.inactivityCloseTimer),this.inactivityTimer=setTimeout(()=>{var t,e;this.state==="active"&&(console.log("[HolostaffWidget] Inactivity — prompting user"),(t=this.realtimeSession)==null||t.sendJSON({type:"conversation.item.create",item:{type:"message",role:"system",content:[{type:"input_text",text:'The visitor has been silent for a while. Ask them "Still there?" in a friendly way.'}]}}),(e=this.realtimeSession)==null||e.sendJSON({type:"response.create"}),this.inactivityCloseTimer=setTimeout(()=>{this.state==="active"&&(console.log("[HolostaffWidget] Inactivity — auto-closing"),this.endConversation())},Vx-eu))},eu)}clearSessionTimers(){this.maxDurationTimer&&(clearTimeout(this.maxDurationTimer),this.maxDurationTimer=null),this.maxDurationWarnTimer&&(clearTimeout(this.maxDurationWarnTimer),this.maxDurationWarnTimer=null),this.inactivityTimer&&(clearTimeout(this.inactivityTimer),this.inactivityTimer=null),this.inactivityCloseTimer&&(clearTimeout(this.inactivityCloseTimer),this.inactivityCloseTimer=null)}endConversation(){var t,e,i,r,n,o,a,l;(t=this.logger)==null||t.flush(),this.logger=null,this.clearSessionTimers(),(e=this.controls)==null||e.hide(),this.controls=null,(i=this.audioForwarder)==null||i.stop(),this.audioForwarder=null,(r=this.anamSession)==null||r.close(),this.anamSession=null,(n=this.realtimeSession)==null||n.close(),this.realtimeSession=null,this.sessionResponse=null,this.avatarState="idle",this.toolHandler=null,this.domAnalyzer=null,(o=this.highlightRenderer)==null||o.clearAll(),this.highlightRenderer=null,(a=this.confirmationPrompt)==null||a.dismiss(),this.confirmationPrompt=null,(l=this.overlayRenderer)==null||l.dismissAll(),this.overlayRenderer=null,this.avatar&&this.stage&&this.avatar.clearLiveVideo(this.stage.app.ticker),this.state="idle",console.log("[HolostaffWidget] Conversation ended")}destroy(){var t,e,i;this.state="destroyed",this.endConversation(),this.scrollHandler&&window.removeEventListener("scroll",this.scrollHandler),this.bubbleTimer&&clearTimeout(this.bubbleTimer),(t=this.bubble)==null||t.destroy(),(e=this.avatar)==null||e.destroy(),(i=this.stage)==null||i.destroy(),this.bubble=null,this.avatar=null,this.stage=null}}function $x(){const s=document.currentScript??document.querySelector("script[data-staff-id]");if(!s){console.error("[HolostaffWidget] Could not find script tag with data-staff-id");return}try{const t=vu(s);async function e(){let i=t,r=null;try{const o=await Au(t.staffId,t.backendUrl);i=Cu(t,s,o),r=o.widgetPrompts}catch(o){console.warn("[HolostaffWidget] Failed to fetch server config, using embed defaults:",o)}const n=new iu(i,r);window.holostaffWidget=n,n.init()}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>e()):e()}catch(t){console.error("[HolostaffWidget]",t)}}$x(),J.add(Ld),J.mixin(kt,Fd),J.add(Ll),J.add(Fl),J.mixin(kt,dm),J.add(Vl),J.add(Hl);const jx=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),Xx=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));ai.HolostaffWidget=iu,Object.defineProperty(ai,Symbol.toStringTag,{value:"Module"})}));
|
|
1003
|
+
//# sourceMappingURL=hs-widget.umd.js.map
|