@ray-js/robot-map-sdk 0.0.15-beta.8 → 0.0.15

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.
Files changed (61) hide show
  1. package/bin/mcp-server.js +1 -1
  2. package/dist/constant/methods.js +1 -1
  3. package/dist/index.d.ts +44 -4
  4. package/dist/index.rjs.js +1 -1
  5. package/dist-app/assets/index-DMEnUYiD.js +1 -0
  6. package/dist-app/index.html +1 -2
  7. package/dist-docs/404.html +2 -2
  8. package/dist-docs/agents/domain.html +39 -0
  9. package/dist-docs/agents/issue-tracker.html +25 -0
  10. package/dist-docs/agents/triage-labels.html +25 -0
  11. package/dist-docs/assets/agents_domain.md.CYB9yWEy.js +15 -0
  12. package/dist-docs/assets/agents_domain.md.CYB9yWEy.lean.js +1 -0
  13. package/dist-docs/assets/agents_issue-tracker.md.CrjzmXmc.js +1 -0
  14. package/dist-docs/assets/agents_issue-tracker.md.CrjzmXmc.lean.js +1 -0
  15. package/dist-docs/assets/agents_triage-labels.md.Cmw0b5xB.js +1 -0
  16. package/dist-docs/assets/agents_triage-labels.md.Cmw0b5xB.lean.js +1 -0
  17. package/dist-docs/assets/{app.qpayiG6C.js → app.BXGPC0v4.js} +1 -1
  18. package/dist-docs/assets/chunks/@localSearchIndexroot.D-feMZmG.js +1 -0
  19. package/dist-docs/assets/chunks/{BitmapFont.C7oZeIsf.js → BitmapFont.DzUyMNlJ.js} +1 -1
  20. package/dist-docs/assets/chunks/{BufferResource.DlhatX3V.js → BufferResource.Drg97r2Z.js} +1 -1
  21. package/dist-docs/assets/chunks/{CanvasRenderer.qtwtojUj.js → CanvasRenderer.vfz9sPE6.js} +1 -1
  22. package/dist-docs/assets/chunks/{RenderTargetSystem.h1UtLLl-.js → RenderTargetSystem.Bkr0oS6j.js} +1 -1
  23. package/dist-docs/assets/chunks/{VPLocalSearchBox.VGFbBqUp.js → VPLocalSearchBox.C7HJ4UkB.js} +1 -1
  24. package/dist-docs/assets/chunks/{WebGLRenderer.CTrQ5cex.js → WebGLRenderer.D4Dgosvx.js} +1 -1
  25. package/dist-docs/assets/chunks/{WebGPURenderer.CbssqhSN.js → WebGPURenderer.CT3AUgw3.js} +1 -1
  26. package/dist-docs/assets/chunks/{browserAll.C-8Fex_M.js → browserAll.NKEQOzVE.js} +1 -1
  27. package/dist-docs/assets/chunks/index.CvitVYBK.js +744 -0
  28. package/dist-docs/assets/chunks/theme.DUpgtHaE.js +4 -0
  29. package/dist-docs/assets/chunks/{webworkerAll.BzbTMnqm.js → webworkerAll.JQUyAE7k.js} +1 -1
  30. package/dist-docs/assets/{guide_getting-started.md.CmPlW_Cy.js → guide_getting-started.md.s0ecK_5b.js} +1 -1
  31. package/dist-docs/assets/{reference_config.md.DJr6BhNY.js → reference_config.md.B45KsJB6.js} +3 -3
  32. package/dist-docs/assets/{reference_config.md.DJr6BhNY.lean.js → reference_config.md.B45KsJB6.lean.js} +1 -1
  33. package/dist-docs/guide/advanced-usage.html +3 -3
  34. package/dist-docs/guide/concepts.html +3 -3
  35. package/dist-docs/guide/getting-started.html +5 -5
  36. package/dist-docs/guide/mcp.html +3 -3
  37. package/dist-docs/hashmap.json +1 -1
  38. package/dist-docs/index.html +3 -3
  39. package/dist-docs/plans/2026-03-04-detected-objects-visibility-design.html +3 -3
  40. package/dist-docs/plans/2026-03-04-show-detected-objects-implementation-plan.html +3 -3
  41. package/dist-docs/plans/2026-03-10-simulator-debug-design.html +3 -3
  42. package/dist-docs/plans/2026-03-10-simulator-events-console-design.html +3 -3
  43. package/dist-docs/plans/2026-03-10-simulator-events-console-implementation-plan.html +3 -3
  44. package/dist-docs/plans/2026-03-10-simulator-runtime-controls-design.html +3 -3
  45. package/dist-docs/plans/2026-03-10-simulator-runtime-controls-implementation-plan.html +3 -3
  46. package/dist-docs/plans/2026-03-10-testing-rollout-next-steps-plan.html +3 -3
  47. package/dist-docs/plans/2026-03-11-simulator-logger-dump-implementation-plan.html +3 -3
  48. package/dist-docs/reference/callbacks.html +3 -3
  49. package/dist-docs/reference/config.html +6 -6
  50. package/dist-docs/reference/data.html +3 -3
  51. package/dist-docs/reference/methods.html +3 -3
  52. package/dist-docs/reference/runtime.html +3 -3
  53. package/dist-docs/reference/types.html +3 -3
  54. package/dist-docs/reference/utils.html +3 -3
  55. package/dist-docs/simulator/index.html +3 -3
  56. package/package.json +2 -1
  57. package/dist-app/assets/index-CV-5yK7G.js +0 -1
  58. package/dist-docs/assets/chunks/@localSearchIndexroot.momHo4OR.js +0 -1
  59. package/dist-docs/assets/chunks/index.BVy8BWUZ.js +0 -744
  60. package/dist-docs/assets/chunks/theme.sPi1G3ho.js +0 -4
  61. /package/dist-docs/assets/{guide_getting-started.md.CmPlW_Cy.lean.js → guide_getting-started.md.s0ecK_5b.lean.js} +0 -0
@@ -0,0 +1,744 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/chunks/browserAll.NKEQOzVE.js","assets/chunks/webworkerAll.JQUyAE7k.js","assets/chunks/framework.CBLqO2Q1.js","assets/chunks/mapValues.D2X8cRgC.js","assets/chunks/theme.DUpgtHaE.js","assets/chunks/WebGPURenderer.CT3AUgw3.js","assets/chunks/BufferResource.Drg97r2Z.js","assets/chunks/RenderTargetSystem.Bkr0oS6j.js","assets/chunks/WebGLRenderer.D4Dgosvx.js","assets/chunks/CanvasRenderer.vfz9sPE6.js","assets/chunks/BitmapFont.DzUyMNlJ.js"])))=>i.map(i=>d[i]);
2
+ var Hc=Object.defineProperty;var Nc=(n,t,e)=>t in n?Hc(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var f=(n,t,e)=>Nc(n,typeof t!="symbol"?t+"":t,e);import{V as Me}from"./framework.CBLqO2Q1.js";import{L as lh,u as ch,m as dh,G as Vc,E as $c,d as Ee,y as Yc,Q as Xc,v as uh,H as jc,R as Zc,T as qc,i as gr,U as ph,V as Kc,W as Qc,I as Jc,X as td,K as to,Y as ed,e as id,w as sd,l as Ln,f as nd,a as rd,x as eo,Z as od,h as ad,_ as hd,j as ld,$ as fh,a0 as cd,a1 as dd,C as ud,a2 as pd,N as zn,O as fd,P as gd,M as io}from"./mapValues.D2X8cRgC.js";import{a as ne,N as Ys,i as Ne,D as gh,b as so,M as no,d as md,H as yd,e as xd}from"./theme.DUpgtHaE.js";var E=(n=>(n.Application="application",n.WebGLPipes="webgl-pipes",n.WebGLPipesAdaptor="webgl-pipes-adaptor",n.WebGLSystem="webgl-system",n.WebGPUPipes="webgpu-pipes",n.WebGPUPipesAdaptor="webgpu-pipes-adaptor",n.WebGPUSystem="webgpu-system",n.CanvasSystem="canvas-system",n.CanvasPipesAdaptor="canvas-pipes-adaptor",n.CanvasPipes="canvas-pipes",n.Asset="asset",n.LoadParser="load-parser",n.ResolveParser="resolve-parser",n.CacheParser="cache-parser",n.DetectionParser="detection-parser",n.MaskEffect="mask-effect",n.BlendMode="blend-mode",n.TextureSource="texture-source",n.Environment="environment",n.ShapeBuilder="shape-builder",n.Batcher="batcher",n))(E||{});const On=n=>{if(typeof n=="function"||typeof n=="object"&&n.extension){if(!n.extension)throw new Error("Extension class must have an extension object");n={...typeof n.extension!="object"?{type:n.extension}:n.extension,ref:n}}if(typeof n=="object")n={...n};else throw new Error("Invalid extension type");return typeof n.type=="string"&&(n.type=[n.type]),n},$i=(n,t)=>On(n).priority??t,q={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...n){return n.map(On).forEach(t=>{t.type.forEach(e=>{var i,s;return(s=(i=this._removeHandlers)[e])==null?void 0:s.call(i,t)})}),this},add(...n){return n.map(On).forEach(t=>{t.type.forEach(e=>{var r,o;const i=this._addHandlers,s=this._queue;i[e]?(o=i[e])==null||o.call(i,t):(s[e]=s[e]||[],(r=s[e])==null||r.push(t))})}),this},handle(n,t,e){var o;const i=this._addHandlers,s=this._removeHandlers;if(i[n]||s[n])throw new Error(`Extension type ${n} already has a handler`);i[n]=t,s[n]=e;const r=this._queue;return r[n]&&((o=r[n])==null||o.forEach(a=>t(a)),delete r[n]),this},handleByMap(n,t){return this.handle(n,e=>{e.name&&(t[e.name]=e.ref)},e=>{e.name&&delete t[e.name]})},handleByNamedList(n,t,e=-1){return this.handle(n,i=>{t.findIndex(r=>r.name===i.name)>=0||(t.push({name:i.name,value:i.ref}),t.sort((r,o)=>$i(o.value,e)-$i(r.value,e)))},i=>{const s=t.findIndex(r=>r.name===i.name);s!==-1&&t.splice(s,1)})},handleByList(n,t,e=-1){return this.handle(n,i=>{t.includes(i.ref)||(t.push(i.ref),t.sort((s,r)=>$i(r,e)-$i(s,e)))},i=>{const s=t.indexOf(i.ref);s!==-1&&t.splice(s,1)})},mixin(n,...t){for(const e of t)Object.defineProperties(n.prototype,Object.getOwnPropertyDescriptors(e))}},Sd={extension:{type:E.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await Me(()=>import("./browserAll.NKEQOzVE.js"),__vite__mapDeps([0,1,2,3,4]))}},vd={extension:{type:E.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await Me(()=>import("./webworkerAll.JQUyAE7k.js"),__vite__mapDeps([1,2,3,4]))}};class lt{constructor(t,e,i){this._x=e||0,this._y=i||0,this._observer=t}clone(t){return new lt(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))}}var mh={exports:{}};(function(n){var t=Object.prototype.hasOwnProperty,e="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(e=!1));function s(h,l,c){this.fn=h,this.context=l,this.once=c||!1}function r(h,l,c,d,u){if(typeof c!="function")throw new TypeError("The listener must be a function");var p=new s(c,d||h,u),g=e?e+l:l;return h._events[g]?h._events[g].fn?h._events[g]=[h._events[g],p]:h._events[g].push(p):(h._events[g]=p,h._eventsCount++),h}function o(h,l){--h._eventsCount===0?h._events=new i:delete h._events[l]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],c,d;if(this._eventsCount===0)return l;for(d in c=this._events)t.call(c,d)&&l.push(e?d.slice(1):d);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},a.prototype.listeners=function(l){var c=e?e+l:l,d=this._events[c];if(!d)return[];if(d.fn)return[d.fn];for(var u=0,p=d.length,g=new Array(p);u<p;u++)g[u]=d[u].fn;return g},a.prototype.listenerCount=function(l){var c=e?e+l:l,d=this._events[c];return d?d.fn?1:d.length:0},a.prototype.emit=function(l,c,d,u,p,g){var y=e?e+l:l;if(!this._events[y])return!1;var m=this._events[y],x=arguments.length,S,v;if(m.fn){switch(m.once&&this.removeListener(l,m.fn,void 0,!0),x){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,c),!0;case 3:return m.fn.call(m.context,c,d),!0;case 4:return m.fn.call(m.context,c,d,u),!0;case 5:return m.fn.call(m.context,c,d,u,p),!0;case 6:return m.fn.call(m.context,c,d,u,p,g),!0}for(v=1,S=new Array(x-1);v<x;v++)S[v-1]=arguments[v];m.fn.apply(m.context,S)}else{var b=m.length,P;for(v=0;v<b;v++)switch(m[v].once&&this.removeListener(l,m[v].fn,void 0,!0),x){case 1:m[v].fn.call(m[v].context);break;case 2:m[v].fn.call(m[v].context,c);break;case 3:m[v].fn.call(m[v].context,c,d);break;case 4:m[v].fn.call(m[v].context,c,d,u);break;default:if(!S)for(P=1,S=new Array(x-1);P<x;P++)S[P-1]=arguments[P];m[v].fn.apply(m[v].context,S)}}return!0},a.prototype.on=function(l,c,d){return r(this,l,c,d,!1)},a.prototype.once=function(l,c,d){return r(this,l,c,d,!0)},a.prototype.removeListener=function(l,c,d,u){var p=e?e+l:l;if(!this._events[p])return this;if(!c)return o(this,p),this;var g=this._events[p];if(g.fn)g.fn===c&&(!u||g.once)&&(!d||g.context===d)&&o(this,p);else{for(var y=0,m=[],x=g.length;y<x;y++)(g[y].fn!==c||u&&!g[y].once||d&&g[y].context!==d)&&m.push(g[y]);m.length?this._events[p]=m.length===1?m[0]:m:o(this,p)}return this},a.prototype.removeAllListeners=function(l){var c;return l?(c=e?e+l:l,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,n.exports=a})(mh);var bd=mh.exports;const Yt=lh(bd),wd=Math.PI*2,Cd=180/Math.PI,_d=Math.PI/180;class Q{constructor(t=0,e=0){this.x=0,this.y=0,this.x=t,this.y=e}clone(){return new Q(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 Xs.x=0,Xs.y=0,Xs}}const Xs=new Q;class U{constructor(t=1,e=0,i=0,s=1,r=0,o=0){this.array=null,this.a=t,this.b=e,this.c=i,this.d=s,this.tx=r,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,s,r,o){return this.a=t,this.b=e,this.c=i,this.d=s,this.tx=r,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 Q;const i=t.x,s=t.y;return e.x=this.a*i+this.c*s+this.tx,e.y=this.b*i+this.d*s+this.ty,e}applyInverse(t,e){e=e||new Q;const i=this.a,s=this.b,r=this.c,o=this.d,a=this.tx,h=this.ty,l=1/(i*o+r*-s),c=t.x,d=t.y;return e.x=o*l*c+-r*l*d+(h*r-a*o)*l,e.y=i*l*d+-s*l*c+(-h*i+a*s)*l,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),s=this.a,r=this.c,o=this.tx;return this.a=s*e-this.b*i,this.b=s*i+this.b*e,this.c=r*e-this.d*i,this.d=r*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,s=this.c,r=this.d;return this.a=t.a*e+t.b*s,this.b=t.a*i+t.b*r,this.c=t.c*e+t.d*s,this.d=t.c*i+t.d*r,this.tx=t.tx*e+t.ty*s+this.tx,this.ty=t.tx*i+t.ty*r+this.ty,this}appendFrom(t,e){const i=t.a,s=t.b,r=t.c,o=t.d,a=t.tx,h=t.ty,l=e.a,c=e.b,d=e.c,u=e.d;return this.a=i*l+s*d,this.b=i*c+s*u,this.c=r*l+o*d,this.d=r*c+o*u,this.tx=a*l+h*d+e.tx,this.ty=a*c+h*u+e.ty,this}setTransform(t,e,i,s,r,o,a,h,l){return this.a=Math.cos(a+l)*r,this.b=Math.sin(a+l)*r,this.c=-Math.sin(a-h)*o,this.d=Math.cos(a-h)*o,this.tx=t-(i*this.a+s*this.c),this.ty=e-(i*this.b+s*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,s=this.c;this.a=i*t.a+this.b*t.c,this.b=i*t.b+this.b*t.d,this.c=s*t.a+this.d*t.c,this.d=s*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,s=this.c,r=this.d,o=t.pivot,a=-Math.atan2(-s,r),h=Math.atan2(i,e),l=Math.abs(a+h);return l<1e-5||Math.abs(wd-l)<1e-5?(t.rotation=h,t.skew.x=t.skew.y=0):(t.rotation=0,t.skew.x=a,t.skew.y=h),t.scale.x=Math.sqrt(e*e+i*i),t.scale.y=Math.sqrt(s*s+r*r),t.position.x=this.tx+(o.x*e+o.y*s),t.position.y=this.ty+(o.x*i+o.y*r),t}invert(){const t=this.a,e=this.b,i=this.c,s=this.d,r=this.tx,o=t*s-e*i;return this.a=s/o,this.b=-e/o,this.c=-i/o,this.d=t/o,this.tx=(i*this.ty-s*r)/o,this.ty=-(t*this.ty-e*r)/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 U;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 Md.identity()}static get shared(){return Pd.identity()}}const Pd=new U,Md=new U,xe=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],Se=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],ve=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],be=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],Wn=[],yh=[],Yi=Math.sign;function Td(){for(let n=0;n<16;n++){const t=[];Wn.push(t);for(let e=0;e<16;e++){const i=Yi(xe[n]*xe[e]+ve[n]*Se[e]),s=Yi(Se[n]*xe[e]+be[n]*Se[e]),r=Yi(xe[n]*ve[e]+ve[n]*be[e]),o=Yi(Se[n]*ve[e]+be[n]*be[e]);for(let a=0;a<16;a++)if(xe[a]===i&&Se[a]===s&&ve[a]===r&&be[a]===o){t.push(a);break}}}for(let n=0;n<16;n++){const t=new U;t.set(xe[n],Se[n],ve[n],be[n],0,0),yh.push(t)}}Td();const X={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:n=>xe[n],uY:n=>Se[n],vX:n=>ve[n],vY:n=>be[n],inv:n=>n&8?n&15:-n&7,add:(n,t)=>Wn[n][t],sub:(n,t)=>Wn[n][X.inv(t)],rotate180:n=>n^4,isVertical:n=>(n&3)===2,byDirection:(n,t)=>Math.abs(n)*2<=Math.abs(t)?t>=0?X.S:X.N:Math.abs(t)*2<=Math.abs(n)?n>0?X.E:X.W:t>0?n>0?X.SE:X.SW:n>0?X.NE:X.NW,matrixAppendRotationInv:(n,t,e=0,i=0,s=0,r=0)=>{const o=yh[X.inv(t)],a=o.a,h=o.b,l=o.c,c=o.d,d=e-Math.min(0,a*s,l*r,a*s+l*r),u=i-Math.min(0,h*s,c*r,h*s+c*r),p=n.a,g=n.b,y=n.c,m=n.d;n.a=a*p+h*y,n.b=a*g+h*m,n.c=l*p+c*y,n.d=l*g+c*m,n.tx=d*p+u*y+n.tx,n.ty=d*g+u*m+n.ty},transformRectCoords:(n,t,e,i)=>{const{x:s,y:r,width:o,height:a}=n,{x:h,y:l,width:c,height:d}=t;return e===X.E?(i.set(s+h,r+l,o,a),i):e===X.S?i.set(c-r-a+h,s+l,a,o):e===X.W?i.set(c-s-o+h,d-r-a+l,o,a):e===X.N?i.set(r+h,d-s-o+l,a,o):i.set(s+h,r+l,o,a)}},Xi=[new Q,new Q,new Q,new Q];class J{constructor(t=0,e=0,i=0,s=0){this.type="rectangle",this.x=Number(t),this.y=Number(e),this.width=Number(i),this.height=Number(s)}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 J(0,0,0,0)}clone(){return new J(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,s=.5){const{width:r,height:o}=this;if(r<=0||o<=0)return!1;const a=this.x,h=this.y,l=i*(1-s),c=i-l,d=a-l,u=a+r+l,p=h-l,g=h+o+l,y=a+c,m=a+r-c,x=h+c,S=h+o-c;return t>=d&&t<=u&&e>=p&&e<=g&&!(t>y&&t<m&&e>x&&e<S)}intersects(t,e){if(!e){const R=this.x<t.x?t.x:this.x;if((this.right>t.right?t.right:this.right)<=R)return!1;const A=this.y<t.y?t.y:this.y;return(this.bottom>t.bottom?t.bottom:this.bottom)>A}const i=this.left,s=this.right,r=this.top,o=this.bottom;if(s<=i||o<=r)return!1;const a=Xi[0].set(t.left,t.top),h=Xi[1].set(t.left,t.bottom),l=Xi[2].set(t.right,t.top),c=Xi[3].set(t.right,t.bottom);if(l.x<=a.x||h.y<=a.y)return!1;const d=Math.sign(e.a*e.d-e.b*e.c);if(d===0||(e.apply(a,a),e.apply(h,h),e.apply(l,l),e.apply(c,c),Math.max(a.x,h.x,l.x,c.x)<=i||Math.min(a.x,h.x,l.x,c.x)>=s||Math.max(a.y,h.y,l.y,c.y)<=r||Math.min(a.y,h.y,l.y,c.y)>=o))return!1;const u=d*(h.y-a.y),p=d*(a.x-h.x),g=u*i+p*r,y=u*s+p*r,m=u*i+p*o,x=u*s+p*o;if(Math.max(g,y,m,x)<=u*a.x+p*a.y||Math.min(g,y,m,x)>=u*c.x+p*c.y)return!1;const S=d*(a.y-l.y),v=d*(l.x-a.x),b=S*i+v*r,P=S*s+v*r,C=S*i+v*o,_=S*s+v*o;return!(Math.max(b,P,C,_)<=S*a.x+v*a.y||Math.min(b,P,C,_)>=S*c.x+v*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),s=Math.max(this.y,t.y),r=Math.min(this.y+this.height,t.y+t.height);return this.x=e,this.width=Math.max(i-e,0),this.y=s,this.height=Math.max(r-s,0),this}ceil(t=1,e=.001){const i=Math.ceil((this.x+this.width-e)*t)/t,s=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=s-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),s=Math.min(this.y,t.y),r=Math.max(this.y+this.height,t.y+t.height);return this.x=e,this.width=i-e,this.y=s,this.height=r-s,this}getBounds(t){return t||(t=new J),t.copyFrom(this),t}containsRect(t){if(this.width<=0||this.height<=0)return!1;const e=t.x,i=t.y,s=t.x+t.width,r=t.y+t.height;return e>=this.x&&e<this.x+this.width&&i>=this.y&&i<this.y+this.height&&s>=this.x&&s<this.x+this.width&&r>=this.y&&r<this.y+this.height}set(t,e,i,s){return this.x=t,this.y=e,this.width=i,this.height=s,this}toString(){return`[pixi.js/math:Rectangle x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`}}const js={default:-1};function ct(n="default"){return js[n]===void 0&&(js[n]=-1),++js[n]}const ro=new Set,K="8.0.0",Ad="8.3.4",Ve={quiet:!1,noColor:!1},N=(n,t,e=3)=>{if(Ve.quiet||ro.has(t))return;let i=new Error().stack;const s=`${t}
3
+ Deprecated since v${n}`,r=typeof console.groupCollapsed=="function"&&!Ve.noColor;typeof i>"u"?console.warn("PixiJS Deprecation Warning: ",s):(i=i.split(`
4
+ `).splice(e).join(`
5
+ `),r?(console.groupCollapsed("%cPixiJS Deprecation Warning: %c%s","color:#614108;background:#fffbe6","font-weight:normal;color:#614108;background:#fffbe6",s),console.warn(i),console.groupEnd()):(console.warn("PixiJS Deprecation Warning: ",s),console.warn(i))),ro.add(t)};Object.defineProperties(N,{quiet:{get:()=>Ve.quiet,set:n=>{Ve.quiet=n},enumerable:!0,configurable:!1},noColor:{get:()=>Ve.noColor,set:n=>{Ve.noColor=n},enumerable:!0,configurable:!1}});const xh=()=>{};function qe(n){return n+=n===0?1:0,--n,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n+1}function oo(n){return!(n&n-1)&&!!n}function Sh(n){const t={};for(const e in n)n[e]!==void 0&&(t[e]=n[e]);return t}const ao=Object.create(null);function Rd(n){const t=ao[n];return t===void 0&&(ao[n]=ct("resource")),t}const vh=class bh extends Yt{constructor(t={}){super(),this._resourceType="textureSampler",this._touched=0,this._maxAnisotropy=1,this.destroyed=!1,t={...bh.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){N(K,"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=Rd(t),this._resourceId}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this.removeAllListeners()}};vh.defaultOptions={addressMode:"clamp-to-edge",scaleMode:"linear"};let Ke=vh;const wh=class Ch extends Yt{constructor(t={}){super(),this.options=t,this._gpuData=Object.create(null),this._gcLastUsed=-1,this.uid=ct("textureSource"),this._resourceType="textureSource",this._resourceId=ct("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={...Ch.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 Ke(Sh(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=ct("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 s=Math.round(t*i),r=Math.round(e*i);return this.width=s/i,this.height=r/i,this._resolution=i,this.pixelWidth===s&&this.pixelHeight===r?!1:(this._refreshPOT(),this.pixelWidth=s,this.pixelHeight=r,this.emit("resize",this),this._resourceId=ct("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=oo(this.pixelWidth)&&oo(this.pixelHeight)}static test(t){throw new Error("Unimplemented")}};wh.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 Bt=wh;class mr extends Bt{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}}mr.extension=E.TextureSource;const ho=new U;class kd{constructor(t,e){this.mapCoord=new U,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 s=0;s<t.length;s+=2){const r=t[s],o=t[s+1];e[s]=r*i.a+o*i.c+i.tx,e[s+1]=r*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,s=t.trim;s&&(ho.set(i.width/s.width,0,0,i.height/s.height,-s.x/s.width,-s.y/s.height),this.mapCoord.append(ho));const r=t.source,o=this.uClampFrame,a=this.clampMargin/r._resolution,h=this.clampOffset/r._resolution;return o[0]=(t.frame.x+a+h)/r.width,o[1]=(t.frame.y+a+h)/r.height,o[2]=(t.frame.x+t.frame.width-a+h)/r.width,o[3]=(t.frame.y+t.frame.height-a+h)/r.height,this.uClampOffset[0]=this.clampOffset/r.pixelWidth,this.uClampOffset[1]=this.clampOffset/r.pixelHeight,this.isSimple=t.frame.width===r.width&&t.frame.height===r.height&&t.rotate===0,!0}}class O extends Yt{constructor({source:t,label:e,frame:i,orig:s,trim:r,defaultAnchor:o,defaultBorders:a,rotate:h,dynamic:l}={}){if(super(),this.uid=ct("texture"),this.uvs={x0:0,y0:0,x1:0,y1:0,x2:0,y2:0,x3:0,y3:0},this.frame=new J,this.noFrame=!1,this.dynamic=!1,this.isTexture=!0,this.label=e,this.source=(t==null?void 0:t.source)??new Bt,this.noFrame=!i,i)this.frame.copyFrom(i);else{const{width:c,height:d}=this._source;this.frame.width=c,this.frame.height=d}this.orig=s||this.frame,this.trim=r,this.rotate=h??0,this.defaultAnchor=o,this.defaultBorders=a,this.destroyed=!1,this.dynamic=l||!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 kd(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:s}=this._source,r=e.x/i,o=e.y/s,a=e.width/i,h=e.height/s;let l=this.rotate;if(l){const c=a/2,d=h/2,u=r+c,p=o+d;l=X.add(l,X.NW),t.x0=u+c*X.uX(l),t.y0=p+d*X.uY(l),l=X.add(l,2),t.x1=u+c*X.uX(l),t.y1=p+d*X.uY(l),l=X.add(l,2),t.x2=u+c*X.uX(l),t.y2=p+d*X.uY(l),l=X.add(l,2),t.x3=u+c*X.uX(l),t.y3=p+d*X.uY(l)}else t.x0=r,t.y0=o,t.x1=r+a,t.y1=o,t.x2=r+a,t.y2=o+h,t.x3=r,t.y3=o+h}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 N(K,"Texture.baseTexture is now Texture.source"),this._source}}O.EMPTY=new O({label:"EMPTY",source:new Bt({label:"EMPTY"})});O.EMPTY.destroy=xh;O.WHITE=new O({source:new mr({resource:new Uint8Array([255,255,255,255]),width:1,height:1,alphaMode:"premultiply-alpha-on-upload",label:"WHITE"}),label:"WHITE"});O.WHITE.destroy=xh;function _h(n,t,e){const{width:i,height:s}=e.orig,r=e.trim;if(r){const o=r.width,a=r.height;n.minX=r.x-t._x*i,n.maxX=n.minX+o,n.minY=r.y-t._y*s,n.maxY=n.minY+a}else n.minX=-t._x*i,n.maxX=n.minX+i,n.minY=-t._y*s,n.maxY=n.minY+s}const lo=new U;class Dt{constructor(t=1/0,e=1/0,i=-1/0,s=-1/0){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=lo,this.minX=t,this.minY=e,this.maxX=i,this.maxY=s}isEmpty(){return this.minX>this.maxX||this.minY>this.maxY}get rectangle(){this._rectangle||(this._rectangle=new J);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=lo,this}set(t,e,i,s){this.minX=t,this.minY=e,this.maxX=i,this.maxY=s}addFrame(t,e,i,s,r){r||(r=this.matrix);const o=r.a,a=r.b,h=r.c,l=r.d,c=r.tx,d=r.ty;let u=this.minX,p=this.minY,g=this.maxX,y=this.maxY,m=o*t+h*e+c,x=a*t+l*e+d;m<u&&(u=m),x<p&&(p=x),m>g&&(g=m),x>y&&(y=x),m=o*i+h*e+c,x=a*i+l*e+d,m<u&&(u=m),x<p&&(p=x),m>g&&(g=m),x>y&&(y=x),m=o*t+h*s+c,x=a*t+l*s+d,m<u&&(u=m),x<p&&(p=x),m>g&&(g=m),x>y&&(y=x),m=o*i+h*s+c,x=a*i+l*s+d,m<u&&(u=m),x<p&&(p=x),m>g&&(g=m),x>y&&(y=x),this.minX=u,this.minY=p,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,s=this.maxX,r=this.maxY,{a:o,b:a,c:h,d:l,tx:c,ty:d}=t;let u=o*e+h*i+c,p=a*e+l*i+d;this.minX=u,this.minY=p,this.maxX=u,this.maxY=p,u=o*s+h*i+c,p=a*s+l*i+d,this.minX=u<this.minX?u:this.minX,this.minY=p<this.minY?p:this.minY,this.maxX=u>this.maxX?u:this.maxX,this.maxY=p>this.maxY?p:this.maxY,u=o*e+h*r+c,p=a*e+l*r+d,this.minX=u<this.minX?u:this.minX,this.minY=p<this.minY?p:this.minY,this.maxX=u>this.maxX?u:this.maxX,this.maxY=p>this.maxY?p:this.maxY,u=o*s+h*r+c,p=a*s+l*r+d,this.minX=u<this.minX?u:this.minX,this.minY=p<this.minY?p:this.minY,this.maxX=u>this.maxX?u:this.maxX,this.maxY=p>this.maxY?p: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,s){return this.minX<t&&(this.minX=t),this.maxX>e&&(this.maxX=e),this.minY<i&&(this.minY=i),this.maxY>s&&(this.maxY=s),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 Dt(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,s){let r=this.minX,o=this.minY,a=this.maxX,h=this.maxY;s||(s=this.matrix);const l=s.a,c=s.b,d=s.c,u=s.d,p=s.tx,g=s.ty;for(let y=e;y<i;y+=2){const m=t[y],x=t[y+1],S=l*m+d*x+p,v=c*m+u*x+g;r=S<r?S:r,o=v<o?v:o,a=S>a?S:a,h=v>h?v:h}this.minX=r,this.minY=o,this.maxX=a,this.maxY=h}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 Ed={grad:.9,turn:360,rad:360/(2*Math.PI)},jt=function(n){return typeof n=="string"?n.length>0:typeof n=="number"},xt=function(n,t,e){return t===void 0&&(t=0),e===void 0&&(e=Math.pow(10,t)),Math.round(e*n)/e+0},Et=function(n,t,e){return t===void 0&&(t=0),e===void 0&&(e=1),n>e?e:n>t?n:t},Ph=function(n){return(n=isFinite(n)?n%360:0)>0?n:n+360},co=function(n){return{r:Et(n.r,0,255),g:Et(n.g,0,255),b:Et(n.b,0,255),a:Et(n.a)}},Zs=function(n){return{r:xt(n.r),g:xt(n.g),b:xt(n.b),a:xt(n.a,3)}},Id=/^#([0-9a-f]{3,8})$/i,ji=function(n){var t=n.toString(16);return t.length<2?"0"+t:t},Mh=function(n){var t=n.r,e=n.g,i=n.b,s=n.a,r=Math.max(t,e,i),o=r-Math.min(t,e,i),a=o?r===t?(e-i)/o:r===e?2+(i-t)/o:4+(t-e)/o:0;return{h:60*(a<0?a+6:a),s:r?o/r*100:0,v:r/255*100,a:s}},Th=function(n){var t=n.h,e=n.s,i=n.v,s=n.a;t=t/360*6,e/=100,i/=100;var r=Math.floor(t),o=i*(1-e),a=i*(1-(t-r)*e),h=i*(1-(1-t+r)*e),l=r%6;return{r:255*[i,a,o,o,h,i][l],g:255*[h,i,i,a,o,o][l],b:255*[o,o,h,i,i,a][l],a:s}},uo=function(n){return{h:Ph(n.h),s:Et(n.s,0,100),l:Et(n.l,0,100),a:Et(n.a)}},po=function(n){return{h:xt(n.h),s:xt(n.s),l:xt(n.l),a:xt(n.a,3)}},fo=function(n){return Th((e=(t=n).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(n){return{h:(t=Mh(n)).h,s:(s=(200-(e=t.s))*(i=t.v)/100)>0&&s<200?e*i/100/(s<=100?s:200-s)*100:0,l:s/2,a:t.a};var t,e,i,s},Dd=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Fd=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Bd=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Ld=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Gn={string:[[function(n){var t=Id.exec(n);return t?(n=t[1]).length<=4?{r:parseInt(n[0]+n[0],16),g:parseInt(n[1]+n[1],16),b:parseInt(n[2]+n[2],16),a:n.length===4?xt(parseInt(n[3]+n[3],16)/255,2):1}:n.length===6||n.length===8?{r:parseInt(n.substr(0,2),16),g:parseInt(n.substr(2,2),16),b:parseInt(n.substr(4,2),16),a:n.length===8?xt(parseInt(n.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(n){var t=Bd.exec(n)||Ld.exec(n);return t?t[2]!==t[4]||t[4]!==t[6]?null:co({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(n){var t=Dd.exec(n)||Fd.exec(n);if(!t)return null;var e,i,s=uo({h:(e=t[1],i=t[2],i===void 0&&(i="deg"),Number(e)*(Ed[i]||1)),s:Number(t[3]),l:Number(t[4]),a:t[5]===void 0?1:Number(t[5])/(t[6]?100:1)});return fo(s)},"hsl"]],object:[[function(n){var t=n.r,e=n.g,i=n.b,s=n.a,r=s===void 0?1:s;return jt(t)&&jt(e)&&jt(i)?co({r:Number(t),g:Number(e),b:Number(i),a:Number(r)}):null},"rgb"],[function(n){var t=n.h,e=n.s,i=n.l,s=n.a,r=s===void 0?1:s;if(!jt(t)||!jt(e)||!jt(i))return null;var o=uo({h:Number(t),s:Number(e),l:Number(i),a:Number(r)});return fo(o)},"hsl"],[function(n){var t=n.h,e=n.s,i=n.v,s=n.a,r=s===void 0?1:s;if(!jt(t)||!jt(e)||!jt(i))return null;var o=function(a){return{h:Ph(a.h),s:Et(a.s,0,100),v:Et(a.v,0,100),a:Et(a.a)}}({h:Number(t),s:Number(e),v:Number(i),a:Number(r)});return Th(o)},"hsv"]]},go=function(n,t){for(var e=0;e<t.length;e++){var i=t[e][0](n);if(i)return[i,t[e][1]]}return[null,void 0]},zd=function(n){return typeof n=="string"?go(n.trim(),Gn.string):typeof n=="object"&&n!==null?go(n,Gn.object):[null,void 0]},qs=function(n,t){var e=bi(n);return{h:e.h,s:Et(e.s+100*t,0,100),l:e.l,a:e.a}},Ks=function(n){return(299*n.r+587*n.g+114*n.b)/1e3/255},mo=function(n,t){var e=bi(n);return{h:e.h,s:e.s,l:Et(e.l+100*t,0,100),a:e.a}},Un=function(){function n(t){this.parsed=zd(t)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return n.prototype.isValid=function(){return this.parsed!==null},n.prototype.brightness=function(){return xt(Ks(this.rgba),2)},n.prototype.isDark=function(){return Ks(this.rgba)<.5},n.prototype.isLight=function(){return Ks(this.rgba)>=.5},n.prototype.toHex=function(){return t=Zs(this.rgba),e=t.r,i=t.g,s=t.b,o=(r=t.a)<1?ji(xt(255*r)):"","#"+ji(e)+ji(i)+ji(s)+o;var t,e,i,s,r,o},n.prototype.toRgb=function(){return Zs(this.rgba)},n.prototype.toRgbString=function(){return t=Zs(this.rgba),e=t.r,i=t.g,s=t.b,(r=t.a)<1?"rgba("+e+", "+i+", "+s+", "+r+")":"rgb("+e+", "+i+", "+s+")";var t,e,i,s,r},n.prototype.toHsl=function(){return po(bi(this.rgba))},n.prototype.toHslString=function(){return t=po(bi(this.rgba)),e=t.h,i=t.s,s=t.l,(r=t.a)<1?"hsla("+e+", "+i+"%, "+s+"%, "+r+")":"hsl("+e+", "+i+"%, "+s+"%)";var t,e,i,s,r},n.prototype.toHsv=function(){return t=Mh(this.rgba),{h:xt(t.h),s:xt(t.s),v:xt(t.v),a:xt(t.a,3)};var t},n.prototype.invert=function(){return Ht({r:255-(t=this.rgba).r,g:255-t.g,b:255-t.b,a:t.a});var t},n.prototype.saturate=function(t){return t===void 0&&(t=.1),Ht(qs(this.rgba,t))},n.prototype.desaturate=function(t){return t===void 0&&(t=.1),Ht(qs(this.rgba,-t))},n.prototype.grayscale=function(){return Ht(qs(this.rgba,-1))},n.prototype.lighten=function(t){return t===void 0&&(t=.1),Ht(mo(this.rgba,t))},n.prototype.darken=function(t){return t===void 0&&(t=.1),Ht(mo(this.rgba,-t))},n.prototype.rotate=function(t){return t===void 0&&(t=15),this.hue(this.hue()+t)},n.prototype.alpha=function(t){return typeof t=="number"?Ht({r:(e=this.rgba).r,g:e.g,b:e.b,a:t}):xt(this.rgba.a,3);var e},n.prototype.hue=function(t){var e=bi(this.rgba);return typeof t=="number"?Ht({h:t,s:e.s,l:e.l,a:e.a}):xt(e.h)},n.prototype.isEqual=function(t){return this.toHex()===Ht(t).toHex()},n}(),Ht=function(n){return n instanceof Un?n:new Un(n)},yo=[],Od=function(n){n.forEach(function(t){yo.indexOf(t)<0&&(t(Un,Gn),yo.push(t))})};function Wd(n,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 s in e)i[e[s]]=s;var r={};n.prototype.toName=function(o){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var a,h,l=i[this.toHex()];if(l)return l;if(o!=null&&o.closest){var c=this.toRgb(),d=1/0,u="black";if(!r.length)for(var p in e)r[p]=new n(e[p]).toRgb();for(var g in e){var y=(a=c,h=r[g],Math.pow(a.r-h.r,2)+Math.pow(a.g-h.g,2)+Math.pow(a.b-h.b,2));y<d&&(d=y,u=g)}return u}},t.string.push([function(o){var a=o.toLowerCase(),h=a==="transparent"?"#0000":e[a];return h?new n(h).toRgb():null},"name"])}Od([Wd]);const Qe=class yi{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 yi)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((r,o)=>r===e[o]);if(t!==null&&e!==null){const r=Object.keys(t),o=Object.keys(e);return r.length!==o.length?!1:r.every(a=>t[a]===e[a])}return t===e}toRgba(){const[t,e,i,s]=this._components;return{r:t,g:e,b:i,a:s}}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,s]=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(s*255),t}toArray(t){this._arrayRgba||(this._arrayRgba=[]),t||(t=this._arrayRgba);const[e,i,s,r]=this._components;return t[0]=e,t[1]=i,t[2]=s,t[3]=r,t}toRgbArray(t){this._arrayRgb||(this._arrayRgb=[]),t||(t=this._arrayRgb);const[e,i,s]=this._components;return t[0]=e,t[1]=i,t[2]=s,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,s,r]=yi._temp.setValue(t)._components;return this._components[0]*=e,this._components[1]*=i,this._components[2]*=s,this._components[3]*=r,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,s=this._int>>8&255,r=this._int&255;return e&&(i=i*t+.5|0,s=s*t+.5|0,r=r*t+.5|0),(t*255<<24)+(i<<16)+(s<<8)+r}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}_normalize(t){let e,i,s,r;if((typeof t=="number"||t instanceof Number)&&t>=0&&t<=16777215){const o=t;e=(o>>16&255)/255,i=(o>>8&255)/255,s=(o&255)/255,r=1}else if((Array.isArray(t)||t instanceof Float32Array)&&t.length>=3&&t.length<=4)t=this._clamp(t),[e,i,s,r=1]=t;else if((t instanceof Uint8Array||t instanceof Uint8ClampedArray)&&t.length>=3&&t.length<=4)t=this._clamp(t,0,255),[e,i,s,r=255]=t,e/=255,i/=255,s/=255,r/=255;else if(typeof t=="string"||typeof t=="object"){if(typeof t=="string"){const a=yi.HEX_PATTERN.exec(t);a&&(t=`#${a[2]}`)}const o=Ht(t);o.isValid()&&({r:e,g:i,b:s,a:r}=o.rgba,e/=255,i/=255,s/=255)}if(e!==void 0)this._components[0]=e,this._components[1]=i,this._components[2]=s,this._components[3]=r,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((s,r)=>{t[r]=Math.min(Math.max(s,e),i)}),t)}static isColorLike(t){return typeof t=="number"||typeof t=="string"||t instanceof Number||t instanceof yi||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}};Qe.shared=new Qe;Qe._temp=new Qe;Qe.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let nt=Qe;const Gd={cullArea:null,cullable:!1,cullableChildren:!0};let Qs=0;const xo=500;function st(...n){Qs!==xo&&(Qs++,Qs===xo?console.warn("PixiJS Warning: too many warnings, no more warnings will be reported to the console by PixiJS."):console.warn("PixiJS Warning: ",...n))}const Gi={_registeredResources:new Set,register(n){this._registeredResources.add(n)},unregister(n){this._registeredResources.delete(n)},release(){this._registeredResources.forEach(n=>n.clear())},get registeredCount(){return this._registeredResources.size},isRegistered(n){return this._registeredResources.has(n)},reset(){this._registeredResources.clear()}};class Ud{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 Hd{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 Ud(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 Hd;Gi.register(Mt);const Nd={get isCachedAsTexture(){var n;return!!((n=this.renderGroup)!=null&&n.isCachedAsTexture)},cacheAsTexture(n){typeof n=="boolean"&&n===!1?this.disableRenderGroup():(this.enableRenderGroup(),this.renderGroup.enableCacheAsTexture(n===!0?{}:n))},updateCacheTexture(){var n;(n=this.renderGroup)==null||n.updateCacheTexture()},get cacheAsBitmap(){return this.isCachedAsTexture},set cacheAsBitmap(n){N("v8.6.0","cacheAsBitmap is deprecated, use cacheAsTexture instead."),this.cacheAsTexture(n)}};function Vd(n,t,e){const i=n.length;let s;if(t>=i||e===0)return;e=t+e>i?i-t:e;const r=i-e;for(s=t;s<r;++s)n[s]=n[s+e];n.length=r}const $d={allowChildren:!0,removeChildren(n=0,t){var r;const e=t??this.children.length,i=e-n,s=[];if(i>0&&i<=e){for(let a=e-1;a>=n;a--){const h=this.children[a];h&&(s.push(h),h.parent=null)}Vd(this.children,n,e);const o=this.renderGroup||this.parentRenderGroup;o&&o.removeChildren(s);for(let a=0;a<s.length;++a){const h=s[a];(r=h.parentRenderLayer)==null||r.detach(h),this.emit("childRemoved",h,this,a),s[a].emit("removed",this)}return s.length>0&&this._didViewChangeTick++,s}else if(i===0&&this.children.length===0)return s;throw new RangeError("removeChildren: numeric values are outside the acceptable range.")},removeChildAt(n){const t=this.getChildAt(n);return this.removeChild(t)},getChildAt(n){if(n<0||n>=this.children.length)throw new Error(`getChildAt: Index (${n}) does not exist.`);return this.children[n]},setChildIndex(n,t){if(t<0||t>=this.children.length)throw new Error(`The index ${t} supplied is out of bounds ${this.children.length}`);this.getChildIndex(n),this.addChildAt(n,t)},getChildIndex(n){const t=this.children.indexOf(n);if(t===-1)throw new Error("The supplied Container must be a child of the caller");return t},addChildAt(n,t){this.allowChildren||N(K,"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(`${n}addChildAt: The index ${t} supplied is out of bounds ${e.length}`);if(n.parent){const s=n.parent.children.indexOf(n);if(n.parent===this&&s===t)return n;s!==-1&&n.parent.children.splice(s,1)}t===e.length?e.push(n):e.splice(t,0,n),n.parent=this,n.didChange=!0,n._updateFlags=15;const i=this.renderGroup||this.parentRenderGroup;return i&&i.addChild(n),this.sortableChildren&&(this.sortDirty=!0),this.emit("childAdded",n,this,t),n.emit("added",this),n},swapChildren(n,t){if(n===t)return;const e=this.getChildIndex(n),i=this.getChildIndex(t);this.children[e]=t,this.children[i]=n;const s=this.renderGroup||this.parentRenderGroup;s&&(s.structureDidChange=!0),this._didContainerChangeTick++},removeFromParent(){var n;(n=this.parent)==null||n.removeChild(this)},reparentChild(...n){return n.length===1?this.reparentChildAt(n[0],this.children.length):(n.forEach(t=>this.reparentChildAt(t,this.children.length)),n[0])},reparentChildAt(n,t){if(n.parent===this)return this.setChildIndex(n,t),n;const e=n.worldTransform.clone();n.removeFromParent(),this.addChildAt(n,t);const i=this.worldTransform.clone();return i.invert(),e.prepend(i),n.setFromMatrix(e),n},replaceChild(n,t){n.updateLocalTransform(),this.addChildAt(t,this.getChildIndex(n)),t.setFromMatrix(n.localTransform),t.updateLocalTransform(),this.removeChild(n)}},Yd={collectRenderables(n,t,e){this.parentRenderLayer&&this.parentRenderLayer!==e||this.globalDisplayStatus<7||!this.includeInBuild||(this.sortableChildren&&this.sortChildren(),this.isSimple?this.collectRenderablesSimple(n,t,e):this.renderGroup?t.renderPipes.renderGroup.addRenderGroup(this.renderGroup,n):this.collectRenderablesWithEffects(n,t,e))},collectRenderablesSimple(n,t,e){const i=this.children,s=i.length;for(let r=0;r<s;r++)i[r].collectRenderables(n,t,e)},collectRenderablesWithEffects(n,t,e){const{renderPipes:i}=t;for(let s=0;s<this.effects.length;s++){const r=this.effects[s];i[r.pipe].push(r,this,n)}this.collectRenderablesSimple(n,t,e);for(let s=this.effects.length-1;s>=0;s--){const r=this.effects[s];i[r.pipe].pop(r,this,n)}}};class So{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 Xd{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 Hn=new Xd;q.handleByList(E.MaskEffect,Hn._effectClasses);const jd={_maskEffect:null,_maskOptions:{inverse:!1},_filterEffect:null,effects:[],_markStructureAsChanged(){const n=this.renderGroup||this.parentRenderGroup;n&&(n.structureDidChange=!0)},addEffect(n){this.effects.indexOf(n)===-1&&(this.effects.push(n),this.effects.sort((e,i)=>e.priority-i.priority),this._markStructureAsChanged(),this._updateIsSimple())},removeEffect(n){const t=this.effects.indexOf(n);t!==-1&&(this.effects.splice(t,1),this._markStructureAsChanged(),this._updateIsSimple())},set mask(n){const t=this._maskEffect;(t==null?void 0:t.mask)!==n&&(t&&(this.removeEffect(t),Hn.returnMaskEffect(t),this._maskEffect=null),n!=null&&(this._maskEffect=Hn.getMaskEffect(n),this.addEffect(this._maskEffect)))},get mask(){var n;return(n=this._maskEffect)==null?void 0:n.mask},setMask(n){this._maskOptions={...this._maskOptions,...n},n.mask&&(this.mask=n.mask),this._markStructureAsChanged()},set filters(n){var r;!Array.isArray(n)&&n&&(n=[n]);const t=this._filterEffect||(this._filterEffect=new So);n=n;const e=(n==null?void 0:n.length)>0,i=((r=t.filters)==null?void 0:r.length)>0,s=e!==i;n=Array.isArray(n)?n.slice(0):n,t.filters=Object.freeze(n),s&&(e?this.addEffect(t):(this.removeEffect(t),t.filters=n??null))},get filters(){var n;return(n=this._filterEffect)==null?void 0:n.filters},set filterArea(n){this._filterEffect||(this._filterEffect=new So),this._filterEffect.filterArea=n},get filterArea(){var n;return(n=this._filterEffect)==null?void 0:n.filterArea}},Zd={label:null,get name(){return N(K,"Container.name property has been removed, use Container.label instead"),this.label},set name(n){N(K,"Container.name property has been removed, use Container.label instead"),this.label=n},getChildByName(n,t=!1){return this.getChildByLabel(n,t)},getChildByLabel(n,t=!1){const e=this.children;for(let i=0;i<e.length;i++){const s=e[i];if(s.label===n||n instanceof RegExp&&n.test(s.label))return s}if(t)for(let i=0;i<e.length;i++){const r=e[i].getChildByLabel(n,!0);if(r)return r}return null},getChildrenByLabel(n,t=!1,e=[]){const i=this.children;for(let s=0;s<i.length;s++){const r=i[s];(r.label===n||n instanceof RegExp&&n.test(r.label))&&e.push(r)}if(t)for(let s=0;s<i.length;s++)i[s].getChildrenByLabel(n,!0,e);return e}},Ct=Mt.getPool(U),Jt=Mt.getPool(Dt),qd=new U,Kd={getFastGlobalBounds(n,t){t||(t=new Dt),t.clear(),this._getGlobalBoundsRecursive(!!n,t,this.parentRenderLayer),t.isValid||t.set(0,0,0,0);const e=this.renderGroup||this.parentRenderGroup;return t.applyMatrix(e.worldTransform),t},_getGlobalBoundsRecursive(n,t,e){let i=t;if(n&&this.parentRenderLayer&&this.parentRenderLayer!==e||this.localDisplayStatus!==7||!this.measurable)return;const s=!!this.effects.length;if((this.renderGroup||s)&&(i=Jt.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 r=this.children;for(let o=0;o<r.length;o++)r[o]._getGlobalBoundsRecursive(n,i,e)}if(s){let r=!1;const o=this.renderGroup||this.parentRenderGroup;for(let a=0;a<this.effects.length;a++)this.effects[a].addBounds&&(r||(r=!0,i.applyMatrix(o.worldTransform)),this.effects[a].addBounds(i,!0));r&&i.applyMatrix(o.worldTransform.copyTo(qd).invert()),t.addBounds(i),Jt.return(i)}else this.renderGroup&&(t.addBounds(i,this.relativeGroupTransform),Jt.return(i))}};function Ah(n,t,e){e.clear();let i,s;return n.parent?t?i=n.parent.worldTransform:(s=Ct.get().identity(),i=yr(n,s)):i=U.IDENTITY,Rh(n,e,i,t),s&&Ct.return(s),e.isValid||e.set(0,0,0,0),e}function Rh(n,t,e,i){var a,h;if(!n.visible||!n.measurable)return;let s;i?s=n.worldTransform:(n.updateLocalTransform(),s=Ct.get(),s.appendFrom(n.localTransform,e));const r=t,o=!!n.effects.length;if(o&&(t=Jt.get().clear()),n.boundsArea)t.addRect(n.boundsArea,s);else{const l=n.bounds;l&&!l.isEmpty()&&(t.matrix=s,t.addBounds(l));for(let c=0;c<n.children.length;c++)Rh(n.children[c],t,s,i)}if(o){for(let l=0;l<n.effects.length;l++)(h=(a=n.effects[l]).addBounds)==null||h.call(a,t);r.addBounds(t,U.IDENTITY),Jt.return(t)}i||Ct.return(s)}function yr(n,t){const e=n.parent;return e&&(yr(e,t),e.updateLocalTransform(),t.append(e.localTransform)),t}function xr(n,t){if(n===16777215||!t)return t;if(t===16777215||!n)return n;const e=n>>16&255,i=n>>8&255,s=n&255,r=t>>16&255,o=t>>8&255,a=t&255,h=e*r/255|0,l=i*o/255|0,c=s*a/255|0;return(h<<16)+(l<<8)+c}const vo=16777215;function bo(n,t){return n===vo?t:t===vo?n:xr(n,t)}function wi(n){return((n&255)<<16)+(n&65280)+(n>>16&255)}const Qd={getGlobalAlpha(n){if(n)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(n=new U,t){if(t)return n.copyFrom(this.worldTransform);this.updateLocalTransform();const e=yr(this,Ct.get().identity());return n.appendFrom(this.localTransform,e),Ct.return(e),n},getGlobalTint(n){if(n)return this.renderGroup?wi(this.renderGroup.worldColor):this.parentRenderGroup?wi(bo(this.localColor,this.parentRenderGroup.worldColor)):this.tint;let t=this.localColor,e=this.parent;for(;e;)t=bo(t,e.localColor),e=e.parent;return wi(t)}};function kh(n,t,e){return t.clear(),e||(e=U.IDENTITY),Eh(n,t,e,n,!0),t.isValid||t.set(0,0,0,0),t}function Eh(n,t,e,i,s){var h,l;let r;if(s)r=Ct.get(),r=e.copyTo(r);else{if(!n.visible||!n.measurable)return;n.updateLocalTransform();const c=n.localTransform;r=Ct.get(),r.appendFrom(c,e)}const o=t,a=!!n.effects.length;if(a&&(t=Jt.get().clear()),n.boundsArea)t.addRect(n.boundsArea,r);else{n.renderPipeId&&(t.matrix=r,t.addBounds(n.bounds));const c=n.children;for(let d=0;d<c.length;d++)Eh(c[d],t,r,i,!1)}if(a){for(let c=0;c<n.effects.length;c++)(l=(h=n.effects[c]).addLocalBounds)==null||l.call(h,t,i);o.addBounds(t,U.IDENTITY),Jt.return(t)}Ct.return(r)}function Ih(n,t){const e=n.children;for(let i=0;i<e.length;i++){const s=e[i],r=s.uid,o=(s._didViewChangeTick&65535)<<16|s._didContainerChangeTick&65535,a=t.index;(t.data[a]!==r||t.data[a+1]!==o)&&(t.data[t.index]=r,t.data[t.index+1]=o,t.didChange=!0),t.index=a+2,s.children.length&&Ih(s,t)}return t.didChange}const Jd=new U,tu={_localBoundsCacheId:-1,_localBoundsCacheData:null,_setWidth(n,t){const e=Math.sign(this.scale.x)||1;t!==0?this.scale.x=n/t*e:this.scale.x=e},_setHeight(n,t){const e=Math.sign(this.scale.y)||1;t!==0?this.scale.y=n/t*e:this.scale.y=e},getLocalBounds(){this._localBoundsCacheData||(this._localBoundsCacheData={data:[],index:1,didChange:!1,localBounds:new Dt});const n=this._localBoundsCacheData;return n.index=1,n.didChange=!1,n.data[0]!==this._didViewChangeTick&&(n.didChange=!0,n.data[0]=this._didViewChangeTick),Ih(this,n),n.didChange&&kh(this,n.localBounds,Jd),n.localBounds},getBounds(n,t){return Ah(this,n,t||new Dt)}},eu={_onRender:null,set onRender(n){const t=this.renderGroup||this.parentRenderGroup;if(!n){this._onRender&&(t==null||t.removeOnRender(this)),this._onRender=null;return}this._onRender||t==null||t.addOnRender(this),this._onRender=n},get onRender(){return this._onRender}},iu={_zIndex:0,sortDirty:!1,sortableChildren:!1,get zIndex(){return this._zIndex},set zIndex(n){this._zIndex!==n&&(this._zIndex=n,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(su))}};function su(n,t){return n._zIndex-t._zIndex}const nu={getGlobalPosition(n=new Q,t=!1){return this.parent?this.parent.toGlobal(this._position,n,t):(n.x=this._position.x,n.y=this._position.y),n},toGlobal(n,t,e=!1){const i=this.getGlobalTransform(Ct.get(),e);return t=i.apply(n,t),Ct.return(i),t},toLocal(n,t,e,i){t&&(n=t.toGlobal(n,e,i));const s=this.getGlobalTransform(Ct.get(),i);return e=s.applyInverse(n,e),Ct.return(s),e}};class Sr{constructor(){this.uid=ct("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 ru=0;class ou{constructor(t){this._poolKeyHash=Object.create(null),this._texturePool={},this.textureOptions=t||{},this.enableFullScreen=!1,this.textureStyle=new Ke(this.textureOptions)}createTexture(t,e,i){const s=new Bt({...this.textureOptions,width:t,height:e,resolution:1,antialias:i,autoGarbageCollect:!1});return new O({source:s,label:`texturePool_${ru++}`})}getOptimalTexture(t,e,i=1,s){let r=Math.ceil(t*i-1e-6),o=Math.ceil(e*i-1e-6);r=qe(r),o=qe(o);const a=(r<<17)+(o<<1)+(s?1:0);this._texturePool[a]||(this._texturePool[a]=[]);let h=this._texturePool[a].pop();return h||(h=this.createTexture(r,o,s)),h.source._resolution=i,h.source.width=r/i,h.source.height=o/i,h.source.pixelWidth=r,h.source.pixelHeight=o,h.frame.x=0,h.frame.y=0,h.frame.width=t,h.frame.height=e,h.updateUvs(),this._poolKeyHash[h.uid]=a,h}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 s=0;s<i.length;s++)i[s].destroy(!0)}this._texturePool={}}}const Rs=new ou;Gi.register(Rs);class au{constructor(){this.renderPipeId="renderGroup",this.root=null,this.canBundle=!1,this.renderGroupParent=null,this.renderGroupChildren=[],this.worldTransform=new U,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 Sr,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 s=e[i];s._updateFlags=15,this.addChild(s)}}enableCacheAsTexture(t={}){this.textureOptions=t,this.isCachedAsTexture=!0,this.textureNeedsUpdate=!0}disableCacheAsTexture(){this.isCachedAsTexture=!1,this.texture&&(Rs.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 s=0;s<i.length;s++)this._getChildren(i[s],e);return e}invalidateMatrices(){this._matrixDirty=7}get inverseWorldTransform(){return this._matrixDirty&1?(this._matrixDirty&=-2,this._inverseWorldTransform||(this._inverseWorldTransform=new U),this._inverseWorldTransform.copyFrom(this.worldTransform).invert()):this._inverseWorldTransform}get textureOffsetInverseTransform(){return this._matrixDirty&2?(this._matrixDirty&=-3,this._textureOffsetInverseTransform||(this._textureOffsetInverseTransform=new U),this._textureOffsetInverseTransform.copyFrom(this.inverseWorldTransform).translate(-this._textureBounds.x,-this._textureBounds.y)):this._textureOffsetInverseTransform}get inverseParentTextureTransform(){if(!(this._matrixDirty&4))return this._inverseParentTextureTransform;this._matrixDirty&=-5;const t=this._parentCacheAsTextureRenderGroup;return t?(this._inverseParentTextureTransform||(this._inverseParentTextureTransform=new U),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 hu(n,t,e={}){for(const i in t)!e[i]&&t[i]!==void 0&&(n[i]=t[i])}const Js=new lt(null),Zi=new lt(null),tn=new lt(null,1,1),qi=new lt(null),wo=1,lu=2,en=4;class W extends Yt{constructor(t={}){var e,i;super(),this.uid=ct("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 U,this.relativeGroupTransform=new U,this.groupTransform=this.relativeGroupTransform,this.destroyed=!1,this._position=new lt(this,0,0),this._scale=tn,this._pivot=Zi,this._origin=qi,this._skew=Js,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=[],hu(this,t,{children:!0,parent:!0,effects:!0}),(e=t.children)==null||e.forEach(s=>this.addChild(s)),(i=t.parent)==null||i.addChild(this)}static mixin(t){N("8.8.0","Container.mixin is deprecated, please use extensions.mixin instead."),q.mixin(W,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||N(K,"addChild: Only Containers will be allowed to add children in v8.0.0"),t.length>1){for(let s=0;s<t.length;s++)this.addChild(t[s]);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 s=0;s<t.length;s++)this.removeChild(t[s]);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(au,this),this.groupTransform=U.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 U),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*Cd}set angle(t){this.rotation=t*_d}get pivot(){return this._pivot===Zi&&(this._pivot=new lt(this,0,0)),this._pivot}set pivot(t){this._pivot===Zi&&(this._pivot=new lt(this,0,0),this._origin!==qi&&st("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===Js&&(this._skew=new lt(this,0,0)),this._skew}set skew(t){this._skew===Js&&(this._skew=new lt(this,0,0)),this._skew.copyFrom(t)}get scale(){return this._scale===tn&&(this._scale=new lt(this,1,1)),this._scale}set scale(t){this._scale===tn&&(this._scale=new lt(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===qi&&(this._origin=new lt(this,0,0)),this._origin}set origin(t){this._origin===qi&&(this._origin=new lt(this,0,0),this._pivot!==Zi&&st("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,s=this._pivot,r=this._origin,o=this._position,a=i._x,h=i._y,l=s._x,c=s._y,d=-r._x,u=-r._y;e.a=this._cx*a,e.b=this._sx*a,e.c=this._cy*h,e.d=this._sy*h,e.tx=o._x-(l*e.a+c*e.c)+(d*e.a+u*e.c)-d,e.ty=o._y-(l*e.b+c*e.d)+(d*e.b+u*e.d)-u}set alpha(t){t!==this.localAlpha&&(this.localAlpha=t,this._updateFlags|=wo,this._onUpdate())}get alpha(){return this.localAlpha}set tint(t){const i=nt.shared.setValue(t??16777215).toBgrNumber();i!==this.localColor&&(this.localColor=i,this._updateFlags|=wo,this._onUpdate())}get tint(){return wi(this.localColor)}set blendMode(t){this.localBlendMode!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=lu,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|=en,this.localDisplayStatus^=2,this._onUpdate())}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|=en,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|=en,this.localDisplayStatus^=1,this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._onUpdate())}get isRenderable(){return this.localDisplayStatus===7&&this.groupAlpha>0}destroy(t=!1){var s;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 r=0;r<e.length;++r)e[r].destroy(t);(s=this.renderGroup)==null||s.destroy(),this.renderGroup=null}}q.mixin(W,$d,Kd,nu,eu,tu,jd,Zd,iu,Gd,Nd,Qd,Yd);class ni extends W{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 Dt(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:s}=t;return i>=e.minX&&i<=e.maxX&&s>=e.minY&&s<=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:s}=e;s.blendMode.pushBlendMode(this,this.groupBlendMode,t);const o=s[this.renderPipeId];o!=null&&o.addRenderable&&o.addRenderable(this,t),this.didViewUpdate=!1;const a=this.children,h=a.length;for(let l=0;l<h;l++)a[l].collectRenderables(t,e,i);s.blendMode.popBlendMode(t)}}class $t extends ni{constructor(t=O.EMPTY){t instanceof O&&(t={texture:t});const{texture:e=O.EMPTY,anchor:i,roundPixels:s,width:r,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 lt({_onUpdate:()=>{this.onViewUpdate()}}),i?this.anchor=i:e.defaultAnchor&&(this.anchor=e.defaultAnchor),this.texture=e,this.allowChildren=!1,this.roundPixels=s??!1,r!==void 0&&(this.width=r),o!==void 0&&(this.height=o)}static from(t,e=!1){return t instanceof O?new $t(t):new $t(O.from(t,e))}set texture(t){t||(t=O.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 _h(this._visualBounds,this._anchor,this._texture),this._visualBounds}get sourceBounds(){return N("8.6.1","Sprite.sourceBounds is deprecated, use visualBounds instead."),this.visualBounds}updateBounds(){const t=this._anchor,e=this._texture,i=this._bounds,{width:s,height:r}=e.orig;i.minX=-t._x*s,i.maxX=i.minX+s,i.minY=-t._y*r,i.maxY=i.minY+r}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 cu=new Dt;function Dh(n,t,e){const i=cu;n.measurable=!0,Ah(n,e,i),t.addBoundsMask(i),n.measurable=!1}function Fh(n,t,e){const i=Jt.get();n.measurable=!0;const s=Ct.get().identity(),r=Bh(n,e,s);kh(n,i,r),n.measurable=!1,t.addBoundsMask(i),Ct.return(s),Jt.return(i)}function Bh(n,t,e){return n?(n!==t&&(Bh(n.parent,t,e),n.updateLocalTransform(),e.append(n.localTransform)),e):(st("Mask bounds, renderable is not inside the root container"),e)}class Lh{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 $t),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||Dh(this.mask,t,e)}addLocalBounds(t,e){Fh(this.mask,t,e)}containsPoint(t,e){const i=this.mask;return e(i,t)}destroy(){this.reset()}static test(t){return t instanceof $t}}Lh.extension=E.MaskEffect;class zh{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"}}zh.extension=E.MaskEffect;class Oh{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){Dh(this.mask,t,e)}addLocalBounds(t,e){Fh(this.mask,t,e)}containsPoint(t,e){const i=this.mask;return e(i,t)}destroy(){this.reset()}static test(t){return t instanceof W}}Oh.extension=E.MaskEffect;const du={createCanvas:(n,t)=>{const e=document.createElement("canvas");return e.width=n,e.height=t,e},createImage:()=>new Image,getCanvasRenderingContext2D:()=>CanvasRenderingContext2D,getWebGLRenderingContext:()=>WebGLRenderingContext,getNavigator:()=>navigator,getBaseUrl:()=>document.baseURI??window.location.href,getFontFaceSet:()=>document.fonts,fetch:(n,t)=>fetch(n,t),parseXML:n=>new DOMParser().parseFromString(n,"text/xml")};let Co=du;const $={get(){return Co},set(n){Co=n}};class vr extends Bt{constructor(t){t.resource||(t.resource=$.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 s=super.resize(t,e,i);return s&&this.resizeCanvas(),s}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"))}}vr.extension=E.TextureSource;class Je extends Bt{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}}Je.extension=E.TextureSource;var Ie=(n=>(n[n.INTERACTION=50]="INTERACTION",n[n.HIGH=25]="HIGH",n[n.NORMAL=0]="NORMAL",n[n.LOW=-25]="LOW",n[n.UTILITY=-50]="UTILITY",n))(Ie||{});class sn{constructor(t,e=null,i=0,s=!1){this.next=null,this.previous=null,this._destroyed=!1,this._fn=t,this._context=e,this.priority=i,this._once=s}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 Wh=class Tt{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 sn(null,null,1/0),this.deltaMS=1/Tt.targetFPMS,this.elapsedMS=1/Tt.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=Ie.NORMAL){return this._addListener(new sn(t,e,i))}addOnce(t,e,i=Ie.NORMAL){return this._addListener(new sn(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 r=t-this._lastFrame|0;if(r<this._minElapsedMS)return;this._lastFrame=t-r%this._minElapsedMS}this.deltaMS=e,this.deltaTime=this.deltaMS*Tt.targetFPMS;const i=this._head;let s=i.next;for(;s;)s=s.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(this.maxFPS,t),i=Math.min(Math.max(0,e)/1e3,Tt.targetFPMS);this._maxElapsedMS=1/i}get maxFPS(){return this._minElapsedMS?Math.round(1e3/this._minElapsedMS):0}set maxFPS(t){if(t===0)this._minElapsedMS=0;else{const e=Math.max(this.minFPS,t);this._minElapsedMS=1/(e/1e3)}}static get shared(){if(!Tt._shared){const t=Tt._shared=new Tt;t.autoStart=!0,t._protected=!0}return Tt._shared}static get system(){if(!Tt._system){const t=Tt._system=new Tt;t.autoStart=!0,t._protected=!0}return Tt._system}};Wh.targetFPMS=.06;let mt=Wh,nn;async function Gh(){return nn??(nn=(async()=>{var o;const t=$.get().createCanvas(1,1).getContext("webgl");if(!t)return"premultiply-alpha-on-upload";const e=await new Promise(a=>{const h=document.createElement("video");h.onloadeddata=()=>a(h),h.onerror=()=>a(null),h.autoplay=!1,h.crossOrigin="anonymous",h.preload="auto",h.src="data:video/webm;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAHTEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHGTbuMU6uEElTDZ1OsggEXTbuMU6uEHFO7a1OsggG97AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmoCrXsYMPQkBNgIRMYXZmV0GETGF2ZkSJiEBEAAAAAAAAFlSua8yuAQAAAAAAAEPXgQFzxYgAAAAAAAAAAZyBACK1nIN1bmSIgQCGhVZfVlA5g4EBI+ODhAJiWgDglLCBArqBApqBAlPAgQFVsIRVuYEBElTDZ9Vzc9JjwItjxYgAAAAAAAAAAWfInEWjh0VOQ09ERVJEh49MYXZjIGxpYnZweC12cDlnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjA0MDAwMDAwMAAAH0O2dcfngQCgwqGggQAAAIJJg0IAABAAFgA4JBwYSgAAICAAEb///4r+AAB1oZ2mm+6BAaWWgkmDQgAAEAAWADgkHBhKAAAgIABIQBxTu2uRu4+zgQC3iveBAfGCAXHwgQM=",h.load()});if(!e)return"premultiply-alpha-on-upload";const i=t.createTexture();t.bindTexture(t.TEXTURE_2D,i);const s=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,s),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 r=new Uint8Array(4);return t.readPixels(0,0,1,1,t.RGBA,t.UNSIGNED_BYTE,r),t.deleteFramebuffer(s),t.deleteTexture(i),(o=t.getExtension("WEBGL_lose_context"))==null||o.loseContext(),r[0]<=r[3]?"premultiplied-alpha":"premultiply-alpha-on-upload"})()),nn}const ks=class Uh extends Bt{constructor(t){super(t),this.isReady=!1,this.uploadMethodId="video",t={...Uh.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=mt.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 Gh(),this._load=new Promise((i,s)=>{this.isValid?i(this):(this._resolve=i,this._reject=s,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&&(mt.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||(mt.shared.add(this.updateFrame,this),this._isConnectedToTicker=!0,this._msToNextUpdate=0)):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker&&(mt.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0))}static test(t){return globalThis.HTMLVideoElement&&t instanceof HTMLVideoElement}};ks.extension=E.TextureSource;ks.defaultOptions={...Bt.defaultOptions,autoLoad:!0,autoPlay:!0,updateFPS:0,crossorigin:!0,loop:!1,muted:!0,playsinline:!0,preload:!1};ks.MIME_TYPES={ogv:"video/ogg",mov:"video/quicktime",m4v:"video/mp4"};let Ci=ks;const zt=(n,t,e=!1)=>(Array.isArray(n)||(n=[n]),t?n.map(i=>typeof i=="string"||e?t(i):i):n);class uu{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||st(`[Assets] Asset id ${t} was not found in the Cache`),e}set(t,e){const i=zt(t);let s;for(let h=0;h<this.parsers.length;h++){const l=this.parsers[h];if(l.test(e)){s=l.getCacheableAssets(i,e);break}}const r=new Map(Object.entries(s||{}));s||i.forEach(h=>{r.set(h,e)});const o=[...r.keys()],a={cacheKeys:o,keys:i};i.forEach(h=>{this._cacheMap.set(h,a)}),o.forEach(h=>{const l=s?s[h]:e;this._cache.has(h)&&this._cache.get(h)!==l&&st("[Cache] already has key:",h),this._cache.set(h,r.get(h))})}remove(t){if(!this._cacheMap.has(t)){st(`[Assets] Asset id ${t} was not found in the Cache`);return}const e=this._cacheMap.get(t);e.cacheKeys.forEach(s=>{this._cache.delete(s)}),e.keys.forEach(s=>{this._cacheMap.delete(s)})}get parsers(){return this._parsers}}const yt=new uu,Nn=[];q.handleByList(E.TextureSource,Nn);function Hh(n={}){const t=n&&n.resource,e=t?n.resource:n,i=t?n:{resource:n};for(let s=0;s<Nn.length;s++){const r=Nn[s];if(r.test(e))return new r(i)}throw new Error(`Could not find a source type for resource: ${i.resource}`)}function pu(n={},t=!1){const e=n&&n.resource,i=e?n.resource:n,s=e?n:{resource:n};if(!t&&yt.has(i))return yt.get(i);const r=new O({source:Hh(s)});return r.on("destroy",()=>{yt.has(i)&&yt.remove(i)}),t||yt.set(i,r),r}function fu(n,t=!1){return typeof n=="string"?yt.get(n):n instanceof Bt?new O({source:n}):pu(n,t)}O.from=fu;Bt.from=Hh;q.add(Lh,zh,Oh,Ci,Je,vr,mr);var ce=(n=>(n[n.Low=0]="Low",n[n.Normal=1]="Normal",n[n.High=2]="High",n))(ce||{});function Lt(n){if(typeof n!="string")throw new TypeError(`Path must be a string. Received ${JSON.stringify(n)}`)}function hi(n){return n.split("?")[0].split("#")[0]}function gu(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function mu(n,t,e){return n.replace(new RegExp(gu(t),"g"),e)}function yu(n,t){let e="",i=0,s=-1,r=0,o=-1;for(let a=0;a<=n.length;++a){if(a<n.length)o=n.charCodeAt(a);else{if(o===47)break;o=47}if(o===47){if(!(s===a-1||r===1))if(s!==a-1&&r===2){if(e.length<2||i!==2||e.charCodeAt(e.length-1)!==46||e.charCodeAt(e.length-2)!==46){if(e.length>2){const h=e.lastIndexOf("/");if(h!==e.length-1){h===-1?(e="",i=0):(e=e.slice(0,h),i=e.length-1-e.lastIndexOf("/")),s=a,r=0;continue}}else if(e.length===2||e.length===1){e="",i=0,s=a,r=0;continue}}}else e.length>0?e+=`/${n.slice(s+1,a)}`:e=n.slice(s+1,a),i=a-s-1;s=a,r=0}else o===46&&r!==-1?++r:r=-1}return e}const Pt={toPosix(n){return mu(n,"\\","/")},isUrl(n){return/^https?:/.test(this.toPosix(n))},isDataUrl(n){return/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i.test(n)},isBlobUrl(n){return n.startsWith("blob:")},hasProtocol(n){return/^[^/:]+:/.test(this.toPosix(n))},getProtocol(n){Lt(n),n=this.toPosix(n);const t=/^file:\/\/\//.exec(n);if(t)return t[0];const e=/^[^/:]+:\/{0,2}/.exec(n);return e?e[0]:""},toAbsolute(n,t,e){if(Lt(n),this.isDataUrl(n)||this.isBlobUrl(n))return n;const i=hi(this.toPosix(t??$.get().getBaseUrl())),s=hi(this.toPosix(e??this.rootname(i)));return n=this.toPosix(n),n.startsWith("/")?Pt.join(s,n.slice(1)):this.isAbsolute(n)?n:this.join(i,n)},normalize(n){if(Lt(n),n.length===0)return".";if(this.isDataUrl(n)||this.isBlobUrl(n))return n;n=this.toPosix(n);let t="";const e=n.startsWith("/");this.hasProtocol(n)&&(t=this.rootname(n),n=n.slice(t.length));const i=n.endsWith("/");return n=yu(n),n.length>0&&i&&(n+="/"),e?`/${n}`:t+n},isAbsolute(n){return Lt(n),n=this.toPosix(n),this.hasProtocol(n)?!0:n.startsWith("/")},join(...n){if(n.length===0)return".";let t;for(let e=0;e<n.length;++e){const i=n[e];if(Lt(i),i.length>0)if(t===void 0)t=i;else{const s=n[e-1]??"";this.joinExtensions.includes(this.extname(s).toLowerCase())?t+=`/../${i}`:t+=`/${i}`}}return t===void 0?".":this.normalize(t)},dirname(n){if(Lt(n),n.length===0)return".";n=this.toPosix(n);let t=n.charCodeAt(0);const e=t===47;let i=-1,s=!0;const r=this.getProtocol(n),o=n;n=n.slice(r.length);for(let a=n.length-1;a>=1;--a)if(t=n.charCodeAt(a),t===47){if(!s){i=a;break}}else s=!1;return i===-1?e?"/":this.isUrl(o)?r+n:r:e&&i===1?"//":r+n.slice(0,i)},rootname(n){Lt(n),n=this.toPosix(n);let t="";if(n.startsWith("/")?t="/":t=this.getProtocol(n),this.isUrl(n)){const e=n.indexOf("/",t.length);e!==-1?t=n.slice(0,e):t=n,t.endsWith("/")||(t+="/")}return t},basename(n,t){Lt(n),t&&Lt(t),n=hi(this.toPosix(n));let e=0,i=-1,s=!0,r;if(t!==void 0&&t.length>0&&t.length<=n.length){if(t.length===n.length&&t===n)return"";let o=t.length-1,a=-1;for(r=n.length-1;r>=0;--r){const h=n.charCodeAt(r);if(h===47){if(!s){e=r+1;break}}else a===-1&&(s=!1,a=r+1),o>=0&&(h===t.charCodeAt(o)?--o===-1&&(i=r):(o=-1,i=a))}return e===i?i=a:i===-1&&(i=n.length),n.slice(e,i)}for(r=n.length-1;r>=0;--r)if(n.charCodeAt(r)===47){if(!s){e=r+1;break}}else i===-1&&(s=!1,i=r+1);return i===-1?"":n.slice(e,i)},extname(n){Lt(n),n=hi(this.toPosix(n));let t=-1,e=0,i=-1,s=!0,r=0;for(let o=n.length-1;o>=0;--o){const a=n.charCodeAt(o);if(a===47){if(!s){e=o+1;break}continue}i===-1&&(s=!1,i=o+1),a===46?t===-1?t=o:r!==1&&(r=1):t!==-1&&(r=-1)}return t===-1||i===-1||r===0||r===1&&t===i-1&&t===e+1?"":n.slice(t,i)},parse(n){Lt(n);const t={root:"",dir:"",base:"",ext:"",name:""};if(n.length===0)return t;n=hi(this.toPosix(n));let e=n.charCodeAt(0);const i=this.isAbsolute(n);let s;t.root=this.rootname(n),i||this.hasProtocol(n)?s=1:s=0;let r=-1,o=0,a=-1,h=!0,l=n.length-1,c=0;for(;l>=s;--l){if(e=n.charCodeAt(l),e===47){if(!h){o=l+1;break}continue}a===-1&&(h=!1,a=l+1),e===46?r===-1?r=l:c!==1&&(c=1):r!==-1&&(c=-1)}return r===-1||a===-1||c===0||c===1&&r===a-1&&r===o+1?a!==-1&&(o===0&&i?t.base=t.name=n.slice(1,a):t.base=t.name=n.slice(o,a)):(o===0&&i?(t.name=n.slice(1,r),t.base=n.slice(1,a)):(t.name=n.slice(o,r),t.base=n.slice(o,a)),t.ext=n.slice(r,a)),t.dir=this.dirname(n),t},sep:"/",delimiter:":",joinExtensions:[".html"]};function Nh(n,t,e,i,s){const r=t[e];for(let o=0;o<r.length;o++){const a=r[o];e<t.length-1?Nh(n.replace(i[e],a),t,e+1,i,s):s.push(n.replace(i[e],a))}}function xu(n){const t=/\{(.*?)\}/g,e=n.match(t),i=[];if(e){const s=[];e.forEach(r=>{const o=r.substring(1,r.length-1).split(",");s.push(o)}),Nh(n,s,0,e,i)}else i.push(n);return i}const xs=n=>!Array.isArray(n);class ri{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 zt(e||i,r=>typeof r=="string"?r:Array.isArray(r)?r.map(o=>(o==null?void 0:o.src)??o):r!=null&&r.src?r.src:r,!0)}addManifest(t){this._manifest&&st("[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 s=e;Array.isArray(e)||(s=Object.entries(e).map(([r,o])=>typeof o=="string"||Array.isArray(o)?{alias:r,src:o}:{alias:r,...o})),s.forEach(r=>{const o=r.src,a=r.alias;let h;if(typeof a=="string"){const l=this._createBundleAssetId(t,a);i.push(l),h=[a,l]}else{const l=a.map(c=>this._createBundleAssetId(t,c));i.push(...l),h=[...a,...l]}this.add({...r,alias:h,src:o})}),this._bundles[t]=i}add(t){const e=[];Array.isArray(t)?e.push(...t):e.push(t);let i;i=r=>{this.hasKey(r)&&st(`[Resolver] already has key: ${r} overwriting`)},zt(e).forEach(r=>{const{src:o}=r;let{data:a,format:h,loadParser:l,parser:c}=r;const d=zt(o).map(y=>typeof y=="string"?xu(y):Array.isArray(y)?y:[y]),u=this.getAlias(r);Array.isArray(u)?u.forEach(i):i(u);const p=[],g=y=>{const m=this._parsers.find(x=>x.test(y));return{src:y,...m==null?void 0:m.parse(y)}};d.forEach(y=>{y.forEach(m=>{let x={};if(typeof m!="object"?x=g(m):(a=m.data??a,h=m.format??h,(m.loadParser||m.parser)&&(l=m.loadParser??l,c=m.parser??c),x={...g(m.src),...m}),!u)throw new Error(`[Resolver] alias is undefined for this asset: ${x.src}`);x=this._buildResolvedAsset(x,{aliases:u,data:a,format:h,loadParser:l,parser:c,progressSize:r.progressSize}),p.push(x)})}),u.forEach(y=>{this._assetMap[y]=p})})}resolveBundle(t){const e=xs(t);t=zt(t);const i={};return t.forEach(s=>{const r=this._bundles[s];if(r){const o=this.resolve(r),a={};for(const h in o){const l=o[h];a[this._extractAssetIdFromBundle(s,h)]=l}i[s]=a}}),e?i[t[0]]:i}resolveUrl(t){const e=this.resolve(t);if(typeof t!="string"){const i={};for(const s in e)i[s]=e[s].src;return i}return e.src}resolve(t){const e=xs(t);t=zt(t);const i={};return t.forEach(s=>{if(!this._resolverHash[s])if(this._assetMap[s]){let r=this._assetMap[s];const o=this._getPreferredOrder(r);o==null||o.priority.forEach(a=>{o.params[a].forEach(h=>{const l=r.filter(c=>c[a]?c[a]===h:!1);l.length&&(r=l)})}),this._resolverHash[s]=r[0]}else this._resolverHash[s]=this._buildResolvedAsset({alias:[s],src:s},{});i[s]=this._resolverHash[s]}),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],s=this._preferredOrder.find(r=>r.params.format.includes(i.format));if(s)return s}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:s,loadParser:r,parser:o,format:a,progressSize:h}=e;return(this._basePath||this._rootPath)&&(t.src=Pt.toAbsolute(t.src,this._basePath,this._rootPath)),t.alias=i??t.alias??[t.src],t.src=this._appendDefaultSearchParams(t.src),t.data={...s||{},...t.data},t.loadParser=r??t.loadParser,t.parser=o??t.parser,t.format=a??t.format??Su(t.src),h!==void 0&&(t.progressSize=h),t}}ri.RETINA_PREFIX=/@([0-9\.]+)x/;function Su(n){return n.split(".").pop().split("?").shift().split("#").shift()}const Vn=(n,t)=>{const e=t.split("?")[1];return e&&(n+=`?${e}`),n},Vh=class xi{constructor(t,e){this.linkedSheets=[];let i=t;(t==null?void 0:t.source)instanceof Bt&&(i={texture:t,data:e});const{texture:s,data:r,cachePrefix:o=""}=i;this.cachePrefix=o,this._texture=s instanceof O?s:null,this.textureSource=s.source,this.textures={},this.animations={},this.data=r;const a=parseFloat(r.meta.scale);a?(this.resolution=a,s.source.resolution=this.resolution):this.resolution=s.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<=xi.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 s=e?1/0:xi.BATCH_SIZE;for(;i-t<s&&i<this._frameKeys.length;){const r=this._frameKeys[i],o=this._frames[r],a=o.frame;if(a){let h=null,l=null;const c=o.trimmed!==!1&&o.sourceSize?o.sourceSize:o.frame,d=new J(0,0,Math.floor(c.w)/this.resolution,Math.floor(c.h)/this.resolution);o.rotated?h=new J(Math.floor(a.x)/this.resolution,Math.floor(a.y)/this.resolution,Math.floor(a.h)/this.resolution,Math.floor(a.w)/this.resolution):h=new J(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&&(l=new J(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[r]=new O({source:this.textureSource,frame:h,orig:d,trim:l,rotate:o.rotated?2:0,defaultAnchor:o.anchor,defaultBorders:o.borders,label:r.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 s=t[e][i];this.animations[e].push(this.textures[s])}}}_parseComplete(){const t=this._callback;this._callback=null,this._batchIndex=0,t.call(this,this.textures)}_nextBatch(){this._processFrames(this._batchIndex*xi.BATCH_SIZE),this._batchIndex++,setTimeout(()=>{this._batchIndex*xi.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=[]}};Vh.BATCH_SIZE=1e3;let $n=Vh;const vu=["jpg","png","jpeg","avif","webp","basis","etc2","bc7","bc6h","bc5","bc4","bc3","bc2","bc1","eac","astc"];function $h(n,t,e){const i={};if(n.forEach(s=>{i[s]=t}),Object.keys(t.textures).forEach(s=>{i[`${t.cachePrefix}${s}`]=t.textures[s]}),!e){const s=Pt.dirname(n[0]);t.linkedSheets.forEach((r,o)=>{const a=$h([`${s}/${t.data.meta.related_multi_packs[o]}`],r,!0);Object.assign(i,a)})}return i}const bu={extension:E.Asset,cache:{test:n=>n instanceof $n,getCacheableAssets:(n,t)=>$h(n,t,!1)},resolver:{extension:{type:E.ResolveParser,name:"resolveSpritesheet"},test:n=>{const e=n.split("?")[0].split("."),i=e.pop(),s=e.pop();return i==="json"&&vu.includes(s)},parse:n=>{var e;const t=n.split(".");return{resolution:parseFloat(((e=ri.RETINA_PREFIX.exec(n))==null?void 0:e[1])??"1"),format:t[t.length-2],src:n}}},loader:{name:"spritesheetLoader",id:"spritesheet",extension:{type:E.LoadParser,priority:ce.Normal,name:"spritesheetLoader"},async testParse(n,t){return Pt.extname(t.src).toLowerCase()===".json"&&!!n.frames},async parse(n,t,e){var d,u;const{texture:i,imageFilename:s,textureOptions:r,cachePrefix:o}=(t==null?void 0:t.data)??{};let a=Pt.dirname(t.src);a&&a.lastIndexOf("/")!==a.length-1&&(a+="/");let h;if(i instanceof O)h=i;else{const p=Vn(a+(s??n.meta.image),t.src);h=(await e.load([{src:p,data:r}]))[p]}const l=new $n({texture:h.source,data:n,cachePrefix:o});await l.parse();const c=(d=n==null?void 0:n.meta)==null?void 0:d.related_multi_packs;if(Array.isArray(c)){const p=[];for(const y of c){if(typeof y!="string")continue;let m=a+y;(u=t.data)!=null&&u.ignoreMultiPack||(m=Vn(m,t.src),p.push(e.load({src:m,data:{textureOptions:r,ignoreMultiPack:!0}})))}const g=await Promise.all(p);l.linkedSheets=g,g.forEach(y=>{y.linkedSheets=[l].concat(l.linkedSheets.filter(m=>m!==y))})}return l},async unload(n,t,e){await e.unload(n.textureSource._sourceOrigin),n.destroy(!1)}}};q.add(bu);class wu{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,s=this._canvas.height,r=e.width/i*this._renderer.resolution,o=e.height/s*this._renderer.resolution,a=e.left,h=e.top,l=`translate(${a}px, ${h}px) scale(${r}, ${o})`;l!==this._lastTransform&&(this._domElement.style.transform=l,this._lastTransform=l)},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,s=this.canvas.height,r=e.contentRect.width/i*this._renderer.resolution,o=e.contentRect.height/s*this._renderer.resolution;(this._lastScaleX!==r||this._lastScaleY!==o)&&(this.updateTranslation(),this._lastScaleX=r,this._lastScaleY=o)}}),this._observer.observe(this._canvas)):this._tickerAttached||mt.shared.add(this.updateTranslation,this,Ie.HIGH)}destroy(){this._observer?(this._observer.disconnect(),this._observer=null):this._tickerAttached&&mt.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 br{constructor(t){this.bubbles=!0,this.cancelBubble=!0,this.cancelable=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=br.prototype.NONE,this.propagationStopped=!1,this.propagationImmediatelyStopped=!1,this.layer=new Q,this.page=new Q,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,s,r){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 rn=/iPhone/i,_o=/iPod/i,Po=/iPad/i,Mo=/\biOS-universal(?:.+)Mac\b/i,on=/\bAndroid(?:.+)Mobile\b/i,To=/Android/i,ze=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,Ki=/Silk/i,Zt=/Windows Phone/i,Ao=/\bWindows(?:.+)ARM\b/i,Ro=/BlackBerry/i,ko=/BB10/i,Eo=/Opera Mini/i,Io=/\b(CriOS|Chrome)(?:.+)Mobile/i,Do=/Mobile(?:.+)Firefox\b/i,Fo=function(n){return typeof n<"u"&&n.platform==="MacIntel"&&typeof n.maxTouchPoints=="number"&&n.maxTouchPoints>1&&typeof MSStream>"u"};function Cu(n){return function(t){return t.test(n)}}function Bo(n){var t={userAgent:"",platform:"",maxTouchPoints:0};!n&&typeof navigator<"u"?t={userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints||0}:typeof n=="string"?t.userAgent=n:n&&n.userAgent&&(t={userAgent:n.userAgent,platform:n.platform,maxTouchPoints:n.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 s=Cu(e),r={apple:{phone:s(rn)&&!s(Zt),ipod:s(_o),tablet:!s(rn)&&(s(Po)||Fo(t))&&!s(Zt),universal:s(Mo),device:(s(rn)||s(_o)||s(Po)||s(Mo)||Fo(t))&&!s(Zt)},amazon:{phone:s(ze),tablet:!s(ze)&&s(Ki),device:s(ze)||s(Ki)},android:{phone:!s(Zt)&&s(ze)||!s(Zt)&&s(on),tablet:!s(Zt)&&!s(ze)&&!s(on)&&(s(Ki)||s(To)),device:!s(Zt)&&(s(ze)||s(Ki)||s(on)||s(To))||s(/\bokhttp\b/i)},windows:{phone:s(Zt),tablet:s(Ao),device:s(Zt)||s(Ao)},other:{blackberry:s(Ro),blackberry10:s(ko),opera:s(Eo),firefox:s(Do),chrome:s(Io),device:s(Ro)||s(ko)||s(Eo)||s(Do)||s(Io)},any:!1,phone:!1,tablet:!1};return r.any=r.apple.device||r.android.device||r.windows.device||r.other.device,r.phone=r.apple.phone||r.android.phone||r.windows.phone,r.tablet=r.apple.tablet||r.android.tablet||r.windows.tablet,r}const _u=Bo.default??Bo,Pu=_u(globalThis.navigator),an=Object.create(null),Lo=Object.create(null);function wr(n,t){let e=Lo[n];return e===void 0&&(an[t]===void 0&&(an[t]=1),Lo[n]=e=an[t]++),e}let Oe;function Yh(){return(!Oe||Oe!=null&&Oe.isContextLost())&&(Oe=$.get().createCanvas().getContext("webgl",{})),Oe}let Qi;function Mu(){if(!Qi){Qi="mediump";const n=Yh();n&&n.getShaderPrecisionFormat&&(Qi=n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.HIGH_FLOAT).precision?"highp":"mediump")}return Qi}function Tu(n,t,e){return t?n:e?(n=n.replace("out vec4 finalColor;",""),`
6
+
7
+ #ifdef GL_ES // This checks if it is WebGL1
8
+ #define in varying
9
+ #define finalColor gl_FragColor
10
+ #define texture texture2D
11
+ #endif
12
+ ${n}
13
+ `):`
14
+
15
+ #ifdef GL_ES // This checks if it is WebGL1
16
+ #define in attribute
17
+ #define out varying
18
+ #endif
19
+ ${n}
20
+ `}function Au(n,t,e){const i=e?t.maxSupportedFragmentPrecision:t.maxSupportedVertexPrecision;if(n.substring(0,9)!=="precision"){let s=e?t.requestedFragmentPrecision:t.requestedVertexPrecision;return s==="highp"&&i!=="highp"&&(s="mediump"),`precision ${s} float;
21
+ ${n}`}else if(i!=="highp"&&n.substring(0,15)==="precision highp")return n.replace("precision highp","precision mediump");return n}function Ru(n,t){return t?`#version 300 es
22
+ ${n}`:n}const ku={},Eu={};function Iu(n,{name:t="pixi-program"},e=!0){t=t.replace(/\s+/g,"-"),t+=e?"-fragment":"-vertex";const i=e?ku:Eu;return i[t]?(i[t]++,t+=`-${i[t]}`):i[t]=1,n.indexOf("#define SHADER_NAME")!==-1?n:`${`#define SHADER_NAME ${t}`}
23
+ ${n}`}function Du(n,t){return t?n.replace("#version 300 es",""):n}const hn={stripVersion:Du,ensurePrecision:Au,addProgramDefines:Tu,setProgramName:Iu,insertVersion:Ru},li=Object.create(null),Xh=class Yn{constructor(t){t={...Yn.defaultOptions,...t};const e=t.fragment.indexOf("#version 300 es")!==-1,i={stripVersion:e,ensurePrecision:{requestedFragmentPrecision:t.preferredFragmentPrecision,requestedVertexPrecision:t.preferredVertexPrecision,maxSupportedVertexPrecision:"highp",maxSupportedFragmentPrecision:Mu()},setProgramName:{name:t.name},addProgramDefines:e,insertVersion:e};let s=t.fragment,r=t.vertex;Object.keys(hn).forEach(o=>{const a=i[o];s=hn[o](s,a,!0),r=hn[o](r,a,!1)}),this.fragment=s,this.vertex=r,this.transformFeedbackVaryings=t.transformFeedbackVaryings,this._key=wr(`${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,li[this._cacheKey]=null}static from(t){const e=`${t.vertex}:${t.fragment}`;return li[e]||(li[e]=new Yn(t),li[e]._cacheKey=e),li[e]}};Xh.defaultOptions={preferredVertexPrecision:"highp",preferredFragmentPrecision:"mediump"};let ti=Xh;const zo={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 Fu(n){return zo[n]??zo.float32}const Bu={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"},Oo=/@location\((\d+)\)\s+([a-zA-Z0-9_]+)\s*:\s*([a-zA-Z0-9_<>]+)(?:,|\s|\)|$)/g;function Wo(n,t){let e;for(;(e=Oo.exec(n))!==null;){const i=Bu[e[3]]??"float32";t[e[2]]={location:parseInt(e[1],10),format:i,stride:Fu(i).stride,offset:0,instance:!1,start:0}}Oo.lastIndex=0}function Lu(n){return n.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"")}function zu({source:n,entryPoint:t}){const e={},i=Lu(n),s=i.indexOf(`fn ${t}(`);if(s===-1)return e;const r=i.indexOf("->",s);if(r===-1)return e;const o=i.substring(s,r);if(Wo(o,e),Object.keys(e).length===0){const a=o.match(/\(\s*\w+\s*:\s*(\w+)/);if(a){const h=a[1],l=new RegExp(`struct\\s+${h}\\s*\\{([^}]+)\\}`,"s"),c=i.match(l);c&&Wo(c[1],e)}}return e}function ln(n){var d,u;const t=/(^|[^/])@(group|binding)\(\d+\)[^;]+;/g,e=/@group\((\d+)\)/,i=/@binding\((\d+)\)/,s=/var(<[^>]+>)? (\w+)/,r=/:\s*([\w<>]+)/,o=/struct\s+(\w+)\s*{([^}]+)}/g,a=/(\w+)\s*:\s*([\w\<\>]+)/g,h=/struct\s+(\w+)/,l=(d=n.match(t))==null?void 0:d.map(p=>({group:parseInt(p.match(e)[1],10),binding:parseInt(p.match(i)[1],10),name:p.match(s)[2],isUniform:p.match(s)[1]==="<uniform>",type:p.match(r)[1]}));if(!l)return{groups:[],structs:[]};const c=((u=n.match(o))==null?void 0:u.map(p=>{const g=p.match(h)[1],y=p.match(a).reduce((m,x)=>{const[S,v]=x.split(":");return m[S.trim()]=v.trim(),m},{});return y?{name:g,members:y}:null}).filter(({name:p})=>l.some(g=>g.type===p||g.type.includes(`<${p}>`))))??[];return{groups:l,structs:c}}var we=(n=>(n[n.VERTEX=1]="VERTEX",n[n.FRAGMENT=2]="FRAGMENT",n[n.COMPUTE=4]="COMPUTE",n))(we||{});function Ou({groups:n}){const t=[];for(let e=0;e<n.length;e++){const i=n[e];t[i.group]||(t[i.group]=[]),i.isUniform?t[i.group].push({binding:i.binding,visibility:we.VERTEX|we.FRAGMENT,buffer:{type:"uniform"}}):i.type==="sampler"?t[i.group].push({binding:i.binding,visibility:we.FRAGMENT,sampler:{type:"filtering"}}):i.type==="texture_2d"||i.type.startsWith("texture_2d<")?t[i.group].push({binding:i.binding,visibility:we.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:we.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:we.FRAGMENT,texture:{sampleType:"float",viewDimension:"cube",multisampled:!1}})}for(let e=0;e<t.length;e++)t[e]||(t[e]=[]);return t}function Wu({groups:n}){const t=[];for(let e=0;e<n.length;e++){const i=n[e];t[i.group]||(t[i.group]={}),t[i.group][i.name]=i.binding}return t}function Gu(n,t){const e=new Set,i=new Set,s=[...n.structs,...t.structs].filter(o=>e.has(o.name)?!1:(e.add(o.name),!0)),r=[...n.groups,...t.groups].filter(o=>{const a=`${o.name}-${o.binding}`;return i.has(a)?!1:(i.add(a),!0)});return{structs:s,groups:r}}const ci=Object.create(null);class he{constructor(t){var a,h;this._layoutKey=0,this._attributeLocationsKey=0;const{fragment:e,vertex:i,layout:s,gpuLayout:r,name:o}=t;if(this.name=o,this.fragment=e,this.vertex=i,e.source===i.source){const l=ln(e.source);this.structsAndGroups=l}else{const l=ln(i.source),c=ln(e.source);this.structsAndGroups=Gu(l,c)}this.layout=s??Wu(this.structsAndGroups),this.gpuLayout=r??Ou(this.structsAndGroups),this.autoAssignGlobalUniforms=((a=this.layout[0])==null?void 0:a.globalUniforms)!==void 0,this.autoAssignLocalUniforms=((h=this.layout[1])==null?void 0:h.localUniforms)!==void 0,this._generateProgramKey()}_generateProgramKey(){const{vertex:t,fragment:e}=this,i=t.source+e.source+t.entryPoint+e.entryPoint;this._layoutKey=wr(i,"program")}get attributeData(){return this._attributeData??(this._attributeData=zu(this.vertex)),this._attributeData}destroy(){this.gpuLayout=null,this.layout=null,this.structsAndGroups=null,this.fragment=null,this.vertex=null,ci[this._cacheKey]=null}static from(t){const e=`${t.vertex.source}:${t.fragment.source}:${t.fragment.entryPoint}:${t.vertex.entryPoint}`;return ci[e]||(ci[e]=new he(t),ci[e]._cacheKey=e),ci[e]}}const jh=["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>"],Uu=jh.reduce((n,t)=>(n[t]=!0,n),{});function Hu(n,t){switch(n){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 Zh=class qh{constructor(t,e){this._touched=0,this.uid=ct("uniform"),this._resourceType="uniformGroup",this._resourceId=ct("resource"),this.isUniformGroup=!0,this._dirtyId=0,this.destroyed=!1,e={...qh.defaultOptions,...e},this.uniformStructures=t;const i={};for(const s in t){const r=t[s];if(r.name=s,r.size=r.size??1,!Uu[r.type]){const o=r.type.match(/^array<(\w+(?:<\w+>)?),\s*(\d+)>$/);if(o){const[,a,h]=o;throw new Error(`Uniform type ${r.type} is not supported. Use type: '${a}', size: ${h} instead.`)}throw new Error(`Uniform type ${r.type} is not supported. Supported uniform types are: ${jh.join(", ")}`)}r.value??(r.value=Hu(r.type,r.size)),i[s]=r.value}this.uniforms=i,this._dirtyId=1,this.ubo=e.ubo,this.isStatic=e.isStatic,this._signature=wr(Object.keys(i).map(s=>`${s}-${t[s].type}`).join("-"),"uniform-group")}update(){this._dirtyId++}};Zh.defaultOptions={ubo:!1,isStatic:!1};let ei=Zh;class _i{constructor(t){this.resources=Object.create(null),this._dirty=!0;let e=0;for(const i in t){const s=t[i];this.setResource(s,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 s,r;const i=this.resources[e];t!==i&&(i&&((s=i.off)==null||s.call(i,"change",this.onResourceChange,this)),(r=t.on)==null||r.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 s in i)i[s]._gcLastUsed=t,i[s]._touched=e}destroy(){var e;const t=this.resources;for(const i in t){const s=t[i];(e=s==null?void 0:s.off)==null||e.call(s,"change",this.onResourceChange,this)}this.resources=null}onResourceChange(t){if(this._dirty=!0,t.destroyed){const e=this.resources;for(const i in e)e[i]===t&&(e[i]=null)}else this._updateKey()}}var Qt=(n=>(n[n.WEBGL=1]="WEBGL",n[n.WEBGPU=2]="WEBGPU",n[n.CANVAS=4]="CANVAS",n[n.BOTH=3]="BOTH",n))(Qt||{});class De extends Yt{constructor(t){super(),this.uid=ct("shader"),this._uniformBindMap=Object.create(null),this._ownedBindGroups=[],this._destroyed=!1;let{gpuProgram:e,glProgram:i,groups:s,resources:r,compatibleRenderers:o,groupMap:a}=t;this.gpuProgram=e,this.glProgram=i,o===void 0&&(o=0,e&&(o|=Qt.WEBGPU),i&&(o|=Qt.WEBGL)),this.compatibleRenderers=o;const h={};if(!r&&!s&&(r={}),r&&s)throw new Error("[Shader] Cannot have both resources and groups");if(!e&&s&&!a)throw new Error("[Shader] No group map or WebGPU shader provided - consider using resources instead.");if(!e&&s&&a)for(const l in a)for(const c in a[l]){const d=a[l][c];h[d]={group:l,binding:c,name:d}}else if(e&&s&&!a){const l=e.structsAndGroups.groups;a={},l.forEach(c=>{a[c.group]=a[c.group]||{},a[c.group][c.binding]=c.name,h[c.name]=c})}else if(r){s={},a={},e&&e.structsAndGroups.groups.forEach(d=>{a[d.group]=a[d.group]||{},a[d.group][d.binding]=d.name,h[d.name]=d});let l=0;for(const c in r)h[c]||(s[99]||(s[99]=new _i,this._ownedBindGroups.push(s[99])),h[c]={group:99,binding:l,name:c},a[99]=a[99]||{},a[99][l]=c,l++);for(const c in r){const d=c;let u=r[c];!u.source&&!u._resourceType&&(u=new ei(u));const p=h[d];p&&(s[p.group]||(s[p.group]=new _i,this._ownedBindGroups.push(s[p.group])),s[p.group].setResource(u,p.binding))}}this.groups=s,this._uniformBindMap=a,this.resources=this._buildResourceAccessor(s,h)}addResource(t,e,i){var s,r;(s=this._uniformBindMap)[e]||(s[e]={}),(r=this._uniformBindMap[e])[i]||(r[i]=t),this.groups[e]||(this.groups[e]=new _i,this._ownedBindGroups.push(this.groups[e]))}_buildResourceAccessor(t,e){const i={};for(const s in e){const r=e[s];Object.defineProperty(i,r.name,{get(){return t[r.group].getResource(r.binding)},set(o){t[r.group].setResource(o,r.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(s=>{s.destroy()}),this._ownedBindGroups=null,this.resources=null,this.groups=null)}static from(t){const{gpu:e,gl:i,...s}=t;let r,o;return e&&(r=he.from(e)),i&&(o=ti.from(i)),new De({gpuProgram:r,glProgram:o,...s})}}const Nu={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},cn=0,dn=1,un=2,pn=3,fn=4,gn=5,Xn=class Kh{constructor(){this.data=0,this.blendMode="normal",this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(this.data&1<<cn)}set blend(t){!!(this.data&1<<cn)!==t&&(this.data^=1<<cn)}get offsets(){return!!(this.data&1<<dn)}set offsets(t){!!(this.data&1<<dn)!==t&&(this.data^=1<<dn)}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<<un)}set culling(t){!!(this.data&1<<un)!==t&&(this.data^=1<<un)}get depthTest(){return!!(this.data&1<<pn)}set depthTest(t){!!(this.data&1<<pn)!==t&&(this.data^=1<<pn)}get depthMask(){return!!(this.data&1<<gn)}set depthMask(t){!!(this.data&1<<gn)!==t&&(this.data^=1<<gn)}get clockwiseFrontFace(){return!!(this.data&1<<fn)}set clockwiseFrontFace(t){!!(this.data&1<<fn)!==t&&(this.data^=1<<fn)}get blendMode(){return this._blendMode}set blendMode(t){this.blend=t!=="none",this._blendMode=t,this._blendModeId=Nu[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 Kh;return t.depthTest=!1,t.blend=!0,t}};Xn.default2d=Xn.for2d();let Ui=Xn;const Qh=class jn extends De{constructor(t){t={...jn.defaultOptions,...t},super(t),this.enabled=!0,this._state=Ui.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,s){t.applyFilter(this,e,i,s)}get blendMode(){return this._state.blendMode}set blendMode(t){this._state.blendMode=t}static from(t){const{gpu:e,gl:i,...s}=t;let r,o;return e&&(r=he.from(e)),i&&(o=ti.from(i)),new jn({gpuProgram:r,glProgram:o,...s})}};Qh.defaultOptions={blendMode:"normal",resolution:1,padding:0,antialias:"off",blendRequired:!1,clipToViewport:!0};let Vu=Qh;const Zn=[];q.handleByNamedList(E.Environment,Zn);async function $u(n){if(!n)for(let t=0;t<Zn.length;t++){const e=Zn[t];if(e.value.test()){await e.value.load();return}}}let di;function Yu(){if(typeof di=="boolean")return di;try{di=new Function("param1","param2","param3","return param1[param2] === param3;")({a:"b"},"a","b")===!0}catch{di=!1}return di}function Go(n,t,e=2){const i=t&&t.length,s=i?t[0]*e:n.length;let r=Jh(n,0,s,e,!0);const o=[];if(!r||r.next===r.prev)return o;let a,h,l;if(i&&(r=Ku(n,t,r,e)),n.length>80*e){a=n[0],h=n[1];let c=a,d=h;for(let u=e;u<s;u+=e){const p=n[u],g=n[u+1];p<a&&(a=p),g<h&&(h=g),p>c&&(c=p),g>d&&(d=g)}l=Math.max(c-a,d-h),l=l!==0?32767/l:0}return Ii(r,o,e,a,h,l,0),o}function Jh(n,t,e,i,s){let r;if(s===hp(n,t,e,i)>0)for(let o=t;o<e;o+=i)r=Uo(o/i|0,n[o],n[o+1],r);else for(let o=e-i;o>=t;o-=i)r=Uo(o/i|0,n[o],n[o+1],r);return r&&ii(r,r.next)&&(Fi(r),r=r.next),r}function Fe(n,t){if(!n)return n;t||(t=n);let e=n,i;do if(i=!1,!e.steiner&&(ii(e,e.next)||ot(e.prev,e,e.next)===0)){if(Fi(e),e=t=e.prev,e===e.next)break;i=!0}else e=e.next;while(i||e!==t);return t}function Ii(n,t,e,i,s,r,o){if(!n)return;!o&&r&&ip(n,i,s,r);let a=n;for(;n.prev!==n.next;){const h=n.prev,l=n.next;if(r?ju(n,i,s,r):Xu(n)){t.push(h.i,n.i,l.i),Fi(n),n=l.next,a=l.next;continue}if(n=l,n===a){o?o===1?(n=Zu(Fe(n),t),Ii(n,t,e,i,s,r,2)):o===2&&qu(n,t,e,i,s,r):Ii(Fe(n),t,e,i,s,r,1);break}}}function Xu(n){const t=n.prev,e=n,i=n.next;if(ot(t,e,i)>=0)return!1;const s=t.x,r=e.x,o=i.x,a=t.y,h=e.y,l=i.y,c=Math.min(s,r,o),d=Math.min(a,h,l),u=Math.max(s,r,o),p=Math.max(a,h,l);let g=i.next;for(;g!==t;){if(g.x>=c&&g.x<=u&&g.y>=d&&g.y<=p&&Si(s,a,r,h,o,l,g.x,g.y)&&ot(g.prev,g,g.next)>=0)return!1;g=g.next}return!0}function ju(n,t,e,i){const s=n.prev,r=n,o=n.next;if(ot(s,r,o)>=0)return!1;const a=s.x,h=r.x,l=o.x,c=s.y,d=r.y,u=o.y,p=Math.min(a,h,l),g=Math.min(c,d,u),y=Math.max(a,h,l),m=Math.max(c,d,u),x=qn(p,g,t,e,i),S=qn(y,m,t,e,i);let v=n.prevZ,b=n.nextZ;for(;v&&v.z>=x&&b&&b.z<=S;){if(v.x>=p&&v.x<=y&&v.y>=g&&v.y<=m&&v!==s&&v!==o&&Si(a,c,h,d,l,u,v.x,v.y)&&ot(v.prev,v,v.next)>=0||(v=v.prevZ,b.x>=p&&b.x<=y&&b.y>=g&&b.y<=m&&b!==s&&b!==o&&Si(a,c,h,d,l,u,b.x,b.y)&&ot(b.prev,b,b.next)>=0))return!1;b=b.nextZ}for(;v&&v.z>=x;){if(v.x>=p&&v.x<=y&&v.y>=g&&v.y<=m&&v!==s&&v!==o&&Si(a,c,h,d,l,u,v.x,v.y)&&ot(v.prev,v,v.next)>=0)return!1;v=v.prevZ}for(;b&&b.z<=S;){if(b.x>=p&&b.x<=y&&b.y>=g&&b.y<=m&&b!==s&&b!==o&&Si(a,c,h,d,l,u,b.x,b.y)&&ot(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function Zu(n,t){let e=n;do{const i=e.prev,s=e.next.next;!ii(i,s)&&el(i,e,e.next,s)&&Di(i,s)&&Di(s,i)&&(t.push(i.i,e.i,s.i),Fi(e),Fi(e.next),e=n=s),e=e.next}while(e!==n);return Fe(e)}function qu(n,t,e,i,s,r){let o=n;do{let a=o.next.next;for(;a!==o.prev;){if(o.i!==a.i&&rp(o,a)){let h=il(o,a);o=Fe(o,o.next),h=Fe(h,h.next),Ii(o,t,e,i,s,r,0),Ii(h,t,e,i,s,r,0);return}a=a.next}o=o.next}while(o!==n)}function Ku(n,t,e,i){const s=[];for(let r=0,o=t.length;r<o;r++){const a=t[r]*i,h=r<o-1?t[r+1]*i:n.length,l=Jh(n,a,h,i,!1);l===l.next&&(l.steiner=!0),s.push(np(l))}s.sort(Qu);for(let r=0;r<s.length;r++)e=Ju(s[r],e);return e}function Qu(n,t){let e=n.x-t.x;if(e===0&&(e=n.y-t.y,e===0)){const i=(n.next.y-n.y)/(n.next.x-n.x),s=(t.next.y-t.y)/(t.next.x-t.x);e=i-s}return e}function Ju(n,t){const e=tp(n,t);if(!e)return t;const i=il(e,n);return Fe(i,i.next),Fe(e,e.next)}function tp(n,t){let e=t;const i=n.x,s=n.y;let r=-1/0,o;if(ii(n,e))return e;do{if(ii(n,e.next))return e.next;if(s<=e.y&&s>=e.next.y&&e.next.y!==e.y){const d=e.x+(s-e.y)*(e.next.x-e.x)/(e.next.y-e.y);if(d<=i&&d>r&&(r=d,o=e.x<e.next.x?e:e.next,d===i))return o}e=e.next}while(e!==t);if(!o)return null;const a=o,h=o.x,l=o.y;let c=1/0;e=o;do{if(i>=e.x&&e.x>=h&&i!==e.x&&tl(s<l?i:r,s,h,l,s<l?r:i,s,e.x,e.y)){const d=Math.abs(s-e.y)/(i-e.x);Di(e,n)&&(d<c||d===c&&(e.x>o.x||e.x===o.x&&ep(o,e)))&&(o=e,c=d)}e=e.next}while(e!==a);return o}function ep(n,t){return ot(n.prev,n,t.prev)<0&&ot(t.next,n,n.next)<0}function ip(n,t,e,i){let s=n;do s.z===0&&(s.z=qn(s.x,s.y,t,e,i)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next;while(s!==n);s.prevZ.nextZ=null,s.prevZ=null,sp(s)}function sp(n){let t,e=1;do{let i=n,s;n=null;let r=null;for(t=0;i;){t++;let o=i,a=0;for(let l=0;l<e&&(a++,o=o.nextZ,!!o);l++);let h=e;for(;a>0||h>0&&o;)a!==0&&(h===0||!o||i.z<=o.z)?(s=i,i=i.nextZ,a--):(s=o,o=o.nextZ,h--),r?r.nextZ=s:n=s,s.prevZ=r,r=s;i=o}r.nextZ=null,e*=2}while(t>1);return n}function qn(n,t,e,i,s){return n=(n-e)*s|0,t=(t-i)*s|0,n=(n|n<<8)&16711935,n=(n|n<<4)&252645135,n=(n|n<<2)&858993459,n=(n|n<<1)&1431655765,t=(t|t<<8)&16711935,t=(t|t<<4)&252645135,t=(t|t<<2)&858993459,t=(t|t<<1)&1431655765,n|t<<1}function np(n){let t=n,e=n;do(t.x<e.x||t.x===e.x&&t.y<e.y)&&(e=t),t=t.next;while(t!==n);return e}function tl(n,t,e,i,s,r,o,a){return(s-o)*(t-a)>=(n-o)*(r-a)&&(n-o)*(i-a)>=(e-o)*(t-a)&&(e-o)*(r-a)>=(s-o)*(i-a)}function Si(n,t,e,i,s,r,o,a){return!(n===o&&t===a)&&tl(n,t,e,i,s,r,o,a)}function rp(n,t){return n.next.i!==t.i&&n.prev.i!==t.i&&!op(n,t)&&(Di(n,t)&&Di(t,n)&&ap(n,t)&&(ot(n.prev,n,t.prev)||ot(n,t.prev,t))||ii(n,t)&&ot(n.prev,n,n.next)>0&&ot(t.prev,t,t.next)>0)}function ot(n,t,e){return(t.y-n.y)*(e.x-t.x)-(t.x-n.x)*(e.y-t.y)}function ii(n,t){return n.x===t.x&&n.y===t.y}function el(n,t,e,i){const s=ts(ot(n,t,e)),r=ts(ot(n,t,i)),o=ts(ot(e,i,n)),a=ts(ot(e,i,t));return!!(s!==r&&o!==a||s===0&&Ji(n,e,t)||r===0&&Ji(n,i,t)||o===0&&Ji(e,n,i)||a===0&&Ji(e,t,i))}function Ji(n,t,e){return t.x<=Math.max(n.x,e.x)&&t.x>=Math.min(n.x,e.x)&&t.y<=Math.max(n.y,e.y)&&t.y>=Math.min(n.y,e.y)}function ts(n){return n>0?1:n<0?-1:0}function op(n,t){let e=n;do{if(e.i!==n.i&&e.next.i!==n.i&&e.i!==t.i&&e.next.i!==t.i&&el(e,e.next,n,t))return!0;e=e.next}while(e!==n);return!1}function Di(n,t){return ot(n.prev,n,n.next)<0?ot(n,t,n.next)>=0&&ot(n,n.prev,t)>=0:ot(n,t,n.prev)<0||ot(n,n.next,t)<0}function ap(n,t){let e=n,i=!1;const s=(n.x+t.x)/2,r=(n.y+t.y)/2;do e.y>r!=e.next.y>r&&e.next.y!==e.y&&s<(e.next.x-e.x)*(r-e.y)/(e.next.y-e.y)+e.x&&(i=!i),e=e.next;while(e!==n);return i}function il(n,t){const e=Kn(n.i,n.x,n.y),i=Kn(t.i,t.x,t.y),s=n.next,r=t.prev;return n.next=t,t.prev=n,e.next=s,s.prev=e,i.next=e,e.prev=i,r.next=i,i.prev=r,i}function Uo(n,t,e,i){const s=Kn(n,t,e);return i?(s.next=i.next,s.prev=i,i.next.prev=s,i.next=s):(s.prev=s,s.next=s),s}function Fi(n){n.next.prev=n.prev,n.prev.next=n.next,n.prevZ&&(n.prevZ.nextZ=n.nextZ),n.nextZ&&(n.nextZ.prevZ=n.prevZ)}function Kn(n,t,e){return{i:n,x:t,y:e,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function hp(n,t,e,i){let s=0;for(let r=t,o=e-i;r<e;r+=i)s+=(n[o]-n[r])*(n[r+1]+n[o+1]),o=r;return s}const lp=Go.default||Go;var sl=(n=>(n[n.NONE=0]="NONE",n[n.COLOR=16384]="COLOR",n[n.STENCIL=1024]="STENCIL",n[n.DEPTH=256]="DEPTH",n[n.COLOR_DEPTH=16640]="COLOR_DEPTH",n[n.COLOR_STENCIL=17408]="COLOR_STENCIL",n[n.DEPTH_STENCIL=1280]="DEPTH_STENCIL",n[n.ALL=17664]="ALL",n))(sl||{});class cp{constructor(t){this.items=[],this._name=t}emit(t,e,i,s,r,o,a,h){const{name:l,items:c}=this;for(let d=0,u=c.length;d<u;d++)c[d][l](t,e,i,s,r,o,a,h);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 dp=["init","destroy","contextChange","resolutionChange","resetState","renderEnd","renderStart","render","update","postrender","prerender"],nl=class rl extends Yt{constructor(t){super(),this.tick=0,this.uid=ct("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=[...dp,...this.config.runners??[]];this._addRunners(...e),this._unsafeEvalCheck()}async init(t={}){const e=t.skipExtensionImports===!0?!0:t.manageImports===!1;await $u(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={...rl.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 W&&(i={container:i},e&&(N(K,"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 s=Array.isArray(i.clearColor)&&i.clearColor.length===4;i.clearColor=s?i.clearColor:nt.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 s=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!==s&&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=sl.ALL);const{clear:i,clearColor:s,target:r,mipLevel:o,layer:a}=t;nt.shared.setValue(s??this.background.colorRgba),e.renderTarget.clear(r,i,nt.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 cp(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 s in this.runners)this.runners[s].add(i);return this}_addPipes(t,e){const i=e.reduce((s,r)=>(s[r.name]=r.value,s),{});t.forEach(s=>{const r=s.value,o=s.name,a=i[o];this.renderPipes[o]=new r(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)&&Gi.release(),Object.values(this.runners).forEach(e=>{e.destroy()}),this._systemsHash=null,this.renderPipes=null}generateTexture(t){return this.textureGenerator.generateTexture(t)}get roundPixels(){return!!this._roundPixels}_unsafeEvalCheck(){if(!Yu())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()}};nl.defaultOptions={resolution:1,failIfMajorPerformanceCaveat:!1,roundPixels:!1};let ol=nl,es;function up(n){return es!==void 0||(es=(()=>{var e;const t={stencil:!0,failIfMajorPerformanceCaveat:n??ol.defaultOptions.failIfMajorPerformanceCaveat};try{if(!$.get().getWebGLRenderingContext())return!1;let s=$.get().createCanvas().getContext("webgl",t);const r=!!((e=s==null?void 0:s.getContextAttributes())!=null&&e.stencil);if(s){const o=s.getExtension("WEBGL_lose_context");o&&o.loseContext()}return s=null,r}catch{return!1}})()),es}let is;async function pp(n={}){return is!==void 0||(is=await(async()=>{const t=$.get().getNavigator().gpu;if(!t)return!1;try{return await(await t.requestAdapter(n)).requestDevice(),!0}catch{return!1}})()),is}const Ho=["webgl","webgpu","canvas"];async function fp(n){let t=[];n.preference?(t.push(n.preference),Ho.forEach(r=>{r!==n.preference&&t.push(r)})):t=Ho.slice();let e,i={};for(let r=0;r<t.length;r++){const o=t[r];if(o==="webgpu"&&await pp()){const{WebGPURenderer:a}=await Me(async()=>{const{WebGPURenderer:h}=await import("./WebGPURenderer.CT3AUgw3.js");return{WebGPURenderer:h}},__vite__mapDeps([5,6,7,2,3,4]));e=a,i={...n,...n.webgpu};break}else if(o==="webgl"&&up(n.failIfMajorPerformanceCaveat??ol.defaultOptions.failIfMajorPerformanceCaveat)){const{WebGLRenderer:a}=await Me(async()=>{const{WebGLRenderer:h}=await import("./WebGLRenderer.D4Dgosvx.js");return{WebGLRenderer:h}},__vite__mapDeps([8,6,7,2,3,4]));e=a,i={...n,...n.webgl};break}else if(o==="canvas"){const{CanvasRenderer:a}=await Me(async()=>{const{CanvasRenderer:h}=await import("./CanvasRenderer.vfz9sPE6.js");return{CanvasRenderer:h}},__vite__mapDeps([9,7,2,3,4]));e=a,i={...n,...n.canvasOptions};break}}if(delete i.webgpu,delete i.webgl,delete i.canvasOptions,!e)throw new Error("No available renderer for the current environment");const s=new e;return await s.init(i),s}const al="8.16.0";class hl{static init(){var t;(t=globalThis.__PIXI_APP_INIT__)==null||t.call(globalThis,this,al)}static destroy(){}}hl.extension=E.Application;class gp{constructor(t){this._renderer=t}init(){var t;(t=globalThis.__PIXI_RENDERER_INIT__)==null||t.call(globalThis,this._renderer,al)}destroy(){this._renderer=null}}gp.extension={type:[E.WebGLSystem,E.WebGPUSystem],name:"initHook",priority:-10};class ll{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:s,clientHeight:r}=this._resizeTo;e=s,i=r}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}}ll.extension=E.Application;class cl{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,Ie.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=t.sharedTicker?mt.shared:new mt,t.autoStart&&this.start()}static destroy(){if(this._ticker){const t=this._ticker;this.ticker=null,t.destroy()}}}cl.extension=E.Application;q.add(ll);q.add(cl);const dl=class Qn{constructor(...t){this.stage=new W,t[0]!==void 0&&N(K,"Application constructor options are deprecated, please use Application.init() instead.")}async init(t){t={...t},this.stage||(this.stage=new W),this.renderer=await fp(t),Qn._plugins.forEach(e=>{e.init.call(this,t)})}render(){this.renderer.render({container:this.stage})}get canvas(){return this.renderer.canvas}get view(){return N(K,"Application.view is deprecated, please use Application.canvas instead."),this.renderer.canvas}get screen(){return this.renderer.screen}destroy(t=!1,e=!1){const i=Qn._plugins.slice(0);i.reverse(),i.forEach(s=>{s.destroy.call(this)}),this.stage.destroy(e),this.stage=null,this.renderer.destroy(t),this.renderer=null}};dl._plugins=[];let ul=dl;q.handleByList(E.Application,ul._plugins);q.add(hl);const mn={test(n){return typeof n=="string"&&n.startsWith("info face=")},parse(n){const t=n.match(/^[a-z]+\s+.+$/gm),e={info:[],common:[],page:[],char:[],chars:[],kerning:[],kernings:[],distanceField:[]};for(const d in t){const u=t[d].match(/^[a-z]+/gm)[0],p=t[d].match(/[a-zA-Z]+=([^\s"']+|"([^"]*)")/gm),g={};for(const y in p){const m=p[y].split("="),x=m[0],S=m[1].replace(/"/gm,""),v=parseFloat(S),b=isNaN(v)?S:v;g[x]=b}e[u].push(g)}const i={chars:{},pages:[],lineHeight:0,fontSize:0,fontFamily:"",distanceField:null,baseLineOffset:0},[s]=e.info,[r]=e.common,[o]=e.distanceField??[];o&&(i.distanceField={range:parseInt(o.distanceRange,10),type:o.fieldType}),i.fontSize=parseInt(s.size,10),i.fontFamily=s.face,i.lineHeight=parseInt(r.lineHeight,10);const a=e.page;for(let d=0;d<a.length;d++)i.pages.push({id:parseInt(a[d].id,10)||0,file:a[d].file});const h={};i.baseLineOffset=i.lineHeight-parseInt(r.base,10);const l=e.char;for(let d=0;d<l.length;d++){const u=l[d],p=parseInt(u.id,10);let g=u.letter??u.char??String.fromCharCode(p);g==="space"&&(g=" "),h[p]=g,i.chars[g]={id:p,page:parseInt(u.page,10)||0,x:parseInt(u.x,10),y:parseInt(u.y,10),width:parseInt(u.width,10),height:parseInt(u.height,10),xOffset:parseInt(u.xoffset,10),yOffset:parseInt(u.yoffset,10),xAdvance:parseInt(u.xadvance,10),kerning:{}}}const c=e.kerning||[];for(let d=0;d<c.length;d++){const u=parseInt(c[d].first,10),p=parseInt(c[d].second,10),g=parseInt(c[d].amount,10);i.chars[h[p]].kerning[h[u]]=g}return i}},No={test(n){const t=n;return typeof t!="string"&&"getElementsByTagName"in t&&t.getElementsByTagName("page").length&&t.getElementsByTagName("info")[0].getAttribute("face")!==null},parse(n){const t={chars:{},pages:[],lineHeight:0,fontSize:0,fontFamily:"",distanceField:null,baseLineOffset:0},e=n.getElementsByTagName("info")[0],i=n.getElementsByTagName("common")[0],s=n.getElementsByTagName("distanceField")[0];s&&(t.distanceField={type:s.getAttribute("fieldType"),range:parseInt(s.getAttribute("distanceRange"),10)});const r=n.getElementsByTagName("page"),o=n.getElementsByTagName("char"),a=n.getElementsByTagName("kerning");t.fontSize=parseInt(e.getAttribute("size"),10),t.fontFamily=e.getAttribute("face"),t.lineHeight=parseInt(i.getAttribute("lineHeight"),10);for(let l=0;l<r.length;l++)t.pages.push({id:parseInt(r[l].getAttribute("id"),10)||0,file:r[l].getAttribute("file")});const h={};t.baseLineOffset=t.lineHeight-parseInt(i.getAttribute("base"),10);for(let l=0;l<o.length;l++){const c=o[l],d=parseInt(c.getAttribute("id"),10);let u=c.getAttribute("letter")??c.getAttribute("char")??String.fromCharCode(d);u==="space"&&(u=" "),h[d]=u,t.chars[u]={id:d,page:parseInt(c.getAttribute("page"),10)||0,x:parseInt(c.getAttribute("x"),10),y:parseInt(c.getAttribute("y"),10),width:parseInt(c.getAttribute("width"),10),height:parseInt(c.getAttribute("height"),10),xOffset:parseInt(c.getAttribute("xoffset"),10),yOffset:parseInt(c.getAttribute("yoffset"),10),xAdvance:parseInt(c.getAttribute("xadvance"),10),kerning:{}}}for(let l=0;l<a.length;l++){const c=parseInt(a[l].getAttribute("first"),10),d=parseInt(a[l].getAttribute("second"),10),u=parseInt(a[l].getAttribute("amount"),10);t.chars[h[d]].kerning[h[c]]=u}return t}},Vo={test(n){return typeof n=="string"&&n.match(/<font(\s|>)/)?No.test($.get().parseXML(n)):!1},parse(n){return No.parse($.get().parseXML(n))}},mp=[".xml",".fnt"],yp={extension:{type:E.CacheParser,name:"cacheBitmapFont"},test:n=>!!(n!=null&&n.pages)&&!!(n!=null&&n.chars)&&typeof(n==null?void 0:n.fontFamily)=="string",getCacheableAssets(n,t){const e={};return n.forEach(i=>{e[i]=t,e[`${i}-bitmap`]=t}),e[`${t.fontFamily}-bitmap`]=t,e}},xp={extension:{type:E.LoadParser,priority:ce.Normal},name:"loadBitmapFont",id:"bitmap-font",test(n){return mp.includes(Pt.extname(n).toLowerCase())},async testParse(n){return mn.test(n)||Vo.test(n)},async parse(n,t,e){const i=mn.test(n)?mn.parse(n):Vo.parse(n),{src:s}=t,{pages:r}=i,o=[],a=i.distanceField?{scaleMode:"linear",alphaMode:"premultiply-alpha-on-upload",autoGenerateMipmaps:!1,resolution:1}:{};for(let u=0;u<r.length;++u){const p=r[u].file;let g=Pt.join(Pt.dirname(s),p);g=Vn(g,s),o.push({src:g,data:a})}const[h,{BitmapFont:l}]=await Promise.all([e.load(o),Me(()=>import("./BitmapFont.DzUyMNlJ.js"),__vite__mapDeps([10,2,3,4]))]),c=o.map(u=>h[u.src]);return new l({data:i,textures:c},s)},async load(n,t){return await(await $.get().fetch(n)).text()},async unload(n,t,e){await Promise.all(n.pages.map(i=>e.unload(i.texture.source._sourceOrigin))),n.destroy()}};class Sp{constructor(t,e=!1){this._loader=t,this._assetList=[],this._isLoading=!1,this._maxConcurrent=1,this.verbose=e}add(t){t.forEach(e=>{this._assetList.push(e)}),this.verbose&&console.log("[BackgroundLoader] assets: ",this._assetList),this._isActive&&!this._isLoading&&this._next()}async _next(){if(this._assetList.length&&this._isActive){this._isLoading=!0;const t=[],e=Math.min(this._assetList.length,this._maxConcurrent);for(let i=0;i<e;i++)t.push(this._assetList.pop());await this._loader.load(t),this._isLoading=!1,this._next()}}get active(){return this._isActive}set active(t){this._isActive!==t&&(this._isActive=t,t&&!this._isLoading&&this._next())}}const vp={extension:{type:E.CacheParser,name:"cacheTextureArray"},test:n=>Array.isArray(n)&&n.every(t=>t instanceof O),getCacheableAssets:(n,t)=>{const e={};return n.forEach(i=>{t.forEach((s,r)=>{e[i+(r===0?"":r+1)]=s})}),e}};async function pl(n){if("Image"in globalThis)return new Promise(t=>{const e=new Image;e.onload=()=>{t(!0)},e.onerror=()=>{t(!1)},e.src=n});if("createImageBitmap"in globalThis&&"fetch"in globalThis){try{const t=await(await fetch(n)).blob();await createImageBitmap(t)}catch{return!1}return!0}return!1}const bp={extension:{type:E.DetectionParser,priority:1},test:async()=>pl("data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAAB0AAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAIAAAACAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQ0MAAAAABNjb2xybmNseAACAAIAAYAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAACVtZGF0EgAKCBgANogQEAwgMg8f8D///8WfhwB8+ErK42A="),add:async n=>[...n,"avif"],remove:async n=>n.filter(t=>t!=="avif")},$o=["png","jpg","jpeg"],wp={extension:{type:E.DetectionParser,priority:-1},test:()=>Promise.resolve(!0),add:async n=>[...n,...$o],remove:async n=>n.filter(t=>!$o.includes(t))},Cp="WorkerGlobalScope"in globalThis&&globalThis instanceof globalThis.WorkerGlobalScope;function Es(n){return Cp?!1:document.createElement("video").canPlayType(n)!==""}const _p={extension:{type:E.DetectionParser,priority:0},test:async()=>Es("video/mp4"),add:async n=>[...n,"mp4","m4v"],remove:async n=>n.filter(t=>t!=="mp4"&&t!=="m4v")},Pp={extension:{type:E.DetectionParser,priority:0},test:async()=>Es("video/ogg"),add:async n=>[...n,"ogv"],remove:async n=>n.filter(t=>t!=="ogv")},Mp={extension:{type:E.DetectionParser,priority:0},test:async()=>Es("video/webm"),add:async n=>[...n,"webm"],remove:async n=>n.filter(t=>t!=="webm")},Tp={extension:{type:E.DetectionParser,priority:0},test:async()=>pl("data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA="),add:async n=>[...n,"webp"],remove:async n=>n.filter(t=>t!=="webp")},fl=class us{constructor(){this.loadOptions={...us.defaultOptions},this._parsers=[],this._parsersValidated=!1,this.parsers=new Proxy(this._parsers,{set:(t,e,i)=>(this._parsersValidated=!1,t[e]=i,!0)}),this.promiseCache={}}reset(){this._parsersValidated=!1,this.promiseCache={}}_getLoadPromiseAndParser(t,e){const i={promise:null,parser:null};return i.promise=(async()=>{var o,a;let s=null,r=null;if((e.parser||e.loadParser)&&(r=this._parserHash[e.parser||e.loadParser],e.loadParser&&st(`[Assets] "loadParser" is deprecated, use "parser" instead for ${t}`),r||st(`[Assets] specified load parser "${e.parser||e.loadParser}" not found while loading ${t}`)),!r){for(let h=0;h<this.parsers.length;h++){const l=this.parsers[h];if(l.load&&((o=l.test)!=null&&o.call(l,t,e,this))){r=l;break}}if(!r)return st(`[Assets] ${t} could not be loaded as we don't know how to parse it, ensure the correct parser has been added`),null}s=await r.load(t,e,this),i.parser=r;for(let h=0;h<this.parsers.length;h++){const l=this.parsers[h];l.parse&&l.parse&&await((a=l.testParse)==null?void 0:a.call(l,s,e,this))&&(s=await l.parse(s,e,this)||s,i.parser=l)}return s})(),i}async load(t,e){this._parsersValidated||this._validateParsers();const i=typeof e=="function"?{...us.defaultOptions,...this.loadOptions,onProgress:e}:{...us.defaultOptions,...this.loadOptions,...e||{}},{onProgress:s,onError:r,strategy:o,retryCount:a,retryDelay:h}=i;let l=0;const c={},d=xs(t),u=zt(t,y=>({alias:[y],src:y,data:{}})),p=u.reduce((y,m)=>y+(m.progressSize||1),0),g=u.map(async y=>{const m=Pt.toAbsolute(y.src);c[y.src]||(await this._loadAssetWithRetry(m,y,{onProgress:s,onError:r,strategy:o,retryCount:a,retryDelay:h},c),l+=y.progressSize||1,s&&s(l/p))});return await Promise.all(g),d?c[u[0].src]:c}async unload(t){const i=zt(t,s=>({alias:[s],src:s})).map(async s=>{var a,h;const r=Pt.toAbsolute(s.src),o=this.promiseCache[r];if(o){const l=await o.promise;delete this.promiseCache[r],await((h=(a=o.parser)==null?void 0:a.unload)==null?void 0:h.call(a,l,s,this))}});await Promise.all(i)}_validateParsers(){this._parsersValidated=!0,this._parserHash=this._parsers.filter(t=>t.name||t.id).reduce((t,e)=>(!e.name&&!e.id?st("[Assets] parser should have an id"):(t[e.name]||t[e.id])&&st(`[Assets] parser id conflict "${e.id}"`),t[e.name]=e,e.id&&(t[e.id]=e),t),{})}async _loadAssetWithRetry(t,e,i,s){let r=0;const{onError:o,strategy:a,retryCount:h,retryDelay:l}=i,c=d=>new Promise(u=>setTimeout(u,d));for(;;)try{this.promiseCache[t]||(this.promiseCache[t]=this._getLoadPromiseAndParser(t,e)),s[e.src]=await this.promiseCache[t].promise;return}catch(d){delete this.promiseCache[t],delete s[e.src],r++;const u=a!=="retry"||r>h;if(a==="retry"&&!u){o&&o(d,e),await c(l);continue}if(a==="skip"){o&&o(d,e);return}o&&o(d,e);const p=new Error(`[Loader.load] Failed to load ${t}.
24
+ ${d}`);throw d instanceof Error&&d.stack&&(p.stack=d.stack),p}}};fl.defaultOptions={onProgress:void 0,onError:void 0,strategy:"throw",retryCount:3,retryDelay:250};let Ap=fl;function de(n,t){if(Array.isArray(t)){for(const e of t)if(n.startsWith(`data:${e}`))return!0;return!1}return n.startsWith(`data:${t}`)}function oi(n,t){const e=n.split("?")[0],i=Pt.extname(e).toLowerCase();return Array.isArray(t)?t.includes(i):i===t}const Rp=".json",kp="application/json",Ep={extension:{type:E.LoadParser,priority:ce.Low},name:"loadJson",id:"json",test(n){return de(n,kp)||oi(n,Rp)},async load(n){return await(await $.get().fetch(n)).json()}},Ip=".txt",Dp="text/plain",Fp={name:"loadTxt",id:"text",extension:{type:E.LoadParser,priority:ce.Low,name:"loadTxt"},test(n){return de(n,Dp)||oi(n,Ip)},async load(n){return await(await $.get().fetch(n)).text()}},Bp=["normal","bold","100","200","300","400","500","600","700","800","900"],Lp=[".ttf",".otf",".woff",".woff2"],zp=["font/ttf","font/otf","font/woff","font/woff2"],Op=/^(--|-?[A-Z_])[0-9A-Z_-]*$/i;function Wp(n){const t=Pt.extname(n),s=Pt.basename(n,t).replace(/(-|_)/g," ").toLowerCase().split(" ").map(a=>a.charAt(0).toUpperCase()+a.slice(1));let r=s.length>0;for(const a of s)if(!a.match(Op)){r=!1;break}let o=s.join(" ");return r||(o=`"${o.replace(/[\\"]/g,"\\$&")}"`),o}const Gp=/^[0-9A-Za-z%:/?#\[\]@!\$&'()\*\+,;=\-._~]*$/;function Up(n){return Gp.test(n)?n:encodeURI(n)}const Hp={extension:{type:E.LoadParser,priority:ce.Low},name:"loadWebFont",id:"web-font",test(n){return de(n,zp)||oi(n,Lp)},async load(n,t){var i,s,r;const e=$.get().getFontFaceSet();if(e){const o=[],a=((i=t.data)==null?void 0:i.family)??Wp(n),h=((r=(s=t.data)==null?void 0:s.weights)==null?void 0:r.filter(c=>Bp.includes(c)))??["normal"],l=t.data??{};for(let c=0;c<h.length;c++){const d=h[c],u=new FontFace(a,`url(${Up(n)})`,{...l,weight:d});await u.load(),e.add(u),o.push(u)}return yt.has(`${a}-and-url`)?yt.get(`${a}-and-url`).entries.push({url:n,faces:o}):yt.set(`${a}-and-url`,{entries:[{url:n,faces:o}]}),o.length===1?o[0]:o}return st("[loadWebFont] FontFace API is not supported. Skipping loading font"),null},unload(n){const t=Array.isArray(n)?n:[n],e=t[0].family,i=yt.get(`${e}-and-url`),s=i.entries.find(r=>r.faces.some(o=>t.indexOf(o)!==-1));s.faces=s.faces.filter(r=>t.indexOf(r)===-1),s.faces.length===0&&(i.entries=i.entries.filter(r=>r!==s)),t.forEach(r=>{$.get().getFontFaceSet().delete(r)}),i.entries.length===0&&yt.remove(`${e}-and-url`)}};var Np=$p,yn={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},Vp=/([astvzqmhlc])([^astvzqmhlc]*)/ig;function $p(n){var t=[];return n.replace(Vp,function(e,i,s){var r=i.toLowerCase();for(s=Xp(s),r=="m"&&s.length>2&&(t.push([i].concat(s.splice(0,2))),r="l",i=i=="m"?"l":"L");;){if(s.length==yn[r])return s.unshift(i),t.push(s);if(s.length<yn[r])throw new Error("malformed path data");t.push([i].concat(s.splice(0,yn[r])))}}),t}var Yp=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig;function Xp(n){var t=n.match(Yp);return t?t.map(Number):[]}const jp=lh(Np);function Zp(n,t){const e=jp(n),i=[];let s=null,r=0,o=0;for(let a=0;a<e.length;a++){const h=e[a],l=h[0],c=h;switch(l){case"M":r=c[1],o=c[2],t.moveTo(r,o);break;case"m":r+=c[1],o+=c[2],t.moveTo(r,o);break;case"H":r=c[1],t.lineTo(r,o);break;case"h":r+=c[1],t.lineTo(r,o);break;case"V":o=c[1],t.lineTo(r,o);break;case"v":o+=c[1],t.lineTo(r,o);break;case"L":r=c[1],o=c[2],t.lineTo(r,o);break;case"l":r+=c[1],o+=c[2],t.lineTo(r,o);break;case"C":r=c[5],o=c[6],t.bezierCurveTo(c[1],c[2],c[3],c[4],r,o);break;case"c":t.bezierCurveTo(r+c[1],o+c[2],r+c[3],o+c[4],r+c[5],o+c[6]),r+=c[5],o+=c[6];break;case"S":r=c[3],o=c[4],t.bezierCurveToShort(c[1],c[2],r,o);break;case"s":t.bezierCurveToShort(r+c[1],o+c[2],r+c[3],o+c[4]),r+=c[3],o+=c[4];break;case"Q":r=c[3],o=c[4],t.quadraticCurveTo(c[1],c[2],r,o);break;case"q":t.quadraticCurveTo(r+c[1],o+c[2],r+c[3],o+c[4]),r+=c[3],o+=c[4];break;case"T":r=c[1],o=c[2],t.quadraticCurveToShort(r,o);break;case"t":r+=c[1],o+=c[2],t.quadraticCurveToShort(r,o);break;case"A":r=c[6],o=c[7],t.arcToSvg(c[1],c[2],c[3],c[4],c[5],r,o);break;case"a":r+=c[6],o+=c[7],t.arcToSvg(c[1],c[2],c[3],c[4],c[5],r,o);break;case"Z":case"z":t.closePath(),i.length>0&&(s=i.pop(),s?(r=s.startX,o=s.startY):(r=0,o=0)),s=null;break;default:st(`Unknown SVG path command: ${l}`)}l!=="Z"&&l!=="z"&&s===null&&(s={startX:r,startY:o},i.push(s))}return t}class Is{constructor(t=0,e=0,i=0){this.type="circle",this.x=t,this.y=e,this.radius=i}clone(){return new Is(this.x,this.y,this.radius)}contains(t,e){if(this.radius<=0)return!1;const i=this.radius*this.radius;let s=this.x-t,r=this.y-e;return s*=s,r*=r,s+r<=i}strokeContains(t,e,i,s=.5){if(this.radius===0)return!1;const r=this.x-t,o=this.y-e,a=this.radius,h=(1-s)*i,l=Math.sqrt(r*r+o*o);return l<=a+h&&l>a-(i-h)}getBounds(t){return t||(t=new J),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 Cr{constructor(t=0,e=0,i=0,s=0){this.type="ellipse",this.x=t,this.y=e,this.halfWidth=i,this.halfHeight=s}clone(){return new Cr(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,s=(e-this.y)/this.halfHeight;return i*=i,s*=s,i+s<=1}strokeContains(t,e,i,s=.5){const{halfWidth:r,halfHeight:o}=this;if(r<=0||o<=0)return!1;const a=i*(1-s),h=i-a,l=r-h,c=o-h,d=r+a,u=o+a,p=t-this.x,g=e-this.y,y=p*p/(l*l)+g*g/(c*c),m=p*p/(d*d)+g*g/(u*u);return y>1&&m<=1}getBounds(t){return t||(t=new J),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 qp(n,t,e,i,s,r){const o=n-e,a=t-i,h=s-e,l=r-i,c=o*h+a*l,d=h*h+l*l;let u=-1;d!==0&&(u=c/d);let p,g;u<0?(p=e,g=i):u>1?(p=s,g=r):(p=e+u*h,g=i+u*l);const y=n-p,m=t-g;return y*y+m*m}let Kp,Qp;class Te{constructor(...t){this.type="polygon";let e=Array.isArray(t[0])?t[0]:t;if(typeof e[0]!="number"){const i=[];for(let s=0,r=e.length;s<r;s++)i.push(e[s].x,e[s].y);e=i}this.points=e,this.closePath=!0}isClockwise(){let t=0;const e=this.points,i=e.length;for(let s=0;s<i;s+=2){const r=e[s],o=e[s+1],a=e[(s+2)%i],h=e[(s+3)%i];t+=(a-r)*(h+o)}return t<0}containsPolygon(t){const e=this.getBounds(Kp),i=t.getBounds(Qp);if(!e.containsRect(i))return!1;const s=t.points;for(let r=0;r<s.length;r+=2){const o=s[r],a=s[r+1];if(!this.contains(o,a))return!1}return!0}clone(){const t=this.points.slice(),e=new Te(t);return e.closePath=this.closePath,e}contains(t,e){let i=!1;const s=this.points.length/2;for(let r=0,o=s-1;r<s;o=r++){const a=this.points[r*2],h=this.points[r*2+1],l=this.points[o*2],c=this.points[o*2+1];h>e!=c>e&&t<(l-a)*((e-h)/(c-h))+a&&(i=!i)}return i}strokeContains(t,e,i,s=.5){const r=i*i,o=r*(1-s),a=r-o,{points:h}=this,l=h.length-(this.closePath?0:2);for(let c=0;c<l;c+=2){const d=h[c],u=h[c+1],p=h[(c+2)%h.length],g=h[(c+3)%h.length],y=qp(t,e,d,u,p,g),m=Math.sign((p-d)*(e-u)-(g-u)*(t-d));if(y<=(m<0?a:o))return!0}return!1}getBounds(t){t||(t=new J);const e=this.points;let i=1/0,s=-1/0,r=1/0,o=-1/0;for(let a=0,h=e.length;a<h;a+=2){const l=e[a],c=e[a+1];i=l<i?l:i,s=l>s?l:s,r=c<r?c:r,o=c>o?c:o}return t.x=i,t.width=s-i,t.y=r,t.height=o-r,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 N("8.11.0","Polygon.lastX is deprecated, please use Polygon.lastX instead."),this.points[this.points.length-2]}get y(){return N("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 ss=(n,t,e,i,s,r,o)=>{const a=n-e,h=t-i,l=Math.sqrt(a*a+h*h);return l>=s-r&&l<=s+o};class _r{constructor(t=0,e=0,i=0,s=0,r=20){this.type="roundedRectangle",this.x=t,this.y=e,this.width=i,this.height=s,this.radius=r}getBounds(t){return t||(t=new J),t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t}clone(){return new _r(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 s=t-(this.x+i),r=e-(this.y+i);const o=i*i;if(s*s+r*r<=o||(s=t-(this.x+this.width-i),s*s+r*r<=o)||(r=e-(this.y+this.height-i),s*s+r*r<=o)||(s=t-(this.x+i),s*s+r*r<=o))return!0}return!1}strokeContains(t,e,i,s=.5){const{x:r,y:o,width:a,height:h,radius:l}=this,c=i*(1-s),d=i-c,u=r+l,p=o+l,g=a-l*2,y=h-l*2,m=r+a,x=o+h;return(t>=r-c&&t<=r+d||t>=m-d&&t<=m+c)&&e>=p&&e<=p+y||(e>=o-c&&e<=o+d||e>=x-d&&e<=x+c)&&t>=u&&t<=u+g?!0:t<u&&e<p&&ss(t,e,u,p,l,d,c)||t>m-l&&e<p&&ss(t,e,m-l,p,l,d,c)||t>m-l&&e>x-l&&ss(t,e,m-l,x-l,l,d,c)||t<u&&e>x-l&&ss(t,e,u,x-l,l,d,c)}toString(){return`[pixi.js/math:RoundedRectangle x=${this.x} y=${this.y}width=${this.width} height=${this.height} radius=${this.radius}]`}}const gl={};function Jp(n,t,e){let i=2166136261;for(let s=0;s<t;s++)i^=n[s].uid,i=Math.imul(i,16777619),i>>>=0;return gl[i]||tf(n,t,i,e)}function tf(n,t,e,i){const s={};let r=0;for(let a=0;a<i;a++){const h=a<t?n[a]:O.EMPTY.source;s[r++]=h.source,s[r++]=h.style}const o=new _i(s);return gl[e]=o,o}class Yo{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 Xo(n,t,e,i){if(e??(e=0),i??(i=Math.min(n.byteLength-e,t.byteLength)),!(e&7)&&!(i&7)){const s=i/8;new Float64Array(t,0,s).set(new Float64Array(n,e,s))}else if(!(e&3)&&!(i&3)){const s=i/4;new Float32Array(t,0,s).set(new Float32Array(n,e,s))}else new Uint8Array(t).set(new Uint8Array(n,e,i))}const ef={normal:"normal-npm",add:"add-npm",screen:"screen-npm"};var sf=(n=>(n[n.DISABLED=0]="DISABLED",n[n.RENDERING_MASK_ADD=1]="RENDERING_MASK_ADD",n[n.MASK_ACTIVE=2]="MASK_ACTIVE",n[n.INVERSE_MASK_ACTIVE=3]="INVERSE_MASK_ACTIVE",n[n.RENDERING_MASK_REMOVE=4]="RENDERING_MASK_REMOVE",n[n.NONE=5]="NONE",n))(sf||{});function Ss(n,t){return t.alphaMode==="no-premultiply-alpha"&&ef[n]||n}const nf=["precision mediump float;","void main(void){","float test = 0.1;","%forloop%","gl_FragColor = vec4(0.0);","}"].join(`
25
+ `);function rf(n){let t="";for(let e=0;e<n;++e)e>0&&(t+=`
26
+ else `),e<n-1&&(t+=`if(test == ${e}.0){}`);return t}function of(n,t){if(n===0)throw new Error("Invalid value of `0` passed to `checkMaxIfStatementsInShader`");const e=t.createShader(t.FRAGMENT_SHADER);try{for(;;){const i=nf.replace(/%forloop%/gi,rf(n));if(t.shaderSource(e,i),t.compileShader(e),!t.getShaderParameter(e,t.COMPILE_STATUS))n=n/2|0;else break}}finally{t.deleteShader(e)}return n}let We=null;function af(){var t;if(We)return We;const n=Yh();return We=n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS),We=of(We,n),(t=n.getExtension("WEBGL_lose_context"))==null||t.loseContext(),We}class hf{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 lf{constructor(){this.renderPipeId="batch",this.action="startBatch",this.start=0,this.size=0,this.textures=new hf,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 Pi=[];let vs=0;Gi.register({clear:()=>{if(Pi.length>0)for(const n of Pi)n&&n.destroy();Pi.length=0,vs=0}});function jo(){return vs>0?Pi[--vs]:new lf}function Zo(n){n.elements=null,Pi[vs++]=n}let ui=0;const ml=class yl{constructor(t){this.uid=ct("batcher"),this.dirty=!0,this.batchIndex=0,this.batches=[],this._elements=[],t={...yl.defaultOptions,...t},t.maxTextures||(N("v8.8.0","maxTextures is a required option for Batcher now, please pass it in the options"),t.maxTextures=af());const{maxTextures:e,attributesInitialSize:i,indicesInitialSize:s}=t;this.attributeBuffer=new Yo(i*4),this.indexBuffer=new Uint16Array(s),this.maxTextures=e}begin(){this.elementSize=0,this.elementStart=0,this.indexSize=0,this.attributeSize=0;for(let t=0;t<this.batchIndex;t++)Zo(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=jo(),s=i.textures;s.clear();const r=e[this.elementStart];let o=Ss(r.blendMode,r.texture._source),a=r.topology;this.attributeSize*4>this.attributeBuffer.size&&this._resizeAttributeBuffer(this.attributeSize*4),this.indexSize>this.indexBuffer.length&&this._resizeIndexBuffer(this.indexSize);const h=this.attributeBuffer.float32View,l=this.attributeBuffer.uint32View,c=this.indexBuffer;let d=this._batchIndexSize,u=this._batchIndexStart,p="startBatch",g=[];const y=this.maxTextures;for(let m=this.elementStart;m<this.elementSize;++m){const x=e[m];e[m]=null;const v=x.texture._source,b=Ss(x.blendMode,v),P=o!==b||a!==x.topology;if(v._batchTick===ui&&!P){x._textureId=v._textureBindLocation,d+=x.indexSize,x.packAsQuad?(this.packQuadAttributes(x,h,l,x._attributeStart,x._textureId),this.packQuadIndex(c,x._indexStart,x._attributeStart/this.vertexSize)):(this.packAttributes(x,h,l,x._attributeStart,x._textureId),this.packIndex(x,c,x._indexStart,x._attributeStart/this.vertexSize)),x._batch=i,g.push(x);continue}v._batchTick=ui,(s.count>=y||P)&&(this._finishBatch(i,u,d-u,s,o,a,t,p,g),p="renderBatch",u=d,o=b,a=x.topology,i=jo(),s=i.textures,s.clear(),g=[],++ui),x._textureId=v._textureBindLocation=s.count,s.ids[v.uid]=s.count,s.textures[s.count++]=v,x._batch=i,g.push(x),d+=x.indexSize,x.packAsQuad?(this.packQuadAttributes(x,h,l,x._attributeStart,x._textureId),this.packQuadIndex(c,x._indexStart,x._attributeStart/this.vertexSize)):(this.packAttributes(x,h,l,x._attributeStart,x._textureId),this.packIndex(x,c,x._indexStart,x._attributeStart/this.vertexSize))}s.count>0&&(this._finishBatch(i,u,d-u,s,o,a,t,p,g),u=d,++ui),this.elementStart=this.elementSize,this._batchIndexStart=u,this._batchIndexSize=d}_finishBatch(t,e,i,s,r,o,a,h,l){t.gpuBindGroup=null,t.bindGroup=null,t.action=h,t.batcher=this,t.textures=s,t.blendMode=r,t.topology=o,t.start=e,t.size=i,t.elements=l,++ui,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 Yo(e);Xo(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 s=i>65535?new Uint32Array(i):new Uint16Array(i);if(s.BYTES_PER_ELEMENT!==e.BYTES_PER_ELEMENT)for(let r=0;r<e.length;r++)s[r]=e[r];else Xo(e.buffer,s.buffer);this.indexBuffer=s}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,s){const r=t.indices,o=t.indexSize,a=t.indexOffset,h=t.attributeOffset;for(let l=0;l<o;l++)e[i++]=s+r[l+a]-h}destroy(t={}){var e;if(this.batches!==null){for(let i=0;i<this.batchIndex;i++)Zo(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}}};ml.defaultOptions={maxTextures:null,attributesInitialSize:4,indicesInitialSize:6};let cf=ml;var ft=(n=>(n[n.MAP_READ=1]="MAP_READ",n[n.MAP_WRITE=2]="MAP_WRITE",n[n.COPY_SRC=4]="COPY_SRC",n[n.COPY_DST=8]="COPY_DST",n[n.INDEX=16]="INDEX",n[n.VERTEX=32]="VERTEX",n[n.UNIFORM=64]="UNIFORM",n[n.STORAGE=128]="STORAGE",n[n.INDIRECT=256]="INDIRECT",n[n.QUERY_RESOLVE=512]="QUERY_RESOLVE",n[n.STATIC=1024]="STATIC",n))(ft||{});class oe extends Yt{constructor(t){let{data:e,size:i}=t;const{usage:s,label:r,shrinkToFit:o}=t;super(),this._gpuData=Object.create(null),this._gcLastUsed=-1,this.autoGarbageCollect=!0,this.uid=ct("buffer"),this._resourceType="buffer",this._resourceId=ct("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:s,mappedAtCreation:a,label:r},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&ft.STATIC)}set static(t){t?this.descriptor.usage|=ft.STATIC:this.descriptor.usage&=~ft.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 s=this._data;if(this._data=t,this._dataInt32=null,!s||s.length!==t.length){!this.shrinkToFit&&s&&t.byteLength<s.byteLength?i&&this.emit("update",this):(this.descriptor.size=t.byteLength,this._resourceId=ct("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 xl(n,t){if(!(n instanceof oe)){let e=t?ft.INDEX:ft.VERTEX;n instanceof Array&&(t?(n=new Uint32Array(n),e=ft.INDEX|ft.COPY_DST):(n=new Float32Array(n),e=ft.VERTEX|ft.COPY_DST)),n=new oe({data:n,label:t?"index-mesh-buffer":"vertex-mesh-buffer",usage:e})}return n}function df(n,t,e){const i=n.getAttribute(t);if(!i)return e.minX=0,e.minY=0,e.maxX=0,e.maxY=0,e;const s=i.buffer.data;let r=1/0,o=1/0,a=-1/0,h=-1/0;const l=s.BYTES_PER_ELEMENT,c=(i.offset||0)/l,d=(i.stride||2*4)/l;for(let u=c;u<s.length;u+=d){const p=s[u],g=s[u+1];p>a&&(a=p),g>h&&(h=g),p<r&&(r=p),g<o&&(o=g)}return e.minX=r,e.minY=o,e.maxX=a,e.maxY=h,e}function uf(n){return(n instanceof oe||Array.isArray(n)||n.BYTES_PER_ELEMENT)&&(n={buffer:n}),n.buffer=xl(n.buffer,!1),n}class Bi extends Yt{constructor(t={}){super(),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=ct("geometry"),this._layoutKey=0,this.instanceCount=1,this._bounds=new Dt,this._boundsDirty=!0;const{attributes:e,indexBuffer:i,topology:s}=t;if(this.buffers=[],this.attributes={},e)for(const r in e)this.addAttribute(r,e[r]);this.instanceCount=t.instanceCount??1,i&&this.addIndex(i),this.topology=s||"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=uf(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=xl(t,!0),this.buffers.push(this.indexBuffer)}get bounds(){return this._boundsDirty?(this._boundsDirty=!1,df(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 pf=new Float32Array(1),ff=new Uint32Array(1);class gf extends Bi{constructor(){const e=new oe({data:pf,label:"attribute-batch-buffer",usage:ft.VERTEX|ft.COPY_DST,shrinkToFit:!1}),i=new oe({data:ff,label:"index-batch-buffer",usage:ft.INDEX|ft.COPY_DST,shrinkToFit:!1}),s=6*4;super({attributes:{aPosition:{buffer:e,format:"float32x2",stride:s,offset:0},aUV:{buffer:e,format:"float32x2",stride:s,offset:2*4},aColor:{buffer:e,format:"unorm8x4",stride:s,offset:4*4},aTextureIdAndRound:{buffer:e,format:"uint16x2",stride:s,offset:5*4}},indexBuffer:i})}}function qo(n,t,e){if(n)for(const i in n){const s=i.toLocaleLowerCase(),r=t[s];if(r){let o=n[i];i==="header"&&(o=o.replace(/@in\s+[^;]+;\s*/g,"").replace(/@out\s+[^;]+;\s*/g,"")),e&&r.push(`//----${e}----//`),r.push(o)}else st(`${i} placement hook does not exist in shader`)}}const mf=/\{\{(.*?)\}\}/g;function Ko(n){var i;const t={};return(((i=n.match(mf))==null?void 0:i.map(s=>s.replace(/[{()}]/g,"")))??[]).forEach(s=>{t[s]=[]}),t}function Qo(n,t){let e;const i=/@in\s+([^;]+);/g;for(;(e=i.exec(n))!==null;)t.push(e[1])}function Jo(n,t,e=!1){const i=[];Qo(t,i),n.forEach(a=>{a.header&&Qo(a.header,i)});const s=i;e&&s.sort();const r=s.map((a,h)=>` @location(${h}) ${a},`).join(`
27
+ `);let o=t.replace(/@in\s+[^;]+;\s*/g,"");return o=o.replace("{{in}}",`
28
+ ${r}
29
+ `),o}function ta(n,t){let e;const i=/@out\s+([^;]+);/g;for(;(e=i.exec(n))!==null;)t.push(e[1])}function yf(n){const e=/\b(\w+)\s*:/g.exec(n);return e?e[1]:""}function xf(n){const t=/@.*?\s+/g;return n.replace(t,"")}function Sf(n,t){const e=[];ta(t,e),n.forEach(h=>{h.header&&ta(h.header,e)});let i=0;const s=e.sort().map(h=>h.indexOf("builtin")>-1?h:`@location(${i++}) ${h}`).join(`,
30
+ `),r=e.sort().map(h=>` var ${xf(h)};`).join(`
31
+ `),o=`return VSOutput(
32
+ ${e.sort().map(h=>` ${yf(h)}`).join(`,
33
+ `)});`;let a=t.replace(/@out\s+[^;]+;\s*/g,"");return a=a.replace("{{struct}}",`
34
+ ${s}
35
+ `),a=a.replace("{{start}}",`
36
+ ${r}
37
+ `),a=a.replace("{{return}}",`
38
+ ${o}
39
+ `),a}function ea(n,t){let e=n;for(const i in t){const s=t[i];s.join(`
40
+ `).length?e=e.replace(`{{${i}}}`,`//-----${i} START-----//
41
+ ${s.join(`
42
+ `)}
43
+ //----${i} FINISH----//`):e=e.replace(`{{${i}}}`,"")}return e}const re=Object.create(null),xn=new Map;let vf=0;function bf({template:n,bits:t}){const e=Sl(n,t);if(re[e])return re[e];const{vertex:i,fragment:s}=Cf(n,t);return re[e]=vl(i,s,t),re[e]}function wf({template:n,bits:t}){const e=Sl(n,t);return re[e]||(re[e]=vl(n.vertex,n.fragment,t)),re[e]}function Cf(n,t){const e=t.map(o=>o.vertex).filter(o=>!!o),i=t.map(o=>o.fragment).filter(o=>!!o);let s=Jo(e,n.vertex,!0);s=Sf(e,s);const r=Jo(i,n.fragment,!0);return{vertex:s,fragment:r}}function Sl(n,t){return t.map(e=>(xn.has(e)||xn.set(e,vf++),xn.get(e))).sort((e,i)=>e-i).join("-")+n.vertex+n.fragment}function vl(n,t,e){const i=Ko(n),s=Ko(t);return e.forEach(r=>{qo(r.vertex,i,r.name),qo(r.fragment,s,r.name)}),{vertex:ea(n,i),fragment:ea(t,s)}}const _f=`
44
+ @in aPosition: vec2<f32>;
45
+ @in aUV: vec2<f32>;
46
+
47
+ @out @builtin(position) vPosition: vec4<f32>;
48
+ @out vUV : vec2<f32>;
49
+ @out vColor : vec4<f32>;
50
+
51
+ {{header}}
52
+
53
+ struct VSOutput {
54
+ {{struct}}
55
+ };
56
+
57
+ @vertex
58
+ fn main( {{in}} ) -> VSOutput {
59
+
60
+ var worldTransformMatrix = globalUniforms.uWorldTransformMatrix;
61
+ var modelMatrix = mat3x3<f32>(
62
+ 1.0, 0.0, 0.0,
63
+ 0.0, 1.0, 0.0,
64
+ 0.0, 0.0, 1.0
65
+ );
66
+ var position = aPosition;
67
+ var uv = aUV;
68
+
69
+ {{start}}
70
+
71
+ vColor = vec4<f32>(1., 1., 1., 1.);
72
+
73
+ {{main}}
74
+
75
+ vUV = uv;
76
+
77
+ var modelViewProjectionMatrix = globalUniforms.uProjectionMatrix * worldTransformMatrix * modelMatrix;
78
+
79
+ vPosition = vec4<f32>((modelViewProjectionMatrix * vec3<f32>(position, 1.0)).xy, 0.0, 1.0);
80
+
81
+ vColor *= globalUniforms.uWorldColorAlpha;
82
+
83
+ {{end}}
84
+
85
+ {{return}}
86
+ };
87
+ `,Pf=`
88
+ @in vUV : vec2<f32>;
89
+ @in vColor : vec4<f32>;
90
+
91
+ {{header}}
92
+
93
+ @fragment
94
+ fn main(
95
+ {{in}}
96
+ ) -> @location(0) vec4<f32> {
97
+
98
+ {{start}}
99
+
100
+ var outColor:vec4<f32>;
101
+
102
+ {{main}}
103
+
104
+ var finalColor:vec4<f32> = outColor * vColor;
105
+
106
+ {{end}}
107
+
108
+ return finalColor;
109
+ };
110
+ `,Mf=`
111
+ in vec2 aPosition;
112
+ in vec2 aUV;
113
+
114
+ out vec4 vColor;
115
+ out vec2 vUV;
116
+
117
+ {{header}}
118
+
119
+ void main(void){
120
+
121
+ mat3 worldTransformMatrix = uWorldTransformMatrix;
122
+ mat3 modelMatrix = mat3(
123
+ 1.0, 0.0, 0.0,
124
+ 0.0, 1.0, 0.0,
125
+ 0.0, 0.0, 1.0
126
+ );
127
+ vec2 position = aPosition;
128
+ vec2 uv = aUV;
129
+
130
+ {{start}}
131
+
132
+ vColor = vec4(1.);
133
+
134
+ {{main}}
135
+
136
+ vUV = uv;
137
+
138
+ mat3 modelViewProjectionMatrix = uProjectionMatrix * worldTransformMatrix * modelMatrix;
139
+
140
+ gl_Position = vec4((modelViewProjectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);
141
+
142
+ vColor *= uWorldColorAlpha;
143
+
144
+ {{end}}
145
+ }
146
+ `,Tf=`
147
+
148
+ in vec4 vColor;
149
+ in vec2 vUV;
150
+
151
+ out vec4 finalColor;
152
+
153
+ {{header}}
154
+
155
+ void main(void) {
156
+
157
+ {{start}}
158
+
159
+ vec4 outColor;
160
+
161
+ {{main}}
162
+
163
+ finalColor = outColor * vColor;
164
+
165
+ {{end}}
166
+ }
167
+ `,Af={name:"global-uniforms-bit",vertex:{header:`
168
+ struct GlobalUniforms {
169
+ uProjectionMatrix:mat3x3<f32>,
170
+ uWorldTransformMatrix:mat3x3<f32>,
171
+ uWorldColorAlpha: vec4<f32>,
172
+ uResolution: vec2<f32>,
173
+ }
174
+
175
+ @group(0) @binding(0) var<uniform> globalUniforms : GlobalUniforms;
176
+ `}},Rf={name:"global-uniforms-bit",vertex:{header:`
177
+ uniform mat3 uProjectionMatrix;
178
+ uniform mat3 uWorldTransformMatrix;
179
+ uniform vec4 uWorldColorAlpha;
180
+ uniform vec2 uResolution;
181
+ `}};function bl({bits:n,name:t}){const e=bf({template:{fragment:Pf,vertex:_f},bits:[Af,...n]});return he.from({name:t,vertex:{source:e.vertex,entryPoint:"main"},fragment:{source:e.fragment,entryPoint:"main"}})}function wl({bits:n,name:t}){return new ti({name:t,...wf({template:{vertex:Mf,fragment:Tf},bits:[Rf,...n]})})}const kf={name:"color-bit",vertex:{header:`
182
+ @in aColor: vec4<f32>;
183
+ `,main:`
184
+ vColor *= vec4<f32>(aColor.rgb * aColor.a, aColor.a);
185
+ `}},Ef={name:"color-bit",vertex:{header:`
186
+ in vec4 aColor;
187
+ `,main:`
188
+ vColor *= vec4(aColor.rgb * aColor.a, aColor.a);
189
+ `}},Sn={};function If(n){const t=[];if(n===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<n;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(`
190
+ `)}function Df(n){const t=[];if(n===1)t.push("outColor = textureSampleGrad(textureSource1, textureSampler1, vUV, uvDx, uvDy);");else{t.push("switch vTextureId {");for(let e=0;e<n;e++)e===n-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(`
191
+ `)}function Ff(n){return Sn[n]||(Sn[n]={name:"texture-batch-bit",vertex:{header:`
192
+ @in aTextureIdAndRound: vec2<u32>;
193
+ @out @interpolate(flat) vTextureId : u32;
194
+ `,main:`
195
+ vTextureId = aTextureIdAndRound.y;
196
+ `,end:`
197
+ if(aTextureIdAndRound.x == 1)
198
+ {
199
+ vPosition = vec4<f32>(roundPixels(vPosition.xy, globalUniforms.uResolution), vPosition.zw);
200
+ }
201
+ `},fragment:{header:`
202
+ @in @interpolate(flat) vTextureId: u32;
203
+
204
+ ${If(n)}
205
+ `,main:`
206
+ var uvDx = dpdx(vUV);
207
+ var uvDy = dpdy(vUV);
208
+
209
+ ${Df(n)}
210
+ `}}),Sn[n]}const vn={};function Bf(n){const t=[];for(let e=0;e<n;e++)e>0&&t.push("else"),e<n-1&&t.push(`if(vTextureId < ${e}.5)`),t.push("{"),t.push(` outColor = texture(uTextures[${e}], vUV);`),t.push("}");return t.join(`
211
+ `)}function Lf(n){return vn[n]||(vn[n]={name:"texture-batch-bit",vertex:{header:`
212
+ in vec2 aTextureIdAndRound;
213
+ out float vTextureId;
214
+
215
+ `,main:`
216
+ vTextureId = aTextureIdAndRound.y;
217
+ `,end:`
218
+ if(aTextureIdAndRound.x == 1.)
219
+ {
220
+ gl_Position.xy = roundPixels(gl_Position.xy, uResolution);
221
+ }
222
+ `},fragment:{header:`
223
+ in float vTextureId;
224
+
225
+ uniform sampler2D uTextures[${n}];
226
+
227
+ `,main:`
228
+
229
+ ${Bf(n)}
230
+ `}}),vn[n]}const Cl={name:"round-pixels-bit",vertex:{header:`
231
+ fn roundPixels(position: vec2<f32>, targetSize: vec2<f32>) -> vec2<f32>
232
+ {
233
+ return (floor(((position * 0.5 + 0.5) * targetSize) + 0.5) / targetSize) * 2.0 - 1.0;
234
+ }
235
+ `}},_l={name:"round-pixels-bit",vertex:{header:`
236
+ vec2 roundPixels(vec2 position, vec2 targetSize)
237
+ {
238
+ return (floor(((position * 0.5 + 0.5) * targetSize) + 0.5) / targetSize) * 2.0 - 1.0;
239
+ }
240
+ `}},ia={};function zf(n){let t=ia[n];if(t)return t;const e=new Int32Array(n);for(let i=0;i<n;i++)e[i]=i;return t=ia[n]=new ei({uTextures:{value:e,type:"i32",size:n}},{isStatic:!0}),t}class sa extends De{constructor(t){const e=wl({name:"batch",bits:[Ef,Lf(t),_l]}),i=bl({name:"batch",bits:[kf,Ff(t),Cl]});super({glProgram:e,gpuProgram:i,resources:{batchSamplers:zf(t)}}),this.maxTextures=t}}let pi=null;const Pl=class Ml extends cf{constructor(t){super(t),this.geometry=new gf,this.name=Ml.extension.name,this.vertexSize=6,pi??(pi=new sa(t.maxTextures)),this.shader=pi}packAttributes(t,e,i,s,r){const o=r<<16|t.roundPixels&65535,a=t.transform,h=a.a,l=a.b,c=a.c,d=a.d,u=a.tx,p=a.ty,{positions:g,uvs:y}=t,m=t.color,x=t.attributeOffset,S=x+t.attributeSize;for(let v=x;v<S;v++){const b=v*2,P=g[b],C=g[b+1];e[s++]=h*P+c*C+u,e[s++]=d*C+l*P+p,e[s++]=y[b],e[s++]=y[b+1],i[s++]=m,i[s++]=o}}packQuadAttributes(t,e,i,s,r){const o=t.texture,a=t.transform,h=a.a,l=a.b,c=a.c,d=a.d,u=a.tx,p=a.ty,g=t.bounds,y=g.maxX,m=g.minX,x=g.maxY,S=g.minY,v=o.uvs,b=t.color,P=r<<16|t.roundPixels&65535;e[s+0]=h*m+c*S+u,e[s+1]=d*S+l*m+p,e[s+2]=v.x0,e[s+3]=v.y0,i[s+4]=b,i[s+5]=P,e[s+6]=h*y+c*S+u,e[s+7]=d*S+l*y+p,e[s+8]=v.x1,e[s+9]=v.y1,i[s+10]=b,i[s+11]=P,e[s+12]=h*y+c*x+u,e[s+13]=d*x+l*y+p,e[s+14]=v.x2,e[s+15]=v.y2,i[s+16]=b,i[s+17]=P,e[s+18]=h*m+c*x+u,e[s+19]=d*x+l*m+p,e[s+20]=v.x3,e[s+21]=v.y3,i[s+22]=b,i[s+23]=P}_updateMaxTextures(t){this.shader.maxTextures!==t&&(pi=new sa(t),this.shader=pi)}destroy(){this.shader=null,super.destroy()}};Pl.extension={type:[E.Batcher],name:"default"};let Of=Pl;class ai{constructor(t){this.items=Object.create(null);const{renderer:e,type:i,onUnload:s,priority:r,name:o}=t;this._renderer=e,e.gc.addResourceHash(this,"items",i,r??0),this._onUnload=s,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 s;if(!this.items[t.uid])return;const i=t._gpuData[this._renderer.uid];i&&((s=this._onUnload)==null||s.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 Wf(n,t,e,i,s,r,o,a=null){let h=0;e*=t,s*=r;const l=a.a,c=a.b,d=a.c,u=a.d,p=a.tx,g=a.ty;for(;h<o;){const y=n[e],m=n[e+1];i[s]=l*y+d*m+p,i[s+1]=c*y+u*m+g,s+=r,e+=t,h++}}function Gf(n,t,e,i){let s=0;for(t*=e;s<i;)n[t]=0,n[t+1]=0,t+=e,s++}function Tl(n,t,e,i,s){const r=t.a,o=t.b,a=t.c,h=t.d,l=t.tx,c=t.ty;e||(e=0),i||(i=2),s||(s=n.length/i-e);let d=e*i;for(let u=0;u<s;u++){const p=n[d],g=n[d+1];n[d]=r*p+a*g+l,n[d+1]=o*p+h*g+c,d+=i}}const Uf=new U;class Pr{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?xr(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)||Uf}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 Li={extension:{type:E.ShapeBuilder,name:"circle"},build(n,t){let e,i,s,r,o,a;if(n.type==="circle"){const b=n;if(o=a=b.radius,o<=0)return!1;e=b.x,i=b.y,s=r=0}else if(n.type==="ellipse"){const b=n;if(o=b.halfWidth,a=b.halfHeight,o<=0||a<=0)return!1;e=b.x,i=b.y,s=r=0}else{const b=n,P=b.width/2,C=b.height/2;e=b.x+P,i=b.y+C,o=a=Math.max(0,Math.min(b.radius,Math.min(P,C))),s=P-o,r=C-a}if(s<0||r<0)return!1;const h=Math.ceil(2.3*Math.sqrt(o+a)),l=h*8+(s?4:0)+(r?4:0);if(l===0)return!1;if(h===0)return t[0]=t[6]=e+s,t[1]=t[3]=i+r,t[2]=t[4]=e-s,t[5]=t[7]=i-r,!0;let c=0,d=h*4+(s?2:0)+2,u=d,p=l,g=s+o,y=r,m=e+g,x=e-g,S=i+y;if(t[c++]=m,t[c++]=S,t[--d]=S,t[--d]=x,r){const b=i-y;t[u++]=x,t[u++]=b,t[--p]=b,t[--p]=m}for(let b=1;b<h;b++){const P=Math.PI/2*(b/h),C=s+Math.cos(P)*o,_=r+Math.sin(P)*a,R=e+C,M=e-C,A=i+_,T=i-_;t[c++]=R,t[c++]=A,t[--d]=A,t[--d]=M,t[u++]=M,t[u++]=T,t[--p]=T,t[--p]=R}g=s,y=r+a,m=e+g,x=e-g,S=i+y;const v=i-y;return t[c++]=m,t[c++]=S,t[--p]=v,t[--p]=m,s&&(t[c++]=x,t[c++]=S,t[--p]=v,t[--p]=x),!0},triangulate(n,t,e,i,s,r){if(n.length===0)return;let o=0,a=0;for(let c=0;c<n.length;c+=2)o+=n[c],a+=n[c+1];o/=n.length/2,a/=n.length/2;let h=i;t[h*e]=o,t[h*e+1]=a;const l=h++;for(let c=0;c<n.length;c+=2)t[h*e]=n[c],t[h*e+1]=n[c+1],c>0&&(s[r++]=h,s[r++]=l,s[r++]=h-1),h++;s[r++]=l+1,s[r++]=l,s[r++]=h-1}},Hf={...Li,extension:{...Li.extension,name:"ellipse"}},Nf={...Li,extension:{...Li.extension,name:"roundedRectangle"}},Al=1e-4,na=1e-4;function Vf(n){const t=n.length;if(t<6)return 1;let e=0;for(let i=0,s=n[t-2],r=n[t-1];i<t;i+=2){const o=n[i],a=n[i+1];e+=(o-s)*(a+r),s=o,r=a}return e<0?-1:1}function ra(n,t,e,i,s,r,o,a){const h=n-e*s,l=t-i*s,c=n+e*r,d=t+i*r;let u,p;o?(u=i,p=-e):(u=-i,p=e);const g=h+u,y=l+p,m=c+u,x=d+p;return a.push(g,y),a.push(m,x),2}function me(n,t,e,i,s,r,o,a){const h=e-n,l=i-t;let c=Math.atan2(h,l),d=Math.atan2(s-n,r-t);a&&c<d?c+=Math.PI*2:!a&&c>d&&(d+=Math.PI*2);let u=c;const p=d-c,g=Math.abs(p),y=Math.sqrt(h*h+l*l),m=(15*g*Math.sqrt(y)/Math.PI>>0)+1,x=p/m;if(u+=x,a){o.push(n,t),o.push(e,i);for(let S=1,v=u;S<m;S++,v+=x)o.push(n,t),o.push(n+Math.sin(v)*y,t+Math.cos(v)*y);o.push(n,t),o.push(s,r)}else{o.push(e,i),o.push(n,t);for(let S=1,v=u;S<m;S++,v+=x)o.push(n+Math.sin(v)*y,t+Math.cos(v)*y),o.push(n,t);o.push(s,r),o.push(n,t)}return m*2}function $f(n,t,e,i,s,r){const o=Al;if(n.length===0)return;const a=t;let h=a.alignment;if(t.alignment!==.5){let L=Vf(n);h=(h-.5)*L+.5}const l=new Q(n[0],n[1]),c=new Q(n[n.length-2],n[n.length-1]),d=i,u=Math.abs(l.x-c.x)<o&&Math.abs(l.y-c.y)<o;if(d){n=n.slice(),u&&(n.pop(),n.pop(),c.set(n[n.length-2],n[n.length-1]));const L=(l.x+c.x)*.5,Z=(c.y+l.y)*.5;n.unshift(L,Z),n.push(L,Z)}const p=s,g=n.length/2;let y=n.length;const m=p.length/2,x=a.width/2,S=x*x,v=a.miterLimit*a.miterLimit;let b=n[0],P=n[1],C=n[2],_=n[3],R=0,M=0,A=-(P-_),T=b-C,I=0,D=0,B=Math.sqrt(A*A+T*T);A/=B,T/=B,A*=x,T*=x;const j=h,k=(1-j)*2,F=j*2;d||(a.cap==="round"?y+=me(b-A*(k-F)*.5,P-T*(k-F)*.5,b-A*k,P-T*k,b+A*F,P+T*F,p,!0)+2:a.cap==="square"&&(y+=ra(b,P,A,T,k,F,!0,p))),p.push(b-A*k,P-T*k),p.push(b+A*F,P+T*F);for(let L=1;L<g-1;++L){b=n[(L-1)*2],P=n[(L-1)*2+1],C=n[L*2],_=n[L*2+1],R=n[(L+1)*2],M=n[(L+1)*2+1],A=-(P-_),T=b-C,B=Math.sqrt(A*A+T*T),A/=B,T/=B,A*=x,T*=x,I=-(_-M),D=C-R,B=Math.sqrt(I*I+D*D),I/=B,D/=B,I*=x,D*=x;const Z=C-b,Y=P-_,at=C-R,bt=M-_,wt=Z*at+Y*bt,Rt=Y*at-bt*Z,Gt=Rt<0;if(Math.abs(Rt)<.001*Math.abs(wt)){p.push(C-A*k,_-T*k),p.push(C+A*F,_+T*F),wt>=0&&(a.join==="round"?y+=me(C,_,C-A*k,_-T*k,C-I*k,_-D*k,p,!1)+4:y+=2,p.push(C-I*F,_-D*F),p.push(C+I*k,_+D*k));continue}const Hi=(-A+b)*(-T+_)-(-A+C)*(-T+P),Qr=(-I+R)*(-D+_)-(-I+C)*(-D+M),Ni=(Z*Qr-at*Hi)/Rt,Vi=(bt*Hi-Y*Qr)/Rt,$s=(Ni-C)*(Ni-C)+(Vi-_)*(Vi-_),ue=C+(Ni-C)*k,pe=_+(Vi-_)*k,fe=C-(Ni-C)*F,ge=_-(Vi-_)*F,Gc=Math.min(Z*Z+Y*Y,at*at+bt*bt),Jr=Gt?k:F,Uc=Gc+Jr*Jr*S;$s<=Uc?a.join==="bevel"||$s/S>v?(Gt?(p.push(ue,pe),p.push(C+A*F,_+T*F),p.push(ue,pe),p.push(C+I*F,_+D*F)):(p.push(C-A*k,_-T*k),p.push(fe,ge),p.push(C-I*k,_-D*k),p.push(fe,ge)),y+=2):a.join==="round"?Gt?(p.push(ue,pe),p.push(C+A*F,_+T*F),y+=me(C,_,C+A*F,_+T*F,C+I*F,_+D*F,p,!0)+4,p.push(ue,pe),p.push(C+I*F,_+D*F)):(p.push(C-A*k,_-T*k),p.push(fe,ge),y+=me(C,_,C-A*k,_-T*k,C-I*k,_-D*k,p,!1)+4,p.push(C-I*k,_-D*k),p.push(fe,ge)):(p.push(ue,pe),p.push(fe,ge)):(p.push(C-A*k,_-T*k),p.push(C+A*F,_+T*F),a.join==="round"?Gt?y+=me(C,_,C+A*F,_+T*F,C+I*F,_+D*F,p,!0)+2:y+=me(C,_,C-A*k,_-T*k,C-I*k,_-D*k,p,!1)+2:a.join==="miter"&&$s/S<=v&&(Gt?(p.push(fe,ge),p.push(fe,ge)):(p.push(ue,pe),p.push(ue,pe)),y+=2),p.push(C-I*k,_-D*k),p.push(C+I*F,_+D*F),y+=2)}b=n[(g-2)*2],P=n[(g-2)*2+1],C=n[(g-1)*2],_=n[(g-1)*2+1],A=-(P-_),T=b-C,B=Math.sqrt(A*A+T*T),A/=B,T/=B,A*=x,T*=x,p.push(C-A*k,_-T*k),p.push(C+A*F,_+T*F),d||(a.cap==="round"?y+=me(C-A*(k-F)*.5,_-T*(k-F)*.5,C-A*k,_-T*k,C+A*F,_+T*F,p,!1)+2:a.cap==="square"&&(y+=ra(C,_,A,T,k,F,!1,p)));const rt=na*na;for(let L=m;L<y+m-2;++L)b=p[L*2],P=p[L*2+1],C=p[(L+1)*2],_=p[(L+1)*2+1],R=p[(L+2)*2],M=p[(L+2)*2+1],!(Math.abs(b*(_-M)+C*(M-P)+R*(P-_))<rt)&&r.push(L,L+1,L+2)}function Yf(n,t,e,i){const s=Al;if(n.length===0)return;const r=n[0],o=n[1],a=n[n.length-2],h=n[n.length-1],l=t||Math.abs(r-a)<s&&Math.abs(o-h)<s,c=e,d=n.length/2,u=c.length/2;for(let p=0;p<d;p++)c.push(n[p*2]),c.push(n[p*2+1]);for(let p=0;p<d-1;p++)i.push(u+p,u+p+1);l&&i.push(u+d-1,u)}function Rl(n,t,e,i,s,r,o){const a=lp(n,t,2);if(!a)return;for(let l=0;l<a.length;l+=3)r[o++]=a[l]+s,r[o++]=a[l+1]+s,r[o++]=a[l+2]+s;let h=s*i;for(let l=0;l<n.length;l+=2)e[h]=n[l],e[h+1]=n[l+1],h+=i}const Xf=[],jf={extension:{type:E.ShapeBuilder,name:"polygon"},build(n,t){for(let e=0;e<n.points.length;e++)t[e]=n.points[e];return!0},triangulate(n,t,e,i,s,r){Rl(n,Xf,t,e,i,s,r)}},Zf={extension:{type:E.ShapeBuilder,name:"rectangle"},build(n,t){const e=n,i=e.x,s=e.y,r=e.width,o=e.height;return r>0&&o>0?(t[0]=i,t[1]=s,t[2]=i+r,t[3]=s,t[4]=i+r,t[5]=s+o,t[6]=i,t[7]=s+o,!0):!1},triangulate(n,t,e,i,s,r){let o=0;i*=e,t[i+o]=n[0],t[i+o+1]=n[1],o+=e,t[i+o]=n[2],t[i+o+1]=n[3],o+=e,t[i+o]=n[6],t[i+o+1]=n[7],o+=e,t[i+o]=n[4],t[i+o+1]=n[5],o+=e;const a=i/e;s[r++]=a,s[r++]=a+1,s[r++]=a+2,s[r++]=a+1,s[r++]=a+3,s[r++]=a+2}},qf={extension:{type:E.ShapeBuilder,name:"triangle"},build(n,t){return t[0]=n.x,t[1]=n.y,t[2]=n.x2,t[3]=n.y2,t[4]=n.x3,t[5]=n.y3,!0},triangulate(n,t,e,i,s,r){let o=0;i*=e,t[i+o]=n[0],t[i+o+1]=n[1],o+=e,t[i+o]=n[2],t[i+o+1]=n[3],o+=e,t[i+o]=n[4],t[i+o+1]=n[5];const a=i/e;s[r++]=a,s[r++]=a+1,s[r++]=a+2}},oa=[{offset:0,color:"white"},{offset:1,color:"black"}],Mr=class Jn{constructor(...t){this.uid=ct("fillGradient"),this._tick=0,this.type="linear",this.colorStops=[];let e=Kf(t);e={...e.type==="radial"?Jn.defaultRadialOptions:Jn.defaultLinearOptions,...Sh(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(s=>{this.addColorStop(s.offset,s.color)})}addColorStop(t,e){return this.colorStops.push({offset:t,color:nt.shared.setValue(e).toHexa()}),this}buildLinearGradient(){if(this.texture)return;let{x:t,y:e}=this.start,{x:i,y:s}=this.end,r=i-t,o=s-e;const a=r<0||o<0;if(this._wrapMode==="clamp-to-edge"){if(r<0){const m=t;t=i,i=m,r*=-1}if(o<0){const m=e;e=s,s=m,o*=-1}}const h=this.colorStops.length?this.colorStops:oa,l=this._textureSize,{canvas:c,context:d}=ha(l,1),u=a?d.createLinearGradient(this._textureSize,0,0,0):d.createLinearGradient(0,0,this._textureSize,0);aa(u,h),d.fillStyle=u,d.fillRect(0,0,l,1),this.texture=new O({source:new Je({resource:c,addressMode:this._wrapMode})});const p=Math.sqrt(r*r+o*o),g=Math.atan2(o,r),y=new U;y.scale(p/l,1),y.rotate(g),y.translate(t,e),this.textureSpace==="local"&&y.scale(l,l),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:oa,e=this._textureSize,{canvas:i,context:s}=ha(e,e),{x:r,y:o}=this.center,{x:a,y:h}=this.outerCenter,l=this.innerRadius,c=this.outerRadius,d=a-c,u=h-c,p=e/(c*2),g=(r-d)*p,y=(o-u)*p,m=s.createRadialGradient(g,y,l*p,(a-d)*p,(h-u)*p,c*p);aa(m,t),s.fillStyle=t[t.length-1].color,s.fillRect(0,0,e,e),s.fillStyle=m,s.translate(g,y),s.rotate(this.rotation),s.scale(1,this.scale),s.translate(-g,-y),s.fillRect(0,0,e,e),this.texture=new O({source:new Je({resource:i,addressMode:this._wrapMode})});const x=new U;x.scale(1/p,1/p),x.translate(d,u),this.textureSpace==="local"&&x.scale(e,e),this.transform=x}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}`}};Mr.defaultLinearOptions={start:{x:0,y:0},end:{x:0,y:1},colorStops:[],textureSpace:"local",type:"linear",textureSize:256,wrapMode:"clamp-to-edge"};Mr.defaultRadialOptions={center:{x:.5,y:.5},innerRadius:0,outerRadius:.5,colorStops:[],scale:1,textureSpace:"local",type:"radial",textureSize:256,wrapMode:"clamp-to-edge"};let Wt=Mr;function aa(n,t){for(let e=0;e<t.length;e++){const i=t[e];n.addColorStop(i.offset,i.color)}}function ha(n,t){const e=$.get().createCanvas(n,t),i=e.getContext("2d");return{canvas:e,context:i}}function Kf(n){let t=n[0]??{};return(typeof t=="number"||n[1])&&(N("8.5.2","use options object instead"),t={type:"linear",start:{x:n[0],y:n[1]},end:{x:n[2],y:n[3]},textureSpace:n[4],textureSize:n[5]??Wt.defaultLinearOptions.textureSize}),t}const Qf=new U,Jf=new J;function tg(n,t,e,i){const s=t.matrix?n.copyFrom(t.matrix).invert():n.identity();if(t.textureSpace==="local"){const o=e.getBounds(Jf);t.width&&o.pad(t.width);const{x:a,y:h}=o,l=1/o.width,c=1/o.height,d=-a*l,u=-h*c,p=s.a,g=s.b,y=s.c,m=s.d;s.a*=l,s.b*=l,s.c*=c,s.d*=c,s.tx=d*p+u*y+s.tx,s.ty=d*g+u*m+s.ty}else s.translate(t.texture.frame.x,t.texture.frame.y),s.scale(1/t.texture.source.width,1/t.texture.source.height);const r=t.texture.source.style;return!(t.fill instanceof Wt)&&r.addressMode==="clamp-to-edge"&&(r.addressMode="repeat",r.update()),i&&s.append(Qf.copyFrom(i).invert()),s}const Ds={};q.handleByMap(E.ShapeBuilder,Ds);q.add(Zf,jf,qf,Li,Hf,Nf);const eg=new J,ig=new U;function sg(n,t){const{geometryData:e,batches:i}=t;i.length=0,e.indices.length=0,e.vertices.length=0,e.uvs.length=0;for(let s=0;s<n.instructions.length;s++){const r=n.instructions[s];if(r.action==="texture")ng(r.data,i,e);else if(r.action==="fill"||r.action==="stroke"){const o=r.action==="stroke",a=r.data.path.shapePath,h=r.data.style,l=r.data.hole;o&&l&&la(l.shapePath,h,!0,i,e),l&&(a.shapePrimitives[a.shapePrimitives.length-1].holes=l.shapePath.shapePrimitives),la(a,h,o,i,e)}}}function ng(n,t,e){const i=[],s=Ds.rectangle,r=eg;r.x=n.dx,r.y=n.dy,r.width=n.dw,r.height=n.dh;const o=n.transform;if(!s.build(r,i))return;const{vertices:a,uvs:h,indices:l}=e,c=l.length,d=a.length/2;o&&Tl(i,o),s.triangulate(i,a,2,d,l,c);const u=n.image,p=u.uvs;h.push(p.x0,p.y0,p.x1,p.y1,p.x3,p.y3,p.x2,p.y2);const g=Mt.get(Pr);g.indexOffset=c,g.indexSize=l.length-c,g.attributeOffset=d,g.attributeSize=a.length/2-d,g.baseColor=n.style,g.alpha=n.alpha,g.texture=u,g.geometryData=e,t.push(g)}function la(n,t,e,i,s){const{vertices:r,uvs:o,indices:a}=s;n.shapePrimitives.forEach(({shape:h,transform:l,holes:c})=>{const d=[],u=Ds[h.type];if(!u.build(h,d))return;const p=a.length,g=r.length/2;let y="triangle-list";if(l&&Tl(d,l),e){const v=h.closePath??!0,b=t;b.pixelLine?(Yf(d,v,r,a),y="line-list"):$f(d,b,!1,v,r,a)}else if(c){const v=[],b=d.slice();rg(c).forEach(C=>{v.push(b.length/2),b.push(...C)}),Rl(b,v,r,2,g,a,p)}else u.triangulate(d,r,2,g,a,p);const m=o.length/2,x=t.texture;if(x!==O.WHITE){const v=tg(ig,t,h,l);Wf(r,2,g,o,m,2,r.length/2-g,v)}else Gf(o,m,2,r.length/2-g);const S=Mt.get(Pr);S.indexOffset=p,S.indexSize=a.length-p,S.attributeOffset=g,S.attributeSize=r.length/2-g,S.baseColor=t.color,S.alpha=t.alpha,S.texture=x,S.geometryData=s,S.topology=y,i.push(S)})}function rg(n){const t=[];for(let e=0;e<n.length;e++){const i=n[e].shape,s=[];Ds[i.type].build(i,s)&&t.push(s)}return t}class og{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 ag{constructor(){this.instructions=new Sr}init(t){const e=t.maxTextures;this.batcher?this.batcher._updateMaxTextures(e):this.batcher=new Of({maxTextures:e}),this.instructions.reset()}get geometry(){return N(Ad,"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 Tr=class tr{constructor(t){this._renderer=t,this._managedContexts=new ai({renderer:t,type:"resource",name:"graphicsContext"})}init(t){tr.defaultOptions.bezierSmoothness=(t==null?void 0:t.bezierSmoothness)??tr.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(),sg(t,i);const s=t.batchMode;t.customShader||s==="no-batch"?i.isBatchable=!1:s==="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(ag,{maxTextures:this._renderer.limits.maxBatchableTextures}),i=t._gpuData[this._renderer.uid],{batches:s,geometryData:r}=i;i.graphicsData=e;const o=r.vertices.length,a=r.indices.length;for(let d=0;d<s.length;d++)s[d].applyTransform=!1;const h=e.batcher;h.ensureAttributeBuffer(o),h.ensureIndexBuffer(a),h.begin();for(let d=0;d<s.length;d++){const u=s[d];h.add(u)}h.finish(e.instructions);const l=h.geometry;l.indexBuffer.setDataWithSize(h.indexBuffer,h.indexSize,!0),l.buffers[0].setDataWithSize(h.attributeBuffer.float32View,h.attributeSize,!0);const c=h.batches;for(let d=0;d<c.length;d++){const u=c[d];u.bindGroup=Jp(u.textures.textures,u.textures.count,this._renderer.limits.maxBatchableTextures)}return e}_initContext(t){const e=new og;return e.context=t,t._gpuData[this._renderer.uid]=e,this._managedContexts.add(t),e}destroy(){this._managedContexts.destroy(),this._renderer=null}};Tr.extension={type:[E.WebGLSystem,E.WebGPUSystem],name:"graphicsContext"};Tr.defaultOptions={bezierSmoothness:.5};let Ar=Tr;const hg=8,ns=11920929e-14,lg=1;function kl(n,t,e,i,s,r,o,a,h,l){const d=Math.min(.99,Math.max(0,l??Ar.defaultOptions.bezierSmoothness));let u=(lg-d)/1;return u*=u,cg(t,e,i,s,r,o,a,h,n,u),n}function cg(n,t,e,i,s,r,o,a,h,l){er(n,t,e,i,s,r,o,a,h,l,0),h.push(o,a)}function er(n,t,e,i,s,r,o,a,h,l,c){if(c>hg)return;const d=(n+e)/2,u=(t+i)/2,p=(e+s)/2,g=(i+r)/2,y=(s+o)/2,m=(r+a)/2,x=(d+p)/2,S=(u+g)/2,v=(p+y)/2,b=(g+m)/2,P=(x+v)/2,C=(S+b)/2;if(c>0){let _=o-n,R=a-t;const M=Math.abs((e-o)*R-(i-a)*_),A=Math.abs((s-o)*R-(r-a)*_);if(M>ns&&A>ns){if((M+A)*(M+A)<=l*(_*_+R*R)){h.push(P,C);return}}else if(M>ns){if(M*M<=l*(_*_+R*R)){h.push(P,C);return}}else if(A>ns){if(A*A<=l*(_*_+R*R)){h.push(P,C);return}}else if(_=P-(n+o)/2,R=C-(t+a)/2,_*_+R*R<=l){h.push(P,C);return}}er(n,t,d,u,x,S,P,C,h,l,c+1),er(P,C,v,b,y,m,o,a,h,l,c+1)}const dg=8,ug=11920929e-14,pg=1;function fg(n,t,e,i,s,r,o,a){const l=Math.min(.99,Math.max(0,a??Ar.defaultOptions.bezierSmoothness));let c=(pg-l)/1;return c*=c,gg(t,e,i,s,r,o,n,c),n}function gg(n,t,e,i,s,r,o,a){ir(o,n,t,e,i,s,r,a,0),o.push(s,r)}function ir(n,t,e,i,s,r,o,a,h){if(h>dg)return;const l=(t+i)/2,c=(e+s)/2,d=(i+r)/2,u=(s+o)/2,p=(l+d)/2,g=(c+u)/2;let y=r-t,m=o-e;const x=Math.abs((i-r)*m-(s-o)*y);if(x>ug){if(x*x<=a*(y*y+m*m)){n.push(p,g);return}}else if(y=p-(t+r)/2,m=g-(e+o)/2,y*y+m*m<=a){n.push(p,g);return}ir(n,t,e,l,c,p,g,a,h+1),ir(n,p,g,d,u,r,o,a,h+1)}function El(n,t,e,i,s,r,o,a){let h=Math.abs(s-r);(!o&&s>r||o&&r>s)&&(h=2*Math.PI-h),a||(a=Math.max(6,Math.floor(6*Math.pow(i,1/3)*(h/Math.PI)))),a=Math.max(a,3);let l=h/a,c=s;l*=o?-1:1;for(let d=0;d<a+1;d++){const u=Math.cos(c),p=Math.sin(c),g=t+u*i,y=e+p*i;n.push(g,y),c+=l}}function mg(n,t,e,i,s,r){const o=n[n.length-2],h=n[n.length-1]-e,l=o-t,c=s-e,d=i-t,u=Math.abs(h*d-l*c);if(u<1e-8||r===0){(n[n.length-2]!==t||n[n.length-1]!==e)&&n.push(t,e);return}const p=h*h+l*l,g=c*c+d*d,y=h*c+l*d,m=r*Math.sqrt(p)/u,x=r*Math.sqrt(g)/u,S=m*y/p,v=x*y/g,b=m*d+x*l,P=m*c+x*h,C=l*(x+S),_=h*(x+S),R=d*(m+v),M=c*(m+v),A=Math.atan2(_-P,C-b),T=Math.atan2(M-P,R-b);El(n,b+t,P+e,r,A,T,l*c>d*h)}const Mi=Math.PI*2,bn={centerX:0,centerY:0,ang1:0,ang2:0},wn=({x:n,y:t},e,i,s,r,o,a,h)=>{n*=e,t*=i;const l=s*n-r*t,c=r*n+s*t;return h.x=l+o,h.y=c+a,h};function yg(n,t){const e=t===-1.5707963267948966?-.551915024494:1.3333333333333333*Math.tan(t/4),i=t===1.5707963267948966?.551915024494:e,s=Math.cos(n),r=Math.sin(n),o=Math.cos(n+t),a=Math.sin(n+t);return[{x:s-r*i,y:r+s*i},{x:o+a*i,y:a-o*i},{x:o,y:a}]}const ca=(n,t,e,i)=>{const s=n*i-t*e<0?-1:1;let r=n*e+t*i;return r>1&&(r=1),r<-1&&(r=-1),s*Math.acos(r)},xg=(n,t,e,i,s,r,o,a,h,l,c,d,u)=>{const p=Math.pow(s,2),g=Math.pow(r,2),y=Math.pow(c,2),m=Math.pow(d,2);let x=p*g-p*m-g*y;x<0&&(x=0),x/=p*m+g*y,x=Math.sqrt(x)*(o===a?-1:1);const S=x*s/r*d,v=x*-r/s*c,b=l*S-h*v+(n+e)/2,P=h*S+l*v+(t+i)/2,C=(c-S)/s,_=(d-v)/r,R=(-c-S)/s,M=(-d-v)/r,A=ca(1,0,C,_);let T=ca(C,_,R,M);a===0&&T>0&&(T-=Mi),a===1&&T<0&&(T+=Mi),u.centerX=b,u.centerY=P,u.ang1=A,u.ang2=T};function Sg(n,t,e,i,s,r,o,a=0,h=0,l=0){if(r===0||o===0)return;const c=Math.sin(a*Mi/360),d=Math.cos(a*Mi/360),u=d*(t-i)/2+c*(e-s)/2,p=-c*(t-i)/2+d*(e-s)/2;if(u===0&&p===0)return;r=Math.abs(r),o=Math.abs(o);const g=Math.pow(u,2)/Math.pow(r,2)+Math.pow(p,2)/Math.pow(o,2);g>1&&(r*=Math.sqrt(g),o*=Math.sqrt(g)),xg(t,e,i,s,r,o,h,l,c,d,u,p,bn);let{ang1:y,ang2:m}=bn;const{centerX:x,centerY:S}=bn;let v=Math.abs(m)/(Mi/4);Math.abs(1-v)<1e-7&&(v=1);const b=Math.max(Math.ceil(v),1);m/=b;let P=n[n.length-2],C=n[n.length-1];const _={x:0,y:0};for(let R=0;R<b;R++){const M=yg(y,m),{x:A,y:T}=wn(M[0],r,o,d,c,x,S,_),{x:I,y:D}=wn(M[1],r,o,d,c,x,S,_),{x:B,y:j}=wn(M[2],r,o,d,c,x,S,_);kl(n,P,C,A,T,I,D,B,j),P=B,C=j,y+=m}}function vg(n,t,e){const i=(o,a)=>{const h=a.x-o.x,l=a.y-o.y,c=Math.sqrt(h*h+l*l),d=h/c,u=l/c;return{len:c,nx:d,ny:u}},s=(o,a)=>{o===0?n.moveTo(a.x,a.y):n.lineTo(a.x,a.y)};let r=t[t.length-1];for(let o=0;o<t.length;o++){const a=t[o%t.length],h=a.radius??e;if(h<=0){s(o,a),r=a;continue}const l=t[(o+1)%t.length],c=i(a,r),d=i(a,l);if(c.len<1e-4||d.len<1e-4){s(o,a),r=a;continue}let u=Math.asin(c.nx*d.ny-c.ny*d.nx),p=1,g=!1;c.nx*d.nx-c.ny*-d.ny<0?u<0?u=Math.PI+u:(u=Math.PI-u,p=-1,g=!0):u>0&&(p=-1,g=!0);const y=u/2;let m,x=Math.abs(Math.cos(y)*h/Math.sin(y));x>Math.min(c.len/2,d.len/2)?(x=Math.min(c.len/2,d.len/2),m=Math.abs(x*Math.sin(y)/Math.cos(y))):m=h;const S=a.x+d.nx*x+-d.ny*m*p,v=a.y+d.ny*x+d.nx*m*p,b=Math.atan2(c.ny,c.nx)+Math.PI/2*p,P=Math.atan2(d.ny,d.nx)-Math.PI/2*p;o===0&&n.moveTo(S+Math.cos(b)*m,v+Math.sin(b)*m),n.arc(S,v,m,b,P,g),r=a}}function bg(n,t,e,i){const s=(a,h)=>Math.sqrt((a.x-h.x)**2+(a.y-h.y)**2),r=(a,h,l)=>({x:a.x+(h.x-a.x)*l,y:a.y+(h.y-a.y)*l}),o=t.length;for(let a=0;a<o;a++){const h=t[(a+1)%o],l=h.radius??e;if(l<=0){a===0?n.moveTo(h.x,h.y):n.lineTo(h.x,h.y);continue}const c=t[a],d=t[(a+2)%o],u=s(c,h);let p;if(u<1e-4)p=h;else{const m=Math.min(u/2,l);p=r(h,c,m/u)}const g=s(d,h);let y;if(g<1e-4)y=h;else{const m=Math.min(g/2,l);y=r(h,d,m/g)}a===0?n.moveTo(p.x,p.y):n.lineTo(p.x,p.y),n.quadraticCurveTo(h.x,h.y,y.x,y.y,i)}}const wg=new J;class Cg{constructor(t){this.shapePrimitives=[],this._currentPoly=null,this._bounds=new Dt,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,s=i[i.length-2],r=i[i.length-1];return(s!==t||r!==e)&&i.push(t,e),this}arc(t,e,i,s,r,o){this._ensurePoly(!1);const a=this._currentPoly.points;return El(a,t,e,i,s,r,o),this}arcTo(t,e,i,s,r){this._ensurePoly();const o=this._currentPoly.points;return mg(o,t,e,i,s,r),this}arcToSvg(t,e,i,s,r,o,a){const h=this._currentPoly.points;return Sg(h,this._currentPoly.lastX,this._currentPoly.lastY,o,a,t,e,i,s,r),this}bezierCurveTo(t,e,i,s,r,o,a){this._ensurePoly();const h=this._currentPoly;return kl(this._currentPoly.points,h.lastX,h.lastY,t,e,i,s,r,o,a),this}quadraticCurveTo(t,e,i,s,r){this._ensurePoly();const o=this._currentPoly;return fg(this._currentPoly.points,o.lastX,o.lastY,t,e,i,s,r),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,s=i.length;for(let r=0;r<t.instructions.length;r++){const o=t.instructions[r];this[o.action](...o.data)}if(t.checkForHoles&&i.length-s>1){let r=null;for(let o=s;o<i.length;o++){const a=i[o];if(a.shape.type==="polygon"){const h=a.shape,l=r==null?void 0:r.shape;l&&l.containsPolygon(h)?(r.holes||(r.holes=[]),r.holes.push(a),i.copyWithin(o,o+1),i.length--,o--):r=a}}}return this}finish(t=!1){this.endPoly(t)}rect(t,e,i,s,r){return this.drawShape(new J(t,e,i,s),r),this}circle(t,e,i,s){return this.drawShape(new Is(t,e,i),s),this}poly(t,e,i){const s=new Te(t);return s.closePath=e,this.drawShape(s,i),this}regularPoly(t,e,i,s,r=0,o){s=Math.max(s|0,3);const a=-1*Math.PI/2+r,h=Math.PI*2/s,l=[];for(let c=0;c<s;c++){const d=a-c*h;l.push(t+i*Math.cos(d),e+i*Math.sin(d))}return this.poly(l,!0,o),this}roundPoly(t,e,i,s,r,o=0,a){if(s=Math.max(s|0,3),r<=0)return this.regularPoly(t,e,i,s,o);const h=i*Math.sin(Math.PI/s)-.001;r=Math.min(r,h);const l=-1*Math.PI/2+o,c=Math.PI*2/s,d=(s-2)*Math.PI/s/2;for(let u=0;u<s;u++){const p=u*c+l,g=t+i*Math.cos(p),y=e+i*Math.sin(p),m=p+Math.PI+d,x=p-Math.PI-d,S=g+r*Math.cos(m),v=y+r*Math.sin(m),b=g+r*Math.cos(x),P=y+r*Math.sin(x);u===0?this.moveTo(S,v):this.lineTo(S,v),this.quadraticCurveTo(g,y,b,P,a)}return this.closePath()}roundShape(t,e,i=!1,s){return t.length<3?this:(i?bg(this,t,e,s):vg(this,t,e),this.closePath())}filletRect(t,e,i,s,r){if(r===0)return this.rect(t,e,i,s);const o=Math.min(i,s)/2,a=Math.min(o,Math.max(-o,r)),h=t+i,l=e+s,c=a<0?-a:0,d=Math.abs(a);return this.moveTo(t,e+d).arcTo(t+c,e+c,t+d,e,d).lineTo(h-d,e).arcTo(h-c,e+c,h,e+d,d).lineTo(h,l-d).arcTo(h-c,l-c,t+i-d,l,d).lineTo(t+d,l).arcTo(t+c,l-c,t,l-d,d).closePath()}chamferRect(t,e,i,s,r,o){if(r<=0)return this.rect(t,e,i,s);const a=Math.min(r,Math.min(i,s)/2),h=t+i,l=e+s,c=[t+a,e,h-a,e,h,e+a,h,l-a,h-a,l,t+a,l,t,l-a,t,e+a];for(let d=c.length-1;d>=2;d-=2)c[d]===c[d-2]&&c[d-1]===c[d-3]&&c.splice(d-1,2);return this.poly(c,!0,o)}ellipse(t,e,i,s,r){return this.drawShape(new Cr(t,e,i,s),r),this}roundRect(t,e,i,s,r,o){return this.drawShape(new _r(t,e,i,s,r),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 Te,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 Te,t)){const e=this.shapePrimitives[this.shapePrimitives.length-1];if(e){let i=e.shape.x,s=e.shape.y;if(e.transform&&!e.transform.isIdentity()){const r=e.transform,o=i;i=r.a*i+r.c*s+r.tx,s=r.b*o+r.d*s+r.ty}this._currentPoly.points.push(i,s)}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 s=e[i],r=s.shape.getBounds(wg);s.transform?t.addRect(r,s.transform):t.addRect(r)}return t}}class te{constructor(t,e=!1){this.instructions=[],this.uid=ct("graphicsPath"),this._dirty=!0,this.checkForHoles=e,typeof t=="string"?Zp(t,this):this.instructions=(t==null?void 0:t.slice())??[]}get shapePath(){return this._shapePath||(this._shapePath=new Cg(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,s,r){const o=this.instructions[this.instructions.length-1],a=this.getLastPoint(Q.shared);let h=0,l=0;if(!o||o.action!=="bezierCurveTo")h=a.x,l=a.y;else{h=o.data[2],l=o.data[3];const c=a.x,d=a.y;h=c+(c-h),l=d+(d-l)}return this.instructions.push({action:"bezierCurveTo",data:[h,l,t,e,i,s,r]}),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 s=this.instructions[this.instructions.length-1],r=this.getLastPoint(Q.shared);let o=0,a=0;if(!s||s.action!=="quadraticCurveTo")o=r.x,a=r.y;else{o=s.data[0],a=s.data[1];const h=r.x,l=r.y;o=h+(h-o),a=l+(l-a)}return this.instructions.push({action:"quadraticCurveTo",data:[o,a,t,e,i]}),this._dirty=!0,this}rect(t,e,i,s,r){return this.instructions.push({action:"rect",data:[t,e,i,s,r]}),this._dirty=!0,this}circle(t,e,i,s){return this.instructions.push({action:"circle",data:[t,e,i,s]}),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,s,r,o,a){r||(r=s/2);const h=-1*Math.PI/2+o,l=i*2,c=Math.PI*2/l,d=[];for(let u=0;u<l;u++){const p=u%2?r:s,g=u*c+h;d.push(t+p*Math.cos(g),e+p*Math.sin(g))}return this.poly(d,!0,a),this}clone(t=!1){const e=new te;if(e.checkForHoles=this.checkForHoles,!t)e.instructions=this.instructions.slice();else for(let i=0;i<this.instructions.length;i++){const s=this.instructions[i];e.instructions.push({action:s.action,data:s.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,s=t.c,r=t.d,o=t.tx,a=t.ty;let h=0,l=0,c=0,d=0,u=0,p=0,g=0,y=0;for(let m=0;m<this.instructions.length;m++){const x=this.instructions[m],S=x.data;switch(x.action){case"moveTo":case"lineTo":h=S[0],l=S[1],S[0]=e*h+s*l+o,S[1]=i*h+r*l+a;break;case"bezierCurveTo":c=S[0],d=S[1],u=S[2],p=S[3],h=S[4],l=S[5],S[0]=e*c+s*d+o,S[1]=i*c+r*d+a,S[2]=e*u+s*p+o,S[3]=i*u+r*p+a,S[4]=e*h+s*l+o,S[5]=i*h+r*l+a;break;case"quadraticCurveTo":c=S[0],d=S[1],h=S[2],l=S[3],S[0]=e*c+s*d+o,S[1]=i*c+r*d+a,S[2]=e*h+s*l+o,S[3]=i*h+r*l+a;break;case"arcToSvg":h=S[5],l=S[6],g=S[0],y=S[1],S[0]=e*g+s*y,S[1]=i*g+r*y,S[5]=e*h+s*l+o,S[6]=i*h+r*l+a;break;case"circle":S[4]=fi(S[3],t);break;case"rect":S[4]=fi(S[4],t);break;case"ellipse":S[8]=fi(S[8],t);break;case"roundRect":S[5]=fi(S[5],t);break;case"addPath":S[0].transform(t);break;case"poly":S[2]=fi(S[2],t);break;default:st("unknown transform action",x.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 fi(n,t){return n?n.prepend(t):t.clone()}function ht(n,t,e){const i=n.getAttribute(t);return i?Number(i):e}function _g(n,t){const e=n.querySelectorAll("defs");for(let i=0;i<e.length;i++){const s=e[i];for(let r=0;r<s.children.length;r++){const o=s.children[r];switch(o.nodeName.toLowerCase()){case"lineargradient":t.defs[o.id]=Pg(o);break;case"radialgradient":t.defs[o.id]=Mg();break}}}}function Pg(n){const t=ht(n,"x1",0),e=ht(n,"y1",0),i=ht(n,"x2",1),s=ht(n,"y2",0),r=n.getAttribute("gradientUnits")||"objectBoundingBox",o=new Wt(t,e,i,s,r==="objectBoundingBox"?"local":"global");for(let a=0;a<n.children.length;a++){const h=n.children[a],l=ht(h,"offset",0),c=nt.shared.setValue(h.getAttribute("stop-color")).toNumber();o.addColorStop(l,c)}return o}function Mg(n){return st("[SVG Parser] Radial gradients are not yet supported"),new Wt(0,0,1,0)}function da(n){const t=n.match(/url\s*\(\s*['"]?\s*#([^'"\s)]+)\s*['"]?\s*\)/i);return t?t[1]:""}const ua={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 Il(n,t){const e=n.getAttribute("style"),i={},s={},r={strokeStyle:i,fillStyle:s,useFill:!1,useStroke:!1};for(const o in ua){const a=n.getAttribute(o);a&&pa(t,r,o,a.trim())}if(e){const o=e.split(";");for(let a=0;a<o.length;a++){const h=o[a].trim(),[l,c]=h.split(":");ua[l]&&pa(t,r,l,c.trim())}}return{strokeStyle:r.useStroke?i:null,fillStyle:r.useFill?s:null,useFill:r.useFill,useStroke:r.useStroke}}function pa(n,t,e,i){switch(e){case"stroke":if(i!=="none"){if(i.startsWith("url(")){const s=da(i);t.strokeStyle.fill=n.defs[s]}else t.strokeStyle.color=nt.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 s=da(i);t.fillStyle.fill=n.defs[s]}else t.fillStyle.color=nt.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 Tg(n){if(n.length<=2)return!0;const t=n.map(a=>a.area).sort((a,h)=>h-a),[e,i]=t,s=t[t.length-1],r=e/i,o=i/s;return!(r>3&&o<2)}function Ag(n){return n.split(/(?=[Mm])/).filter(i=>i.trim().length>0)}function Rg(n){const t=n.match(/[-+]?[0-9]*\.?[0-9]+/g);if(!t||t.length<4)return 0;const e=t.map(Number),i=[],s=[];for(let c=0;c<e.length;c+=2)c+1<e.length&&(i.push(e[c]),s.push(e[c+1]));if(i.length===0||s.length===0)return 0;const r=Math.min(...i),o=Math.max(...i),a=Math.min(...s),h=Math.max(...s);return(o-r)*(h-a)}function fa(n,t){const e=new te(n,!1);for(const i of e.instructions)t.instructions.push(i)}function kg(n,t){if(typeof n=="string"){const o=document.createElement("div");o.innerHTML=n.trim(),n=o.querySelector("svg")}const e={context:t,defs:{},path:new te};_g(n,e);const i=n.children,{fillStyle:s,strokeStyle:r}=Il(n,e);for(let o=0;o<i.length;o++){const a=i[o];a.nodeName.toLowerCase()!=="defs"&&Dl(a,e,s,r)}return t}function Dl(n,t,e,i){const s=n.children,{fillStyle:r,strokeStyle:o}=Il(n,t);r&&e?e={...e,...r}:r&&(e=r),o&&i?i={...i,...o}:o&&(i=o);const a=!e&&!i;a&&(e={color:0});let h,l,c,d,u,p,g,y,m,x,S,v,b,P,C,_,R;switch(n.nodeName.toLowerCase()){case"path":{P=n.getAttribute("d");const M=n.getAttribute("fill-rule"),A=Ag(P),T=M==="evenodd",I=A.length>1;if(T&&I){const B=A.map(k=>({path:k,area:Rg(k)}));if(B.sort((k,F)=>F.area-k.area),A.length>3||!Tg(B))for(let k=0;k<B.length;k++){const F=B[k],rt=k===0;t.context.beginPath();const L=new te(void 0,!0);fa(F.path,L),t.context.path(L),rt?(e&&t.context.fill(e),i&&t.context.stroke(i)):t.context.cut()}else for(let k=0;k<B.length;k++){const F=B[k],rt=k%2===1;t.context.beginPath();const L=new te(void 0,!0);fa(F.path,L),t.context.path(L),rt?t.context.cut():(e&&t.context.fill(e),i&&t.context.stroke(i))}}else{const B=M?M==="evenodd":!0;C=new te(P,B),t.context.path(C),e&&t.context.fill(e),i&&t.context.stroke(i)}break}case"circle":g=ht(n,"cx",0),y=ht(n,"cy",0),m=ht(n,"r",0),t.context.ellipse(g,y,m,m),e&&t.context.fill(e),i&&t.context.stroke(i);break;case"rect":h=ht(n,"x",0),l=ht(n,"y",0),_=ht(n,"width",0),R=ht(n,"height",0),x=ht(n,"rx",0),S=ht(n,"ry",0),x||S?t.context.roundRect(h,l,_,R,x||S):t.context.rect(h,l,_,R),e&&t.context.fill(e),i&&t.context.stroke(i);break;case"ellipse":g=ht(n,"cx",0),y=ht(n,"cy",0),x=ht(n,"rx",0),S=ht(n,"ry",0),t.context.beginPath(),t.context.ellipse(g,y,x,S),e&&t.context.fill(e),i&&t.context.stroke(i);break;case"line":c=ht(n,"x1",0),d=ht(n,"y1",0),u=ht(n,"x2",0),p=ht(n,"y2",0),t.context.beginPath(),t.context.moveTo(c,d),t.context.lineTo(u,p),i&&t.context.stroke(i);break;case"polygon":b=n.getAttribute("points"),v=b.match(/-?\d+/g).map(M=>parseInt(M,10)),t.context.poly(v,!0),e&&t.context.fill(e),i&&t.context.stroke(i);break;case"polyline":b=n.getAttribute("points"),v=b.match(/-?\d+/g).map(M=>parseInt(M,10)),t.context.poly(v,!1),i&&t.context.stroke(i);break;case"g":case"svg":break;default:{st(`[SVG parser] <${n.nodeName}> elements unsupported`);break}}a&&(e=null);for(let M=0;M<s.length;M++)Dl(s[M],t,e,i)}const ga={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 Fs{constructor(t,e){this.uid=ct("fillPattern"),this._tick=0,this.transform=new U,this.texture=t,this.transform.scale(1/t.frame.width,1/t.frame.height),e&&(t.source.style.addressModeU=ga[e].addressModeU,t.source.style.addressModeV=ga[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 Eg(n){return nt.isColorLike(n)}function ma(n){return n instanceof Fs}function ya(n){return n instanceof Wt}function Ig(n){return n instanceof O}function Dg(n,t,e){const i=nt.shared.setValue(t??0);return n.color=i.toNumber(),n.alpha=i.alpha===1?e.alpha:i.alpha,n.texture=O.WHITE,{...e,...n}}function Fg(n,t,e){return n.texture=t,{...e,...n}}function xa(n,t,e){return n.fill=t,n.color=16777215,n.texture=t.texture,n.matrix=t.transform,{...e,...n}}function Sa(n,t,e){return t.buildGradient(),n.fill=t,n.color=16777215,n.texture=t.texture,n.matrix=t.transform,n.textureSpace=t.textureSpace,{...e,...n}}function Bg(n,t){const e={...t,...n},i=nt.shared.setValue(e.color);return e.alpha*=i.alpha,e.color=i.toNumber(),e}function _e(n,t){if(n==null)return null;const e={},i=n;return Eg(n)?Dg(e,n,t):Ig(n)?Fg(e,n,t):ma(n)?xa(e,n,t):ya(n)?Sa(e,n,t):i.fill&&ma(i.fill)?xa(i,i.fill,t):i.fill&&ya(i.fill)?Sa(i,i.fill,t):Bg(i,t)}function bs(n,t){const{width:e,alignment:i,miterLimit:s,cap:r,join:o,pixelLine:a,...h}=t,l=_e(n,h);return l?{width:e,alignment:i,miterLimit:s,cap:r,join:o,pixelLine:a,...l}:null}const Lg=new Q,va=new U,Rr=class Nt extends Yt{constructor(){super(...arguments),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=ct("graphicsContext"),this.dirty=!0,this.batchMode="auto",this.instructions=[],this.destroyed=!1,this._activePath=new te,this._transform=new U,this._fillStyle={...Nt.defaultFillStyle},this._strokeStyle={...Nt.defaultStrokeStyle},this._stateStack=[],this._tick=0,this._bounds=new Dt,this._boundsDirty=!0}clone(){const t=new Nt;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=_e(t,Nt.defaultFillStyle)}get strokeStyle(){return this._strokeStyle}set strokeStyle(t){this._strokeStyle=bs(t,Nt.defaultStrokeStyle)}setFillStyle(t){return this._fillStyle=_e(t,Nt.defaultFillStyle),this}setStrokeStyle(t){return this._strokeStyle=_e(t,Nt.defaultStrokeStyle),this}texture(t,e,i,s,r,o){return this.instructions.push({action:"texture",data:{image:t,dx:i||0,dy:s||0,dw:r||t.frame.width,dh:o||t.frame.height,transform:this._transform.clone(),alpha:this._fillStyle.alpha,style:e||e===0?nt.shared.setValue(e).toNumber():16777215}}),this.onUpdate(),this}beginPath(){return this._activePath=new te,this}fill(t,e){let i;const s=this.instructions[this.instructions.length-1];return this._tick===0&&(s==null?void 0:s.action)==="stroke"?i=s.data.path:i=this._activePath.clone(),i?(t!=null&&(e!==void 0&&typeof t=="number"&&(N(K,"GraphicsContext.fill(color, alpha) is deprecated, use GraphicsContext.fill({ color, alpha }) instead"),t={color:t,alpha:e}),this._fillStyle=_e(t,Nt.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(Q.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=bs(t,Nt.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,s,r,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,s,r,o),this}arcTo(t,e,i,s,r){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*s+o.tx,o.b*i+o.d*s+o.ty,r),this}arcToSvg(t,e,i,s,r,o,a){this._tick++;const h=this._transform;return this._activePath.arcToSvg(t,e,i,s,r,h.a*o+h.c*a+h.tx,h.b*o+h.d*a+h.ty),this}bezierCurveTo(t,e,i,s,r,o,a){this._tick++;const h=this._transform;return this._activePath.bezierCurveTo(h.a*t+h.c*e+h.tx,h.b*t+h.d*e+h.ty,h.a*i+h.c*s+h.tx,h.b*i+h.d*s+h.ty,h.a*r+h.c*o+h.tx,h.b*r+h.d*o+h.ty,a),this}closePath(){var t;return this._tick++,(t=this._activePath)==null||t.closePath(),this}ellipse(t,e,i,s){return this._tick++,this._activePath.ellipse(t,e,i,s,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,s=this._activePath.instructions,r=i.a*t+i.c*e+i.tx,o=i.b*t+i.d*e+i.ty;return s.length===1&&s[0].action==="moveTo"?(s[0].data[0]=r,s[0].data[1]=o,this):(this._activePath.moveTo(r,o),this)}quadraticCurveTo(t,e,i,s,r){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*s+o.tx,o.b*i+o.d*s+o.ty,r),this}rect(t,e,i,s){return this._tick++,this._activePath.rect(t,e,i,s,this._transform.clone()),this}roundRect(t,e,i,s,r){return this._tick++,this._activePath.roundRect(t,e,i,s,r,this._transform.clone()),this}poly(t,e){return this._tick++,this._activePath.poly(t,e,this._transform.clone()),this}regularPoly(t,e,i,s,r=0,o){return this._tick++,this._activePath.regularPoly(t,e,i,s,r,o),this}roundPoly(t,e,i,s,r,o){return this._tick++,this._activePath.roundPoly(t,e,i,s,r,o),this}roundShape(t,e,i,s){return this._tick++,this._activePath.roundShape(t,e,i,s),this}filletRect(t,e,i,s,r){return this._tick++,this._activePath.filletRect(t,e,i,s,r),this}chamferRect(t,e,i,s,r,o){return this._tick++,this._activePath.chamferRect(t,e,i,s,r,o),this}star(t,e,i,s,r=0,o=0){return this._tick++,this._activePath.star(t,e,i,s,r,o,this._transform.clone()),this}svg(t){return this._tick++,kg(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,s,r,o){return t instanceof U?(this._transform.set(t.a,t.b,t.c,t.d,t.tx,t.ty),this):(this._transform.set(t,e,i,s,r,o),this)}transform(t,e,i,s,r,o){return t instanceof U?(this._transform.append(t),this):(va.set(t,e,i,s,r,o),this._transform.append(va),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&&(this.emit("update",this,16),this.dirty=!0)}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],s=i.action;if(s==="fill"){const r=i.data;t.addBounds(r.path.bounds)}else if(s==="texture"){const r=i.data;t.addFrame(r.dx,r.dy,r.dx+r.dw,r.dy+r.dh,r.transform)}if(s==="stroke"){const r=i.data,o=r.style.alignment,a=r.style.width*(1-o),h=r.path.bounds;t.addFrame(h.minX-a,h.minY-a,h.maxX+a,h.maxY+a)}}return t}containsPoint(t){var s;if(!this.bounds.containsPoint(t.x,t.y))return!1;const e=this.instructions;let i=!1;for(let r=0;r<e.length;r++){const o=e[r],a=o.data,h=a.path;if(!o.action||!h)continue;const l=a.style,c=h.shapePath.shapePrimitives;for(let d=0;d<c.length;d++){const u=c[d].shape;if(!l||!u)continue;const p=c[d].transform,g=p?p.applyInverse(t,Lg):t;if(o.action==="fill")i=u.contains(g.x,g.y);else{const m=l;i=u.strokeContains(g.x,g.y,m.width,m.alignment)}const y=a.hole;if(y){const m=(s=y.shapePath)==null?void 0:s.shapePrimitives;if(m)for(let x=0;x<m.length;x++)m[x].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}};Rr.defaultFillStyle={color:16777215,alpha:1,texture:O.WHITE,matrix:null,fill:null,textureSpace:"local"};Rr.defaultStrokeStyle={width:1,color:16777215,alpha:1,alignment:.5,miterLimit:10,cap:"butt",join:"miter",texture:O.WHITE,matrix:null,fill:null,textureSpace:"local",pixelLine:!1};let gt=Rr;function kr(n,t=1){var i;const e=(i=ri.RETINA_PREFIX)==null?void 0:i.exec(n);return e?parseFloat(e[1]):t}function Er(n,t,e){n.label=e,n._sourceOrigin=e;const i=new O({source:n,label:e}),s=()=>{delete t.promiseCache[e],yt.has(e)&&yt.remove(e)};return i.source.once("destroy",()=>{t.promiseCache[e]&&(st("[Assets] A TextureSource managed by Assets was destroyed instead of unloaded! Use Assets.unload() instead of destroying the TextureSource."),s())}),i.once("destroy",()=>{n.destroyed||(st("[Assets] A Texture managed by Assets was destroyed instead of unloaded! Use Assets.unload() instead of destroying the Texture."),s())}),i}const zg=".svg",Ir="image/svg+xml",Og={extension:{type:E.LoadParser,priority:ce.Low,name:"loadSVG"},name:"loadSVG",id:"svg",config:{crossOrigin:"anonymous",parseAsGraphicsContext:!1},test(n){return de(n,Ir)||oi(n,zg)},async load(n,t,e){var i;return((i=t.data)==null?void 0:i.parseAsGraphicsContext)??this.config.parseAsGraphicsContext?Ug(n):Wg(n,t,e,this.config.crossOrigin)},unload(n){n.destroy(!0)}};async function Wg(n,t,e,i){var m,x,S;const s=de(n,Ir),r=$.get().createImage();r.crossOrigin=i,r.src=n,await new Promise((v,b)=>{r.complete?v(r):(r.onload=()=>v(r),r.onerror=b)}),await r.decode();const o=((m=t.data)==null?void 0:m.width)??r.width,a=((x=t.data)==null?void 0:x.height)??r.height,h=((S=t.data)==null?void 0:S.resolution)||kr(n),l=Math.ceil(o*h),c=Math.ceil(a*h),d=$.get().createCanvas(l,c),u=d.getContext("2d");u.imageSmoothingEnabled=!0,u.imageSmoothingQuality="high",u.drawImage(r,0,0,o*h,a*h);const{parseAsGraphicsContext:p,...g}=t.data??{},y=new Je({resource:d,alphaMode:"premultiply-alpha-on-upload",resolution:h,...g});return Er(y,e,n)}function Gg(n){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let e="",i=0;for(n=n.replace(/[^A-Za-z0-9\+\/\=]/g,"");i<n.length;){const s=t.indexOf(n.charAt(i++)),r=t.indexOf(n.charAt(i++)),o=t.indexOf(n.charAt(i++)),a=t.indexOf(n.charAt(i++)),h=s<<2|r>>4,l=(r&15)<<4|o>>2,c=(o&3)<<6|a;e+=String.fromCharCode(h),o!==64&&(e+=String.fromCharCode(l)),a!==64&&(e+=String.fromCharCode(c))}return e}async function Ug(n){const t=de(n,Ir);let e;if(t)if(n.includes(";base64,")){const s=n.split(";base64,")[1];e=Gg(s)}else{const s=n.split(",")[1];e=decodeURIComponent(s)}else e=await(await $.get().fetch(n)).text();const i=new gt;return i.svg(e),i}const Hg=`(function () {
241
+ 'use strict';
242
+
243
+ const WHITE_PNG = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=";
244
+ async function checkImageBitmap() {
245
+ try {
246
+ if (typeof createImageBitmap !== "function") return false;
247
+ const response = await fetch(WHITE_PNG);
248
+ const imageBlob = await response.blob();
249
+ const imageBitmap = await createImageBitmap(imageBlob);
250
+ return imageBitmap.width === 1 && imageBitmap.height === 1;
251
+ } catch (_e) {
252
+ return false;
253
+ }
254
+ }
255
+ void checkImageBitmap().then((result) => {
256
+ self.postMessage(result);
257
+ });
258
+
259
+ })();
260
+ `;let Xe=null,sr=class{constructor(){Xe||(Xe=URL.createObjectURL(new Blob([Hg],{type:"application/javascript"}))),this.worker=new Worker(Xe)}};sr.revokeObjectURL=function(){Xe&&(URL.revokeObjectURL(Xe),Xe=null)};const Ng=`(function () {
261
+ 'use strict';
262
+
263
+ async function loadImageBitmap(url, alphaMode) {
264
+ const response = await fetch(url);
265
+ if (!response.ok) {
266
+ throw new Error(\`[WorkerManager.loadImageBitmap] Failed to fetch \${url}: \${response.status} \${response.statusText}\`);
267
+ }
268
+ const imageBlob = await response.blob();
269
+ return alphaMode === "premultiplied-alpha" ? createImageBitmap(imageBlob, { premultiplyAlpha: "none" }) : createImageBitmap(imageBlob);
270
+ }
271
+ self.onmessage = async (event) => {
272
+ try {
273
+ const imageBitmap = await loadImageBitmap(event.data.data[0], event.data.data[1]);
274
+ self.postMessage({
275
+ data: imageBitmap,
276
+ uuid: event.data.uuid,
277
+ id: event.data.id
278
+ }, [imageBitmap]);
279
+ } catch (e) {
280
+ self.postMessage({
281
+ error: e,
282
+ uuid: event.data.uuid,
283
+ id: event.data.id
284
+ });
285
+ }
286
+ };
287
+
288
+ })();
289
+ `;let je=null;class Fl{constructor(){je||(je=URL.createObjectURL(new Blob([Ng],{type:"application/javascript"}))),this.worker=new Worker(je)}}Fl.revokeObjectURL=function(){je&&(URL.revokeObjectURL(je),je=null)};let ba=0,Cn;class Vg{constructor(){this._initialized=!1,this._createdWorkers=0,this._workerPool=[],this._queue=[],this._resolveHash={}}isImageBitmapSupported(){return this._isImageBitmapSupported!==void 0?this._isImageBitmapSupported:(this._isImageBitmapSupported=new Promise(t=>{const{worker:e}=new sr;e.addEventListener("message",i=>{e.terminate(),sr.revokeObjectURL(),t(i.data)})}),this._isImageBitmapSupported)}loadImageBitmap(t,e){var i;return this._run("loadImageBitmap",[t,(i=e==null?void 0:e.data)==null?void 0:i.alphaMode])}async _initWorkers(){this._initialized||(this._initialized=!0)}_getWorker(){Cn===void 0&&(Cn=navigator.hardwareConcurrency||4);let t=this._workerPool.pop();return!t&&this._createdWorkers<Cn&&(this._createdWorkers++,t=new Fl().worker,t.addEventListener("message",e=>{this._complete(e.data),this._returnWorker(e.target),this._next()})),t}_returnWorker(t){this._workerPool.push(t)}_complete(t){this._resolveHash[t.uuid]&&(t.error!==void 0?this._resolveHash[t.uuid].reject(t.error):this._resolveHash[t.uuid].resolve(t.data),delete this._resolveHash[t.uuid])}async _run(t,e){await this._initWorkers();const i=new Promise((s,r)=>{this._queue.push({id:t,arguments:e,resolve:s,reject:r})});return this._next(),i}_next(){if(!this._queue.length)return;const t=this._getWorker();if(!t)return;const e=this._queue.pop(),i=e.id;this._resolveHash[ba]={resolve:e.resolve,reject:e.reject},t.postMessage({data:e.arguments,uuid:ba++,id:i})}reset(){this._workerPool.forEach(t=>t.terminate()),this._workerPool.length=0,Object.values(this._resolveHash).forEach(({reject:t})=>{t==null||t(new Error("WorkerManager has been reset before completion"))}),this._resolveHash={},this._queue.length=0,this._initialized=!1,this._createdWorkers=0}}const wa=new Vg,$g=[".jpeg",".jpg",".png",".webp",".avif"],Yg=["image/jpeg","image/png","image/webp","image/avif"];async function Xg(n,t){var s;const e=await $.get().fetch(n);if(!e.ok)throw new Error(`[loadImageBitmap] Failed to fetch ${n}: ${e.status} ${e.statusText}`);const i=await e.blob();return((s=t==null?void 0:t.data)==null?void 0:s.alphaMode)==="premultiplied-alpha"?createImageBitmap(i,{premultiplyAlpha:"none"}):createImageBitmap(i)}const Bl={name:"loadTextures",id:"texture",extension:{type:E.LoadParser,priority:ce.High,name:"loadTextures"},config:{preferWorkers:!0,preferCreateImageBitmap:!0,crossOrigin:"anonymous"},test(n){return de(n,Yg)||oi(n,$g)},async load(n,t,e){var r;let i=null;globalThis.createImageBitmap&&this.config.preferCreateImageBitmap?this.config.preferWorkers&&await wa.isImageBitmapSupported()?i=await wa.loadImageBitmap(n,t):i=await Xg(n,t):i=await new Promise((o,a)=>{i=$.get().createImage(),i.crossOrigin=this.config.crossOrigin,i.src=n,i.complete?o(i):(i.onload=()=>{o(i)},i.onerror=a)});const s=new Je({resource:i,alphaMode:"premultiply-alpha-on-upload",resolution:((r=t.data)==null?void 0:r.resolution)||kr(n),...t.data});return Er(s,e,n)},unload(n){n.destroy(!0)}},jg=[".mp4",".m4v",".webm",".ogg",".ogv",".h264",".avi",".mov"];let _n,Pn;function Zg(n,t,e){e===void 0&&!t.startsWith("data:")?n.crossOrigin=Kg(t):e!==!1&&(n.crossOrigin=typeof e=="string"?e:"anonymous")}function qg(n){return new Promise((t,e)=>{n.addEventListener("canplaythrough",i),n.addEventListener("error",s),n.load();function i(){r(),t()}function s(o){r(),e(o)}function r(){n.removeEventListener("canplaythrough",i),n.removeEventListener("error",s)}})}function Kg(n,t=globalThis.location){if(n.startsWith("data:"))return"";t||(t=globalThis.location);const e=new URL(n,document.baseURI);return e.hostname!==t.hostname||e.port!==t.port||e.protocol!==t.protocol?"anonymous":""}function Qg(){const n=[],t=[];for(const e of jg){const i=Ci.MIME_TYPES[e.substring(1)]||`video/${e.substring(1)}`;Es(i)&&(n.push(e),t.includes(i)||t.push(i))}return{validVideoExtensions:n,validVideoMime:t}}const Jg={name:"loadVideo",id:"video",extension:{type:E.LoadParser,name:"loadVideo"},test(n){if(!_n||!Pn){const{validVideoExtensions:i,validVideoMime:s}=Qg();_n=i,Pn=s}const t=de(n,Pn),e=oi(n,_n);return t||e},async load(n,t,e){var h,l;const i={...Ci.defaultOptions,resolution:((h=t.data)==null?void 0:h.resolution)||kr(n),alphaMode:((l=t.data)==null?void 0:l.alphaMode)||await Gh(),...t.data},s=document.createElement("video"),r={preload:i.autoLoad!==!1?"auto":void 0,"webkit-playsinline":i.playsinline!==!1?"":void 0,playsinline:i.playsinline!==!1?"":void 0,muted:i.muted===!0?"":void 0,loop:i.loop===!0?"":void 0,autoplay:i.autoPlay!==!1?"":void 0};Object.keys(r).forEach(c=>{const d=r[c];d!==void 0&&s.setAttribute(c,d)}),i.muted===!0&&(s.muted=!0),Zg(s,n,i.crossorigin);const o=document.createElement("source");let a;if(i.mime)a=i.mime;else if(n.startsWith("data:"))a=n.slice(5,n.indexOf(";"));else if(!n.startsWith("blob:")){const c=n.split("?")[0].slice(n.lastIndexOf(".")+1).toLowerCase();a=Ci.MIME_TYPES[c]||`video/${c}`}return o.src=n,a&&(o.type=a),new Promise((c,d)=>{i.preload&&!i.autoPlay&&s.load(),s.addEventListener("canplay",u),s.addEventListener("error",p),o.addEventListener("error",p),s.appendChild(o);async function u(){const y=new Ci({...i,resource:s});g(),t.data.preload&&await qg(s),c(Er(y,e,n))}function p(y){g(),d(y)}function g(){s.removeEventListener("canplay",u),s.removeEventListener("error",p),o.removeEventListener("error",p)}})},unload(n){n.destroy(!0)}},Ll={extension:{type:E.ResolveParser,name:"resolveTexture"},test:Bl.test,parse:n=>{var t;return{resolution:parseFloat(((t=ri.RETINA_PREFIX.exec(n))==null?void 0:t[1])??"1"),format:n.split(".").pop(),src:n}}},tm={extension:{type:E.ResolveParser,priority:-2,name:"resolveJson"},test:n=>ri.RETINA_PREFIX.test(n)&&n.endsWith(".json"),parse:Ll.parse};class em{constructor(){this._detections=[],this._initialized=!1,this.resolver=new ri,this.loader=new Ap,this.cache=yt,this._backgroundLoader=new Sp(this.loader),this._backgroundLoader.active=!0,this.reset()}async init(t={}){var r,o;if(this._initialized){st("[Assets]AssetManager already initialized, did you load before calling this Assets.init()?");return}if(this._initialized=!0,t.defaultSearchParams&&this.resolver.setDefaultSearchParams(t.defaultSearchParams),t.basePath&&(this.resolver.basePath=t.basePath),t.bundleIdentifier&&this.resolver.setBundleIdentifier(t.bundleIdentifier),t.manifest){let a=t.manifest;typeof a=="string"&&(a=await this.load(a)),this.resolver.addManifest(a)}const e=((r=t.texturePreference)==null?void 0:r.resolution)??1,i=typeof e=="number"?[e]:e,s=await this._detectFormats({preferredFormats:(o=t.texturePreference)==null?void 0:o.format,skipDetections:t.skipDetections,detections:this._detections});this.resolver.prefer({params:{format:s,resolution:i}}),t.preferences&&this.setPreferences(t.preferences),t.loadOptions&&(this.loader.loadOptions={...this.loader.loadOptions,...t.loadOptions})}add(t){this.resolver.add(t)}async load(t,e){this._initialized||await this.init();const i=xs(t),s=zt(t).map(a=>{if(typeof a!="string"){const h=this.resolver.getAlias(a);return h.some(l=>!this.resolver.hasKey(l))&&this.add(a),Array.isArray(h)?h[0]:h}return this.resolver.hasKey(a)||this.add({alias:a,src:a}),a}),r=this.resolver.resolve(s),o=await this._mapLoadToResolve(r,e);return i?o[s[0]]:o}addBundle(t,e){this.resolver.addBundle(t,e)}async loadBundle(t,e){this._initialized||await this.init();let i=!1;typeof t=="string"&&(i=!0,t=[t]);const s=this.resolver.resolveBundle(t),r={},o=Object.keys(s);let a=0;const h=[],l=()=>{e==null||e(h.reduce((d,u)=>d+u,0)/a)},c=o.map((d,u)=>{const p=s[d],g=Object.values(p),m=[...new Set(g.flat())].reduce((x,S)=>x+(S.progressSize||1),0);return h.push(0),a+=m,this._mapLoadToResolve(p,x=>{h[u]=x*m,l()}).then(x=>{r[d]=x})});return await Promise.all(c),i?r[t[0]]:r}async backgroundLoad(t){this._initialized||await this.init(),typeof t=="string"&&(t=[t]);const e=this.resolver.resolve(t);this._backgroundLoader.add(Object.values(e))}async backgroundLoadBundle(t){this._initialized||await this.init(),typeof t=="string"&&(t=[t]);const e=this.resolver.resolveBundle(t);Object.values(e).forEach(i=>{this._backgroundLoader.add(Object.values(i))})}reset(){this.resolver.reset(),this.loader.reset(),this.cache.reset(),this._initialized=!1}get(t){if(typeof t=="string")return yt.get(t);const e={};for(let i=0;i<t.length;i++)e[i]=yt.get(t[i]);return e}async _mapLoadToResolve(t,e){const i=[...new Set(Object.values(t))];this._backgroundLoader.active=!1;const s=await this.loader.load(i,e);this._backgroundLoader.active=!0;const r={};return i.forEach(o=>{const a=s[o.src],h=[o.src];o.alias&&h.push(...o.alias),h.forEach(l=>{r[l]=a}),yt.set(h,a)}),r}async unload(t){this._initialized||await this.init();const e=zt(t).map(s=>typeof s!="string"?s.src:s),i=this.resolver.resolve(e);await this._unloadFromResolved(i)}async unloadBundle(t){this._initialized||await this.init(),t=zt(t);const e=this.resolver.resolveBundle(t),i=Object.keys(e).map(s=>this._unloadFromResolved(e[s]));await Promise.all(i)}async _unloadFromResolved(t){const e=Object.values(t);e.forEach(i=>{yt.remove(i.src)}),await this.loader.unload(e)}async _detectFormats(t){let e=[];t.preferredFormats&&(e=Array.isArray(t.preferredFormats)?t.preferredFormats:[t.preferredFormats]);for(const i of t.detections)t.skipDetections||await i.test()?e=await i.add(e):t.skipDetections||(e=await i.remove(e));return e=e.filter((i,s)=>e.indexOf(i)===s),e}get detections(){return this._detections}setPreferences(t){this.loader.parsers.forEach(e=>{e.config&&Object.keys(e.config).filter(i=>i in t).forEach(i=>{e.config[i]=t[i]})})}}const V=new em;q.handleByList(E.LoadParser,V.loader.parsers).handleByList(E.ResolveParser,V.resolver.parsers).handleByList(E.CacheParser,V.cache.parsers).handleByList(E.DetectionParser,V.detections);q.add(vp,wp,bp,Tp,_p,Pp,Mp,Ep,Fp,Hp,Og,Bl,Jg,xp,yp,Ll,tm);const Ca={loader:E.LoadParser,resolver:E.ResolveParser,cache:E.CacheParser,detection:E.DetectionParser};q.handle(E.Asset,n=>{const t=n.ref;Object.entries(Ca).filter(([e])=>!!t[e]).forEach(([e,i])=>q.add(Object.assign(t[e],{extension:t[e].extension??i})))},n=>{const t=n.ref;Object.keys(Ca).filter(e=>!!t[e]).forEach(e=>q.remove(t[e]))});class zl{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 wu({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],s=i.element;if(!i.parent||i.globalDisplayStatus<7)s==null||s.remove(),t.splice(e,1),e--;else{this._domElement.contains(s)||(s.style.position="absolute",s.style.pointerEvents="auto",this._domElement.appendChild(s));const r=i.worldTransform,o=i._anchor,a=i.width*o.x,h=i.height*o.y;s.style.transformOrigin=`${a}px ${h}px`,s.style.transform=`matrix(${r.a}, ${r.b}, ${r.c}, ${r.d}, ${r.tx-a}, ${r.ty-h})`,s.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}}zl.extension={type:[E.WebGLPipes,E.WebGPUPipes,E.CanvasPipes],name:"dom"};q.add(zl);class im extends ni{constructor(t={}){const{element:e,anchor:i,...s}=t;super({label:"DOMContainer",...s}),this.renderPipeId="dom",this.batched=!1,this._anchor=new Q(0,0),i&&(this.anchor=i),this.element=t.element||document.createElement("div")}get anchor(){return this._anchor}set anchor(t){typeof t=="number"?this._anchor.set(t):this._anchor.copyFrom(t)}set element(t){this._element!==t&&(this._element=t,this.onViewUpdate())}get element(){return this._element}updateBounds(){const t=this._bounds,e=this._element;if(!e){t.minX=0,t.minY=0,t.maxX=0,t.maxY=0;return}const{offsetWidth:i,offsetHeight:s}=e;t.minX=0,t.maxX=i,t.minY=0,t.maxY=s}destroy(t=!1){var e,i;super.destroy(t),(i=(e=this._element)==null?void 0:e.parentNode)==null||i.removeChild(this._element),this._element=null,this._anchor=null}}class sm extends br{constructor(){super(...arguments),this.client=new Q,this.movement=new Q,this.offset=new Q,this.global=new Q,this.screen=new Q}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,s,r,o,a,h,l,c,d,u,p,g,y){throw new Error("Method not implemented.")}}class _a extends sm{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!")}}var nm=`in vec2 aPosition;
290
+ out vec2 vTextureCoord;
291
+
292
+ uniform vec4 uInputSize;
293
+ uniform vec4 uOutputFrame;
294
+ uniform vec4 uOutputTexture;
295
+
296
+ vec4 filterVertexPosition( void )
297
+ {
298
+ vec2 position = aPosition * uOutputFrame.zw + uOutputFrame.xy;
299
+
300
+ position.x = position.x * (2.0 / uOutputTexture.x) - 1.0;
301
+ position.y = position.y * (2.0*uOutputTexture.z / uOutputTexture.y) - uOutputTexture.z;
302
+
303
+ return vec4(position, 0.0, 1.0);
304
+ }
305
+
306
+ vec2 filterTextureCoord( void )
307
+ {
308
+ return aPosition * (uOutputFrame.zw * uInputSize.zw);
309
+ }
310
+
311
+ void main(void)
312
+ {
313
+ gl_Position = filterVertexPosition();
314
+ vTextureCoord = filterTextureCoord();
315
+ }
316
+ `,rm=`
317
+ in vec2 vTextureCoord;
318
+
319
+ out vec4 finalColor;
320
+
321
+ uniform float uAlpha;
322
+ uniform sampler2D uTexture;
323
+
324
+ void main()
325
+ {
326
+ finalColor = texture(uTexture, vTextureCoord) * uAlpha;
327
+ }
328
+ `,Pa=`struct GlobalFilterUniforms {
329
+ uInputSize:vec4<f32>,
330
+ uInputPixel:vec4<f32>,
331
+ uInputClamp:vec4<f32>,
332
+ uOutputFrame:vec4<f32>,
333
+ uGlobalFrame:vec4<f32>,
334
+ uOutputTexture:vec4<f32>,
335
+ };
336
+
337
+ struct AlphaUniforms {
338
+ uAlpha:f32,
339
+ };
340
+
341
+ @group(0) @binding(0) var<uniform> gfu: GlobalFilterUniforms;
342
+ @group(0) @binding(1) var uTexture: texture_2d<f32>;
343
+ @group(0) @binding(2) var uSampler : sampler;
344
+
345
+ @group(1) @binding(0) var<uniform> alphaUniforms : AlphaUniforms;
346
+
347
+ struct VSOutput {
348
+ @builtin(position) position: vec4<f32>,
349
+ @location(0) uv : vec2<f32>
350
+ };
351
+
352
+ fn filterVertexPosition(aPosition:vec2<f32>) -> vec4<f32>
353
+ {
354
+ var position = aPosition * gfu.uOutputFrame.zw + gfu.uOutputFrame.xy;
355
+
356
+ position.x = position.x * (2.0 / gfu.uOutputTexture.x) - 1.0;
357
+ position.y = position.y * (2.0*gfu.uOutputTexture.z / gfu.uOutputTexture.y) - gfu.uOutputTexture.z;
358
+
359
+ return vec4(position, 0.0, 1.0);
360
+ }
361
+
362
+ fn filterTextureCoord( aPosition:vec2<f32> ) -> vec2<f32>
363
+ {
364
+ return aPosition * (gfu.uOutputFrame.zw * gfu.uInputSize.zw);
365
+ }
366
+
367
+ fn globalTextureCoord( aPosition:vec2<f32> ) -> vec2<f32>
368
+ {
369
+ return (aPosition.xy / gfu.uGlobalFrame.zw) + (gfu.uGlobalFrame.xy / gfu.uGlobalFrame.zw);
370
+ }
371
+
372
+ fn getSize() -> vec2<f32>
373
+ {
374
+ return gfu.uGlobalFrame.zw;
375
+ }
376
+
377
+ @vertex
378
+ fn mainVertex(
379
+ @location(0) aPosition : vec2<f32>,
380
+ ) -> VSOutput {
381
+ return VSOutput(
382
+ filterVertexPosition(aPosition),
383
+ filterTextureCoord(aPosition)
384
+ );
385
+ }
386
+
387
+ @fragment
388
+ fn mainFragment(
389
+ @location(0) uv: vec2<f32>,
390
+ @builtin(position) position: vec4<f32>
391
+ ) -> @location(0) vec4<f32> {
392
+
393
+ var sample = textureSample(uTexture, uSampler, uv);
394
+
395
+ return sample * alphaUniforms.uAlpha;
396
+ }`;const Ol=class Wl extends Vu{constructor(t){t={...Wl.defaultOptions,...t};const e=he.from({vertex:{source:Pa,entryPoint:"mainVertex"},fragment:{source:Pa,entryPoint:"mainFragment"}}),i=ti.from({vertex:nm,fragment:rm,name:"alpha-filter"}),{alpha:s,...r}=t,o=new ei({uAlpha:{value:s,type:"f32"}});super({...r,gpuProgram:e,glProgram:i,resources:{alphaUniforms:o}})}get alpha(){return this.resources.alphaUniforms.uniforms.uAlpha}set alpha(t){this.resources.alphaUniforms.uniforms.uAlpha=t}};Ol.defaultOptions={alpha:1};let om=Ol;function Ma(n,t,e,i,s,r,o,a){const h=o-e,l=a-i,c=s-e,d=r-i,u=n-e,p=t-i,g=h*h+l*l,y=h*c+l*d,m=h*u+l*p,x=c*c+d*d,S=c*u+d*p,v=1/(g*x-y*y),b=(x*m-y*S)*v,P=(g*S-y*m)*v;return b>=0&&P>=0&&b+P<1}class am{constructor(){this.isBatchable=!1}reset(){this.isBatchable=!1,this.context=null,this.graphicsData&&(this.graphicsData.destroy(),this.graphicsData=null)}destroy(){this.reset()}}class hm{constructor(){this.instructions=new Sr}init(){this.instructions.reset()}destroy(){this.instructions.destroy(),this.instructions=null}}const Dr=class nr{constructor(t){this._renderer=t,this._managedContexts=new ai({renderer:t,type:"resource",name:"graphicsContext"})}init(t){nr.defaultOptions.bezierSmoothness=(t==null?void 0:t.bezierSmoothness)??nr.defaultOptions.bezierSmoothness}getContextRenderData(t){return this.getGpuContext(t).graphicsData||this._initContextRenderData(t)}updateGpuContext(t){const e=t._gpuData,i=!!e[this._renderer.uid],s=e[this._renderer.uid]||this._initContext(t);return(t.dirty||!i)&&(i&&s.reset(),s.isBatchable=!1,t.dirty=!1),s}getGpuContext(t){return t._gpuData[this._renderer.uid]||this._initContext(t)}_initContextRenderData(t){const e=new hm,i=this.getGpuContext(t);return i.graphicsData=e,e.init(),e}_initContext(t){const e=new am;return e.context=t,t._gpuData[this._renderer.uid]=e,this._managedContexts.add(t),e}destroy(){this._managedContexts.destroy(),this._renderer=null}};Dr.extension={type:[E.CanvasSystem],name:"graphicsContext"};Dr.defaultOptions={bezierSmoothness:.5};let lm=Dr;class Gl{constructor(t,e){this.state=Ui.for2d(),this.renderer=t,this._adaptor=e,this.renderer.runners.contextChange.add(this),this._managedGraphics=new ai({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}}Gl.extension={type:[E.CanvasPipes],name:"graphics"};function Fr(n,t,e){const i=(n>>24&255)/255;t[e++]=(n&255)/255*i,t[e++]=(n>>8&255)/255*i,t[e++]=(n>>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 Ul{constructor(t,e){this.state=Ui.for2d(),this.renderer=t,this._adaptor=e,this.renderer.runners.contextChange.add(this),this._managedGraphics=new ai({renderer:t,type:"renderable",priority:-1,name:"graphics"})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(t){const e=t.context,i=!!t._gpuData,r=this.renderer.graphicsContext.updateGpuContext(e);return!!(r.isBatchable||i!==r.isBatchable)}addRenderable(t,e){const s=this.renderer.graphicsContext.updateGpuContext(t.context);t.didViewUpdate&&this._rebuild(t),s.isBatchable?this._addToBatcher(t,e):(this.renderer.renderPipes.batch.break(e),e.add(t))}updateRenderable(t){const i=this._getGpuDataForRenderable(t).batches;for(let s=0;s<i.length;s++){const r=i[s];r._batcher.updateElement(r)}}execute(t){if(!t.isRenderable)return;const e=this.renderer,i=t.context;if(!e.graphicsContext.getGpuContext(i).batches.length)return;const r=i.customShader||this._adaptor.shader;this.state.blendMode=t.groupBlendMode;const o=r.resources.localUniforms.uniforms;o.uTransformMatrix=t.groupTransform,o.uRound=e._roundPixels|t._roundPixels,Fr(t.groupColorAlpha,o.uColor,0),this._adaptor.execute(this,t)}_rebuild(t){const e=this._getGpuDataForRenderable(t),s=this.renderer.graphicsContext.updateGpuContext(t.context);e.destroy(),s.isBatchable&&this._updateBatchesForRenderable(t,e)}_addToBatcher(t,e){const i=this.renderer.renderPipes.batch,s=this._getGpuDataForRenderable(t).batches;for(let r=0;r<s.length;r++){const o=s[r];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,r=this.renderer.graphicsContext.getGpuContext(i),o=this.renderer._roundPixels|t._roundPixels;e.batches=r.batches.map(a=>{const h=Mt.get(Pr);return a.copyTo(h),h.renderable=t,h.roundPixels=o,h})}destroy(){this._managedGraphics.destroy(),this.renderer=null,this._adaptor.destroy(),this._adaptor=null,this.state=null}}Ul.extension={type:[E.WebGLPipes,E.WebGPUPipes],name:"graphics"};q.add(Gl);q.add(Ul);q.add(lm);q.add(Ar);class H extends ni{constructor(t){t instanceof gt&&(t={context:t});const{context:e,roundPixels:i,...s}=t||{};super({label:"Graphics",...s}),this.renderPipeId="graphics",e?this.context=e:(this.context=this._ownedContext=new gt,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 H(this._context.clone()):(this._ownedContext=null,new H(this._context))}lineStyle(t,e,i){N(K,"Graphics#lineStyle is no longer needed. Use Graphics#setStrokeStyle to set the stroke style.");const s={};return t&&(s.width=t),e&&(s.color=e),i&&(s.alpha=i),this.context.strokeStyle=s,this}beginFill(t,e){N(K,"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(){N(K,"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!==gt.defaultStrokeStyle.width||t.color!==gt.defaultStrokeStyle.color||t.alpha!==gt.defaultStrokeStyle.alpha)&&this.context.stroke(),this}drawCircle(...t){return N(K,"Graphics#drawCircle has been renamed to Graphics#circle"),this._callContextMethod("circle",t)}drawEllipse(...t){return N(K,"Graphics#drawEllipse has been renamed to Graphics#ellipse"),this._callContextMethod("ellipse",t)}drawPolygon(...t){return N(K,"Graphics#drawPolygon has been renamed to Graphics#poly"),this._callContextMethod("poly",t)}drawRect(...t){return N(K,"Graphics#drawRect has been renamed to Graphics#rect"),this._callContextMethod("rect",t)}drawRoundedRect(...t){return N(K,"Graphics#drawRoundedRect has been renamed to Graphics#roundRect"),this._callContextMethod("roundRect",t)}drawStar(...t){return N(K,"Graphics#drawStar has been renamed to Graphics#star"),this._callContextMethod("star",t)}}const Hl=class Nl extends Bi{constructor(...t){let e=t[0]??{};e instanceof Float32Array&&(N(K,"use new MeshGeometry({ positions, uvs, indices }) instead"),e={positions:e,uvs:t[1],indices:t[2]}),e={...Nl.defaultOptions,...e};const i=e.positions||new Float32Array([0,0,1,0,1,1,0,1]);let s=e.uvs;s||(e.positions?s=new Float32Array(i.length):s=new Float32Array([0,0,1,0,1,1,0,1]));const r=e.indices||new Uint32Array([0,1,2,0,2,3]),o=e.shrinkBuffersToFit,a=new oe({data:i,label:"attribute-mesh-positions",shrinkToFit:o,usage:ft.VERTEX|ft.COPY_DST}),h=new oe({data:s,label:"attribute-mesh-uvs",shrinkToFit:o,usage:ft.VERTEX|ft.COPY_DST}),l=new oe({data:r,label:"index-mesh-buffer",shrinkToFit:o,usage:ft.INDEX|ft.COPY_DST});super({attributes:{aPosition:{buffer:a,format:"float32x2",stride:2*4,offset:0},aUV:{buffer:h,format:"float32x2",stride:2*4,offset:0}},indexBuffer:l,topology:e.topology}),this.batchMode="auto"}get positions(){return this.attributes.aPosition.buffer.data}set positions(t){this.attributes.aPosition.buffer.data=t}get uvs(){return this.attributes.aUV.buffer.data}set uvs(t){this.attributes.aUV.buffer.data=t}get indices(){return this.indexBuffer.data}set indices(t){this.indexBuffer.data=t}};Hl.defaultOptions={topology:"triangle-list",shrinkBuffersToFit:!1};let Br=Hl;class Vl{constructor(){this.batcherName="default",this.packAsQuad=!1,this.indexOffset=0,this.attributeOffset=0,this.roundPixels=0,this._batcher=null,this._batch=null,this._textureMatrixUpdateId=-1,this._uvUpdateId=-1}get blendMode(){return this.renderable.groupBlendMode}get topology(){return this._topology||this.geometry.topology}set topology(t){this._topology=t}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.geometry=null,this._uvUpdateId=-1,this._textureMatrixUpdateId=-1}setTexture(t){this.texture!==t&&(this.texture=t,this._textureMatrixUpdateId=-1)}get uvs(){const e=this.geometry.getBuffer("aUV"),i=e.data;let s=i;const r=this.texture.textureMatrix;return r.isSimple||(s=this._transformedUvs,(this._textureMatrixUpdateId!==r._updateID||this._uvUpdateId!==e._updateID)&&((!s||s.length<i.length)&&(s=this._transformedUvs=new Float32Array(i.length)),this._textureMatrixUpdateId=r._updateID,this._uvUpdateId=e._updateID,r.multiplyUvs(i,s))),s}get positions(){return this.geometry.positions}get indices(){return this.geometry.indices}get color(){return this.renderable.groupColorAlpha}get groupTransform(){return this.renderable.groupTransform}get attributeSize(){return this.geometry.positions.length/2}get indexSize(){return this.geometry.indices.length}}class Ta{destroy(){}}class $l{constructor(t,e){this.localUniforms=new ei({uTransformMatrix:{value:new U,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}}),this.localUniformsBindGroup=new _i({0:this.localUniforms}),this.renderer=t,this._adaptor=e,this._adaptor.init()}validateRenderable(t){const e=this._getMeshData(t),i=e.batched,s=t.batched;if(e.batched=s,i!==s)return!0;if(s){const r=t._geometry;if(r.indices.length!==e.indexSize||r.positions.length!==e.vertexSize)return e.indexSize=r.indices.length,e.vertexSize=r.positions.length,!0;const o=this._getBatchableMesh(t);return o.texture.uid!==t._texture.uid&&(o._textureMatrixUpdateId=-1),!o._batcher.checkAndUpdateTexture(o,t._texture)}return!1}addRenderable(t,e){var r,o;const i=this.renderer.renderPipes.batch,s=this._getMeshData(t);if(t.didViewUpdate&&(s.indexSize=(r=t._geometry.indices)==null?void 0:r.length,s.vertexSize=(o=t._geometry.positions)==null?void 0:o.length),s.batched){const a=this._getBatchableMesh(t);a.setTexture(t._texture),a.geometry=t._geometry,i.addToBatch(a,e)}else i.break(e),e.add(t)}updateRenderable(t){if(t.batched){const e=this._getBatchableMesh(t);e.setTexture(t._texture),e.geometry=t._geometry,e._batcher.updateElement(e)}}execute(t){if(!t.isRenderable)return;t.state.blendMode=Ss(t.groupBlendMode,t.texture._source);const e=this.localUniforms;e.uniforms.uTransformMatrix=t.groupTransform,e.uniforms.uRound=this.renderer._roundPixels|t._roundPixels,e.update(),Fr(t.groupColorAlpha,e.uniforms.uColor,0),this._adaptor.execute(this,t)}_getMeshData(t){var e,i;return(e=t._gpuData)[i=this.renderer.uid]||(e[i]=new Ta),t._gpuData[this.renderer.uid].meshData||this._initMeshData(t)}_initMeshData(t){return t._gpuData[this.renderer.uid].meshData={batched:t.batched,indexSize:0,vertexSize:0},t._gpuData[this.renderer.uid].meshData}_getBatchableMesh(t){var e,i;return(e=t._gpuData)[i=this.renderer.uid]||(e[i]=new Ta),t._gpuData[this.renderer.uid].batchableMesh||this._initBatchableMesh(t)}_initBatchableMesh(t){const e=new Vl;return e.renderable=t,e.setTexture(t._texture),e.transform=t.groupTransform,e.roundPixels=this.renderer._roundPixels|t._roundPixels,t._gpuData[this.renderer.uid].batchableMesh=e,e}destroy(){this.localUniforms=null,this.localUniformsBindGroup=null,this._adaptor.destroy(),this._adaptor=null,this.renderer=null}}$l.extension={type:[E.WebGLPipes,E.WebGPUPipes],name:"mesh"};q.add($l);class Aa extends ni{constructor(...t){let e=t[0];e instanceof Bi&&(N(K,"Mesh: use new Mesh({ geometry, shader }) instead"),e={geometry:e,shader:t[1]},t[3]&&(N(K,"Mesh: drawMode argument has been removed, use geometry.topology instead"),e.geometry.topology=t[3]));const{geometry:i,shader:s,texture:r,roundPixels:o,state:a,...h}=e;super({label:"Mesh",...h}),this.renderPipeId="mesh",this._shader=null,this.allowChildren=!1,this.shader=s??null,this.texture=r??(s==null?void 0:s.texture)??O.WHITE,this.state=a??Ui.for2d(),this._geometry=i,this._geometry.on("update",this.onViewUpdate,this),this.roundPixels=o??!1}get material(){return N(K,"mesh.material property has been removed, use mesh.shader instead"),this._shader}set shader(t){this._shader!==t&&(this._shader=t,this.onViewUpdate())}get shader(){return this._shader}set geometry(t){var e;this._geometry!==t&&((e=this._geometry)==null||e.off("update",this.onViewUpdate,this),t.on("update",this.onViewUpdate,this),this._geometry=t,this.onViewUpdate())}get geometry(){return this._geometry}set texture(t){t||(t=O.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.shader&&(this.shader.texture=t),this._texture=t,this.onViewUpdate())}get texture(){return this._texture}get batched(){return this._shader||this.state.data&12?!1:this._geometry instanceof Br?this._geometry.batchMode==="auto"?this._geometry.positions.length/2<=100:this._geometry.batchMode==="batch":!1}get bounds(){return this._geometry.bounds}updateBounds(){this._bounds=this._geometry.bounds}containsPoint(t){const{x:e,y:i}=t;if(!this.bounds.containsPoint(e,i))return!1;const s=this.geometry.getBuffer("aPosition").data,r=this.geometry.topology==="triangle-strip"?3:1;if(this.geometry.getIndex()){const o=this.geometry.getIndex().data,a=o.length;for(let h=0;h+2<a;h+=r){const l=o[h]*2,c=o[h+1]*2,d=o[h+2]*2;if(Ma(e,i,s[l],s[l+1],s[c],s[c+1],s[d],s[d+1]))return!0}}else{const o=s.length/2;for(let a=0;a+2<o;a+=r){const h=a*2,l=(a+1)*2,c=(a+2)*2;if(Ma(e,i,s[h],s[h+1],s[l],s[l+1],s[c],s[c+1]))return!0}}return!1}destroy(t){var i;if(super.destroy(t),typeof t=="boolean"?t:t==null?void 0:t.texture){const s=typeof t=="boolean"?t:t==null?void 0:t.textureSource;this._texture.destroy(s)}(i=this._geometry)==null||i.off("update",this.onViewUpdate,this),this._texture=null,this._geometry=null,this._shader=null}}class ws extends $t{constructor(...t){let e=t[0];Array.isArray(t[0])&&(e={textures:t[0],autoUpdate:t[1]});const{animationSpeed:i=1,autoPlay:s=!1,autoUpdate:r=!0,loop:o=!0,onComplete:a=null,onFrameChange:h=null,onLoop:l=null,textures:c,updateAnchor:d=!1,...u}=e,[p]=c;super({...u,texture:p instanceof O?p:p.texture}),this._textures=null,this._durations=null,this._autoUpdate=r,this._isConnectedToTicker=!1,this.animationSpeed=i,this.loop=o,this.updateAnchor=d,this.onComplete=a,this.onFrameChange=h,this.onLoop=l,this._currentTime=0,this._playing=!1,this._previousFrame=null,this.textures=c,s&&this.play()}stop(){this._playing&&(this._playing=!1,this._autoUpdate&&this._isConnectedToTicker&&(mt.shared.remove(this.update,this),this._isConnectedToTicker=!1))}play(){this._playing||(this._playing=!0,this._autoUpdate&&!this._isConnectedToTicker&&(mt.shared.add(this.update,this,Ie.HIGH),this._isConnectedToTicker=!0))}gotoAndStop(t){this.stop(),this.currentFrame=t}gotoAndPlay(t){this.currentFrame=t,this.play()}update(t){if(!this._playing)return;const e=t.deltaTime,i=this.animationSpeed*e,s=this.currentFrame;if(this._durations!==null){let r=this._currentTime%1*this._durations[this.currentFrame];for(r+=i/60*1e3;r<0;)this._currentTime--,r+=this._durations[this.currentFrame];const o=Math.sign(this.animationSpeed*e);for(this._currentTime=Math.floor(this._currentTime);r>=this._durations[this.currentFrame];)r-=this._durations[this.currentFrame]*o,this._currentTime+=o;this._currentTime+=r/this._durations[this.currentFrame]}else this._currentTime+=i;this._currentTime<0&&!this.loop?(this.gotoAndStop(0),this.onComplete&&this.onComplete()):this._currentTime>=this._textures.length&&!this.loop?(this.gotoAndStop(this._textures.length-1),this.onComplete&&this.onComplete()):s!==this.currentFrame&&(this.loop&&this.onLoop&&(this.animationSpeed>0&&this.currentFrame<s||this.animationSpeed<0&&this.currentFrame>s)&&this.onLoop(),this._updateTexture())}_updateTexture(){const t=this.currentFrame;this._previousFrame!==t&&(this._previousFrame=t,this.texture=this._textures[t],this.updateAnchor&&this.texture.defaultAnchor&&this.anchor.copyFrom(this.texture.defaultAnchor),this.onFrameChange&&this.onFrameChange(this.currentFrame))}destroy(t=!1){if(typeof t=="boolean"?t:t==null?void 0:t.texture){const i=typeof t=="boolean"?t:t==null?void 0:t.textureSource;this._textures.forEach(s=>{this.texture!==s&&s.destroy(i)})}this._textures=[],this._durations=null,this.stop(),super.destroy(t),this.onComplete=null,this.onFrameChange=null,this.onLoop=null}static fromFrames(t){const e=[];for(let i=0;i<t.length;++i)e.push(O.from(t[i]));return new ws(e)}static fromImages(t){const e=[];for(let i=0;i<t.length;++i)e.push(O.from(t[i]));return new ws(e)}get totalFrames(){return this._textures.length}get textures(){return this._textures}set textures(t){if(t[0]instanceof O)this._textures=t,this._durations=null;else{this._textures=[],this._durations=[];for(let e=0;e<t.length;e++)this._textures.push(t[e].texture),this._durations.push(t[e].time)}this._previousFrame=null,this.gotoAndStop(0),this._updateTexture()}get currentFrame(){let t=Math.floor(this._currentTime)%this._textures.length;return t<0&&(t+=this._textures.length),t}set currentFrame(t){if(t<0||t>this.totalFrames-1)throw new Error(`[AnimatedSprite]: Invalid frame index value ${t}, expected to be between 0 and totalFrames ${this.totalFrames}.`);const e=this.currentFrame;this._currentTime=t,e!==this.currentFrame&&this._updateTexture()}get playing(){return this._playing}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){t!==this._autoUpdate&&(this._autoUpdate=t,!this._autoUpdate&&this._isConnectedToTicker?(mt.shared.remove(this.update,this),this._isConnectedToTicker=!1):this._autoUpdate&&!this._isConnectedToTicker&&this._playing&&(mt.shared.add(this.update,this),this._isConnectedToTicker=!0))}}class dm{constructor({matrix:t,observer:e}={}){this.dirty=!0,this._matrix=t??new U,this.observer=e,this.position=new lt(this,0,0),this.scale=new lt(this,1,1),this.pivot=new lt(this,0,0),this.skew=new lt(this,0,0),this._rotation=0,this._cx=1,this._sx=0,this._cy=0,this._sy=1}get matrix(){const t=this._matrix;return this.dirty&&(t.a=this._cx*this.scale.x,t.b=this._sx*this.scale.x,t.c=this._cy*this.scale.y,t.d=this._sy*this.scale.y,t.tx=this.position.x-(this.pivot.x*t.a+this.pivot.y*t.c),t.ty=this.position.y-(this.pivot.x*t.b+this.pivot.y*t.d),this.dirty=!1),t}_onUpdate(t){var e;this.dirty=!0,t===this.skew&&this.updateSkew(),(e=this.observer)==null||e._onUpdate(this)}updateSkew(){this._cx=Math.cos(this._rotation+this.skew.y),this._sx=Math.sin(this._rotation+this.skew.y),this._cy=-Math.sin(this._rotation-this.skew.x),this._sy=Math.cos(this._rotation-this.skew.x),this.dirty=!0}toString(){return`[pixi.js/math:Transform position=(${this.position.x}, ${this.position.y}) rotation=${this.rotation} scale=(${this.scale.x}, ${this.scale.y}) skew=(${this.skew.x}, ${this.skew.y}) ]`}setFromMatrix(t){t.decompose(this),this.dirty=!0}get rotation(){return this._rotation}set rotation(t){this._rotation!==t&&(this._rotation=t,this._onUpdate(this.skew))}}let Ge;function Ra(n){const t=$.get().createCanvas(6,1),e=t.getContext("2d");return e.fillStyle=n,e.fillRect(0,0,6,1),t}function um(){if(Ge!==void 0)return Ge;try{const n=Ra("#ff00ff"),t=Ra("#ffff00"),i=$.get().createCanvas(6,1).getContext("2d");i.globalCompositeOperation="multiply",i.drawImage(n,0,0),i.drawImage(t,2,0);const s=i.getImageData(2,0,1,1);if(!s)Ge=!1;else{const r=s.data;Ge=r[0]===255&&r[1]===0&&r[2]===0}}catch{Ge=!1}return Ge}const it={canvas:null,convertTintToImage:!1,cacheStepsPerColorChannel:8,canUseMultiply:um(),tintMethod:null,_canvasSourceCache:new WeakMap,_unpremultipliedCache:new WeakMap,getCanvasSource:n=>{const t=n.source,e=t==null?void 0:t.resource;if(!e)return null;const i=t.alphaMode==="premultiplied-alpha",s=t.resourceWidth??t.pixelWidth,r=t.resourceHeight??t.pixelHeight,o=s!==t.pixelWidth||r!==t.pixelHeight;if(i){if((e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)&&!o)return e;const a=it._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=it._canvasSourceCache.get(t);if((a==null?void 0:a.resourceId)===t._resourceId)return a.canvas;const h=$.get().createCanvas(t.pixelWidth,t.pixelHeight),l=h.getContext("2d"),c=l.createImageData(t.pixelWidth,t.pixelHeight),d=c.data,u=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(t.format==="bgra8unorm")for(let p=0;p<d.length&&p+3<u.length;p+=4)d[p]=u[p+2],d[p+1]=u[p+1],d[p+2]=u[p],d[p+3]=u[p+3];else d.set(u.subarray(0,d.length));return l.putImageData(c,0,0),it._canvasSourceCache.set(t,{canvas:h,resourceId:t._resourceId}),h}if(i){const a=$.get().createCanvas(t.pixelWidth,t.pixelHeight),h=a.getContext("2d",{willReadFrequently:!0});a.width=t.pixelWidth,a.height=t.pixelHeight,h.drawImage(e,0,0);const l=h.getImageData(0,0,a.width,a.height),c=l.data;for(let d=0;d<c.length;d+=4){const u=c[d+3];if(u>0){const p=255/u;c[d]=Math.min(255,c[d]*p+.5),c[d+1]=Math.min(255,c[d+1]*p+.5),c[d+2]=Math.min(255,c[d+2]*p+.5)}}return h.putImageData(l,0,0),it._unpremultipliedCache.set(t,{canvas:a,resourceId:t._resourceId}),a}if(o){const a=it._canvasSourceCache.get(t);if((a==null?void 0:a.resourceId)===t._resourceId)return a.canvas;const h=$.get().createCanvas(t.pixelWidth,t.pixelHeight),l=h.getContext("2d");return h.width=t.pixelWidth,h.height=t.pixelHeight,l.drawImage(e,0,0),it._canvasSourceCache.set(t,{canvas:h,resourceId:t._resourceId}),h}return e},getTintedCanvas:(n,t)=>{const e=n.texture,i=nt.shared.setValue(t).toHex(),s=e.tintCache||(e.tintCache={}),r=s[i],o=e.source._resourceId;if((r==null?void 0:r.tintId)===o)return r;const a=r&&"getContext"in r?r:$.get().createCanvas();return it.tintMethod(e,t,a),a.tintId=o,s[i]=a,s[i]},getTintedPattern:(n,t)=>{const e=nt.shared.setValue(t).toHex(),i=n.patternCache||(n.patternCache={}),s=n.source._resourceId;let r=i[e];return(r==null?void 0:r.tintId)===s||(it.canvas||(it.canvas=$.get().createCanvas()),it.tintMethod(n,t,it.canvas),r=it.canvas.getContext("2d").createPattern(it.canvas,"repeat"),r.tintId=s,i[e]=r),r},applyPatternTransform:(n,t,e=!0)=>{if(!t)return;const i=n;if(!i.setTransform)return;const s=globalThis.DOMMatrix;if(!s)return;const r=new s([t.a,t.b,t.c,t.d,t.tx,t.ty]);i.setTransform(e?r.inverse():r)},tintWithMultiply:(n,t,e)=>{const i=e.getContext("2d"),s=n.frame.clone(),r=n.source._resolution??n.source.resolution??1,o=n.rotate;s.x*=r,s.y*=r,s.width*=r,s.height*=r;const a=X.isVertical(o),h=a?s.height:s.width,l=a?s.width:s.height;e.width=Math.ceil(h),e.height=Math.ceil(l),i.save(),i.fillStyle=nt.shared.setValue(t).toHex(),i.fillRect(0,0,h,l),i.globalCompositeOperation="multiply";const c=it.getCanvasSource(n);if(!c){i.restore();return}o&&it._applyInverseRotation(i,o,s.width,s.height),i.drawImage(c,s.x,s.y,s.width,s.height,0,0,s.width,s.height),i.globalCompositeOperation="destination-atop",i.drawImage(c,s.x,s.y,s.width,s.height,0,0,s.width,s.height),i.restore()},tintWithOverlay:(n,t,e)=>{const i=e.getContext("2d"),s=n.frame.clone(),r=n.source._resolution??n.source.resolution??1,o=n.rotate;s.x*=r,s.y*=r,s.width*=r,s.height*=r;const a=X.isVertical(o),h=a?s.height:s.width,l=a?s.width:s.height;e.width=Math.ceil(h),e.height=Math.ceil(l),i.save(),i.globalCompositeOperation="copy",i.fillStyle=nt.shared.setValue(t).toHex(),i.fillRect(0,0,h,l),i.globalCompositeOperation="destination-atop";const c=it.getCanvasSource(n);if(!c){i.restore();return}o&&it._applyInverseRotation(i,o,s.width,s.height),i.drawImage(c,s.x,s.y,s.width,s.height,0,0,s.width,s.height),i.restore()},tintWithPerPixel:(n,t,e)=>{const i=e.getContext("2d"),s=n.frame.clone(),r=n.source._resolution??n.source.resolution??1,o=n.rotate;s.x*=r,s.y*=r,s.width*=r,s.height*=r;const a=X.isVertical(o),h=a?s.height:s.width,l=a?s.width:s.height;e.width=Math.ceil(h),e.height=Math.ceil(l),i.save(),i.globalCompositeOperation="copy";const c=it.getCanvasSource(n);if(!c){i.restore();return}o&&it._applyInverseRotation(i,o,s.width,s.height),i.drawImage(c,s.x,s.y,s.width,s.height,0,0,s.width,s.height),i.restore();const d=t>>16&255,u=t>>8&255,p=t&255,g=i.getImageData(0,0,h,l),y=g.data;for(let m=0;m<y.length;m+=4)y[m]=y[m]*d/255,y[m+1]=y[m+1]*u/255,y[m+2]=y[m+2]*p/255;i.putImageData(g,0,0)},_applyInverseRotation:(n,t,e,i)=>{const s=X.inv(t),r=X.uX(s),o=X.uY(s),a=X.vX(s),h=X.vY(s),l=-Math.min(0,r*e,a*i,r*e+a*i),c=-Math.min(0,o*e,h*i,o*e+h*i);n.transform(r,o,a,h,l,c)}};it.tintMethod=it.canUseMultiply?it.tintWithMultiply:it.tintWithPerPixel;const rs=new U,gi=new U,Ut=[new Q,new Q,new Q,new Q];class Yl{constructor(t){this._renderer=t}validateRenderable(t){return!1}addRenderable(t,e){this._renderer.renderPipes.batch.break(e),e.add(t)}updateRenderable(t){}execute(t){var _,R;const e=this._renderer,i=e.canvasContext,s=i.activeContext;s.save(),i.setBlendMode(t.groupBlendMode);const r=((_=e.globalUniforms.globalUniformData)==null?void 0:_.worldColor)??4294967295,o=t.groupColorAlpha,a=(r>>>24&255)/255,h=(o>>>24&255)/255,l=((R=e.filter)==null?void 0:R.alphaMultiplier)??1,c=a*h*l;if(c<=0){s.restore();return}s.globalAlpha=c;const d=r&16777215,u=o&16777215,p=wi(xr(u,d)),g=t.texture,y=it.getTintedPattern(g,p),m=t.width,x=t.height,S=t.groupTransform,v=g.source._resolution??g.source.resolution??1;gi.copyFrom(t._tileTransform.matrix),t.applyAnchorToTexture||gi.translate(-t.anchor.x*m,-t.anchor.y*x),gi.scale(1/v,1/v),rs.identity(),rs.prepend(gi),rs.prepend(S);const b=e._roundPixels|t._roundPixels;i.setContextTransform(rs,b===1),s.fillStyle=y;const P=t.anchor.x*-m,C=t.anchor.y*-x;Ut[0].set(P,C),Ut[1].set(P+m,C),Ut[2].set(P+m,C+x),Ut[3].set(P,C+x);for(let M=0;M<4;M++)gi.applyInverse(Ut[M],Ut[M]);s.beginPath(),s.moveTo(Ut[0].x,Ut[0].y);for(let M=1;M<4;M++)s.lineTo(Ut[M].x,Ut[M].y);s.closePath(),s.fill(),s.restore()}destroy(){this._renderer=null}}Yl.extension={type:[E.CanvasPipes],name:"tilingSprite"};const ps={name:"local-uniform-bit",vertex:{header:`
397
+
398
+ struct LocalUniforms {
399
+ uTransformMatrix:mat3x3<f32>,
400
+ uColor:vec4<f32>,
401
+ uRound:f32,
402
+ }
403
+
404
+ @group(1) @binding(0) var<uniform> localUniforms : LocalUniforms;
405
+ `,main:`
406
+ vColor *= localUniforms.uColor;
407
+ modelMatrix *= localUniforms.uTransformMatrix;
408
+ `,end:`
409
+ if(localUniforms.uRound == 1)
410
+ {
411
+ vPosition = vec4(roundPixels(vPosition.xy, globalUniforms.uResolution), vPosition.zw);
412
+ }
413
+ `}},iv={...ps,vertex:{...ps.vertex,header:ps.vertex.header.replace("group(1)","group(2)")}},pm={name:"local-uniform-bit",vertex:{header:`
414
+
415
+ uniform mat3 uTransformMatrix;
416
+ uniform vec4 uColor;
417
+ uniform float uRound;
418
+ `,main:`
419
+ vColor *= uColor;
420
+ modelMatrix = uTransformMatrix;
421
+ `,end:`
422
+ if(uRound == 1.)
423
+ {
424
+ gl_Position.xy = roundPixels(gl_Position.xy, uResolution);
425
+ }
426
+ `}},fm={name:"tiling-bit",vertex:{header:`
427
+ struct TilingUniforms {
428
+ uMapCoord:mat3x3<f32>,
429
+ uClampFrame:vec4<f32>,
430
+ uClampOffset:vec2<f32>,
431
+ uTextureTransform:mat3x3<f32>,
432
+ uSizeAnchor:vec4<f32>
433
+ };
434
+
435
+ @group(2) @binding(0) var<uniform> tilingUniforms: TilingUniforms;
436
+ @group(2) @binding(1) var uTexture: texture_2d<f32>;
437
+ @group(2) @binding(2) var uSampler: sampler;
438
+ `,main:`
439
+ uv = (tilingUniforms.uTextureTransform * vec3(uv, 1.0)).xy;
440
+
441
+ position = (position - tilingUniforms.uSizeAnchor.zw) * tilingUniforms.uSizeAnchor.xy;
442
+ `},fragment:{header:`
443
+ struct TilingUniforms {
444
+ uMapCoord:mat3x3<f32>,
445
+ uClampFrame:vec4<f32>,
446
+ uClampOffset:vec2<f32>,
447
+ uTextureTransform:mat3x3<f32>,
448
+ uSizeAnchor:vec4<f32>
449
+ };
450
+
451
+ @group(2) @binding(0) var<uniform> tilingUniforms: TilingUniforms;
452
+ @group(2) @binding(1) var uTexture: texture_2d<f32>;
453
+ @group(2) @binding(2) var uSampler: sampler;
454
+ `,main:`
455
+
456
+ var coord = vUV + ceil(tilingUniforms.uClampOffset - vUV);
457
+ coord = (tilingUniforms.uMapCoord * vec3(coord, 1.0)).xy;
458
+ var unclamped = coord;
459
+ coord = clamp(coord, tilingUniforms.uClampFrame.xy, tilingUniforms.uClampFrame.zw);
460
+
461
+ var bias = 0.;
462
+
463
+ if(unclamped.x == coord.x && unclamped.y == coord.y)
464
+ {
465
+ bias = -32.;
466
+ }
467
+
468
+ outColor = textureSampleBias(uTexture, uSampler, coord, bias);
469
+ `}},gm={name:"tiling-bit",vertex:{header:`
470
+ uniform mat3 uTextureTransform;
471
+ uniform vec4 uSizeAnchor;
472
+
473
+ `,main:`
474
+ uv = (uTextureTransform * vec3(aUV, 1.0)).xy;
475
+
476
+ position = (position - uSizeAnchor.zw) * uSizeAnchor.xy;
477
+ `},fragment:{header:`
478
+ uniform sampler2D uTexture;
479
+ uniform mat3 uMapCoord;
480
+ uniform vec4 uClampFrame;
481
+ uniform vec2 uClampOffset;
482
+ `,main:`
483
+
484
+ vec2 coord = vUV + ceil(uClampOffset - vUV);
485
+ coord = (uMapCoord * vec3(coord, 1.0)).xy;
486
+ vec2 unclamped = coord;
487
+ coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);
488
+
489
+ outColor = texture(uTexture, coord, unclamped == coord ? 0.0 : -32.0);// lod-bias very negative to force lod 0
490
+
491
+ `}};let Mn,Tn;class mm extends De{constructor(){Mn??(Mn=bl({name:"tiling-sprite-shader",bits:[ps,fm,Cl]})),Tn??(Tn=wl({name:"tiling-sprite-shader",bits:[pm,gm,_l]}));const t=new ei({uMapCoord:{value:new U,type:"mat3x3<f32>"},uClampFrame:{value:new Float32Array([0,0,1,1]),type:"vec4<f32>"},uClampOffset:{value:new Float32Array([0,0]),type:"vec2<f32>"},uTextureTransform:{value:new U,type:"mat3x3<f32>"},uSizeAnchor:{value:new Float32Array([100,100,.5,.5]),type:"vec4<f32>"}});super({glProgram:Tn,gpuProgram:Mn,resources:{localUniforms:new ei({uTransformMatrix:{value:new U,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}}),tilingUniforms:t,uTexture:O.EMPTY.source,uSampler:O.EMPTY.source.style}})}updateUniforms(t,e,i,s,r,o){const a=this.resources.tilingUniforms,h=o.width,l=o.height,c=o.textureMatrix,d=a.uniforms.uTextureTransform;d.set(i.a*h/t,i.b*h/e,i.c*l/t,i.d*l/e,i.tx/t,i.ty/e),d.invert(),a.uniforms.uMapCoord=c.mapCoord,a.uniforms.uClampFrame=c.uClampFrame,a.uniforms.uClampOffset=c.uClampOffset,a.uniforms.uTextureTransform=d,a.uniforms.uSizeAnchor[0]=t,a.uniforms.uSizeAnchor[1]=e,a.uniforms.uSizeAnchor[2]=s,a.uniforms.uSizeAnchor[3]=r,o&&(this.resources.uTexture=o.source,this.resources.uSampler=o.source.style)}}class ym extends Br{constructor(){super({positions:new Float32Array([0,0,1,0,1,1,0,1]),uvs:new Float32Array([0,0,1,0,1,1,0,1]),indices:new Uint32Array([0,1,2,0,2,3])})}}function xm(n,t){const e=n.anchor.x,i=n.anchor.y;t[0]=-e*n.width,t[1]=-i*n.height,t[2]=(1-e)*n.width,t[3]=-i*n.height,t[4]=(1-e)*n.width,t[5]=(1-i)*n.height,t[6]=-e*n.width,t[7]=(1-i)*n.height}function Sm(n,t,e,i){let s=0;const r=n.length/t,o=i.a,a=i.b,h=i.c,l=i.d,c=i.tx,d=i.ty;for(e*=t;s<r;){const u=n[e],p=n[e+1];n[e]=o*u+h*p+c,n[e+1]=a*u+l*p+d,e+=t,s++}}function vm(n,t){const e=n.texture,i=e.frame.width,s=e.frame.height;let r=0,o=0;n.applyAnchorToTexture&&(r=n.anchor.x,o=n.anchor.y),t[0]=t[6]=-r,t[2]=t[4]=1-r,t[1]=t[3]=-o,t[5]=t[7]=1-o;const a=U.shared;a.copyFrom(n._tileTransform.matrix),a.tx/=n.width,a.ty/=n.height,a.invert(),a.scale(n.width/i,n.height/s),Sm(t,2,0,a)}const fs=new ym;class bm{constructor(){this.canBatch=!0,this.geometry=new Br({indices:fs.indices.slice(),positions:fs.positions.slice(),uvs:fs.uvs.slice()})}destroy(){var t;this.geometry.destroy(),(t=this.shader)==null||t.destroy()}}class Xl{constructor(t){this._state=Ui.default2d,this._renderer=t,this._managedTilingSprites=new ai({renderer:t,type:"renderable",name:"tilingSprite"})}validateRenderable(t){const e=this._getTilingSpriteData(t),i=e.canBatch;this._updateCanBatch(t);const s=e.canBatch;if(s&&s===i){const{batchableMesh:r}=e;return!r._batcher.checkAndUpdateTexture(r,t.texture)}return i!==s}addRenderable(t,e){const i=this._renderer.renderPipes.batch;this._updateCanBatch(t);const s=this._getTilingSpriteData(t),{geometry:r,canBatch:o}=s;if(o){s.batchableMesh||(s.batchableMesh=new Vl);const a=s.batchableMesh;t.didViewUpdate&&(this._updateBatchableMesh(t),a.geometry=r,a.renderable=t,a.transform=t.groupTransform,a.setTexture(t._texture)),a.roundPixels=this._renderer._roundPixels|t._roundPixels,i.addToBatch(a,e)}else i.break(e),s.shader||(s.shader=new mm),this.updateRenderable(t),e.add(t)}execute(t){const e=this._renderer,{shader:i}=this._getTilingSpriteData(t);i.groups[0]=e.globalUniforms.bindGroup;const s=i.resources.localUniforms.uniforms;s.uTransformMatrix=t.groupTransform,s.uRound=e._roundPixels|t._roundPixels,Fr(t.groupColorAlpha,s.uColor,0),this._state.blendMode=Ss(t.groupBlendMode,t.texture._source),e.encoder.draw({geometry:fs,shader:i,state:this._state})}updateRenderable(t){const e=this._getTilingSpriteData(t),{canBatch:i}=e;if(i){const{batchableMesh:s}=e;t.didViewUpdate&&this._updateBatchableMesh(t),s._batcher.updateElement(s)}else if(t.didViewUpdate){const{shader:s}=e;s.updateUniforms(t.width,t.height,t._tileTransform.matrix,t.anchor.x,t.anchor.y,t.texture)}}_getTilingSpriteData(t){return t._gpuData[this._renderer.uid]||this._initTilingSpriteData(t)}_initTilingSpriteData(t){const e=new bm;return e.renderable=t,t._gpuData[this._renderer.uid]=e,this._managedTilingSprites.add(t),e}_updateBatchableMesh(t){const e=this._getTilingSpriteData(t),{geometry:i}=e,s=t.texture.source.style;s.addressMode!=="repeat"&&(s.addressMode="repeat",s.update()),vm(t,i.uvs),xm(t,i.positions)}destroy(){this._managedTilingSprites.destroy(),this._renderer=null}_updateCanBatch(t){const e=this._getTilingSpriteData(t),i=t.texture;let s=!0;return this._renderer.type===Qt.WEBGL&&(s=this._renderer.context.supports.nonPowOf2wrapping),e.canBatch=i.textureMatrix.isSimple&&(s||i.source.isPowerOfTwo),e.canBatch}}Xl.extension={type:[E.WebGLPipes,E.WebGPUPipes],name:"tilingSprite"};q.add(Yl);q.add(Xl);const jl=class gs extends ni{constructor(...t){let e=t[0]||{};e instanceof O&&(e={texture:e}),t.length>1&&(N(K,"use new TilingSprite({ texture, width:100, height:100 }) instead"),e.width=t[1],e.height=t[2]),e={...gs.defaultOptions,...e};const{texture:i,anchor:s,tilePosition:r,tileScale:o,tileRotation:a,width:h,height:l,applyAnchorToTexture:c,roundPixels:d,...u}=e??{};super({label:"TilingSprite",...u}),this.renderPipeId="tilingSprite",this.batched=!0,this.allowChildren=!1,this._anchor=new lt({_onUpdate:()=>{this.onViewUpdate()}}),this.applyAnchorToTexture=c,this.texture=i,this._width=h??i.width,this._height=l??i.height,this._tileTransform=new dm({observer:{_onUpdate:()=>this.onViewUpdate()}}),s&&(this.anchor=s),this.tilePosition=r,this.tileScale=o,this.tileRotation=a,this.roundPixels=d??!1}static from(t,e={}){return typeof t=="string"?new gs({texture:yt.get(t),...e}):new gs({texture:t,...e})}get uvRespectAnchor(){return N(K,"uvRespectAnchor is deprecated, please use applyAnchorToTexture instead"),this.applyAnchorToTexture}set uvRespectAnchor(t){N(K,"uvRespectAnchor is deprecated, please use applyAnchorToTexture instead"),this.applyAnchorToTexture=t}get clampMargin(){return this._texture.textureMatrix.clampMargin}set clampMargin(t){this._texture.textureMatrix.clampMargin=t}get anchor(){return this._anchor}set anchor(t){typeof t=="number"?this._anchor.set(t):this._anchor.copyFrom(t)}get tilePosition(){return this._tileTransform.position}set tilePosition(t){this._tileTransform.position.copyFrom(t)}get tileScale(){return this._tileTransform.scale}set tileScale(t){typeof t=="number"?this._tileTransform.scale.set(t):this._tileTransform.scale.copyFrom(t)}set tileRotation(t){this._tileTransform.rotation=t}get tileRotation(){return this._tileTransform.rotation}get tileTransform(){return this._tileTransform}set texture(t){t||(t=O.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.onViewUpdate())}get texture(){return this._texture}set width(t){this._width=t,this.onViewUpdate()}get width(){return this._width}set height(t){this._height=t,this.onViewUpdate()}get height(){return this._height}setSize(t,e){typeof t=="object"&&(e=t.height??t.width,t=t.width),this._width=t,this._height=e??t,this.onViewUpdate()}getSize(t){return t||(t={}),t.width=this._width,t.height=this._height,t}updateBounds(){const t=this._bounds,e=this._anchor,i=this._width,s=this._height;t.minX=-e._x*i,t.maxX=t.minX+i,t.minY=-e._y*s,t.maxY=t.minY+s}containsPoint(t){const e=this._width,i=this._height,s=-e*this._anchor._x;let r=0;return t.x>=s&&t.x<=s+e&&(r=-i*this._anchor._y,t.y>=r&&t.y<=r+i)}destroy(t=!1){if(super.destroy(t),this._anchor=null,this._tileTransform=null,this._bounds=null,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}};jl.defaultOptions={texture:O.EMPTY,anchor:{x:0,y:0},tilePosition:{x:0,y:0},tileScale:{x:1,y:1},tileRotation:0,applyAnchorToTexture:!1};let Cs=jl;class wm extends ni{constructor(t,e){const{text:i,resolution:s,style:r,anchor:o,width:a,height:h,roundPixels:l,...c}=t;super({...c}),this.batched=!0,this._resolution=null,this._autoResolution=!0,this._didTextUpdate=!0,this._styleClass=e,this.text=i??"",this.style=r,this.resolution=s??null,this.allowChildren=!1,this._anchor=new lt({_onUpdate:()=>{this.onViewUpdate()}}),o&&(this.anchor=o),this.roundPixels=l??!1,a!==void 0&&(this.width=a),h!==void 0&&(this.height=h)}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,s=-e*this.anchor.x;let r=0;return t.x>=s&&t.x<=s+e&&(r=-i*this.anchor.y,t.y>=r&&t.y<=r+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 Cm(n,t){let e=n[0]??{};return(typeof e=="string"||n[1])&&(N(K,`use new ${t}({ text: "hi!", style }) instead`),e={text:e,style:n[1]}),e}class _m{constructor(t){this._canvasPool=Object.create(null),this.canvasOptions=t||{},this.enableFullScreen=!1}_createCanvasAndContext(t,e){const i=$.get().createCanvas();i.width=t,i.height=e;const s=i.getContext("2d");return{canvas:i,context:s}}getOptimalCanvasAndContext(t,e,i=1){t=Math.ceil(t*i-1e-6),e=Math.ceil(e*i-1e-6),t=qe(t),e=qe(e);const s=(t<<17)+(e<<1);this._canvasPool[s]||(this._canvasPool[s]=[]);let r=this._canvasPool[s].pop();return r||(r=this._createCanvasAndContext(t,e)),r}returnCanvasAndContext(t){const e=t.canvas,{width:i,height:s}=e,r=(i<<17)+(s<<1);t.context.resetTransform(),t.context.clearRect(0,0,i,s),this._canvasPool[r].push(t)}clear(){this._canvasPool={}}}const rr=new _m;Gi.register(rr);let ye=null,Kt=null;function Pm(n,t){ye||(ye=$.get().createCanvas(256,128),Kt=ye.getContext("2d",{willReadFrequently:!0}),Kt.globalCompositeOperation="copy",Kt.globalAlpha=1),(ye.width<n||ye.height<t)&&(ye.width=qe(n),ye.height=qe(t))}function ka(n,t,e){for(let i=0,s=4*e*t;i<t;++i,s+=4)if(n[s+3]!==0)return!1;return!0}function Ea(n,t,e,i,s){const r=4*t;for(let o=i,a=i*r+4*e;o<=s;++o,a+=r)if(n[a+3]!==0)return!1;return!0}function Mm(...n){let t=n[0];t.canvas||(t={canvas:n[0],resolution:n[1]});const{canvas:e}=t,i=Math.min(t.resolution??1,1),s=t.width??e.width,r=t.height??e.height;let o=t.output;if(Pm(s,r),!Kt)throw new TypeError("Failed to get canvas 2D context");Kt.drawImage(e,0,0,s,r,0,0,s*i,r*i);const h=Kt.getImageData(0,0,s,r).data;let l=0,c=0,d=s-1,u=r-1;for(;c<r&&ka(h,s,c);)++c;if(c===r)return J.EMPTY;for(;ka(h,s,u);)--u;for(;Ea(h,s,l,c,u);)++l;for(;Ea(h,s,d,c,u);)--d;return++d,++u,Kt.globalCompositeOperation="source-over",Kt.strokeRect(l,c,d-l,u-c),Kt.globalCompositeOperation="copy",o??(o=new J),o.set(l/i,c/i,(d-l)/i,(u-c)/i),o}/**
492
+ * tiny-lru
493
+ *
494
+ * @copyright 2026 Jason Mulligan <jason.mulligan@avoidwork.com>
495
+ * @license BSD-3-Clause
496
+ * @version 11.4.7
497
+ */class Tm{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 s=t[i];e[i]=[s,this.get(s)]}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 s=null;if(this.has(t))this.set(t,e,!0,i);else{this.max>0&&this.size===this.max&&(s={...this.first},this.evict(!0));let r=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=r:this.last.next=r,this.last=r}return s}set(t,e,i=!1,s=this.resetTtl){let r=this.items[t];return i||r!==void 0?(r.value=e,i===!1&&s&&(r.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl),this.moveToEnd(r)):(this.max>0&&this.size===this.max&&this.evict(!0),r=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=r:this.last.next=r,this.last=r),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 Am(n=1e3,t=0,e=!1){if(isNaN(n)||n<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 Tm(n,t,e)}function Zl(n){return!!n.tagStyles&&Object.keys(n.tagStyles).length>0}function ql(n){return n.includes("<")}function Rm(n,t){return n.clone().assign(t)}function km(n,t){const e=[],i=t.tagStyles;if(!Zl(t)||!ql(n))return e.push({text:n,style:t}),e;const s=[t],r=[];let o="",a=0;for(;a<n.length;){const h=n[a];if(h==="<"){const l=n.indexOf(">",a);if(l===-1){o+=h,a++;continue}const c=n.slice(a+1,l);if(c.startsWith("/")){const d=c.slice(1).trim();if(r.length>0&&r[r.length-1]===d){o.length>0&&(e.push({text:o,style:s[s.length-1]}),o=""),s.pop(),r.pop(),a=l+1;continue}else{o+=n.slice(a,l+1),a=l+1;continue}}else{const d=c.trim();if(i[d]){o.length>0&&(e.push({text:o,style:s[s.length-1]}),o="");const u=s[s.length-1],p=Rm(u,i[d]);s.push(p),r.push(d),a=l+1;continue}else{o+=n.slice(a,l+1),a=l+1;continue}}}else o+=h,a++}return o.length>0&&e.push({text:o,style:s[s.length-1]}),e}const Em=[10,13],Im=new Set(Em),Dm=[9,32,8192,8193,8194,8195,8196,8197,8198,8200,8201,8202,8287,12288],Fm=new Set(Dm),Bm=/(\r\n|\r|\n)/,Lm=/(?:\r\n|\r|\n)/;function Lr(n){return typeof n!="string"?!1:Im.has(n.charCodeAt(0))}function Ot(n,t){return typeof n!="string"?!1:Fm.has(n.charCodeAt(0))}function Kl(n){return n==="normal"||n==="pre-line"}function Ql(n){return n==="normal"}function qt(n){if(typeof n!="string")return"";let t=n.length-1;for(;t>=0&&Ot(n[t]);)t--;return t<n.length-1?n.slice(0,t+1):n}function Jl(n){const t=[],e=[];if(typeof n!="string")return t;for(let i=0;i<n.length;i++){const s=n[i],r=n[i+1];if(Ot(s)||Lr(s)){e.length>0&&(t.push(e.join("")),e.length=0),s==="\r"&&r===`
498
+ `?(t.push(`\r
499
+ `),i++):t.push(s);continue}e.push(s)}return e.length>0&&t.push(e.join("")),t}function tc(n,t,e,i){const s=e(n),r=[];for(let o=0;o<s.length;o++){let a=s[o],h=a,l=1;for(;s[o+l];){const c=s[o+l];if(!i(h,c,n,o,t))a+=c,h=c,l++;else break}o+=l-1,r.push(a)}return r}const zm=/\r\n|\r|\n/g;function Om(n,t,e,i,s,r,o,a){var B;const h=km(n,t);if(Ql(t.whiteSpace))for(let j=0;j<h.length;j++){const k=h[j];h[j]={text:k.text.replace(zm," "),style:k.style}}const c=[];let d=[];for(const j of h){const k=j.text.split(Bm);for(let F=0;F<k.length;F++){const rt=k[F];rt===`\r
500
+ `||rt==="\r"||rt===`
501
+ `?(c.push(d),d=[]):rt.length>0&&d.push({text:rt,style:j.style})}}(d.length>0||c.length===0)&&c.push(d);const u=e?Wm(c,t,i,s,o,a):c,p=[],g=[],y=[],m=[],x=[];let S=0;const v=t._fontString,b=r(v);b.fontSize===0&&(b.fontSize=t.fontSize,b.ascent=t.fontSize);let P="",C=!!t.dropShadow;for(const j of u){let k=0,F=b.ascent,rt=b.descent,L="";for(const Y of j){const at=Y.style._fontString,bt=r(at);at!==P&&(i.font=at,P=at);const wt=s(Y.text,Y.style.letterSpacing,i);k+=wt,F=Math.max(F,bt.ascent),rt=Math.max(rt,bt.descent),L+=Y.text,!C&&Y.style.dropShadow&&(C=!0)}j.length===0&&(F=b.ascent,rt=b.descent),p.push(k),g.push(F),y.push(rt),x.push(L);const Z=t.lineHeight||F+rt;m.push(Z+t.leading),S=Math.max(S,k)}const _=((B=t._stroke)==null?void 0:B.width)||0,A=(e&&t.align!=="left"&&t.align!=="justify"?Math.max(S,t.wordWrapWidth):S)+_+(t.dropShadow?t.dropShadow.distance:0);let T=0;for(let j=0;j<m.length;j++)T+=m[j];T=Math.max(T,m[0]+_);const I=T+(t.dropShadow?t.dropShadow.distance:0),D=t.lineHeight||b.fontSize;return{width:A,height:I,lines:x,lineWidths:p,lineHeight:D+t.leading,maxLineWidth:S,fontProperties:b,runsByLine:u,lineAscents:g,lineDescents:y,lineHeights:m,hasDropShadow:C}}function Wm(n,t,e,i,s,r){var m;const{letterSpacing:o,whiteSpace:a,wordWrapWidth:h,breakWords:l}=t,c=Kl(a),d=h+o,u={};let p="";const g=(x,S)=>{const v=`${x}|${S.styleKey}`;let b=u[v];if(b===void 0){const P=S._fontString;P!==p&&(e.font=P,p=P),b=i(x,S.letterSpacing,e)+S.letterSpacing,u[v]=b}return b},y=[];for(const x of n){const S=Gm(x),v=y.length,b=I=>{let D=0,B=I;do{const{token:j,style:k}=S[B];D+=g(j,k),B++}while(B<S.length&&S[B].continuesFromPrevious);return D},P=I=>{const D=[];let B=I;do D.push({token:S[B].token,style:S[B].style}),B++;while(B<S.length&&S[B].continuesFromPrevious);return D};let C=[],_=0,R=!c,M=null;const A=()=>{M&&M.text.length>0&&C.push(M),M=null},T=()=>{if(A(),C.length>0){const I=C[C.length-1];I.text=qt(I.text),I.text.length===0&&C.pop()}y.push(C),C=[],_=0,R=!1};for(let I=0;I<S.length;I++){const{token:D,style:B,continuesFromPrevious:j}=S[I],k=g(D,B);if(c){const L=Ot(D),Z=(M==null?void 0:M.text[M.text.length-1])??((m=C[C.length-1])==null?void 0:m.text.slice(-1))??"",Y=Z?Ot(Z):!1;if(L&&Y)continue}const F=!j,rt=F?b(I):k;if(rt>d&&F)if(_>0&&T(),l){const L=P(I);for(let Z=0;Z<L.length;Z++){const Y=L[Z].token,at=L[Z].style,bt=tc(Y,l,r,s);for(const wt of bt){const Rt=g(wt,at);Rt+_>d&&T(),!M||M.style!==at?(A(),M={text:wt,style:at}):M.text+=wt,_+=Rt}}I+=L.length-1}else{const L=P(I);A(),y.push(L.map(Z=>({text:Z.token,style:Z.style}))),R=!1,I+=L.length-1}else if(rt+_>d&&F){if(Ot(D)){R=!1;continue}T(),M={text:D,style:B},_=k}else if(j&&!l)!M||M.style!==B?(A(),M={text:D,style:B}):M.text+=D,_+=k;else{const L=Ot(D);if(_===0&&L&&!R)continue;!M||M.style!==B?(A(),M={text:D,style:B}):M.text+=D,_+=k}}if(A(),C.length>0){const I=C[C.length-1];I.text=qt(I.text),I.text.length===0&&C.pop()}(C.length>0||y.length===v)&&y.push(C)}return y}function Gm(n){const t=[];let e=!1;for(const i of n){const s=Jl(i.text);let r=!0;for(const o of s){const a=Ot(o)||Lr(o),h=r&&e&&!a;t.push({token:o,style:i.style,continuesFromPrevious:h}),e=!a,r=!1}}return t}const Um={willReadFrequently:!0};function Ia(n,t,e,i,s){let r=e[n];return typeof r!="number"&&(r=s(n,t,i)+t,e[n]=r),r}function Hm(n,t,e,i,s,r,o){const a=e.getContext("2d",Um);a.font=t._fontString;let h=0,l="";const c=[],d=Object.create(null),{letterSpacing:u,whiteSpace:p}=t,g=Kl(p),y=Ql(p);let m=!g;const x=t.wordWrapWidth+u,S=Jl(n);for(let b=0;b<S.length;b++){let P=S[b];if(Lr(P)){if(!y){c.push(qt(l)),m=!g,l="",h=0;continue}P=" "}if(g){const _=Ot(P),R=Ot(l[l.length-1]);if(_&&R)continue}const C=Ia(P,u,d,a,i);if(C>x)if(l!==""&&(c.push(qt(l)),l="",h=0),s(P,t.breakWords)){const _=tc(P,t.breakWords,o,r);for(const R of _){const M=Ia(R,u,d,a,i);M+h>x&&(c.push(qt(l)),m=!1,l="",h=0),l+=R,h+=M}}else l.length>0&&(c.push(qt(l)),l="",h=0),c.push(qt(P)),m=!1,l="",h=0;else C+h>x&&(m=!1,c.push(qt(l)),l="",h=0),(l.length>0||!Ot(P)||m)&&(l+=P,h+=C)}const v=qt(l);return v.length>0&&c.push(v),c.join(`
502
+ `)}const Da={willReadFrequently:!0},ie=class z{static get experimentalLetterSpacingSupported(){let t=z._experimentalLetterSpacingSupported;if(t===void 0){const e=$.get().getCanvasRenderingContext2D().prototype;t=z._experimentalLetterSpacingSupported="letterSpacing"in e||"textLetterSpacing"in e}return t}constructor(t,e,i,s,r,o,a,h,l,c){this.text=t,this.style=e,this.width=i,this.height=s,this.lines=r,this.lineWidths=o,this.lineHeight=a,this.maxLineWidth=h,this.fontProperties=l,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=z._canvas,s=e.wordWrap){var P;const r=`${t}-${e.styleKey}-wordWrap-${s}`;if(z._measurementCache.has(r))return z._measurementCache.get(r);if(Zl(e)&&ql(t)){const C=Om(t,e,s,z._context,z._measureText,z.measureFont,z.canBreakChars,z.wordWrapSplit),_=new z(t,e,C.width,C.height,C.lines,C.lineWidths,C.lineHeight,C.maxLineWidth,C.fontProperties,{runsByLine:C.runsByLine,lineAscents:C.lineAscents,lineDescents:C.lineDescents,lineHeights:C.lineHeights,hasDropShadow:C.hasDropShadow});return z._measurementCache.set(r,_),_}const a=e._fontString,h=z.measureFont(a);h.fontSize===0&&(h.fontSize=e.fontSize,h.ascent=e.fontSize,h.descent=0);const l=z._context;l.font=a;const d=(s?z._wordWrap(t,e,i):t).split(Lm),u=new Array(d.length);let p=0;for(let C=0;C<d.length;C++){const _=z._measureText(d[C],e.letterSpacing,l);u[C]=_,p=Math.max(p,_)}const g=((P=e._stroke)==null?void 0:P.width)??0,y=e.lineHeight||h.fontSize,m=z._getAlignWidth(p,e,s),x=z._adjustWidthForStyle(m,e),S=Math.max(y,h.fontSize+g)+(d.length-1)*(y+e.leading),v=z._adjustHeightForStyle(S,e),b=new z(t,e,x,v,d,u,y+e.leading,p,h);return z._measurementCache.set(r,b),b}static _adjustWidthForStyle(t,e){var r;const i=((r=e._stroke)==null?void 0:r.width)||0;let s=t+i;return e.dropShadow&&(s+=e.dropShadow.distance),s}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"&&e.align!=="justify"?Math.max(t,e.wordWrapWidth):t}static _measureText(t,e,i){let s=!1;z.experimentalLetterSpacingSupported&&(z.experimentalLetterSpacing?(i.letterSpacing=`${e}px`,i.textLetterSpacing=`${e}px`,s=!0):(i.letterSpacing="0px",i.textLetterSpacing="0px"));const r=i.measureText(t);let o=r.width;const a=-(r.actualBoundingBoxLeft??0);let l=(r.actualBoundingBoxRight??0)-a;if(o>0)if(s)o-=e,l-=e;else{const c=(z.graphemeSegmenter(t).length-1)*e;o+=c,l+=c}return Math.max(o,l)}static _wordWrap(t,e,i=z._canvas){return Hm(t,e,i,z._measureText,z.canBreakWords,z.canBreakChars,z.wordWrapSplit)}static isBreakingSpace(t,e){return Ot(t)}static canBreakWords(t,e){return e}static canBreakChars(t,e,i,s,r){return!0}static wordWrapSplit(t){return z.graphemeSegmenter(t)}static measureFont(t){if(z._fonts[t])return z._fonts[t];const e=z._context;e.font=t;const i=e.measureText(z.METRICS_STRING+z.BASELINE_SYMBOL),s=i.actualBoundingBoxAscent??0,r=i.actualBoundingBoxDescent??0,o={ascent:s,descent:r,fontSize:s+r};return z._fonts[t]=o,o}static clearMetrics(t=""){t?delete z._fonts[t]:z._fonts={}}static get _canvas(){if(!z.__canvas){let t;try{const e=new OffscreenCanvas(0,0),i=e.getContext("2d",Da);if(i!=null&&i.measureText)return z.__canvas=e,e;t=$.get().createCanvas()}catch{t=$.get().createCanvas()}t.width=t.height=10,z.__canvas=t}return z.__canvas}static get _context(){return z.__context||(z.__context=z._canvas.getContext("2d",Da)),z.__context}};ie.METRICS_STRING="|ÉqÅ";ie.BASELINE_SYMBOL="M";ie.BASELINE_MULTIPLIER=1.4;ie.HEIGHT_MULTIPLIER=2;ie.graphemeSegmenter=n=>[...n];ie.experimentalLetterSpacing=!1;ie._fonts={};ie._measurementCache=Am(1e3);let se=ie;const Nm=["serif","sans-serif","monospace","cursive","fantasy","system-ui"];function or(n){const t=typeof n.fontSize=="number"?`${n.fontSize}px`:n.fontSize;let e=n.fontFamily;Array.isArray(n.fontFamily)||(e=n.fontFamily.split(","));for(let i=e.length-1;i>=0;i--){let s=e[i].trim();!/([\"\'])[^\'\"]+\1/.test(s)&&!Nm.includes(s)&&(s=`"${s}"`),e[i]=s}return`${n.fontStyle} ${n.fontVariant} ${n.fontWeight} ${t} ${e.join(",")}`}const Fa=1e5;function os(n,t,e,i=0,s=0,r=0){if(n.texture===O.WHITE&&!n.fill)return nt.shared.setValue(n.color).setAlpha(n.alpha??1).toHexa();if(n.fill){if(n.fill instanceof Fs){const o=n.fill,a=t.createPattern(o.texture.source.resource,"repeat"),h=o.transform.copyTo(U.shared);return h.scale(o.texture.source.pixelWidth,o.texture.source.pixelHeight),a.setTransform(h),a}else if(n.fill instanceof Wt){const o=n.fill,a=o.type==="linear",h=o.textureSpace==="local";let l=1,c=1;h&&e&&(l=e.width+i,c=e.height+i);let d,u=!1;if(a){const{start:p,end:g}=o;d=t.createLinearGradient(p.x*l+s,p.y*c+r,g.x*l+s,g.y*c+r),u=Math.abs(g.x-p.x)<Math.abs((g.y-p.y)*.1)}else{const{center:p,innerRadius:g,outerCenter:y,outerRadius:m}=o;d=t.createRadialGradient(p.x*l+s,p.y*c+r,g*l,y.x*l+s,y.y*c+r,m*l)}if(u&&h&&e){const p=e.lineHeight/c;for(let g=0;g<e.lines.length;g++){const y=(g*e.lineHeight+i/2)/c;o.colorStops.forEach(m=>{let x=y+m.offset*p;x=Math.max(0,Math.min(1,x)),d.addColorStop(Math.floor(x*Fa)/Fa,nt.shared.setValue(m.color).toHex())})}}else o.colorStops.forEach(p=>{d.addColorStop(p.offset,nt.shared.setValue(p.color).toHex())});return d}}else{const o=t.createPattern(n.texture.source.resource,"repeat"),a=n.matrix.copyTo(U.shared);return a.scale(n.texture.source.pixelWidth,n.texture.source.pixelHeight),o.setTransform(a),o}return st("FillStyle not recognised",n),"red"}const Ba=new J;class Vm{getCanvasAndContext(t){const{text:e,style:i,resolution:s=1}=t,r=i._getFinalPadding(),o=se.measureText(e||" ",i),a=Math.ceil(Math.ceil(Math.max(1,o.width)+r*2)*s),h=Math.ceil(Math.ceil(Math.max(1,o.height)+r*2)*s),l=rr.getOptimalCanvasAndContext(a,h);this._renderTextToCanvas(i,r,s,l,o);const c=i.trim?Mm({canvas:l.canvas,width:a,height:h,resolution:1,output:Ba}):Ba.set(0,0,a,h);return{canvasAndContext:l,frame:c}}returnCanvasAndContext(t){rr.returnCanvasAndContext(t)}_renderTextToCanvas(t,e,i,s,r){var C,_,R;if(r.runsByLine&&r.runsByLine.length>0){this._renderTaggedTextToCanvas(r,t,e,i,s);return}const{canvas:o,context:a}=s,h=or(t),l=r.lines,c=r.lineHeight,d=r.lineWidths,u=r.maxLineWidth,p=r.fontProperties,g=o.height;if(a.resetTransform(),a.scale(i,i),a.textBaseline=t.textBaseline,(C=t._stroke)!=null&&C.width){const M=t._stroke;a.lineWidth=M.width,a.miterLimit=M.miterLimit,a.lineJoin=M.join,a.lineCap=M.cap}a.font=h;let y,m;const x=t.dropShadow?2:1,S=t.wordWrap?t.wordWrapWidth:u,b=(((_=t._stroke)==null?void 0:_.width)??0)/2;let P=(c-p.fontSize)/2;c-p.fontSize<0&&(P=0);for(let M=0;M<x;++M){const A=t.dropShadow&&M===0,T=A?Math.ceil(Math.max(1,g)+e*2):0,I=T*i;if(A)this._setupDropShadow(a,t,i,I);else{const D=t._gradientBounds,B=t._gradientOffset;if(D){const j={width:D.width,height:D.height,lineHeight:D.height,lines:r.lines};this._setFillAndStrokeStyles(a,t,j,e,b,(B==null?void 0:B.x)??0,(B==null?void 0:B.y)??0)}else B?this._setFillAndStrokeStyles(a,t,r,e,b,B.x,B.y):this._setFillAndStrokeStyles(a,t,r,e,b);a.shadowColor="black"}for(let D=0;D<l.length;D++)y=b,m=b+D*c+p.ascent+P,y+=this._getAlignmentOffset(d[D],S,t.align),(R=t._stroke)!=null&&R.width&&this._drawLetterSpacing(l[D],t,s,y+e,m+e-T,!0),t._fill!==void 0&&this._drawLetterSpacing(l[D],t,s,y+e,m+e-T)}}_renderTaggedTextToCanvas(t,e,i,s,r){var b,P;const{canvas:o,context:a}=r,{runsByLine:h,lineWidths:l,maxLineWidth:c,lineAscents:d,lineHeights:u,hasDropShadow:p}=t,g=o.height;a.resetTransform(),a.scale(s,s),a.textBaseline=e.textBaseline;const y=p?2:1,m=e.wordWrap?e.wordWrapWidth:c,S=(((b=e._stroke)==null?void 0:b.width)??0)/2,v=[];for(let C=0;C<h.length;C++){const _=h[C],R=[];for(const M of _){const A=or(M.style);a.font=A,R.push({width:se._measureText(M.text,M.style.letterSpacing,a),font:A})}v.push(R)}for(let C=0;C<y;++C){const _=p&&C===0,R=_?Math.ceil(Math.max(1,g)+i*2):0,M=R*s;_||(a.shadowColor="black");let A=S;for(let T=0;T<h.length;T++){const I=h[T],D=l[T],B=d[T],j=u[T],k=v[T];let F=S;F+=this._getAlignmentOffset(D,m,e.align);const rt=A+B;let L=F+i;for(let Z=0;Z<I.length;Z++){const Y=I[Z],{width:at,font:bt}=k[Z];if(a.font=bt,a.textBaseline=Y.style.textBaseline,(P=Y.style._stroke)!=null&&P.width){const wt=Y.style._stroke;if(a.lineWidth=wt.width,a.miterLimit=wt.miterLimit,a.lineJoin=wt.join,a.lineCap=wt.cap,_)if(Y.style.dropShadow)this._setupDropShadow(a,Y.style,s,M);else{L+=at;continue}else{const Rt=se.measureFont(bt),Gt=Y.style.lineHeight||Rt.fontSize,Hi={width:at,height:Gt,lineHeight:Gt,lines:[Y.text]};a.strokeStyle=os(wt,a,Hi,i*2,L-i,A)}this._drawLetterSpacing(Y.text,Y.style,r,L,rt+i-R,!0)}L+=at}L=F+i;for(let Z=0;Z<I.length;Z++){const Y=I[Z],{width:at,font:bt}=k[Z];if(a.font=bt,a.textBaseline=Y.style.textBaseline,Y.style._fill!==void 0){if(_)if(Y.style.dropShadow)this._setupDropShadow(a,Y.style,s,M);else{L+=at;continue}else{const wt=se.measureFont(bt),Rt=Y.style.lineHeight||wt.fontSize,Gt={width:at,height:Rt,lineHeight:Rt,lines:[Y.text]};a.fillStyle=os(Y.style._fill,a,Gt,i*2,L-i,A)}this._drawLetterSpacing(Y.text,Y.style,r,L,rt+i-R,!1)}L+=at}A+=j}}}_setFillAndStrokeStyles(t,e,i,s,r,o=0,a=0){var h;if(t.fillStyle=e._fill?os(e._fill,t,i,s*2,o,a):null,(h=e._stroke)!=null&&h.width){const l=r+s*2;t.strokeStyle=os(e._stroke,t,i,l,o,a)}}_setupDropShadow(t,e,i,s){t.fillStyle="black",t.strokeStyle="black";const r=e.dropShadow,o=r.color,a=r.alpha;t.shadowColor=nt.shared.setValue(o).setAlpha(a).toRgbaString();const h=r.blur*i,l=r.distance*i;t.shadowBlur=h,t.shadowOffsetX=Math.cos(r.angle)*l,t.shadowOffsetY=Math.sin(r.angle)*l+s}_getAlignmentOffset(t,e,i){return i==="right"?e-t:i==="center"?(e-t)/2:0}_drawLetterSpacing(t,e,i,s,r,o=!1){const{context:a}=i,h=e.letterSpacing;let l=!1;if(se.experimentalLetterSpacingSupported&&(se.experimentalLetterSpacing?(a.letterSpacing=`${h}px`,a.textLetterSpacing=`${h}px`,l=!0):(a.letterSpacing="0px",a.textLetterSpacing="0px")),h===0||l){o?a.strokeText(t,s,r):a.fillText(t,s,r);return}let c=s;const d=se.graphemeSegmenter(t);let u=a.measureText(t).width,p=0;for(let g=0;g<d.length;++g){const y=d[g];o?a.strokeText(y,c,r):a.fillText(y,c,r);let m="";for(let x=g+1;x<d.length;++x)m+=d[x];p=a.measureText(m).width,c+=u-p+h,u=p}}}const $e=new Vm,zr=class Ce extends Yt{constructor(t={}){super(),this.uid=ct("textStyle"),this._tick=0,this._cachedFontString=null,$m(t),t instanceof Ce&&(t=t._toObject());const s={...Ce.defaultTextStyle,...t};for(const r in s){const o=r;this[o]=s[r]}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({...Ce.defaultDropShadow,...t}):this._dropShadow=t?this._createProxy({...Ce.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({...gt.defaultFillStyle,...t},()=>{this._fill=_e({...this._originalFill},gt.defaultFillStyle)})),this._fill=_e(t===0?"black":t,gt.defaultFillStyle),this.update())}get stroke(){return this._originalStroke}set stroke(t){t!==this._originalStroke&&(this._originalStroke=t,this._isFillStyle(t)&&(this._originalStroke=this._createProxy({...gt.defaultStrokeStyle,...t},()=>{this._stroke=bs({...this._originalStroke},gt.defaultStrokeStyle)})),this._stroke=bs(t,gt.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=Ce.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=or(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 Ce(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,s,r,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),(s=this._originalFill)!=null&&s.texture&&this._originalFill.texture.destroy(a),(r=this._stroke)!=null&&r.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,s,r)=>(i[s]===r||(i[s]=r,e==null||e(s,r),this.update()),!0)})}_isFillStyle(t){return(t??null)!==null&&!(nt.isColorLike(t)||t instanceof Wt||t instanceof Fs)}};zr.defaultDropShadow={alpha:1,angle:Math.PI/6,blur:0,color:"black",distance:5};zr.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 le=zr;function $m(n){const t=n;if(typeof t.dropShadow=="boolean"&&t.dropShadow){const e=le.defaultDropShadow;n.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){N(K,"strokeThickness is now a part of stroke");const e=t.stroke;let i={};if(nt.isColorLike(e))i.color=e;else if(e instanceof Wt||e instanceof Fs)i.fill=e;else if(Object.hasOwnProperty.call(e,"color")||Object.hasOwnProperty.call(e,"fill"))i=e;else throw new Error("Invalid stroke value.");n.stroke={...i,width:t.strokeThickness}}if(Array.isArray(t.fillGradientStops)){if(N(K,"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&&st("The number of fill colors must match the number of fill gradient stops.");const e=new Wt({start:{x:0,y:0},end:{x:0,y:1},textureSpace:"local"}),i=t.fillGradientStops.slice(),s=t.fill.map(r=>nt.shared.setValue(r).toNumber());i.forEach((r,o)=>{e.addColorStop(r,s[o])}),n.fill={fill:e}}}function Ym(n,t){const{texture:e,bounds:i}=n,s=t._style._getFinalPadding();_h(i,t._anchor,e);const r=t._anchor._x*s*2,o=t._anchor._y*s*2;i.minX-=s-r,i.minY-=s-o,i.maxX-=s-r,i.maxY-=s-o}class Xm{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 jm extends Xm{}class ec{constructor(t){this._renderer=t,t.runners.resolutionChange.add(this),this._managedTexts=new ai({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 s=t._autoResolution?this._renderer.resolution:t.resolution;(i.currentKey!==t.styleKey||t._resolution!==s)&&this._updateGpuText(t),t._didTextUpdate=!1,Ym(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 jm;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}}ec.extension={type:[E.WebGLPipes,E.WebGPUPipes,E.CanvasPipes],name:"text"};const Zm=new Dt;function qm(n,t,e,i){const s=Zm;s.minX=0,s.minY=0,s.maxX=n.width/i|0,s.maxY=n.height/i|0;const r=Rs.getOptimalTexture(s.width,s.height,i,!1);return r.source.uploadMethodId="image",r.source.resource=n,r.source.alphaMode="premultiply-alpha-on-upload",r.frame.width=t/i,r.frame.height=e/i,r.source.emit("update",r.source),r.updateUvs(),r}class ic{constructor(t,e){this._activeTextures={},this._renderer=t,this._retainCanvasContext=e}getTexture(t,e,i,s){typeof t=="string"&&(N("8.0.0","CanvasTextSystem.getTexture: Use object TextOptions instead of separate arguments"),t={text:t,style:i,resolution:e}),t.style instanceof le||(t.style=new le(t.style)),t.textureStyle instanceof Ke||(t.textureStyle=new Ke(t.textureStyle)),typeof t.text!="string"&&(t.text=t.text.toString());const{text:r,style:o,textureStyle:a}=t,h=t.resolution??this._renderer.resolution,{frame:l,canvasAndContext:c}=$e.getCanvasAndContext({text:r,style:o,resolution:h}),d=qm(c.canvas,l.width,l.height,h);if(a&&(d.source.style=a),o.trim&&(l.pad(o.padding),d.frame.copyFrom(l),d.frame.scale(1/h),d.updateUvs()),o.filters){const u=this._applyFilters(d,o.filters);return this.returnTexture(d),$e.returnCanvasAndContext(c),u}return this._renderer.texture.initSource(d._source),this._retainCanvasContext||$e.returnCanvasAndContext(c),d}returnTexture(t){const e=t.source,i=e.resource;if(this._retainCanvasContext&&(i!=null&&i.getContext)){const s=i.getContext("2d");s&&$e.returnCanvasAndContext({canvas:i,context:s})}e.resource=null,e.uploadMethodId="unknown",e.alphaMode="no-premultiply-alpha",Rs.returnTexture(t,!0)}renderTextToCanvas(){N("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});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,s=this._renderer.filter.generateFilteredTexture({texture:t,filters:e});return this._renderer.renderTarget.bind(i,!1),s}destroy(){this._renderer=null;for(const t in this._activeTextures)this._activeTextures[t]&&this.returnTexture(this._activeTextures[t].texture);this._activeTextures=null}}class sc extends ic{constructor(t){super(t,!0)}}sc.extension={type:[E.CanvasSystem],name:"canvasText"};class nc extends ic{constructor(t){super(t,!1)}}nc.extension={type:[E.WebGLSystem,E.WebGPUSystem],name:"canvasText"};q.add(sc);q.add(nc);q.add(ec);class Bs extends wm{constructor(...t){const e=Cm(t,"Text");super(e,le),this.renderPipeId="text",e.textureStyle&&(this.textureStyle=e.textureStyle instanceof Ke?e.textureStyle:new Ke(e.textureStyle))}updateBounds(){const t=this._bounds,e=this._anchor;let i=0,s=0;if(this._style.trim){const{frame:r,canvasAndContext:o}=$e.getCanvasAndContext({text:this.text,style:this._style,resolution:1});$e.returnCanvasAndContext(o),i=r.width,s=r.height}else{const r=se.measureText(this._text,this._style);i=r.width,s=r.height}t.minX=-e._x*i,t.maxX=t.minX+i,t.minY=-e._y*s,t.maxY=t.minY+s}}class Or extends O{static create(t){const{dynamic:e,...i}=t;return new Or({source:new Bt(i),dynamic:e??!1})}resize(t,e,i){return this.source.resize(t,e,i),this}}q.add(Sd,vd);function Km(n,t){var e=-1,i=n.length;for(t||(t=Array(i));++e<i;)t[e]=n[e];return t}function Qm(n,t,e,i){var s=!e;e||(e={});for(var r=-1,o=t.length;++r<o;){var a=t[r],h=void 0;h===void 0&&(h=n[a]),s?ch(e,a,h):dh(e,a,h)}return e}function Jm(n){return Vc(function(t,e){var i=-1,s=e.length,r=s>1?e[s-1]:void 0,o=s>2?e[2]:void 0;for(r=n.length>3&&typeof r=="function"?(s--,r):void 0,o&&$c(e[0],e[1],o)&&(r=s<3?void 0:r,s=1),t=Object(t);++i<s;){var a=e[i];a&&n(t,a,i,r)}return t})}function ty(n){var t=[];if(n!=null)for(var e in Object(n))t.push(e);return t}var ey=Object.prototype,iy=ey.hasOwnProperty;function sy(n){if(!Ee(n))return ty(n);var t=Yc(n),e=[];for(var i in n)i=="constructor"&&(t||!iy.call(n,i))||e.push(i);return e}function rc(n){return uh(n)?Xc(n,!0):sy(n)}function ny(n){var t=n==null?0:n.length;return t?jc(n):[]}function ry(n){return Zc(qc(n,void 0,ny),n+"")}var oy="[object Object]",ay=Function.prototype,hy=Object.prototype,oc=ay.toString,ly=hy.hasOwnProperty,cy=oc.call(Object);function dy(n){if(!gr(n)||ph(n)!=oy)return!1;var t=Kc(n);if(t===null)return!0;var e=ly.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&oc.call(e)==cy}var uy=td.isFinite,py=Math.min;function fy(n){var t=Math[n];return function(e,i){if(e=Qc(e),i=i==null?0:py(Jc(i),292),i&&uy(e)){var s=(to(e)+"e").split("e"),r=t(s[0]+"e"+(+s[1]+i));return s=(to(r)+"e").split("e"),+(s[0]+"e"+(+s[1]-i))}return t(e)}}function ar(n,t,e){(e!==void 0&&!ed(n[t],e)||e===void 0&&!(t in n))&&ch(n,t,e)}function gy(n){return gr(n)&&uh(n)}function hr(n,t){if(!(t==="constructor"&&typeof n[t]=="function")&&t!="__proto__")return n[t]}function my(n){return Qm(n,rc(n))}function yy(n,t,e,i,s,r,o){var a=hr(n,e),h=hr(t,e),l=o.get(h);if(l){ar(n,e,l);return}var c=r?r(a,h,e+"",n,t,o):void 0,d=c===void 0;if(d){var u=Ln(h),p=!u&&id(h),g=!u&&!p&&sd(h);c=h,u||p||g?Ln(a)?c=a:gy(a)?c=Km(a):p?(d=!1,c=nd(h,!0)):g?(d=!1,c=rd(h,!0)):c=[]:dy(h)||eo(h)?(c=a,eo(a)?c=my(a):(!Ee(a)||od(a))&&(c=ad(h))):d=!1}d&&(o.set(h,c),s(c,h,i,r,o),o.delete(h)),ar(n,e,c)}function ac(n,t,e,i,s){n!==t&&hd(t,function(r,o){if(s||(s=new ld),Ee(r))yy(n,t,o,e,ac,i,s);else{var a=i?i(hr(n,o),r,o+"",n,t,s):void 0;a===void 0&&(a=r),ar(n,o,a)}},rc)}var La=Jm(function(n,t,e,i){ac(n,t,e,i)}),xy="[object Number]";function za(n){return typeof n=="number"||gr(n)&&ph(n)==xy}function Sy(n,t,e,i){if(!Ee(n))return n;t=fh(t,n);for(var s=-1,r=t.length,o=r-1,a=n;a!=null&&++s<r;){var h=cd(t[s]),l=e;if(h==="__proto__"||h==="constructor"||h==="prototype")return n;if(s!=o){var c=a[h];l=void 0,l===void 0&&(l=Ee(c)?c:dd(t[s+1])?[]:{})}dh(a,h,l),a=a[h]}return n}function vy(n,t,e){for(var i=-1,s=t.length,r={};++i<s;){var o=t[i],a=ud(n,o);e(a,o)&&Sy(r,fh(o,n),a)}return r}function by(n,t){return vy(n,t,function(e,i){return pd(n,i)})}var An=ry(function(n,t){return n==null?{}:by(n,t)}),Oa=fy("round"),wy="Expected a function";function _t(n,t,e){var i=!0,s=!0;if(typeof n!="function")throw new TypeError(wy);return Ee(e)&&(i="leading"in e?!!e.leading:i,s="trailing"in e?!!e.trailing:s),zn(n,t,{leading:i,maxWait:t,trailing:s})}function Cy(n){return n<.5?4*n*n*n:(n-1)*(2*n-2)*(2*n-2)+1}function hc(n,t=2){if(n==null)return n;if(za(n))return Oa(n,t);if(Ln(n))return fd(n,e=>hc(e,t));if(Ee(n)){const e=["x","y","rotation"];return gd(n,(i,s)=>za(i)&&e.includes(s)?Oa(i,t):i)}return n}const _y="ray-robot-map-sdk",Wa=["warn","error"],as="%c[ray-2d-laser-map-sdk]%c ",Py="%c[ray-2d-laser-map-sdk:DEBUG]%c ",My="background: #2196F3; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;",Ty="color: #2196F3;",Ay="background: #FF9800; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;",Ry="color: #FF9800;",ky="background: #F44336; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;",Ey="color: #F44336;",Iy="background: #9C27B0; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;",Dy="color: #9C27B0;",Fy="background: #4CAF50; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;",By="color: #4CAF50;";let At={},zi=!1;function ae(n){if(n)try{return n()}catch{return}}function Ly(n){At={...At,...n},zi=!1}function zy(){return{config:{...At},appLogSinkWarned:zi}}function Oy(n){At=n?{...n.config}:{},zi=(n==null?void 0:n.appLogSinkWarned)??!1}function Wy(){const n=ae(At.getLoggerConfig);if(typeof(n==null?void 0:n.enabled)=="boolean")return n.enabled;const t=ae(At.isEnabled);if(typeof t=="boolean")return t;const e=ae(At.getLegacyEnabled);return typeof e=="boolean"?e:!1}function Gy(){const n=ae(At.getLoggerConfig);if(typeof(n==null?void 0:n.tag)=="string"&&n.tag.length>0)return n.tag;const t=ae(At.getTag);return typeof t=="string"&&t.length>0?t:_y}function hs(n,t,e){return{level:n,message:t,data:e,tag:Gy(),ts:Date.now()}}function Uy(n){const t=ae(At.getLoggerConfig);return typeof(t==null?void 0:t.appLogEnabled)=="boolean"?t.appLogEnabled?(t.appLogLevels??Wa).includes(n):!1:ae(At.isAppLogEnabled)?(ae(At.getAppLogLevels)??Wa).includes(n):!1}function ls(n){if(!Uy(n.level))return;const{appLogSink:t}=At;if(typeof t=="function")try{t(n)}catch(e){if(zi)return;zi=!0,console.warn("[ray-robot-map-sdk] app logger bridge failed",e)}}function mi(n,t,e,i,s,r){Wy()&&console[n](`${t}${s}`,e,i,...r)}const w={log(n,...t){const e=hs("info",n,t);mi("log",as,My,Ty,n,t),ls(e)},warn(n,...t){const e=hs("warn",n,t);mi("warn",as,Ay,Ry,n,t),ls(e)},error(n,...t){const e=hs("error",n,t);mi("error",as,ky,Ey,n,t),ls(e)},debug(n,...t){const e=hs("debug",n,t);mi("log",Py,Iy,Dy,n,t),ls(e)},success(n,...t){mi("log",as,Fy,By,n,t)}},ut=n=>n,Ft=n=>n,lc=n=>n.map(t=>({x:Ft(t.x),y:Ft(t.y)})),vi=(n,t)=>({x:Ft(n),y:Ft(t)}),Ga=n=>{if(n.length<=1)return[...n];const t=Hy(n),e=t.slice(1).map((s,r)=>({prev:t[r],current:s})),i=new Map;return e.forEach(({prev:s,current:r})=>{Ny(s,r).forEach(a=>{const h=`${a.x},${a.y}`;i.has(h)||i.set(h,a)})}),Array.from(i.values())},Hy=n=>{if(n.length<=1)return[...n];const t=n[0],e=n[n.length-1];return t.x===e.x&&t.y===e.y?[...n]:[...n,t]},Ny=(n,t)=>{const e=[],i=Math.abs(t.x-n.x),s=Math.abs(t.y-n.y),r=n.x<t.x?1:-1,o=n.y<t.y?1:-1;let a=i-s,h=n.x,l=n.y;for(;e.push({x:h,y:l}),!(h===t.x&&l===t.y);){const c=2*a;c>-s&&(a-=s,h+=r),c<i&&(a+=i,l+=o)}return e},cc=(n,t)=>{let e=0,i=n.length-1;for(;e<=i;){const s=Math.floor((e+i)/2),r=n[s];if(r===t)return!0;r<t?e=s+1:i=s-1}return!1},Vy=(n,t,e=1,i=2e3)=>{const s=[],r=t.x-n.x,o=t.y-n.y,a=Math.sqrt(r*r+o*o);if(a===0)return[n];const h=Math.min(Math.max(Math.ceil(a/e),2),i);for(let l=0;l<=h;l++){const c=l/h,d={x:n.x+c*r,y:n.y+c*o};s.push(d)}return s},Ua=(n,t,e,i,s,r=8)=>{const o=(t+i)/2,a=(e+s)/2,h={x:o,y:a},l=i-t,c=s-e,d=Math.min(r,Math.min(l,c)*.2);return kt(h,n)&&Ti(h,n)>=d?h:$y(n,h,d)},$y=(n,t,e)=>{const{minX:i,minY:s,maxX:r,maxY:o}=_s(n),a=r-i,h=o-s,l=t.x,c=t.y,d=Math.min(.5,Math.min(a,h)*.05),u=[];if(kt({x:l,y:c},n)){const S=Ti({x:l,y:c},n);u.push({point:{x:l,y:c},distance:S,centerDistance:0})}const p=Math.max(a,h)*.6,g=Math.PI/16;let y=0;const m=1e4;let x=!1;for(let S=d;S<=p&&!x;S+=d){const v=g*(1+S/p);for(let b=0;b<2*Math.PI;b+=v){if(y++,y>m){w.error(`[findBestInnerPoint] Iteration limit reached (${y}). Room size: ${a}x${h}`),x=!0;break}const P=l+S*Math.cos(b),C=c+S*Math.sin(b);if(P>=i&&P<=r&&C>=s&&C<=o){const _={x:P,y:C};if(kt(_,n)){const R=Ti(_,n),M=tt({x:P,y:C},{x:l,y:c});R>=e&&u.push({point:_,distance:R,centerDistance:M})}}}if(u.length>=15)break}if(u.length>0){const S=u.map(v=>({...v,score:v.distance*1.5-v.centerDistance*.5}));return S.sort((v,b)=>b.score-v.score),S[0].point}if(u.length===0){let S={x:l,y:c},v=0;const b=d*2;let P=0;const C=5e3;let _=!1;for(let R=i;R<=r&&!_;R+=b)for(let M=s;M<=o;M+=b){if(P++,P>C){w.error(`[findBestInnerPoint] Coarse search iteration limit reached. Room size: ${a}x${h}`),_=!0;break}const A={x:R,y:M};if(kt(A,n)){const T=Ti(A,n);T>v&&(v=T,S=A)}}return S}return{x:l,y:c}},Ti=(n,t)=>{let e=1/0;for(let i=0,s=t.length-1;i<t.length;s=i++){const r=t[s],o=t[i],a=Wr(n,r,o);e=Math.min(e,a)}return e},Ha=(n,t)=>t.length===1?tt(n,t[0]):t.length===2?Wr(n,t[0],t[1]):t.length===4?kt(n,t)?0:Ti(n,t):(w.warn(`[Distance] Invalid geometry: expected 1, 2 or 4 points, got ${t.length}`),1/0),Wr=(n,t,e)=>{const i=(t.x-e.x)**2+(t.y-e.y)**2;if(i===0)return tt(n,t);const s=Math.max(0,Math.min(1,((n.x-t.x)*(e.x-t.x)+(n.y-t.y)*(e.y-t.y))/i)),r=t.x+s*(e.x-t.x),o=t.y+s*(e.y-t.y);return tt(n,{x:r,y:o})},kt=(n,t,e=!1)=>{if(t.length<3)return!1;if(e&&Yy(n,t))return!0;let i=!1;for(let s=0,r=t.length-1;s<t.length;r=s++){const o=t[s].x,a=t[s].y,h=t[r].x,l=t[r].y;a>n.y!=l>n.y&&n.x<(h-o)*(n.y-a)/(l-a)+o&&(i=!i)}return i},Yy=(n,t)=>{if(t.length<2)return!1;for(let e=0;e<t.length;e++){const i=(e+1)%t.length;if(Xy(n,t[e],t[i]))return!0}return!1},Xy=(n,t,e,i=.5)=>{if(Wr(n,t,e)>i)return!1;const r=Math.min(t.x,e.x)-i,o=Math.max(t.x,e.x)+i,a=Math.min(t.y,e.y)-i,h=Math.max(t.y,e.y)+i;return n.x>=r&&n.x<=o&&n.y>=a&&n.y<=h},_s=n=>{if(n.length===0)return{minX:0,minY:0,maxX:0,maxY:0};let t=1/0,e=1/0,i=-1/0,s=-1/0;for(const r of n)t=Math.min(t,r.x),e=Math.min(e,r.y),i=Math.max(i,r.x),s=Math.max(s,r.y);return{minX:t,minY:e,maxX:i,maxY:s}},Le=n=>{const t=n.reduce((e,i)=>({x:e.x+i.x,y:e.y+i.y}),{x:0,y:0});return{x:t.x/n.length,y:t.y/n.length}},jy=(n,t,e)=>{if(n.length<4)return n;const[i,s,,r]=n,o=tt(i,s),a=tt(i,r),h=o<t||a<t,l=e!=null&&(o>e||a>e);if(!h&&!l)return n;const c=Le(n),d=It(St(i,s)),u=It(St(i,r)),p=S=>{let v=S;return e!=null&&(v=Math.min(v,e)),Math.max(v,t)},g=p(o),y=p(a),m=g/2,x=y/2;return[vi(c.x-d.x*m-u.x*x,c.y-d.y*m-u.y*x),vi(c.x+d.x*m-u.x*x,c.y+d.y*m-u.y*x),vi(c.x+d.x*m+u.x*x,c.y+d.y*m+u.y*x),vi(c.x-d.x*m+u.x*x,c.y-d.y*m+u.y*x)]},Zy=n=>{if(n.length!==4)return n;const t=Le(n),e=tt(n[0],n[1]),i=tt(n[1],n[2]),s=Math.atan2(n[1].y-n[0].y,n[1].x-n[0].x),r=[{x:-e/2,y:-i/2},{x:e/2,y:-i/2},{x:e/2,y:i/2},{x:-e/2,y:i/2}],o=Math.cos(s),a=Math.sin(s);return r.map(h=>vi(h.x*o-h.y*a+t.x,h.x*a+h.y*o+t.y))},cs=(n,t,e,i=Ft(10),s)=>{if(e===0)return 1;const o=(n.x*t.x+n.y*t.y)/e/e,a=i/e;if(o<=0)return a;let h=o;if(s!=null){const l=s/e;h=Math.min(h,l)}return Math.max(h,a)},tt=(n,t)=>{const e=n.x-t.x,i=n.y-t.y;return Math.sqrt(e*e+i*i)},Oi=n=>Math.sqrt(n.x*n.x+n.y*n.y),St=(n,t)=>({x:t.x-n.x,y:t.y-n.y}),It=n=>{const t=Oi(n);return t===0?{x:0,y:0}:{x:n.x/t,y:n.y/t}},dc=(n,t)=>{const e=St(n,t);return It(e)},uc=n=>({x:-n.y,y:n.x}),pc=(n,t)=>{const e=dc(n,t);return uc(e)},fc=(n,t)=>{const e=It(n),i=It(t),s={x:(e.x+i.x)/2,y:(e.y+i.y)/2};return It(s)},ms=(n,t,e=0)=>{const i=St(n,t);let s=Math.atan2(i.y,i.x),o=(s+e)%(2*Math.PI);return o>Math.PI&&(o-=2*Math.PI),o<-Math.PI&&(o+=2*Math.PI),(o>Math.PI/2||o<-Math.PI/2)&&(s+=Math.PI),s},gc=(n,t,e)=>{const i=Le([n,t]),s=pc(n,t);return{x:i.x+s.x*e,y:i.y+s.y*e}},qy=(n,t,e)=>{const i=Math.cos(e),s=Math.sin(e),r=n.x-t.x,o=n.y-t.y;return{x:r*i-o*s+t.x,y:r*s+o*i+t.y}},Ky=(n,t,e)=>n.map(i=>qy(i,t,e)),Qy=(n,t,e)=>{if(tt(n,t)===0)return[n,n,n,n];const s=dc(n,t),r=uc(s),o={x:n.x-s.x*e,y:n.y-s.y*e},a={x:t.x+s.x*e,y:t.y+s.y*e};return[{x:o.x+r.x*e,y:o.y+r.y*e},{x:a.x+r.x*e,y:a.y+r.y*e},{x:a.x-r.x*e,y:a.y-r.y*e},{x:o.x-r.x*e,y:o.y-r.y*e}]},Jy=(n,t)=>{if(n.length<3)return n;const e=[];for(let i=0;i<n.length;i++){const s=n[i],r=n[(i+1)%n.length],o=n[(i-1+n.length)%n.length],a=St(s,r);if(Oi(a)===0){e.push(s);continue}const l=It(a),c={x:l.y,y:-l.x},d=St(o,s),u=Oi(d);let p={x:0,y:0};if(u>0){const S=It(d);p={x:S.y,y:-S.x}}const g=fc(p,c),y=p.x*c.x+p.y*c.y,m=1/Math.max(.1,Math.sqrt((1+y)/2)),x={x:s.x+g.x*t*m,y:s.y+g.y*t*m};e.push(x)}return e},mc=(n,t,e)=>{if(tt(n,t)===0)return[];const s=pc(n,t),r=e/2;return[n.x+s.x*r,n.y+s.y*r,t.x+s.x*r,t.y+s.y*r,t.x-s.x*r,t.y-s.y*r,n.x-s.x*r,n.y-s.y*r]},yc=(n,t,e,i)=>{const s=St(n,t),r=St(n,e),o=fc(s,r),a={x:-o.x,y:-o.y};return{x:n.x+a.x*i,y:n.y+a.y*i}},tx=(n,t,e,i,s,r)=>{const o=new Set(n),a=ex(n,t),h=ix(a,o,t,e,i,s,r);return h||a},ex=(n,t)=>{let e=0,i=0;for(let s=0;s<n.length;s++){const r=n[s],o=r%t,a=Math.floor(r/t);e+=o,i+=a}return{x:e/n.length,y:i/n.length}},ix=(n,t,e,i,s,r,o)=>{const a={x:i-10,y:n.y},h={x:r+10,y:n.y},l={x:i,y:s},c={x:i,y:o},d={x:r,y:s},u={x:r,y:o},p=Wi(a,h,l,c),g=Wi(a,h,d,u);if(!p||!g)return null;const y=[],m=Math.max(i,Math.min(p.x,g.x)),x=Math.min(r,Math.max(p.x,g.x)),S=Math.round(n.y);for(let v=Math.round(m);v<=Math.round(x);v++){const b=S*e+v;t.has(b)&&y.push({x:v,y:S})}if(y.length>=2){const v=sx(y),b={x:(v.min.x+v.max.x)/2,y:(v.min.y+v.max.y)/2},P=Math.round(b.y)*e+Math.round(b.x);if(t.has(P))return b}return null},Wi=(n,t,e,i)=>{const s=(n.x-e.x)*(t.y-e.y)-(n.y-e.y)*(t.x-e.x),r=(n.x-i.x)*(t.y-i.y)-(n.y-i.y)*(t.x-i.x);if(s*r>=0)return null;const o=(e.x-n.x)*(i.y-n.y)-(e.y-n.y)*(i.x-n.x),a=o+s-r;if(o*a>=0)return null;const h=o/(r-s),l=h*(t.x-n.x),c=h*(t.y-n.y);return{x:n.x+l,y:n.y+c}},sx=n=>{if(!n||n.length===0)return{min:{x:0,y:0},max:{x:0,y:0}};let t=n[0],e=n[0];const i=s=>s.x-s.y;for(let s=1;s<n.length;s++){const r=n[s];i(r)<i(t)&&(t=r),i(r)>i(e)&&(e=r)}return{min:t,max:e}},Rn=(n,t)=>({minX:Math.min(n.minX,t.minX),minY:Math.min(n.minY,t.minY),maxX:Math.max(n.maxX,t.maxX),maxY:Math.max(n.maxY,t.maxY)}),nx=n=>{if(n.length===0)return{x:0,y:0,width:0,height:0};let t=n[0].x,e=n[0].y,i=n[0].x+n[0].width,s=n[0].y+n[0].height;return n.forEach(r=>{t=Math.min(t,r.x),e=Math.min(e,r.y),i=Math.max(i,r.x+r.width),s=Math.max(s,r.y+r.height)}),{x:t,y:e,width:i-t,height:s-e}},rx=(n,t,e)=>{let i=1/0,s=1/0,r=-1/0,o=-1/0;for(let a=0;a<n.obstacles.length;a++){const h=n.obstacles[a],l=h%t,c=Math.floor(h/t);i=Math.min(i,l),s=Math.min(s,c),r=Math.max(r,l),o=Math.max(o,c)}return n.rooms.forEach(a=>{for(let h=0;h<a.length;h++){const l=a[h],c=l%t,d=Math.floor(l/t);i=Math.min(i,c),s=Math.min(s,d),r=Math.max(r,c),o=Math.max(o,d)}}),i===1/0?{minX:0,minY:0,maxX:t,maxY:e}:{minX:Math.max(0,i),minY:Math.max(0,s),maxX:Math.min(t,r),maxY:Math.min(e,o)}},ox=(n,t,e,i,s,r)=>{const o=e+s,a=i+r,h=Math.min(n.x,t.x),l=Math.max(n.x,t.x),c=Math.min(n.y,t.y),d=Math.max(n.y,t.y);if(l<e||h>o||d<i||c>a)return!1;if(Na(n,e,i,s,r)||Na(t,e,i,s,r))return!0;const u=[{x:e,y:i},{x:o,y:i},{x:o,y:a},{x:e,y:a}];for(let p=0;p<4;p++){const g=u[p],y=u[(p+1)%4];if(Wi(n,t,g,y))return!0}return!1},Na=(n,t,e,i,s)=>n.x>=t&&n.x<=t+i&&n.y>=e&&n.y<=e+s,ax=(n,t,e,i)=>{const s=e/2;return i==="horizontal"?[{x:n-s,y:t},{x:n+s,y:t}]:[{x:n,y:t-s},{x:n,y:t+s}]},hx=(n,t,e)=>{const i={x:t.x-n.x,y:t.y-n.y},s=Math.sqrt(i.x*i.x+i.y*i.y);if(s===0)return[n,t];const r={x:i.x/s,y:i.y/s},o={x:n.x-r.x*e,y:n.y-r.y*e},a={x:t.x+r.x*e,y:t.y+r.y*e};return[o,a]},Va=(n,t,e)=>{const i=_s(n),s=_s(t),r=Math.max(0,Math.max(i.minX,s.minX)-Math.min(i.maxX,s.maxX)),o=Math.max(0,Math.max(i.minY,s.minY)-Math.min(i.maxY,s.maxY));if(r>e||o>e)return!1;let[a,h]=[n,t];t.length>n.length&&([a,h]=[t,n]);const l=Math.max(1,Math.floor(e)),c=new Map;for(const u of a){const p=Math.floor(u.x/l),g=Math.floor(u.y/l),y=`${p},${g}`;c.has(y)||c.set(y,[]),c.get(y).push(u)}const d=e*e;for(const u of h){const p=Math.floor(u.x/l),g=Math.floor(u.y/l);for(let y=-1;y<=1;y++)for(let m=-1;m<=1;m++){const x=`${p+y},${g+m}`,S=c.get(x);if(S)for(const v of S){const b=u.x-v.x,P=u.y-v.y;if(b*b+P*P<=d)return!0}}}return!1},$a=(n,t,e,i)=>{let[s,r]=[n,t];t.length>n.length&&([s,r]=[t,n]);const o=new Set(s),a=i*i;for(let h=0;h<r.length;h++){const l=r[h],c=l%e,d=Math.floor(l/e);for(let u=-i;u<=i;u++)for(let p=-i;p<=i;p++){const g=c+u,m=(d+p)*e+g;if(o.has(m)&&u*u+p*p<=a)return!0}}return!1},Ya=(n,t)=>{if(n<=1)return!0;if(t.length===0)return!1;const e=Array.from({length:n},(a,h)=>h),i=Array(n).fill(0),s=a=>(e[a]!==a&&(e[a]=s(e[a])),e[a]),r=(a,h)=>{const l=s(a),c=s(h);l!==c&&(i[l]<i[c]?e[l]=c:i[l]>i[c]?e[c]=l:(e[c]=l,i[l]++))};for(const[a,h]of t)r(a,h);const o=s(0);for(let a=1;a<n;a++)if(s(a)!==o)return!1;return!0},lx=(n,t,e,i="priority")=>{const s=new Map;if(n.length===0)return s;if(n.length===1)return s.set(n[0].id,0),s;const r=new Map;for(let l=0;l<n.length;l++){const c=n[l];r.has(c.id)||r.set(c.id,new Set);for(let d=l+1;d<n.length;d++){const u=n[d];t(c,u)&&(r.get(c.id).add(u.id),r.has(u.id)||r.set(u.id,new Set),r.get(u.id).add(c.id))}}const o=new Array(e).fill(0),a=[...n].sort((l,c)=>{const d=(r.get(l.id)||new Set).size,u=(r.get(c.id)||new Set).size,p=n.indexOf(l),g=n.indexOf(c),y=-p*.5+d*.5;return-g*.5+u*.5-y}),h=l=>{const c=r.get(l)||new Set,d=new Map;for(const u of c){const p=s.get(u);p!==void 0&&(d.has(p)||d.set(p,[]),d.get(p).push(u))}for(const[u,p]of d){if(p.length!==1)continue;const g=p[0],y=r.get(g)||new Set,m=new Set;for(const x of y){if(x===l)continue;const S=s.get(x);S!==void 0&&m.add(S)}for(let x=0;x<e;x++)if(x!==u&&!m.has(x))return o[u]--,o[x]++,s.set(g,x),u}return-1};for(const l of a){const c=r.get(l.id)||new Set,d=new Set;for(const p of c){const g=s.get(p);g!==void 0&&d.add(g)}let u=-1;if(i==="priority"){let p=-1,g=-1/0;for(let y=0;y<e;y++)if(!d.has(y)){const m=e-y,x=o[y]*.7,S=m-x;(S>g||S===g&&y<p)&&(g=S,p=y)}if(u=p,u===-1&&(u=h(l.id)),u===-1){w.warn(`[FourColor] Room ${l.id}: recolor failed, falling back to least-conflict color`);let y=1/0;for(let m=0;m<e;m++){let x=0;for(const S of c)s.get(S)===m&&x++;(x<y||x===y&&m<u)&&(y=x,u=m)}}o[u]++}else{const p=[];for(let g=0;g<e;g++)d.has(g)||p.push(g);if(p.length===0){if(u=h(l.id),u===-1){w.warn(`[FourColor] Room ${l.id}: recolor failed, falling back to least-conflict color`);let g=1/0,y=0;for(let m=0;m<e;m++)(o[m]<g||o[m]===g&&m<y)&&(g=o[m],y=m);u=y}}else{u=p[0];let g=o[u];for(const y of p)(o[y]<g||o[y]===g&&y<u)&&(u=y,g=o[y])}o[u]++}s.set(l.id,u)}return s},cx=Symbol(),Xa=Object.getPrototypeOf,lr=new WeakMap,dx=n=>n&&(lr.has(n)?lr.get(n):Xa(n)===Object.prototype||Xa(n)===Array.prototype),ux=n=>dx(n)&&n[cx]||null,ja=(n,t=!0)=>{lr.set(n,t)},Ps={},Gr=n=>typeof n=="object"&&n!==null,px=n=>Gr(n)&&!Ur.has(n)&&(Array.isArray(n)||!(Symbol.iterator in n))&&!(n instanceof WeakMap)&&!(n instanceof WeakSet)&&!(n instanceof Error)&&!(n instanceof Number)&&!(n instanceof Date)&&!(n instanceof String)&&!(n instanceof RegExp)&&!(n instanceof ArrayBuffer)&&!(n instanceof Promise),xc=(n,t)=>{const e=Za.get(n);if((e==null?void 0:e[0])===t)return e[1];const i=Array.isArray(n)?[]:Object.create(Object.getPrototypeOf(n));return ja(i,!0),Za.set(n,[t,i]),Reflect.ownKeys(n).forEach(s=>{if(Object.getOwnPropertyDescriptor(i,s))return;const r=Reflect.get(n,s),{enumerable:o}=Reflect.getOwnPropertyDescriptor(n,s),a={value:r,enumerable:o,configurable:!0};if(Ur.has(r))ja(r,!1);else if(Be.has(r)){const[h,l]=Be.get(r);a.value=xc(h,l())}Object.defineProperty(i,s,a)}),Object.preventExtensions(i)},fx=(n,t,e,i)=>({deleteProperty(s,r){const o=Reflect.get(s,r);e(r);const a=Reflect.deleteProperty(s,r);return a&&i(["delete",[r],o]),a},set(s,r,o,a){const h=!n()&&Reflect.has(s,r),l=Reflect.get(s,r,a);if(h&&(qa(l,o)||Ms.has(o)&&qa(l,Ms.get(o))))return!0;e(r),Gr(o)&&(o=ux(o)||o);const c=!Be.has(o)&&mx(o)?cr(o):o;return t(r,c),Reflect.set(s,r,c,a),i(["set",[r],o,l]),!0}}),Be=new WeakMap,Ur=new WeakSet,Za=new WeakMap,kn=[1],Ms=new WeakMap;let qa=Object.is,gx=(n,t)=>new Proxy(n,t),mx=px,yx=xc,xx=fx;function cr(n={}){if(!Gr(n))throw new Error("object required");const t=Ms.get(n);if(t)return t;let e=kn[0];const i=new Set,s=(m,x=++kn[0])=>{e!==x&&(r=e=x,i.forEach(S=>S(m,x)))};let r=e;const o=(m=kn[0])=>(r!==m&&(r=m,h.forEach(([x])=>{const S=x[1](m);S>e&&(e=S)})),e),a=m=>(x,S)=>{const v=[...x];v[1]=[m,...v[1]],s(v,S)},h=new Map,l=(m,x)=>{const S=!Ur.has(x)&&Be.get(x);if(S){if((Ps?"production":void 0)!=="production"&&h.has(m))throw new Error("prop listener already exists");if(i.size){const v=S[2](a(m));h.set(m,[S,v])}else h.set(m,[S])}},c=m=>{var x;const S=h.get(m);S&&(h.delete(m),(x=S[1])==null||x.call(S))},d=m=>(i.add(m),i.size===1&&h.forEach(([S,v],b)=>{if((Ps?"production":void 0)!=="production"&&v)throw new Error("remove already exists");const P=S[2](a(b));h.set(b,[S,P])}),()=>{i.delete(m),i.size===0&&h.forEach(([S,v],b)=>{v&&(v(),h.set(b,[S]))})});let u=!0;const p=xx(()=>u,l,c,s),g=gx(n,p);Ms.set(n,g);const y=[n,o,d];return Be.set(g,y),Reflect.ownKeys(n).forEach(m=>{const x=Object.getOwnPropertyDescriptor(n,m);"value"in x&&x.writable&&(g[m]=n[m])}),u=!1,g}function Ls(n,t,e){const i=Be.get(n);(Ps?"production":void 0)!=="production"&&!i&&console.warn("Please use proxy object");let s;const r=[],o=i[2];let a=!1;const l=o(c=>{r.push(c),s||(s=Promise.resolve().then(()=>{s=void 0,a&&t(r.splice(0))}))});return a=!0,()=>{a=!1,l()}}function Sx(n){const t=Be.get(n);(Ps?"production":void 0)!=="production"&&!t&&console.warn("Please use proxy object");const[e,i]=t;return yx(e,i())}function G(n,t,e,i){let s=n[t];return Ls(n,()=>{const r=n[t];Object.is(s,r)||e(s=r)})}class vx extends W{constructor(e){super();f(this,"dragStart",null);f(this,"initialTouchDistance",null);f(this,"initialScale",null);f(this,"activeTouches",new Map);f(this,"firstTouchId",null);f(this,"secondTouchId",null);f(this,"taintedPointers",new Set);f(this,"zoomFactor",.8);f(this,"scaleMin",.2);f(this,"scaleMax",5);f(this,"originalPosition",{x:0,y:0});f(this,"targetPosition",{x:0,y:0});f(this,"centerPosition",{x:0,y:0});f(this,"originalScale",{x:1,y:1});f(this,"targetScale",{x:1,y:1});f(this,"defaultScale",{x:1,y:1});f(this,"transitionDuration",500);f(this,"transitionStartTime",null);f(this,"initialPinchCenter",null);f(this,"isGestureValid",!0);f(this,"lastTapTime",0);f(this,"doubleTapDelay",300);f(this,"doubleTapZoomFactor",1.5);f(this,"lastTapPosition",null);f(this,"tapDistanceThreshold",20);f(this,"tapDetectionEnabled",!0);f(this,"mapClickStartPosition",null);f(this,"mapClickStartTime",0);f(this,"mapClickTimeThreshold",300);f(this,"mapClickMoveThreshold",10);f(this,"shouldSuppressMapClick",!1);f(this,"isGestureHijacked",!1);f(this,"hijackedPointerId",null);f(this,"isHijackPaused",!1);f(this,"activeGestureSession",null);f(this,"interactionGraphics");f(this,"viewportBounds");f(this,"boundResetAnimation");f(this,"debouncedStopWheelRender");f(this,"debouncedLogWheelScale");f(this,"interactionState",{isInteracting:!1,isAnimating:!1,interactionTimer:null,renderReasons:new Set});f(this,"throttledAntiScale");f(this,"unsubscribeEnableInteraction",null);f(this,"suppressMapClick",()=>{this.shouldSuppressMapClick=!0});f(this,"handleGestureHijacked",e=>{var r,o;this.isGestureHijacked=!0,this.hijackedPointerId=e.pointerId,this.isHijackPaused=!1,this.clearTouches();const i=e.global.x-this.viewportBounds.x,s=e.global.y-this.viewportBounds.y;this.activeTouches.set(e.pointerId,{x:i,y:s}),this.firstTouchId=e.pointerId,this.dragStart={x:i,y:s},(o=(r=this.appService.events)==null?void 0:r.onGestureStart)==null||o.call(r)});this.appService=e;const i=e.getApp();this.viewportBounds=i.getViewportBounds(),this.eventMode="static",this.unsubscribeEnableInteraction=G(e.runtime,"enableInteraction",s=>{this.updateInteractionMode(s)}),this.updateInteractionMode(e.runtimeSnapshot.enableInteraction),this.interactionGraphics=new H,this.interactionGraphics.rect(0,0,this.viewportBounds.width,this.viewportBounds.height).fill({color:"#ffffff",alpha:0}),this.addChild(this.interactionGraphics),this.scaleMax=i.scaleMax,this.scaleMin=i.scaleMin,this.centerPosition={x:Math.round(this.viewportBounds.width/2),y:Math.round(this.viewportBounds.height/2)},this.originalPosition={x:Math.round(this.viewportBounds.width/2),y:Math.round(this.viewportBounds.height/2)},this.targetPosition={x:Math.round(this.viewportBounds.width/2),y:Math.round(this.viewportBounds.height/2)},this.throttledAntiScale=_t(s=>{this.appService.emitter.emit("antiScale",s)},16,{leading:!0,trailing:!0}),this.boundResetAnimation=this.resetAnimation.bind(this),this.debouncedStopWheelRender=zn(()=>{i.stopRender("wheel")},300),this.debouncedLogWheelScale=zn(s=>{w.debug("[Interaction] 滚轮缩放完成 - Scale:",s.toFixed(3))},500),this.setupInteraction()}updateInteractionMode(e){this.eventMode=e?"static":"none",w.debug(`[Interaction] 交互模式已更新: ${e?"启用":"禁用"}`)}setupInteraction(){this.on("pointerdown",e=>this.onPointerDown(e)),this.on("pointerup",e=>this.onPointerUp(e)),this.on("pointerupoutside",e=>this.onPointerUp(e)),this.on("pointermove",e=>this.onPointerMove(e)),this.on("wheel",e=>this.onWheel(e)),document.addEventListener("pointercancel",e=>{w.debug("[Interaction] Received global pointercancel"),this.handleGlobalCancel(e)})}handleGlobalCancel(e){const i=this.appService;if(this.isGestureHijacked){w.debug("[Interaction] 系统取消或移出视口,强制结束劫持手势");const s=i.getApp(),r=new _a(s.renderer.events);r.pointerId=e.pointerId,this.dispatchGestureEnd(r),this.exitGestureHijacked()}this.clearTouches()}resetPan(e){const i=this.appService,s=i.getApp(),r=i.appContainer;this.transitionStartTime!==null&&(s.ticker.remove(this.boundResetAnimation),this.transitionStartTime=null);const o=this.centerPosition.x-e.x*r.scale.x,a=this.centerPosition.y-e.y*r.scale.y;this.originalPosition={x:r.x,y:r.y},this.targetPosition={x:o,y:a},this.originalScale={x:r.scale.x,y:r.scale.y},this.targetScale={x:r.scale.x,y:r.scale.y};const h=Math.sqrt((r.x-o)**2+(r.y-a)**2),c=(d=>Math.pow(Math.min(1,d/1e3),.5))(h);this.transitionDuration=500+1e3*Math.min(1,Math.pow(c,2)),this.transitionStartTime=s.ticker.lastTime,s.ticker.add(this.boundResetAnimation)}setPanZoom({targetPosition:e,targetScale:i,setCenter:s=!1,setScale:r=!1}={},o=!0){const a=this.appService,h=a.getApp(),l=a.appContainer;if(s&&e&&(this.centerPosition={x:e.x,y:e.y},w.debug("[Interaction] Set center position:",this.centerPosition)),r&&i&&(this.defaultScale={x:i.x,y:i.y},w.debug("[Interaction] Set scale:",this.defaultScale)),this.originalPosition={x:l.x,y:l.y},this.originalScale={x:l.scale.x,y:l.scale.y},e?this.targetPosition=e:this.targetPosition={x:this.centerPosition.x,y:this.centerPosition.y},i?this.targetScale=i:this.targetScale=this.defaultScale,!o){l.position.set(this.targetPosition.x,this.targetPosition.y),l.scale.set(this.targetScale.x,this.targetScale.y),this.antiScale(this.targetScale.x),this.transitionStartTime!==null&&(h.ticker.remove(this.boundResetAnimation),this.transitionStartTime=null),w.debug("[Interaction] 直接设置缩放完成 - Scale:",this.targetScale.x.toFixed(3));return}const c=Math.sqrt((l.x-this.targetPosition.x)**2+(l.y-this.targetPosition.y)**2),u=(m=>Math.pow(Math.min(1,m/1e3),.5))(c),g=((m,x)=>Math.pow(Math.min(1,Math.abs(m-x)/Math.abs(.2-1)),.5))(l.scale.x,this.targetScale.x),y=u*.8+g*.2;this.transitionDuration=500+1e3*Math.min(1,Math.pow(y,2)),this.transitionStartTime!==null&&(h.ticker.remove(this.boundResetAnimation),this.interactionState.isAnimating=!1,h.stopRender("animation")),this.interactionState.isAnimating=!0,h.requestRender("animation",!0),this.transitionStartTime=h.ticker.lastTime,h.ticker.add(this.boundResetAnimation)}clearTouches(){var s,r;const i=this.appService.getApp();this.activeTouches.clear(),this.firstTouchId=null,this.secondTouchId=null,this.dragStart=null,this.initialTouchDistance=null,this.initialScale=null,this.initialPinchCenter=null,this.isGestureValid=!0,this.taintedPointers.clear(),this.transitionStartTime!==null&&(i.ticker.remove(this.boundResetAnimation),this.transitionStartTime=null),this.interactionState.isInteracting&&(this.interactionState.isInteracting=!1,(r=(s=this.appService.events)==null?void 0:s.onGestureEnd)==null||r.call(s)),i.stopRender("interaction")}checkEventListeners(){return{wheel:this.listenerCount("wheel"),pointerdown:this.listenerCount("pointerdown"),pointerup:this.listenerCount("pointerup"),pointerupoutside:this.listenerCount("pointerupoutside"),pointermove:this.listenerCount("pointermove")}}destroy(){this.checkEventListeners(),this.interactionState.interactionTimer&&clearTimeout(this.interactionState.interactionTimer),this.interactionState.renderReasons.clear(),this.interactionState.isInteracting=!1,this.interactionState.isAnimating=!1,this.debouncedStopWheelRender.cancel(),this.debouncedLogWheelScale.cancel(),this.unsubscribeEnableInteraction&&(this.unsubscribeEnableInteraction(),this.unsubscribeEnableInteraction=null),this.releaseGestureSession(),super.destroy()}hijack(e){if(this.activeGestureSession)throw new Error("[Interaction] A gesture session is already live; hijack is exclusive");this.handleGestureHijacked(e);const i={moveCallbacks:[],endCallbacks:[],ended:!1,session:null},s={onMove:r=>{i.ended||i.moveCallbacks.push(r)},onEnd:r=>{i.ended||i.endCallbacks.push(r)},cancel:()=>{this.activeGestureSession!==i||i.ended||(this.dispatchGestureEnd(e),this.exitGestureHijacked())}};return i.session=s,this.activeGestureSession=i,s}dispatchGestureMove(e){const i=this.activeGestureSession;if(!(!i||i.ended))for(const s of i.moveCallbacks)s(e)}dispatchGestureEnd(e){const i=this.activeGestureSession;if(!i||i.ended)return;i.ended=!0;const s=i.endCallbacks;this.activeGestureSession=null;for(const r of s)r(e)}releaseGestureSession(){this.activeGestureSession&&(this.activeGestureSession.ended=!0,this.activeGestureSession=null)}exitGestureHijacked(){var i,s;const e=this.appService;this.hijackedPointerId!==null&&!this.isHijackPaused&&(this.activeTouches.delete(this.hijackedPointerId),this.firstTouchId===this.hijackedPointerId&&(this.firstTouchId=null,this.dragStart=null),this.secondTouchId===this.hijackedPointerId&&(this.secondTouchId=null)),this.isGestureHijacked=!1,this.hijackedPointerId=null,this.isHijackPaused=!1,(s=(i=e.events)==null?void 0:i.onGestureEnd)==null||s.call(i)}forceEndGesture(){if(this.isGestureHijacked){w.debug("[Interaction] 强制结束劫持手势");const e=this.appService.getApp(),i=new _a(e.renderer.events);i.pointerId=this.hijackedPointerId,this.dispatchGestureEnd(i),this.exitGestureHijacked()}this.clearTouches()}pauseGestureHijack(){this.isHijackPaused=!0}resumeGestureHijack(){this.isHijackPaused=!1}antiScale(e){this.throttledAntiScale(e)}resetAnimation(){const e=this.appService,i=e.getApp(),s=e.appContainer;if(this.transitionStartTime===null)return;const{targetPosition:r,targetScale:o}=this,a=i.ticker.lastTime,h=Math.min(1,(a-this.transitionStartTime)/this.transitionDuration);if(h>=1)s.position.set(r.x,r.y),s.scale.set(o.x,o.y),this.antiScale(o.x),i.ticker.remove(this.boundResetAnimation),this.transitionStartTime=null,this.interactionState.isAnimating=!1,i.stopRender("animation"),w.debug("[Interaction] 动画缩放完成 - Scale:",s.scale.x.toFixed(3));else{const l=Cy(h),c=this.originalPosition.x+(r.x-this.originalPosition.x)*l,d=this.originalPosition.y+(r.y-this.originalPosition.y)*l,u=this.originalScale.x+(o.x-this.originalScale.x)*l,p=this.originalScale.y+(o.y-this.originalScale.y)*l;s.position.set(c,d),s.scale.set(u,p),this.antiScale(u)}}onWheel(e){const i=this.appService;if(this.isGestureHijacked){w.warn("⚠️ [onWheel] 被手势劫持阻止执行",{isGestureHijacked:this.isGestureHijacked,hijackedPointerId:this.hijackedPointerId,isHijackPaused:this.isHijackPaused});return}i.getApp().requestRender("wheel",!0),this.debouncedStopWheelRender();const{scaleMin:s,scaleMax:r}=this,o=i.appContainer;e.preventDefault();const a=e.global.x-this.viewportBounds.x,h=e.global.y-this.viewportBounds.y,l=(a-o.x)/o.scale.x,c=(h-o.y)/o.scale.y,d=e.deltaY>0?.95:1.05;let u=o.scale.x*d,p=o.scale.y*d;if(u=Math.max(s,Math.min(r,u)),p=Math.max(s,Math.min(r,p)),!(u!==o.scale.x||p!==o.scale.y))return;const y=a-l*u,m=h-c*p;try{o.scale.set(u,p),o.position.set(y,m),this.antiScale(u),this.debouncedLogWheelScale(u)}catch(x){w.error("❌ [onWheel] 应用缩放时发生错误:",x)}}onPointerDown(e){var l,c;const i=this.appService;this.interactionState.isInteracting||(this.interactionState.isInteracting=!0,i.getApp().requestRender("interaction",!0),(c=(l=i.events)==null?void 0:l.onGestureStart)==null||c.call(l)),this.isGestureHijacked&&e.pointerId!==this.hijackedPointerId&&!this.isHijackPaused&&this.pauseGestureHijack();const s=i.getApp(),r=i.appContainer;this.transitionStartTime!==null&&(s.ticker.remove(this.boundResetAnimation),this.transitionStartTime=null),this.activeTouches.size===0&&this.taintedPointers.size>0&&(w.debug("[Interaction] 清除污染指针列表,准备新手势",Array.from(this.taintedPointers)),this.taintedPointers.clear()),this.activeTouches.size===0&&(this.isGestureValid=!0,this.initialTouchDistance=null,this.initialScale=null,this.initialPinchCenter=null,this.dragStart=null,this.firstTouchId=null,this.secondTouchId=null),this.activeTouches.has(e.pointerId)&&this.activeTouches.size===1&&(this.isGestureValid=!0);const o=e.global.x-this.viewportBounds.x,a=e.global.y-this.viewportBounds.y;this.activeTouches.set(e.pointerId,{x:o,y:a});const h=this.activeTouches.size-this.taintedPointers.size;if(this.taintedPointers.size>0){w.debug("[Interaction] 存在污染指针,阻止多点触摸手势",Array.from(this.taintedPointers)),h===1&&!this.taintedPointers.has(e.pointerId)&&(this.firstTouchId=e.pointerId,this.dragStart={x:o,y:a});return}if(this.activeTouches.size===1)this.firstTouchId=e.pointerId,this.dragStart={x:o,y:a},this.mapClickStartPosition={x:o,y:a},this.mapClickStartTime=performance.now();else if(this.activeTouches.size===2){const d=Array.from(this.activeTouches.keys());this.secondTouchId=d.find(u=>u!==this.firstTouchId)||e.pointerId,this.setInitialScaleAndDistance(r),this.tapDetectionEnabled=!1}}onPointerUp(e){var r,o;const i=this.appService;if(this.taintedPointers.has(e.pointerId)&&(w.debug("[Interaction] 移除污染指针",e.pointerId),this.taintedPointers.delete(e.pointerId)),this.isGestureHijacked)if(e.pointerId===this.hijackedPointerId){this.dispatchGestureEnd(e),this.exitGestureHijacked();return}else this.isHijackPaused;if(!this.activeTouches.has(e.pointerId))return;const s=this.initialTouchDistance!==null&&this.initialScale!==null;if(this.activeTouches.delete(e.pointerId),w.debug(`[Interaction] onPointerUp, remaining touches: ${this.activeTouches.size}`),s&&this.activeTouches.size===1){this.isGestureValid=!1;const a=Array.from(this.activeTouches.keys());setTimeout(()=>{var h,l;!this.isGestureValid&&this.activeTouches.size>0&&(w.debug("[Interaction] 100ms 缓冲结束,检测到真正的幽灵指针,标记为污染并清理",a),a.forEach(c=>{this.activeTouches.has(c)&&(this.taintedPointers.add(c),this.activeTouches.delete(c),this.firstTouchId===c&&(this.firstTouchId=null,this.dragStart=null),this.secondTouchId===c&&(this.secondTouchId=null))}),this.activeTouches.size===0&&this.interactionState.isInteracting&&(w.debug("[Interaction] 清理幽灵指针后所有触摸点已释放,结束手势"),this.interactionState.isInteracting=!1,i.getApp().stopRender("interaction"),(l=(h=i.events)==null?void 0:h.onGestureEnd)==null||l.call(h)))},100),this.initialTouchDistance=null,this.initialScale=null,this.initialPinchCenter=null}e.pointerId===this.firstTouchId?(this.firstTouchId=null,this.dragStart=null,this.activeTouches.size===0&&this.tapDetectionEnabled&&this.detectDoubleTap(e),this.activeTouches.size===0&&!s&&this.detectMapClick(e)):e.pointerId===this.secondTouchId&&(this.secondTouchId=null),this.isGestureHijacked&&this.isHijackPaused&&this.activeTouches.size===1&&Array.from(this.activeTouches.keys())[0]===this.hijackedPointerId&&this.resumeGestureHijack(),this.activeTouches.size===0&&(this.isGestureValid=!0,this.initialTouchDistance=null,this.initialScale=null,this.initialPinchCenter=null,this.firstTouchId=null,this.secondTouchId=null,this.dragStart=null,this.tapDetectionEnabled=!0,this.interactionState.isInteracting&&(this.interactionState.isInteracting=!1,i.getApp().stopRender("interaction"),(o=(r=i.events)==null?void 0:r.onGestureEnd)==null||o.call(r)))}detectDoubleTap(e){const i=this.appService,{interactionConfig:s}=i;if(!s.enableDoubleTapZoom)return;const r=performance.now(),o={x:e.global.x-this.viewportBounds.x,y:e.global.y-this.viewportBounds.y};r-this.lastTapTime<this.doubleTapDelay&&this.lastTapPosition&&tt(o,this.lastTapPosition)<this.tapDistanceThreshold?(this.handleDoubleTap(o),this.lastTapTime=0,this.lastTapPosition=null):(this.lastTapTime=r,this.lastTapPosition=o)}detectMapClick(e){var h;const i=this.appService;if(!i.runtimeSnapshot.enableMapClickCapture||!((h=i.events)!=null&&h.onClickMap)||!this.mapClickStartPosition)return;const r=performance.now()-this.mapClickStartTime,o={x:e.global.x-this.viewportBounds.x,y:e.global.y-this.viewportBounds.y},a=tt(this.mapClickStartPosition,o);if(r<=this.mapClickTimeThreshold&&a<=this.mapClickMoveThreshold&&!this.shouldSuppressMapClick){const l=i.appContainer,c=i.mapState,d=(o.x-l.x)/l.scale.x,u=(o.y-l.y)/l.scale.y,p={x:d-((c==null?void 0:c.origin.x)||0),y:u-((c==null?void 0:c.origin.y)||0)};w.debug("[Interaction] 地图点击捕获",{screenPosition:o,containerPosition:{x:d,y:u},origin:c==null?void 0:c.origin,mapPosition:p,clickDuration:r,moveDistance:a}),i.events.onClickMap(p)}this.mapClickStartPosition=null,this.mapClickStartTime=0,this.shouldSuppressMapClick=!1}handleDoubleTap(e){const i=this.appService,s=i.getApp(),r=i.appContainer,{scaleMin:o,scaleMax:a,doubleTapZoomFactor:h}=this,l=e.x,c=e.y,d=(l-r.x)/r.scale.x,u=(c-r.y)/r.scale.y;let p=r.scale.x*h,g=r.scale.y*h;p=Math.max(o,Math.min(a,p)),g=Math.max(o,Math.min(a,g)),this.originalPosition={x:r.x,y:r.y},this.originalScale={x:r.scale.x,y:r.scale.y};const y=l-d*p,m=c-u*g;this.targetPosition={x:y,y:m},this.targetScale={x:p,y:g},this.interactionState.isAnimating=!0,s.requestRender("animation",!0),this.transitionDuration=300,this.transitionStartTime=s.ticker.lastTime,s.ticker.add(this.boundResetAnimation)}onPointerMove(e){if(this.isGestureHijacked&&!this.isHijackPaused)if(e.pointerId===this.hijackedPointerId){const r=e.global.x-this.viewportBounds.x,o=e.global.y-this.viewportBounds.y;this.activeTouches.set(e.pointerId,{x:r,y:o}),this.dispatchGestureMove(e);return}else return;if(!this.activeTouches.has(e.pointerId)||!this.isGestureValid)return;if(this.taintedPointers.size>0&&(this.initialTouchDistance!==null||this.initialScale!==null)){w.debug("[Interaction] 存在污染指针,阻止多点触摸手势移动");return}const i=e.global.x-this.viewportBounds.x,s=e.global.y-this.viewportBounds.y;this.activeTouches.set(e.pointerId,{x:i,y:s}),this.activeTouches.size===2&&this.initialTouchDistance!==null&&this.initialScale!==null&&this.applyPinchZoom(),this.activeTouches.size===1&&(this.initialTouchDistance!==null||this.initialScale!==null)&&(this.initialTouchDistance=null,this.initialScale=null,this.initialPinchCenter=null,this.secondTouchId=null),this.activeTouches.size===1&&e.pointerId===this.firstTouchId&&this.dragStart!==null&&!this.taintedPointers.has(e.pointerId)&&this.applyPan(e)}applyPan(e){const i=this.appService,s=this.activeTouches.get(e.pointerId),r=i.appContainer,{x:o,y:a}=this.dragStart;r.position.set(r.x+s.x-o,r.y+s.y-a),this.dragStart={x:s.x,y:s.y}}applyPinchZoom(){const i=this.appService.appContainer,s=Array.from(this.activeTouches.values());if(s.length<2||!this.initialTouchDistance||!this.initialScale||!this.initialPinchCenter)return;const r=tt(s[0],s[1]),o={x:(s[0].x+s[1].x)/2,y:(s[0].y+s[1].y)/2},a={x:(o.x-i.position.x)/i.scale.x,y:(o.y-i.position.y)/i.scale.y},h=(r/this.initialTouchDistance)**this.zoomFactor,l=Math.max(this.scaleMin,Math.min(this.scaleMax,this.initialScale.x*h)),c=Math.max(this.scaleMin,Math.min(this.scaleMax,this.initialScale.y*h));i.scale.set(l,c);let d=o.x-a.x*l,u=o.y-a.y*c;const p=o.x-this.initialPinchCenter.x,g=o.y-this.initialPinchCenter.y;d+=p,u+=g,i.position.set(d,u),this.antiScale(l),this.initialPinchCenter=o}setInitialScaleAndDistance(e){const i=Array.from(this.activeTouches.values());i.length<2||(this.initialTouchDistance=tt(i[0],i[1]),this.initialScale={x:e.scale.x,y:e.scale.y},this.initialPinchCenter={x:(i[0].x+i[1].x)/2,y:(i[0].y+i[1].y)/2})}}function bx(n){return{all:n=n||new Map,on:function(t,e){var i=n.get(t);i?i.push(e):n.set(t,[e])},off:function(t,e){var i=n.get(t);i&&(e?i.splice(i.indexOf(e)>>>0,1):n.set(t,[]))},emit:function(t,e){var i=n.get(t);i&&i.slice().map(function(s){s(e)}),(i=n.get("*"))&&i.slice().map(function(s){s(t,e)})}}}const wx="__ray_robot_map_debug_ring__",Sc="__ray_robot_map_late_lifecycle_markers__",Cx=200,_x=20;function Px(){return Date.now()}function Mx(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Hr(){try{return globalThis.localStorage??null}catch{return null}}function Tx(){var n;try{return((n=globalThis.document)==null?void 0:n.visibilityState)??null}catch{return null}}function Ax(n){if(!n||typeof n!="object")return null;const t=n;return typeof t.seq!="number"||typeof t.ts!="number"||typeof t.event!="string"||typeof t.sessionId!="string"?null:{seq:t.seq,ts:t.ts,event:t.event,sessionId:t.sessionId,instanceId:t.instanceId??null,visibilityState:t.visibilityState??null,rendererType:t.rendererType??null,mapId:t.mapId??null,detail:t.detail}}function Ka(n,t){if(!n)return[];try{const e=n.getItem(t);if(!e)return[];const i=JSON.parse(e);return Array.isArray(i)?i.map(s=>Ax(s)).filter(s=>s!==null):[]}catch{return[]}}function Rx(n,t,e){if(n)try{n.setItem(t,JSON.stringify(e))}catch{}}function kx(n){if(!n)return{};try{const t=n.getItem(Sc);if(!t)return{};const e=JSON.parse(t);return typeof e=="object"&&e?e:{}}catch{return{}}}function Ex(n=Hr()){return kx(n)}function Ix(n=Hr()){if(n)try{n.removeItem(Sc)}catch{}}function Dx(n={}){var g;const t=n.storage===void 0?Hr():n.storage,e=n.storageKey??wx,i=n.maxEntries??Cx,s=n.previousTailSize??_x,r=n.now??Px,o=((g=n.createSessionId)==null?void 0:g.call(n))??Mx(),a=Ka(t,e),h=a.length>0?a[a.length-1].sessionId:null;let l=a.length>0?a[a.length-1].seq:0;const c=()=>Ka(t,e);return{getSessionId:()=>o,hasStorage:()=>t!==null,readAll:c,readCurrentSession:()=>c().filter(y=>y.sessionId===o),readPreviousSessionTail:()=>h?c().filter(y=>y.sessionId===h).slice(-s):[],readLateLifecycleMarkers:()=>Ex(t),clear:()=>{if(Ix(t),!!t)try{t.removeItem(e)}catch{}},record:y=>{l+=1;const m={seq:l,ts:r(),event:y.event,sessionId:o,instanceId:y.instanceId??null,visibilityState:y.visibilityState??Tx(),rendererType:y.rendererType??null,mapId:y.mapId??null,detail:y.detail},x=[...c(),m].slice(-i);return Rx(t,e,x),m}}}let En=null;function In(){return En||(En=Dx()),En}class vc{constructor(t){this.app=t}getApp(){return this.app}getConfig(){return this.getApp().config}getDebuggerMode(){return!1}getRoomData(t){return this.getApp().managers.roomsManager.getRoomPropertyById(t)}get coords(){return this.getApp().coords}get ticker(){return this.getApp().ticker}get mapState(){return this.getApp().mapState}get isMapDrawn(){return this.getApp().isMapDrawn}get config(){return this.getConfig()}get gloalConfig(){return this.getConfig().global}get mapConfig(){return this.getConfig().map}get roomConfig(){return this.getConfig().room}get heatMapConfig(){return this.getConfig().heatmap}get pathConfig(){return this.getConfig().path}get carpetConfig(){return this.getConfig().carpet}get robotConfig(){return this.getConfig().robot}get chargingStationConfig(){return this.getConfig().chargingStation}get interactionConfig(){return this.getConfig().interaction}get controlsConfig(){return this.getConfig().controls}get furnitureConfig(){return this.getConfig().furniture}get dividerConfig(){return this.getConfig().divider}get detectedObjectConfig(){return this.getConfig().detectedObject}get snapshotConfig(){return this.getConfig().snapshot}get appContainer(){return this.getApp().components.appContainer}get interaction(){return this.getApp().components.interaction}get gestureController(){return this.getApp().components.interaction}get viewportContainer(){return this.getApp().components.viewportContainer}get mapManager(){return this.getApp().managers.mapManager}get pathManager(){return this.getApp().managers.pathManager}get heatmapManager(){return this.getApp().managers.heatmapManager}get controlsManager(){return this.getApp().managers.controlsManager}get detectedObjectManager(){return this.getApp().managers.detectedObjectManager}get customElementsManager(){return this.getApp().managers.customElementsManager}get roomsManager(){return this.getApp().managers.roomsManager}get editControlManager(){return this.getApp().managers.editControlManager}get furnitureManager(){return this.getApp().managers.furnitureManager}get runtime(){return this.getApp().runtime}get runtimeSnapshot(){return Sx(this.getApp().runtime)}isInteractionEnabled(){return this.runtimeSnapshot.enableInteraction}fixPrecision(t,e){return hc(t,e)}get events(){return this.getApp().events}get baseScale(){return this.getApp().components.interaction.targetScale.x}get currentScale(){return this.getApp().components.appContainer.scale.x}get emitter(){return this.getApp().emitter}getChargerPosition(){const t=this.mapState;return t?this.fixPrecision({x:t.charger.x-t.origin.x,y:t.charger.y-t.origin.y}):null}getRobotPosition(){const t=this.pathManager.robot;return t?t.getCurrentPosition():null}}const Fx=3.28084,Dn=100;class Bx{constructor(t=()=>"meter"){f(this,"cmPerPixel",null);f(this,"getDisplayUnit");this.getDisplayUnit=t}setResolution(t){if(!Number.isFinite(t)||t<=0){w.warn("[CoordinateSpace] Ignoring invalid resolution",t);return}this.cmPerPixel=t}isReady(){return this.cmPerPixel!=null}toPixels(t){const e=this.requireResolution("toPixels");return Ft(t*(Dn/e))}toMeters(t){const e=this.requireResolution("toMeters");return ut(t*(e/Dn))}toDisplayUnit(t){switch(this.getDisplayUnit()){case"feet":return t*Fx;case"centimeter":return t*Dn;case"meter":default:return t}}validateShape(t,e){const i=this.toPixels(e.minSize),s=e.maxSize!=null?this.toPixels(e.maxSize):void 0,r=jy(t,i,s);return Zy(r)}requireResolution(t){if(this.cmPerPixel==null)throw new Error(`[CoordinateSpace] ${t} called before map resolution is ready. Call setResolution(cmPerPixel) (done by MapApplication on map draw) before converting between meters and pixels.`);return this.cmPerPixel}}let Lx="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",Qa=(n=21)=>{let t="",e=n|0;for(;e--;)t+=Lx[Math.random()*64|0];return t};const zs=(n,t,e)=>{if(t!=null){if(typeof t!="number"||!Number.isFinite(t)||t<=n){w.warn(`[${e}] maxSize (${String(t)}) must be a finite number greater than minSize (${n}); ignoring.`);return}return t}};class zx extends W{constructor(e,i){super();f(this,"viewportBounds",{x:0,y:0,width:0,height:0});f(this,"maskGraphics",null);f(this,"containerElement",null);this.containerElement=i||window,this.calculateViewportBounds(e.global),this.position.set(this.viewportBounds.x,this.viewportBounds.y),this.createMask()}calculateViewportBounds(e){const{containerTop:i,containerLeft:s,containerWidth:r,containerHeight:o}=e,{width:a,height:h}=this.getContainerSize(),l=this.parseSize(s,a),c=this.parseSize(i,h),d=this.parseSize(r,a),u=this.parseSize(o,h);this.viewportBounds={x:l,y:c,width:d,height:u}}getContainerSize(){if(!this.containerElement)return{width:window.innerWidth,height:window.innerHeight};if(this.containerElement===window)return{width:window.innerWidth,height:window.innerHeight};const e=this.containerElement;return{width:e.clientWidth||window.innerWidth,height:e.clientHeight||window.innerHeight}}createMask(){this.maskGraphics=new H,this.maskGraphics.rect(0,0,this.viewportBounds.width,this.viewportBounds.height).fill(16777215),this.addChild(this.maskGraphics),this.mask=this.maskGraphics}parseSize(e,i){if(!isNaN(Number(e)))return Number(e);if(e=e.trim(),e.endsWith("%")){const s=parseFloat(e)/100;return i*s}if(e.endsWith("vw")){const s=parseFloat(e)/100;return window.innerWidth*s}if(e.endsWith("vh")){const s=parseFloat(e)/100;return window.innerHeight*s}if(e.endsWith("rpx")){const s=parseFloat(e),r=window.innerWidth/750;return s*r}return e.endsWith("px")||!isNaN(parseFloat(e))?parseFloat(e):(w.warn(`Cannot parse size value: ${e}`),0)}getViewportBounds(){return{...this.viewportBounds}}updateViewport(e){var i,s;this.calculateViewportBounds(e.global),this.position.set(this.viewportBounds.x,this.viewportBounds.y),(i=this.maskGraphics)==null||i.clear(),(s=this.maskGraphics)==null||s.rect(0,0,this.viewportBounds.width,this.viewportBounds.height).fill(16777215)}addContent(e){this.addChild(e)}}const Ox="interaction",bc="roomFill",wc="free",Nr="roomFloorType",Cc="carpet",_c="obstacle",Pc="heatmap",Mc="path",Pe="furniture",Ae="controls",Tc="roomInfo",Ye="detectedObject",Ai="customElement",Ri="customElementGif",Ac="chargingStation",Rc="robot",Ze="customCarpet",Re="editControls",Wx=[Ox,bc,wc,Nr,Cc,Ze,_c,Pc,Mc,Pe,Tc,Ye,Ai,Ri,Ac,Rc,Ae,Re],Gx=[Ae,Re,Ze,Ai,Ri,Ye,Pe];class Ux extends W{constructor(e){super();f(this,"layers",new Map);f(this,"mapRotation",0);f(this,"backgroundGraphics");f(this,"lastBackgroundState",null);this.appService=e;const s=this.appService.getApp().getViewportBounds();this.position.set(Math.round(s.width/2),Math.round(s.height/2)),this.pivot.set(0,0),this.backgroundGraphics=new H,this.backgroundGraphics.label="snapshotBackground",this.backgroundGraphics.visible=!1,this.addChild(this.backgroundGraphics),this.initializeLayers()}initializeLayers(){Object.values(Wx).forEach(i=>{const s=new W;s.label=i,i===Ae&&(s.isRenderGroup=!0),i===Re&&(s.isRenderGroup=!0),i===Nr&&(s.eventMode="none"),this.layers.set(i,s),this.addChild(s)})}getLayer(e){return this.layers.get(e)}addToLayer(e,i,s){const r=this.layers.get(e);return r?(s!==void 0&&(i.zIndex=s),r.addChild(i),!0):(w.warn("[AppContainer Debug] Layer not found:",e),!1)}removeFromLayer(e,i){const s=this.layers.get(e);return s&&i.parent===s?(s.removeChild(i),!0):!1}clearLayer(e){const i=this.layers.get(e);return i?(i.removeChildren(),!0):!1}setLayerVisibility(e,i){const s=this.layers.get(e);return s?(s.visible=i,!0):!1}updateOriginTrackedLayers(e,i){Gx.forEach(s=>{const r=this.layers.get(s);r&&r.position.set(e,i)})}getLayerVisibility(e){const i=this.layers.get(e);return i?i.visible:!1}setMapRotation(e){this.mapRotation=e*Math.PI/180,this.rotation=this.mapRotation}getMapRotation(){return this.mapRotation*180/Math.PI}getMapRotationRadians(){return this.mapRotation}getSnapshotBounds(){this.layers.forEach(s=>{});const e=this.backgroundGraphics.visible;this.backgroundGraphics.visible=!1;const i=this.getLocalBounds();return this.backgroundGraphics.visible=e,new J(i.x,i.y,i.width,i.height)}updateBackground(e,i){if(!i){this.backgroundGraphics.visible=!1,this.lastBackgroundState=null;return}const s=this.getSnapshotBounds(),{x:r,y:o,width:a,height:h}=s;if(this.lastBackgroundState&&this.lastBackgroundState.color===e&&this.lastBackgroundState.width===a&&this.lastBackgroundState.height===h&&this.lastBackgroundState.x===r&&this.lastBackgroundState.y===o){this.backgroundGraphics.visible=!0;return}this.backgroundGraphics.clear(),this.backgroundGraphics.rect(r,o,a,h).fill(e),this.backgroundGraphics.visible=!0,this.lastBackgroundState={color:e,x:r,y:o,width:a,height:h}}}class Xt extends $t{constructor(e,i){super(i);f(this,"throttledUpdateScale");f(this,"fixedWidth",0);f(this,"fixedHeight",0);f(this,"isFixedSizeSet",!1);f(this,"sizeFixed",!0);f(this,"baselineScale",1);this.appService=e,this.anchor.set(.5),this.visible=!1,this.throttledUpdateScale=_t(this.updateScale.bind(this),30,{leading:!0,trailing:!0}),this.registerScaleListener()}setFixedSize(e,i){this.fixedWidth=e,this.fixedHeight=i,this.isFixedSizeSet=!0,this.applySize()}setSizeFixed(e){this.sizeFixed=e,this.baselineScale=1,e&&this.isFixedSizeSet?this.applySize():!e&&this.isFixedSizeSet&&this.applySize()}set width(e){if(this.isFixedSizeSet){w.warn("EnhancedSprite: 使用 setFixedSize() 方法来设置宽度");return}this.setFixedSize(e,this.fixedHeight||e)}set height(e){if(this.isFixedSizeSet){w.warn("EnhancedSprite: 使用 setFixedSize() 方法来设置高度");return}this.setFixedSize(this.fixedWidth||e,e)}get width(){return this.fixedWidth||super.width}get height(){return this.fixedHeight||super.height}registerScaleListener(){this.appService.emitter.on("antiScale",this.throttledUpdateScale)}applySize(){if(this.destroyed||!this.scale||!this.isFixedSizeSet||!this.texture||this.texture.width===0||this.texture.height===0)return;const e=this.appService,i=this.fixedWidth/this.texture.width,s=this.fixedHeight/this.texture.height;if(this.sizeFixed){const r=e.currentScale;if(r===0)return;const o=i/r,a=s/r;this.scale&&super.scale.set(o,a)}else this.scale&&super.scale.set(i/this.baselineScale,s/this.baselineScale)}updateScale(e){this.destroyed||!this.scale||this.sizeFixed&&(this.isFixedSizeSet?this.applySize():e!==0&&super.scale.set(1/e))}async loadTextureAndSetSize(e,i){try{const s=this.appService,r=await V.load(e);if(this.destroyed||(this.texture=r,this.destroyed)||(i.sizeFixed!==void 0&&this.setSizeFixed(i.sizeFixed),this.setFixedSize(i.width,i.height),this.destroyed))return;s.getApp().renderOnceNextFrame()}catch(s){w.error(`Failed to load texture "${e}":`,s)}}draw(e,i){const{x:s,y:r,rotation:o=0}=e;i&&!this.visible?this.visible=i():!i&&!this.visible&&(this.visible=!0),this.rotation=o,this.position.set(s,r)}set texture(e){super.texture=e,this.isFixedSizeSet&&e&&e.width>0&&e.height>0&&this.applySize()}get texture(){return super.texture}destroy(e){this.appService.emitter.off("antiScale",this.throttledUpdateScale),this.throttledUpdateScale.cancel(),super.destroy(e)}}class Hx extends Xt{constructor(t){super(t),this.appService=t,this.initializeSprite()}async initializeSprite(){const t=this.appService;await this.loadTextureAndSetSize("chargingStation",t.chargingStationConfig.icon)}async draw({x:t,y:e,rotation:i}){const s=this.appService;super.draw({x:t,y:e,rotation:i},()=>s.runtimeSnapshot.showChargingStation)}}class kc extends H{constructor(e,i){super();f(this,"currentPosition",null);f(this,"config");f(this,"handleScaleChange",()=>{this.redraw()});this.appService=e,this.setupAntiScaleListener(),this.config=i.config}setupAntiScaleListener(){this.appService.emitter.on("antiScale",this.handleScaleChange)}draw(e){const i=this.appService;this.currentPosition=e;const{size:s,color:r,strokeWidth:o,strokeColor:a,strokeDashed:h,strokeDashArray:l}=this.config;this.clear();const c=i.coords.toPixels(ut(s)),d=i.getApp().toFixedSize(o);this.setFillStyle({color:r}),h&&l.length>=2?this.drawDashedCircle(e,c,a,d,l):this.circle(e.x,e.y,c).fill().stroke({color:a,width:d,cap:"round",join:"round"})}drawDashedCircle(e,i,s,r,o){const a=this.appService;this.circle(e.x,e.y,i).fill();const h=a.getApp().toFixedSize(o[0]),l=a.getApp().toFixedSize(o[1]),c=2*Math.PI*i,d=h+l,u=Math.floor(c/d);if(u===0){this.circle(e.x,e.y,i).stroke({color:s,width:r,cap:"round",join:"round"});return}const p=c/u,g=p*(h/d);for(let y=0;y<u;y++){const m=y*p/i,x=(y*p+g)/i,S=Math.max(4,Math.ceil(Math.abs(x-m)*i/2)),v=(x-m)/S;for(let b=0;b<=S;b++){const P=m+v*b,C=e.x+i*Math.cos(P),_=e.y+i*Math.sin(P);b===0?this.moveTo(C,_):this.lineTo(C,_)}}this.stroke({color:s,width:r,cap:"round",join:"round"})}redraw(){this.currentPosition&&this.draw(this.currentPosition)}destroy(){this.appService.emitter.off("antiScale",this.handleScaleChange),super.destroy()}}class vt{constructor(t,e={}){f(this,"target");f(this,"isPointerDown",!1);f(this,"pointerDownPos",null);f(this,"clickThreshold");f(this,"stopPropagation");f(this,"clickCallback",null);this.target=t,this.clickThreshold=e.clickThreshold??10,this.stopPropagation=e.stopPropagation??!1,this.clickCallback=e.onClick||null,this.setup()}setup(){this.target.interactive=!0,this.target.eventMode="static",this.target.on("pointerdown",this.handlePointerDown.bind(this)),this.target.on("pointermove",this.handlePointerMove.bind(this)),this.target.on("pointerup",this.handlePointerUp.bind(this)),this.target.on("pointerupoutside",this.handlePointerUpOutside.bind(this))}handlePointerDown(t){this.stopPropagation&&t.stopPropagation(),this.isPointerDown=!0,this.pointerDownPos={x:t.globalX,y:t.globalY}}handlePointerMove(t){if(this.stopPropagation&&t.stopPropagation(),this.isPointerDown&&this.pointerDownPos){const e=t.globalX-this.pointerDownPos.x,i=t.globalY-this.pointerDownPos.y;Math.sqrt(e*e+i*i)>this.clickThreshold&&(this.isPointerDown=!1,this.pointerDownPos=null)}}handlePointerUp(t){if(this.stopPropagation&&t.stopPropagation(),this.isPointerDown&&this.pointerDownPos){const e=t.globalX-this.pointerDownPos.x,i=t.globalY-this.pointerDownPos.y;Math.sqrt(e*e+i*i)<=this.clickThreshold&&this.clickCallback&&this.clickCallback(t,this.target)}this.isPointerDown=!1,this.pointerDownPos=null}handlePointerUpOutside(){this.isPointerDown=!1,this.pointerDownPos=null}setClickCallback(t){return this.clickCallback=t,this}setClickThreshold(t){return this.clickThreshold=t,this}getTarget(){return this.target}isInteracting(){return this.isPointerDown}destroy(){this.target.off("pointerdown",this.handlePointerDown),this.target.off("pointermove",this.handlePointerMove),this.target.off("pointerup",this.handlePointerUp),this.target.off("pointerupoutside",this.handlePointerUpOutside),this.clickCallback=null}}class Nx extends W{constructor(e){super();f(this,"chargingStation");f(this,"ring");f(this,"unsubscribeFns",[]);f(this,"clickHandler");this.appService=e,e.appContainer.addToLayer(Ac,this),this.ring=new kc(this.appService,{config:this.appService.chargingStationConfig.ring}),this.ring.visible=this.appService.runtimeSnapshot.showChargingStationRing,this.addChild(this.ring),this.chargingStation=new Hx(this.appService),this.addChild(this.chargingStation);const i=G(this.appService.runtime,"showChargingStationRing",s=>{w.log(`[runtime] showChargingStationRing: ${s}`),this.ring.visible=s});this.unsubscribeFns.push(i),this.initClickInteraction()}async draw({x:e,y:i,rotation:s}){if(e===0&&i===0){this.visible=!1;return}this.visible=!0,this.ring.draw({x:e,y:i}),await this.chargingStation.draw({x:e,y:i,rotation:s})}initClickInteraction(){const{enableChargingStationClick:e}=this.appService.interactionConfig;e&&(this.clickHandler||(this.clickHandler=new vt(this.chargingStation,{onClick:()=>{var i;if((i=this.appService.events)!=null&&i.onClickChargingStation){const s=this.appService.getChargerPosition()??{x:0,y:0};this.appService.events.onClickChargingStation({rotation:this.chargingStation.rotation,...s})}}})))}destroy(){this.unsubscribeFns.forEach(e=>e()),this.unsubscribeFns=[],this.ring.destroy(),this.clickHandler&&this.clickHandler.destroy(),super.destroy()}}class Vx extends W{constructor(e){super({isRenderGroup:!0});f(this,"carpetSprite",null);f(this,"carpetMask",null);this.appService=e,this.appService.appContainer.addToLayer(Cc,this)}async createCarpetFromRasterData(e,i){const s=this.appService;if(!s.runtimeSnapshot.showCarpet||(this.clearCarpet(),e.length===0))return;const{src:r,opacity:o,scale:a}=s.carpetConfig,h=await V.load(r);if(!h){w.warn(`Carpet texture not found: ${r}`);return}const l=this.createCarpetGraphics(e,i),c=l.getLocalBounds();if(c.width===0||c.height===0)return;const d=new Cs({texture:h,width:c.width,height:c.height});d.x=c.x,d.y=c.y,d.alpha=o,d.tileScale.set(a);const u=new W;u.addChild(l),d.mask=u,this.addChild(d),this.carpetSprite=d,this.carpetMask=u,s.getApp().renderOnceNextFrame()}createCarpetGraphics(e,i){const s=new H;for(let r=0;r<e.length;r++){const o=e[r],a=o%i,h=Math.floor(o/i);s.rect(a,h,1,1)}return s.fill(16777215),s}clearCarpet(){this.carpetSprite&&(this.removeChild(this.carpetSprite),this.carpetSprite.destroy(),this.carpetSprite=null),this.carpetMask&&(this.carpetMask.destroy({children:!0}),this.carpetMask=null)}async createCarpetFromStructuredData(e){const i=this.appService;if(!i.runtimeSnapshot.showCarpet||!e||(this.clearCarpet(),e.length===0))return;const{src:s,opacity:r,scale:o}=i.carpetConfig,a=await V.load(s);if(!a){w.warn(`Carpet texture not found: ${s}`);return}const h=this.createCarpetGraphicsFromStructuredData(e),l=h.getLocalBounds();if(l.width===0||l.height===0)return;const c=new Cs({texture:a,width:l.width,height:l.height});c.x=l.x,c.y=l.y,c.alpha=r,c.tileScale.set(o);const d=new W;d.addChild(h),c.mask=d,this.addChild(c),this.carpetSprite=c,this.carpetMask=d,i.getApp().renderOnceNextFrame()}createCarpetGraphicsFromStructuredData(e){const i=new H;for(const s of e){const r=s.coordinates;for(let o=0;o<r.length;o+=2){const a=r[o],h=r[o+1];i.rect(a,h,1,1)}}return i.fill(16777215),i}destroy(){this.clearCarpet(),super.destroy()}}class Ja extends H{constructor(t){super(),this.appService=t,this.appService.appContainer.addToLayer(wc,this)}draw(t){const e=this.appService;this.clear(),this.setFillStyle({color:e.mapConfig.freeColor});for(const i of t){const s=i.coordinates;for(let r=0;r<s.length;r+=2){const o=s[r],a=s[r+1];this.rect(o,a,1,1)}}this.fill()}destroy(t){super.destroy(t)}}class th extends H{constructor(t){super(),this.appService=t,this.appService.appContainer.addToLayer(_c,this)}draw(t){const e=this.appService;this.clear(),this.setFillStyle({color:e.mapConfig.obstacleColor});for(const i of t){const s=i.coordinates;for(let r=0;r<s.length;r+=2){const o=s[r],a=s[r+1];this.rect(o,a,1,1)}}this.fill()}drawRaster(t,e){const i=this.appService;if(this.clear(),t.length!==0){this.setFillStyle({color:i.mapConfig.obstacleColor});for(let s=0;s<t.length;s+=ne){const r=Math.min(s+ne,t.length);for(let o=s;o<r;o++){const a=t[o],h=a%e,l=Math.floor(a/e);this.rect(h,l,1,1)}this.fill(),r<t.length&&this.setFillStyle({color:i.mapConfig.obstacleColor})}}}destroy(t){super.destroy(t)}}class eh extends W{constructor(e){super({isRenderGroup:!0});f(this,"roomGraphicsMap",new Map);f(this,"roomContextMap",new Map);f(this,"roomClickHandlerMap",new Map);f(this,"unsubscribeFns",[]);f(this,"mapWidth",0);f(this,"rasterRoomDataMap",new Map);f(this,"structuredRoomGeometry",new Map);this.appService=e,this.appService.appContainer.addToLayer(bc,this);const i=Ls(this.appService.config.room.colors,()=>{this.refreshRoomColors()});this.unsubscribeFns.push(i)}draw(e){const i=this.appService;this.clearRooms();const s=i.roomConfig,{selectRoomIds:r,enableRoomSelection:o}=i.runtimeSnapshot;e.forEach(a=>{const h=a.id>=255,l=new H,c=new gt,d=new gt,u=new gt;if(h)c.setFillStyle({color:a.color}),d.setFillStyle({color:a.color}),u.setFillStyle({color:a.color});else{const p=a.colorIndex??0,g=s.colors.active[p%s.colors.active.length],y=s.colors.inactive[p%s.colors.inactive.length],m=(s.colors.normal||s.colors.active)[p%(s.colors.normal||s.colors.active).length];c.setFillStyle({color:g}),d.setFillStyle({color:y}),u.setFillStyle({color:m})}if(c.poly(a.polyPoints).fill(),d.poly(a.polyPoints).fill(),u.poly(a.polyPoints).fill(),a.outlinePoints.forEach(p=>{c.rect(p.x,p.y,1,1).fill(),d.rect(p.x,p.y,1,1).fill(),u.rect(p.x,p.y,1,1).fill()}),h?l.context=c:l.context=o?r.includes(a.id)?c:d:u,!h){const p=new vt(l,{clickThreshold:10,onClick:()=>{this.handleRoomClick(a.id)}});this.roomClickHandlerMap.set(a.id,p),this.structuredRoomGeometry.set(a.id,{polyPoints:a.polyPoints,outlinePoints:a.outlinePoints,colorIndex:a.colorIndex??0})}this.roomGraphicsMap.set(a.id,l),this.roomContextMap.set(a.id,{activeContext:c,inactiveContext:d,normalContext:u}),this.addChild(l)})}drawRaster(e){const i=this.appService;if(this.clearRooms(),this.mapWidth=e.width,e.sortedRooms.length===0)return;const{selectRoomIds:s,enableRoomSelection:r}=i.runtimeSnapshot;e.sortedRooms.forEach(o=>{this.drawRasterRoom(o,r,s)})}drawRasterRoom(e,i,s){const{roomId:r,pixelIndices:o,activeColor:a,inactiveColor:h}=e,c=this.appService.roomConfig;let d=a;const u=typeof r=="number";if(u){const S=e.colorIndex??0;d=(c.colors.normal||c.colors.active)[S%(c.colors.normal||c.colors.active).length]}const p=new H,g=new gt,y=new gt,m=new gt;g.setFillStyle({color:a}),y.setFillStyle({color:h}),m.setFillStyle({color:d}),this.drawPixelPointsInBatches(g,o,ne,this.mapWidth),this.drawPixelPointsInBatches(y,o,ne,this.mapWidth),this.drawPixelPointsInBatches(m,o,ne,this.mapWidth);const x=u&&s.includes(r);if(p.context=i?u&&x?g:y:m,u){const S=new vt(p,{clickThreshold:10,onClick:()=>{this.handleRoomClick(r)}});this.roomClickHandlerMap.set(r,S)}this.roomGraphicsMap.set(r,p),this.roomContextMap.set(r,{activeContext:g,inactiveContext:y,normalContext:m}),this.rasterRoomDataMap.set(r,e),this.addChild(p)}drawPixelPointsInBatches(e,i,s,r){for(let o=0;o<i.length;o+=s){const a=Math.min(o+s,i.length);for(let h=o;h<a;h++){const l=i[h],c=l%r,d=Math.floor(l/r);e.rect(c,d,1,1)}e.fill()}}handleRoomClick(e){var s,r;const i=this.appService;(r=(s=i.events)==null?void 0:s.onClickRoom)==null||r.call(s,i.getRoomData(e)??{id:e})}setRoomStateBySelectIds(e){const i=this.appService,{enableRoomSelection:s}=i.runtimeSnapshot;this.roomGraphicsMap.forEach((r,o)=>{if(typeof o=="number"){const a=this.roomContextMap.get(o);if(a)if(s){const h=e.includes(o);r.context=h?a.activeContext:a.inactiveContext}else r.context=a.normalContext}})}setRoomState(e,i){const s=this.roomGraphicsMap.get(e),r=this.roomContextMap.get(e);if(!s||!r){w.warn(`Room ${e} not found`);return}typeof e=="number"&&(s.context=i?r.activeContext:r.inactiveContext)}setAllRoomsState(e){this.roomGraphicsMap.forEach((i,s)=>{typeof s=="number"&&this.setRoomState(s,e)})}getRoomGraphicsMap(){const e=new Map;return this.roomGraphicsMap.forEach((i,s)=>{typeof s=="number"&&e.set(s,i)}),e}getRasterRoomData(e){return this.rasterRoomDataMap.get(e)||null}getMapWidth(){return this.mapWidth}isWallIntersectsAnyRoom(e){const s=this.appService.getApp().mapState;if(!s)return w.warn("[RoomFill] Map state not available"),!1;if(!e||e.length!==2)return w.warn("[RoomFill] Invalid wall points provided"),!1;const[r,o]=e,a={x:r.x+s.origin.x,y:r.y+s.origin.y},h={x:o.x+s.origin.x,y:o.y+s.origin.y};return s.mapType==="raster"?this.isWallIntersectsAnyRoomRaster(a,h):this.isWallIntersectsAnyRoomStructured(a,h)}isZoneIntersectsAnyRoom(e){const s=this.appService.getApp().mapState;if(!s)return w.warn("[RoomFill] Map state not available"),!1;if(!e||e.length!==4)return w.warn("[RoomFill] Invalid zone points provided"),!1;const r=e.map(o=>({x:o.x+s.origin.x,y:o.y+s.origin.y}));return s.mapType==="raster"?this.isZoneIntersectsAnyRoomRaster(r):this.isZoneIntersectsAnyRoomStructured(r)}isWallIntersectsAnyRoomRaster(e,i){if(this.mapWidth===0||this.rasterRoomDataMap.size===0)return!1;const s=this.getLinePixels(e,i);for(const r of this.rasterRoomDataMap.values())for(const o of s)if(cc(r.pixelIndices,o))return!0;return!1}isWallIntersectsAnyRoomStructured(e,i){const r=this.appService.mapManager.getAllRooms();for(const o of r)if(!(!o.outlinePoints||o.outlinePoints.length<3)){if(kt(e,o.outlinePoints,!0)||kt(i,o.outlinePoints,!0))return!0;for(let a=0;a<o.outlinePoints.length;a++){const h=o.outlinePoints[a],l=o.outlinePoints[(a+1)%o.outlinePoints.length];if(Wi(e,i,h,l))return!0}}return!1}isZoneIntersectsAnyRoomRaster(e){if(this.mapWidth===0||this.rasterRoomDataMap.size===0)return!1;const i=[[e[0],e[1]],[e[1],e[2]],[e[2],e[3]],[e[3],e[0]]];for(const[r,o]of i)if(this.isWallIntersectsAnyRoomRaster(r,o))return!0;const s=this.rasterRoomDataMap.values().next().value;if(s&&s.pixelIndices.length>0){const r=s.pixelIndices[0],o=r%this.mapWidth,a=Math.floor(r/this.mapWidth);if(kt({x:o,y:a},e,!0))return!0}return!1}isZoneIntersectsAnyRoomStructured(e){const s=this.appService.mapManager.getAllRooms(),r=[[e[0],e[1]],[e[1],e[2]],[e[2],e[3]],[e[3],e[0]]];for(const o of s)if(!(!o.outlinePoints||o.outlinePoints.length<3)){for(const a of e)if(kt(a,o.outlinePoints,!0))return!0;for(const a of o.outlinePoints)if(kt(a,e,!0))return!0;for(const[a,h]of r)for(let l=0;l<o.outlinePoints.length;l++){const c=o.outlinePoints[l],d=o.outlinePoints[(l+1)%o.outlinePoints.length];if(Wi(a,h,c,d))return!0}}return!1}getLinePixels(e,i){const r=this.appService.getApp().mapState;if(!r)return[];const o=r.height,a=[],h=Math.round(e.x),l=Math.round(e.y),c=Math.round(i.x),d=Math.round(i.y),u=Math.abs(c-h),p=Math.abs(d-l),g=h<c?1:-1,y=l<d?1:-1;let m=u-p,x=h,S=l;for(;;){if(x>=0&&x<this.mapWidth&&S>=0&&S<o){const b=S*this.mapWidth+x;a.push(b)}if(x===c&&S===d)break;const v=2*m;v>-p&&(m-=p,x+=g),v<u&&(m+=u,S+=y)}return a}getZonePixels(e,i,s,r){const a=this.appService.getApp().mapState;if(!a)return[];const h=a.height,l=[],c=Math.max(0,Math.floor(e)),d=Math.min(this.mapWidth-1,Math.ceil(s)),u=Math.max(0,Math.floor(i)),p=Math.min(h-1,Math.ceil(r));for(let g=u;g<=p;g++)for(let y=c;y<=d;y++){const m=g*this.mapWidth+y;l.push(m)}return l}refreshRoomColors(){const{selectRoomIds:e,enableRoomSelection:i}=this.appService.runtimeSnapshot,s=this.appService.roomConfig;this.roomGraphicsMap.forEach((r,o)=>{if(typeof o!="number")return;const a=this.roomContextMap.get(o),h=this.structuredRoomGeometry.get(o);if(a&&h){const l=h.colorIndex,c=s.colors.active[l%s.colors.active.length],d=s.colors.inactive[l%s.colors.inactive.length],u=(s.colors.normal||s.colors.active)[l%(s.colors.normal||s.colors.active).length];a.activeContext.clear(),a.activeContext.setFillStyle({color:c}),a.activeContext.poly(h.polyPoints).fill(),h.outlinePoints.forEach(p=>{a.activeContext.rect(p.x,p.y,1,1).fill()}),a.inactiveContext.clear(),a.inactiveContext.setFillStyle({color:d}),a.inactiveContext.poly(h.polyPoints).fill(),h.outlinePoints.forEach(p=>{a.inactiveContext.rect(p.x,p.y,1,1).fill()}),a.normalContext.clear(),a.normalContext.setFillStyle({color:u}),a.normalContext.poly(h.polyPoints).fill(),h.outlinePoints.forEach(p=>{a.normalContext.rect(p.x,p.y,1,1).fill()}),r.context=i?e.includes(o)?a.activeContext:a.inactiveContext:a.normalContext}else if(a){const l=this.rasterRoomDataMap.get(o);if(l){const c=l.colorIndex??0,d=s.colors.active[c%s.colors.active.length],u=s.colors.inactive[c%s.colors.inactive.length],p=(s.colors.normal||s.colors.active)[c%(s.colors.normal||s.colors.active).length];a.activeContext.clear(),a.activeContext.setFillStyle({color:d}),this.drawPixelPointsInBatches(a.activeContext,l.pixelIndices,ne,this.mapWidth),a.inactiveContext.clear(),a.inactiveContext.setFillStyle({color:u}),this.drawPixelPointsInBatches(a.inactiveContext,l.pixelIndices,ne,this.mapWidth),a.normalContext.clear(),a.normalContext.setFillStyle({color:p}),this.drawPixelPointsInBatches(a.normalContext,l.pixelIndices,ne,this.mapWidth),r.context=i?e.includes(o)?a.activeContext:a.inactiveContext:a.normalContext}}}),this.appService.getApp().renderOnceNextFrame()}clearRooms(){this.children.length===0&&this.roomGraphicsMap.size===0||(this.roomGraphicsMap.forEach(e=>{try{e.destroy()}catch(i){w.warn("Error destroying room graphics:",i)}}),this.roomGraphicsMap.clear(),this.roomContextMap.forEach(e=>{try{e.activeContext.destroy(),e.inactiveContext.destroy(),e.normalContext.destroy()}catch(i){w.warn("Error destroying graphics context:",i)}}),this.roomContextMap.clear(),this.roomClickHandlerMap.forEach(e=>{try{e.destroy()}catch(i){w.warn("Error destroying click handler:",i)}}),this.roomClickHandlerMap.clear(),this.removeChildren(),this.rasterRoomDataMap.clear(),this.structuredRoomGeometry.clear())}destroy(){this.unsubscribeFns.forEach(e=>e()),this.unsubscribeFns=[],this.clearRooms(),super.destroy()}}class $x{constructor(t){f(this,"obstacle");f(this,"free");f(this,"roomFill");f(this,"carpet");f(this,"chargingStation");f(this,"mapBounds",{minX:0,minY:0,maxX:0,maxY:0});f(this,"lastMapId",null);f(this,"lastOrigin",null);f(this,"lastSize",null);f(this,"lastStatus",null);f(this,"roomGeometryMap",new Map);f(this,"rasterRoomPixelsMap",new Map);f(this,"fourColorCache",null);f(this,"carpetData",null);f(this,"unsubscribeFns",[]);this.appService=t,this.obstacle=new th(this.appService),this.free=new Ja(this.appService),this.roomFill=new eh(this.appService),this.carpet=new Vx(this.appService),this.chargingStation=new Nx(this.appService),this.validateColorConfig();const e=G(t.runtime,"enableRoomSelection",o=>{if(w.log(`[runtime] enableRoomSelection: ${o}`),o){this.roomFill.setAllRoomsState(!1);const a=this.appService.runtimeSnapshot.selectRoomIds;this.roomFill.setRoomStateBySelectIds(a)}else this.roomFill.setAllRoomsState(!0)}),i=G(t.runtime,"selectRoomIds",o=>{w.log(`[runtime] selectRoomIds: ${o}`),this.roomFill.setRoomStateBySelectIds(o)}),s=G(t.runtime,"showChargingStation",o=>{w.log(`[runtime] showChargingStation: ${o}`),this.chargingStation.visible=o}),r=G(t.runtime,"showCarpet",o=>{w.log(`[runtime] showCarpet: ${o}`),o?t.getApp().managers.customCarpetManager.getCustomCarpets().length===0&&this.createCarpet():this.carpet.clearCarpet()});this.unsubscribeFns.push(e,i,s,r)}async drawMap(t){const e=this.appService,{id:i,obstacles:s,free:r,rooms:o,charger:a,carpet:h,status:l,origin:c,size:d}=t;this.clearComponents(),this.resetGeometryData();const u=this.processRoomsGeometry(o);this.roomFill.draw(u),r&&this.free.draw(r),s&&this.obstacle.draw(s),this.carpetData=h,this.createCarpet();const p=this.mergeLayerBounds();io(p,this.mapBounds)||(w.debug("[Map] Map bounds updated:",p),this.mapBounds=p,this.shouldFitMapToView(i,l===1,{x:c[0],y:c[1]},{x:d[0],y:d[1]})&&(e.getApp().fitMapToView(this.mapBounds),this.lastMapId=i,this.lastOrigin={x:c[0],y:c[1]},this.lastSize={x:d[0],y:d[1]},this.lastStatus=l===1));const g=((t.charger.angle??0)+e.chargingStationConfig.rotationCorrection)*Math.PI/180;return await this.chargingStation.draw({x:a.coordinate[0],y:a.coordinate[1],rotation:g}),await e.roomsManager.refresh(),!0}async drawRasterMap(t,e){const i=this.appService;this.clearComponents();const{id:s,width:r,height:o,charger:a,chargerDirection:h,status:l,origin:c}=e;w.debug("[Map] Parsed Raster Map Data",t),this.obstacle.drawRaster(t.obstacles,r),this.carpetData=this.convertRasterToStructuredData(t.carpet,r),i.getApp().managers.customCarpetManager.getCustomCarpets().length===0&&this.createCarpet();const u=this.processRasterData(t);this.roomFill.drawRaster(u);const p=rx(t,r,o);io(p,this.mapBounds)||(w.debug("[Map] Raster map bounds updated:",p),this.mapBounds=p,this.shouldFitMapToView(s,l,c,{x:r,y:o})&&(i.getApp().fitMapToView(this.mapBounds),this.lastMapId=s,this.lastOrigin={...c},this.lastSize={x:r,y:o},this.lastStatus=l));const g=(h+i.chargingStationConfig.rotationCorrection)*Math.PI/180;return await this.chargingStation.draw({x:a.x,y:a.y,rotation:g}),this.generateRoomGeometryFromRaster(t),await i.roomsManager.refresh(),!0}resetGeometryData(){this.roomGeometryMap.clear(),this.rasterRoomPixelsMap.clear(),this.fourColorCache=null,this.mapBounds={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}shouldFitMapToView(t,e,i,s){const r=this.appService,{originChangeAutoFitThreshold:o,sizeChangeAutoFitThreshold:a}=r.getApp().config.map;if(this.lastMapId!==t)return w.debug("[Map] Map ID changed, triggering fitMapToView"),!0;if(this.lastStatus!==null&&this.lastStatus!==e)return w.debug(`[Map] Map status changed (${this.lastStatus} -> ${e}), triggering fitMapToView`),!0;if(this.lastOrigin&&i){const h=Math.abs(i.x-this.lastOrigin.x),l=Math.abs(i.y-this.lastOrigin.y);if(h>o||l>o)return w.debug(`[Map] Origin change exceeded threshold (deltaX: ${h}, deltaY: ${l}, threshold: ${o}), triggering fitMapToView`),!0}if(this.lastSize&&s){const h=Math.abs(s.x-this.lastSize.x),l=Math.abs(s.y-this.lastSize.y);if(h>a||l>a)return w.debug(`[Map] Size change exceeded threshold (deltaX: ${h}, deltaY: ${l}, threshold: ${a}), triggering fitMapToView`),!0}return!1}convertRasterToStructuredData(t,e){if(t.length===0)return[];const i=[];for(let s=0;s<t.length;s++){const r=t[s],o=r%e,a=Math.floor(r/e);i.push(o,a)}return[{coordinates:i}]}async createCarpet(){!this.appService.runtimeSnapshot.showCarpet||!this.carpetData||await this.carpet.createCarpetFromStructuredData(this.carpetData)}processRoomsGeometry(t){if(!t)return[];const e=this.appService,{active:i}=e.roomConfig.colors,s=e.roomConfig.colors[Ys.UNKNOWN_ROOM];if(Object.keys(t).length===0)return this.mapBounds={minX:0,minY:0,maxX:0,maxY:0},[];const r=Object.keys(t).sort((u,p)=>Number(u)-Number(p)),o=r.filter(u=>Number(u)<255),a=r.filter(u=>Number(u)>=255),h=[],l=[];o.forEach(u=>{const{coordinates:p}=t[u];if(p.length<4)return;const g=p.filter(T=>!isFinite(T));if(g.length>0){w.error(`[Room ${u}] Contains ${g.length} invalid coordinates (NaN/Infinity)`);return}const y=Number(u);let m=1/0,x=1/0,S=-1/0,v=-1/0;const b=[];for(let T=0;T<p.length;T+=2){const I=p[T],D=p[T+1];m=Math.min(m,I),x=Math.min(x,D),S=Math.max(S,I),v=Math.max(v,D),b.push({x:I,y:D})}const P=S-m,C=v-x;if(P===0||C===0){w.error(`[Room ${u}] Degenerate polygon (${P}x${C}). Skipping.`);return}if(P<2||C<2){w.warn(`[Room ${u}] Room too small (${P}x${C}), skipping`);return}const _=new J(m,x,S-m+1,v-x+1),R=Ga(b),M=R.flatMap(T=>[T.x+.5,T.y+.5]),A=Ua(R,m,x,S,v);l.push({id:y,points:b,outlinePoints:R,polyPoints:M,centerPoint:A,boundingBox:_}),this.mapBounds.minX=Math.min(this.mapBounds.minX,m),this.mapBounds.minY=Math.min(this.mapBounds.minY,x),this.mapBounds.maxX=Math.max(this.mapBounds.maxX,S),this.mapBounds.maxY=Math.max(this.mapBounds.maxY,v)});const c=[...l].sort((u,p)=>{if(e.roomConfig.colors.sortBy==="area"){const g=u.outlinePoints.length;return p.outlinePoints.length-g}else return u.id-p.id}),d=this.assignColorsUsingFourColorAlgorithm(c,i.length,"structured");return l.forEach(u=>{const p=d.get(u.id)||0,g=i[p],y={id:u.id,color:g,colorIndex:p,boundingBox:u.boundingBox,points:u.points,outlinePoints:u.outlinePoints,polyPoints:u.polyPoints,centerPoint:u.centerPoint};this.roomGeometryMap.set(u.id,y),h.push(y)}),a.forEach(u=>{const{coordinates:p}=t[u];if(p.length<4)return;const g=Number(u);let y=1/0,m=1/0,x=-1/0,S=-1/0;const v=[];for(let T=0;T<p.length;T+=2){const I=p[T],D=p[T+1];y=Math.min(y,I),m=Math.min(m,D),x=Math.max(x,I),S=Math.max(S,D),v.push({x:I,y:D})}const b=x-y,P=S-m;if(b===0||P===0){w.error(`[Unknown Room ${u}] Degenerate polygon (${b}x${P}). Skipping.`);return}if(b<2||P<2){w.warn(`[Unknown Room ${u}] Room too small (${b}x${P}), skipping`);return}const C=new J(y,m,x-y+1,S-m+1),_=Ga(v),R=_.flatMap(T=>[T.x+.5,T.y+.5]),M=Ua(_,y,m,x,S),A={id:g,color:s,boundingBox:C,points:v,outlinePoints:_,polyPoints:R,centerPoint:M};h.push(A),this.mapBounds.minX=Math.min(this.mapBounds.minX,y),this.mapBounds.minY=Math.min(this.mapBounds.minY,m),this.mapBounds.maxX=Math.max(this.mapBounds.maxX,x),this.mapBounds.maxY=Math.max(this.mapBounds.maxY,S)}),h}mergeLayerBounds(){let t={...this.mapBounds};if(this.obstacle.bounds&&(t=Rn(t,this.obstacle.bounds)),this.free.bounds&&(t=Rn(t,this.free.bounds)),this.roomFill.children.length>0){const e=this.roomFill.getLocalBounds();e.width>0&&e.height>0&&(t=Rn(t,{minX:e.x,minY:e.y,maxX:e.x+e.width,maxY:e.y+e.height}))}return t}getRoomById(t){return this.roomGeometryMap.get(t)}getAllRooms(){return Array.from(this.roomGeometryMap.values())}isWallIntersectsAnyRoom(t){return this.roomFill.isWallIntersectsAnyRoom(t)}isZoneIntersectsAnyRoom(t){return this.roomFill.isZoneIntersectsAnyRoom(t)}areRoomsAdjacent(t){const e=this.appService,i=e.mapConfig.adjacencyThreshold;if(!t||t.length===0)return w.warn("[MapManager] No room IDs provided"),!1;if(t.length===1)return!0;const s=Array.from(new Set(t));if(s.length===1)return!0;const r=e.getApp().mapState;return((r==null?void 0:r.mapType)??"structured")==="raster"?this.areRasterRoomsAdjacentInternal(s,i):this.areStructuredRoomsAdjacentInternal(s,i)}areStructuredRoomsAdjacentInternal(t,e){const i=[];for(const r of t){const o=this.getRoomById(r);if(!o)return w.warn(`[MapManager] Room ${r} not found in map`),!1;if(!o.outlinePoints||o.outlinePoints.length===0)return w.warn(`[MapManager] Room ${r} has no outline points`),!1;i.push({id:r,points:o.outlinePoints})}const s=[];for(let r=0;r<i.length;r++)for(let o=r+1;o<i.length;o++){const a=i[r],h=i[o];Va(a.points,h.points,e)&&s.push([r,o])}return Ya(i.length,s)}areRasterRoomsAdjacentInternal(t,e){const s=this.appService.getApp().mapState;if(!s)return w.warn("[MapManager] Map state not available"),!1;const r=s.width,o=[];for(const h of t){const l=this.getRasterRoomPixels(h);if(!l)return w.warn(`[MapManager] Room ${h} pixel data not found in raster map`),!1;o.push({id:h,pixels:l})}const a=[];for(let h=0;h<o.length;h++)for(let l=h+1;l<o.length;l++){const c=o[h],d=o[l];$a(c.pixels,d.pixels,r,e)&&a.push([h,l])}return Ya(o.length,a)}isPointInAnyRoom(t){const i=this.appService.getApp().mapState;return i?(i.mapType??"structured")==="raster"?this.isPointInAnyRoomRasterInternal(t,i):this.isPointInAnyRoomStructuredInternal(t,i):(w.warn("[MapManager] Map state not available"),null)}isPointInAnyRoomStructuredInternal(t,e){const i=t.x+e.origin.x,s=t.y+e.origin.y,r={x:i,y:s},o=this.getAllRooms();for(const a of o)if(a.outlinePoints&&a.outlinePoints.length>=3&&kt(r,a.outlinePoints)){const l=this.appService.roomsManager.getRoomPropertyById(a.id);return l||(w.warn(`[MapManager] Room ${a.id} found in geometry but not in RoomManager`),null)}return null}isPointInAnyRoomRasterInternal(t,e){const i=e.width,s=e.height,r=t.x+e.origin.x,o=t.y+e.origin.y,a=Math.round(r),h=Math.round(o);if(a<0||a>=i||h<0||h>=s)return w.warn(`[MapManager] Point (${a}, ${h}) is out of map bounds (${i}x${s})`),null;const l=h*i+a,c=this.getAllRooms();for(const d of c){const u=this.getRasterRoomPixels(d.id);if(u&&u.length>0&&cc(u,l)){const g=this.appService.roomsManager.getRoomPropertyById(d.id);return g||(w.warn(`[MapManager] Room ${d.id} found in geometry but not in RoomManager`),null)}}return null}clearComponents(){this.obstacle.clear(),this.obstacle.destroy(),this.obstacle=new th(this.appService),this.free.clear(),this.free.destroy(),this.free=new Ja(this.appService),this.carpet.clearCarpet(),this.carpetData=null,this.roomFill.clearRooms(),this.roomFill.isRenderGroup&&(this.roomFill.isRenderGroup=!1),this.roomFill.removeChildren(),this.roomFill.destroy(),this.roomFill=new eh(this.appService)}processRasterData(t){const i=this.appService.roomConfig,s=[],r=[];t.rooms.forEach((d,u)=>{typeof u=="number"?s.push([u,d]):r.push([u,d])}),s.sort(([d],[u])=>d-u);const o=s.map(([d,u])=>({id:d,pixels:u})).sort((d,u)=>i.colors.sortBy==="area"?u.pixels.length-d.pixels.length:d.id-u.id),a=this.assignColorsUsingFourColorAlgorithm(o,i.colors.active.length,"raster"),h=s.map(([d,u])=>{const p=a.get(d)||0;return{roomId:d,pixelIndices:u,activeColor:i.colors.active[p],inactiveColor:i.colors.inactive[p%i.colors.inactive.length],colorIndex:p}}),l=r.map(([d,u])=>{let p=i.colors[d];return d===Ys.VERSION0_ROOM&&!p&&(p=i.colors[Ys.NO_ROOM_DATA]),{roomId:d,pixelIndices:u,activeColor:p,inactiveColor:p}}),c=[...h,...l];return{obstacles:t.obstacles,carpet:t.carpet,sortedRooms:c,width:t.width,height:t.height,totalPixels:t.totalPixels}}generateRoomGeometryFromRaster(t){const e=this.appService;this.roomGeometryMap.clear(),this.rasterRoomPixelsMap.clear();const{active:i}=e.roomConfig.colors,s=[];t.rooms.forEach((h,l)=>{typeof l=="number"&&s.push(l)}),s.sort((h,l)=>h-l);const r=[];s.forEach(h=>{const l=t.rooms.get(h);this.rasterRoomPixelsMap.set(h,l);let c=1/0,d=1/0,u=-1/0,p=-1/0;for(let m=0;m<l.length;m++){const x=l[m],S=x%t.width,v=Math.floor(x/t.width);c=Math.min(c,S),d=Math.min(d,v),u=Math.max(u,S),p=Math.max(p,v)}const g=tx(l,t.width,c,d,u,p),y=new J(c,d,u-c+1,p-d+1);r.push({id:h,pixelIndices:l,boundingBox:y,centerPoint:g})});const o=[...r].sort((h,l)=>e.roomConfig.colors.sortBy==="area"?l.pixelIndices.length-h.pixelIndices.length:h.id-l.id),a=this.assignColorsUsingFourColorAlgorithm(o,i.length,"raster");r.forEach(h=>{const l=a.get(h.id)||0,c=i[l],d={id:h.id,color:c,colorIndex:l,boundingBox:h.boundingBox,points:[],outlinePoints:[],polyPoints:[],centerPoint:h.centerPoint};this.roomGeometryMap.set(h.id,d)})}getRasterRoomPixels(t){return this.rasterRoomPixelsMap.get(t)}validateColorConfig(){const e=this.appService.roomConfig.colors,i=e.active.length,s=e.inactive.length,r=e.name.length,o=e.propertyTheme.length,a=e.selectionIndicatorBackground.length,h=e.selectionIndicatorIcon.length;i<4&&w.warn(`[FourColor] room.colors.active requires at least 4 colors for the four-color theorem, but got ${i}. Adjacent rooms may have the same color.`),s!==i&&w.warn(`[FourColor] room.colors.inactive length (${s}) does not match room.colors.active length (${i}). Using modulo for color assignment.`),r!==i&&w.warn(`[FourColor] room.colors.name length (${r}) does not match room.colors.active length (${i}). Using modulo for color assignment.`),o!==i&&w.warn(`[FourColor] room.colors.propertyTheme length (${o}) does not match room.colors.active length (${i}). Using modulo for color assignment.`),a!==i&&w.warn(`[FourColor] room.colors.selectionIndicatorBackground length (${a}) does not match room.colors.active length (${i}). Using modulo for color assignment.`),h!==i&&w.warn(`[FourColor] room.colors.selectionIndicatorIcon length (${h}) does not match room.colors.active length (${i}). Using modulo for color assignment.`)}assignColorsUsingFourColorAlgorithm(t,e,i){var d;const s=this.appService,r=((d=s.mapState)==null?void 0:d.id)??null;if(this.fourColorCache&&this.fourColorCache.mapId===r&&this.fourColorCache.colorMap.size===t.length)return w.debug("[FourColor] Using cached color map"),this.fourColorCache.colorMap;const o=s.getApp().config.map.adjacencyThreshold||3,a=s.roomConfig.colors.strategy,l=lx(t,(u,p)=>{var g;if(i==="structured"){const y=u.outlinePoints,m=p.outlinePoints;return!y||!m?!1:Va(y,m,o)}else{const y=u.pixels,m=p.pixels;if(!y||!m)return!1;const x=((g=s.mapState)==null?void 0:g.width)||0;return $a(y,m,x,o)}},e,a);this.fourColorCache={mapId:r,colorMap:l};const c=new Array(e).fill(0);return l.forEach(u=>{c[u]++}),w.debug("[FourColor] Color distribution:",c),l}destroy(){this.unsubscribeFns.forEach(t=>t()),this.unsubscribeFns=[],this.obstacle.destroy(),this.free.destroy(),this.roomFill.destroy(),this.carpet.destroy(),this.chargingStation.destroy(),this.fourColorCache=null}}class Yx extends W{constructor(e){super({isRenderGroup:!0});f(this,"commonPath");f(this,"chargePath");f(this,"transitionsPath");f(this,"mopPath");f(this,"mopPathTrack");f(this,"mopPathTrackContainer");f(this,"debugPoints");f(this,"pathData",null);f(this,"lastPointCount",0);f(this,"lastDrawnPosition",null);f(this,"isRealTimeDrawing",!1);f(this,"throttledUpdateLineWidth");f(this,"throttledHandleRobotPosition");f(this,"unsubscribeFns",[]);f(this,"handleRobotAnimationComplete",()=>{this.isRealTimeDrawing&&this.stopRealTimeDrawing()});this.appService=e,this.appService.appContainer.addToLayer(Mc,this),this.eventMode="none",this.commonPath=new H,this.chargePath=new H,this.transitionsPath=new H,this.mopPathTrackContainer=new W,this.mopPathTrackContainer.filters=[new om],this.mopPathTrack=new H,this.mopPath=new H,this.debugPoints=new H,this.mopPathTrackContainer.addChild(this.mopPathTrack),this.addChild(this.mopPathTrackContainer),this.addChild(this.commonPath),this.addChild(this.chargePath),this.addChild(this.transitionsPath),this.addChild(this.mopPath),this.addChild(this.debugPoints),this.visible=e.runtimeSnapshot.showPath,this.commonPath.visible=e.pathConfig.commonPath.visible,this.chargePath.visible=e.pathConfig.chargePath.visible,this.transitionsPath.visible=e.pathConfig.transitionPath.visible,this.mopPathTrackContainer.visible=e.pathConfig.mopPath.trackVisible,this.mopPath.visible=e.pathConfig.mopPath.lineVisible,this.throttledUpdateLineWidth=_t(()=>{this.updateLineWidth()},50,{leading:!0,trailing:!0}),this.throttledHandleRobotPosition=_t(this.handleRobotPositionUpdate.bind(this),0),this.registerEventListeners()}registerEventListeners(){const{emitter:e}=this.appService;e.on("antiScale",this.throttledUpdateLineWidth),e.on("robotPositionUpdate",this.throttledHandleRobotPosition),e.on("robotAnimationComplete",this.handleRobotAnimationComplete);const i=Ls(this.appService.config.path,()=>{this.pathData&&(this.redrawPaths(this.pathData),this.appService.getApp().renderOnceNextFrame())});this.unsubscribeFns.push(i)}handleRobotPositionUpdate(e){if(!this.isRealTimeDrawing||!this.lastDrawnPosition)return;const i=e.pathType||"common";let s=[];switch(i){case"common":s=[this.commonPath];break;case"charge":s=[this.chargePath];break;case"transitions":s=[this.transitionsPath];break;case"mop":s=[this.mopPathTrack,this.mopPath];break;default:s=[this.commonPath]}s.forEach(r=>{r.moveTo(this.lastDrawnPosition.x,this.lastDrawnPosition.y),r.lineTo(e.x,e.y),r.stroke()}),this.lastDrawnPosition={x:e.x,y:e.y}}updateLineWidth(){const e=this.appService;this.pathData&&e.pathConfig.lineWidthFixed&&this.redrawPaths(this.pathData)}redrawPaths(e){const{pathPoints:i}=e;if(this.commonPath.clear(),this.chargePath.clear(),this.transitionsPath.clear(),this.mopPathTrack.clear(),this.mopPath.clear(),this.debugPoints.clear(),!i||i.length===0)return;this.setupPathStyles(),this.drawPathSegments(i),this.commonPath.stroke(),this.chargePath.stroke(),this.transitionsPath.stroke(),this.mopPathTrack.stroke(),this.mopPath.stroke(),this.appService.getDebuggerMode()&&this.drawDebugPoints(i)}setupPathStyles(){var r;const e=this.appService,i=e.pathConfig,s=o=>i.lineWidthFixed?e.getApp().toFixedSize(o):o;this.commonPath.setStrokeStyle({width:s(i.commonPath.width),color:i.commonPath.color,join:"round",cap:"round"}),this.chargePath.setStrokeStyle({width:s(i.chargePath.width),color:i.chargePath.color,join:"round",cap:"round"}),this.transitionsPath.setStrokeStyle({width:s(i.transitionPath.width),color:i.transitionPath.color,join:"round",cap:"round"}),this.mopPathTrack.setStrokeStyle({width:s(i.mopPath.trackWidth),color:i.mopPath.trackColor,alpha:1,join:"round",cap:"round"}),(r=this.mopPathTrackContainer.filters)!=null&&r[0]&&(this.mopPathTrackContainer.filters[0].alpha=i.mopPath.trackAlpha),this.mopPathTrackContainer.visible=i.mopPath.trackVisible,this.mopPath.setStrokeStyle({width:s(i.mopPath.lineWidth),color:i.mopPath.lineColor,join:"round",cap:"round"}),this.mopPath.visible=i.mopPath.lineVisible}drawPathSegments(e){let i=null,s=null;for(let r=0;r<e.length;r++){const o=e[r],a=o.type||"common";let h;switch(a){case"common":h=[this.commonPath];break;case"charge":h=[this.chargePath];break;case"transitions":h=[this.transitionsPath];break;case"mop":h=[this.mopPathTrack,this.mopPath];break;default:h=[this.commonPath]}r===0||a!==i?h.forEach(c=>c.moveTo(o.x,o.y)):s&&h.length===s.length&&h.every((c,d)=>c===s[d])&&h.forEach(c=>c.lineTo(o.x,o.y)),i=a,s=h}}drawDebugPoints(e){const i={common:16711935,charge:65535,transitions:16776960,mop:65280},s=1;for(const r of e){const o=r.type||"common",a=i[o];this.debugPoints.rect(r.x-s/2,r.y-s/2,s,s),this.debugPoints.fill(a)}}updatePositionByOrigin(e,i){this.position.set(e,i)}drawFull(e){var i;w.debug("[Path] Draw Full Path",e),this.pathData=e,this.redrawPaths(e),this.lastPointCount=((i=e.pathPoints)==null?void 0:i.length)||0}drawIncremental(e){var o,a,h,l;const i=this.appService,s=this.lastPointCount,r=((o=e.pathPoints)==null?void 0:o.slice(s))||[];if(r.length>0)if(this.setupPathStyles(),w.debug("[Path] Draw Incremental Path",r),i.robotConfig.speed>0){if(this.isRealTimeDrawing=!0,s>0&&((a=this.pathData)!=null&&a.pathPoints)){const u=this.pathData.pathPoints[s-1];this.lastDrawnPosition={x:u.x,y:u.y}}}else this.drawNewPathSegments(r,s,e.pathPoints,(h=this.pathData)==null?void 0:h.pathPoints);this.pathData=e,this.lastPointCount=((l=e.pathPoints)==null?void 0:l.length)||0}drawNewPathSegments(e,i,s,r){if(!s||e.length===0)return;let o=null;i>0&&(r&&r[i-1]?o=r[i-1]:s[i-1]&&(o=s[i-1]));let a=null,h=null,l=!1;for(let c=0;c<e.length;c++){const d=e[c],u=d.type||"common";let p;switch(u){case"common":p=[this.commonPath];break;case"charge":p=[this.chargePath];break;case"transitions":p=[this.transitionsPath];break;case"mop":p=[this.mopPathTrack,this.mopPath];break;default:p=[this.commonPath]}u!==a||c===0?(h&&l&&h.forEach(y=>y.stroke()),a=u,h=p,l=!0,o&&c===0&&o.type===u?p.forEach(y=>{y.moveTo(o.x,o.y),y.lineTo(d.x,d.y)}):p.forEach(y=>y.moveTo(d.x,d.y))):p.forEach(y=>y.lineTo(d.x,d.y))}h&&l&&h.forEach(c=>c.stroke())}stopRealTimeDrawing(){this.isRealTimeDrawing=!1,this.lastDrawnPosition=null}clear(){this.commonPath.clear(),this.chargePath.clear(),this.transitionsPath.clear(),this.mopPathTrack.clear(),this.mopPath.clear(),this.debugPoints.clear(),this.pathData=null,this.lastPointCount=0,this.lastDrawnPosition=null,this.isRealTimeDrawing=!1}destroy(e){const{emitter:i}=this.appService;i.off("antiScale",this.throttledUpdateLineWidth),i.off("robotPositionUpdate",this.throttledHandleRobotPosition),i.off("robotAnimationComplete",this.handleRobotAnimationComplete),this.unsubscribeFns.forEach(s=>s()),this.unsubscribeFns=[],this.stopRealTimeDrawing(),super.destroy(e)}}class Xx extends Xt{constructor(t){super(t),this.appService=t,this.initializeSprite()}async initializeSprite(){await this.loadTextureAndSetSize("robot",this.appService.robotConfig.icon)}async draw({x:t,y:e,rotation:i}){super.draw({x:t,y:e,rotation:i})}}const et=class et extends ws{constructor(e,i){super(i||[]);f(this,"throttledUpdateScale");f(this,"fixedWidth",0);f(this,"fixedHeight",0);f(this,"isFixedSizeSet",!1);f(this,"sizeFixed",!0);f(this,"baselineScale",1);this.appService=e,this.anchor.set(.5),this.visible=!1,this.throttledUpdateScale=_t(this.updateScale.bind(this),30,{leading:!0,trailing:!0}),this.registerScaleListener()}setFixedSize(e,i){this.fixedWidth=e,this.fixedHeight=i,this.isFixedSizeSet=!0,this.applySize()}setSizeFixed(e){this.sizeFixed=e,this.baselineScale=1,e&&this.isFixedSizeSet?this.applySize():!e&&this.isFixedSizeSet&&this.applySize()}set width(e){this.isFixedSizeSet||this.setFixedSize(e,this.fixedHeight||e)}set height(e){this.isFixedSizeSet||this.setFixedSize(this.fixedWidth||e,e)}get width(){return this.fixedWidth||super.width}get height(){return this.fixedHeight||super.height}registerScaleListener(){this.appService.emitter.on("antiScale",this.throttledUpdateScale)}applySize(){if(!this.isFixedSizeSet||!this.textures||this.textures.length===0||!this.textures[0]||this.textures[0].width===0||this.textures[0].height===0)return;const e=this.textures[0],i=this.fixedWidth/e.width,s=this.fixedHeight/e.height;if(this.sizeFixed){const r=this.appService.currentScale;if(r===0||!isFinite(r)){const h=i,l=s;super.scale.set(h,l);return}const o=i/r,a=s/r;super.scale.set(o,a)}else super.scale.set(i/this.baselineScale,s/this.baselineScale)}updateScale(e){this.sizeFixed&&(this.isFixedSizeSet?this.applySize():e!==0&&super.scale.set(1/e))}static async loadAnimationTextures(e,i,s="sleep_",r=96){try{const a=await(await fetch(e)).json();a.meta&&(a.meta.image=i),await V.load(i);const h=O.from(i),l=new $n(h.source,a);await l.parse();const c=[];for(let d=0;d<r;d++){const u=d.toString().padStart(3,"0"),p=`${s}${u}.png`,g=l.textures[p];g?c.push(g):w.warn(`[EnhancedAnimatedSprite] Frame not found: ${p}`)}return c}catch(o){return w.error("[EnhancedAnimatedSprite] Failed to load textures:",o),[]}}setupAnimation(e){e.sizeFixed!==void 0&&this.setSizeFixed(e.sizeFixed),this.setFixedSize(e.width,e.height),this.animationSpeed=.5,this.loop=!0,w.log(`Animation setup complete, visible=${this.visible}, scale=(${this.scale.x.toFixed(3)}, ${this.scale.y.toFixed(3)})`)}draw(e,i){const{x:s,y:r}=e;i&&!this.visible?this.visible=i():!i&&!this.visible&&(this.visible=!0),this.position.set(s,r)}play(){this.textures&&this.textures.length>0&&(super.play(),et.animatedSprites.add(this),et.startAnimationTicker())}stop(){super.stop(),et.animatedSprites.delete(this),et.updateAnimationTicker()}set textures(e){super.textures=e,this.isFixedSizeSet&&e&&e.length>0&&e[0]&&e[0].width>0&&e[0].height>0&&this.applySize()}get textures(){return super.textures}static startAnimationTicker(){var e;(e=et.animationTicker)!=null&&e.started||(et.animationTicker||(et.animationTicker=new mt,et.animationTicker.maxFPS=24,et.animationTicker.add(()=>{const i=et.animatedSprites.values().next().value;i&&et.updateAnimations(i.appService)})),et.animationTicker.start(),w.log("🎬 [AnimationTicker] Started animation ticker"))}static updateAnimationTicker(){et.animatedSprites.size>0?et.startAnimationTicker():et.stopAnimationTicker()}static stopAnimationTicker(){var e;(e=et.animationTicker)!=null&&e.started&&(w.log("⏸️ [AnimationTicker] Stopped animation ticker"),et.animationTicker.stop())}static updateAnimations(e){if(et.animatedSprites.size===0)return;const i=e.getApp();i.renderer.render(i.stage)}destroy(e){et.animatedSprites.delete(this),et.updateAnimationTicker(),this.appService.emitter.off("antiScale",this.throttledUpdateScale),super.destroy(e)}};f(et,"animationTicker",null),f(et,"animatedSprites",new Set);let Ts=et;class Vr extends Ts{constructor(e,i){super(e,i);f(this,"unsubscribeFns",[]);f(this,"throttledUpdateOffset");f(this,"fixedOffsetX",0);f(this,"fixedOffsetY",0);this.appService=e,this.throttledUpdateOffset=_t(this.updateOffset.bind(this),30,{leading:!0,trailing:!0}),this.initializeAnimation()}static async create(e){const i=e.robotConfig,s=await Ts.loadAnimationTextures(i.sleepAnimation.jsonSrc,i.sleepAnimation.imageSrc,i.sleepAnimation.framePrefix,i.sleepAnimation.frameCount);s.length===0&&(w.warn("No textures loaded for sleep animation"),s.push(O.EMPTY));const r=new Vr(e,s);return r.setupAnimation({width:i.sleepAnimation.width,height:i.sleepAnimation.height,sizeFixed:i.sleepAnimation.sizeFixed}),r}initializeAnimation(){this.visible=!1,this.fixedOffsetX=this.appService.robotConfig.sleepAnimation.offsetX,this.fixedOffsetY=this.appService.robotConfig.sleepAnimation.offsetY,this.appService.emitter.on("antiScale",this.throttledUpdateOffset);const e=G(this.appService.runtime,"showRobotSleepAnimation",i=>{w.log(`[runtime] showRobotSleepAnimation: ${i}`),this.updateVisibility()});this.unsubscribeFns.push(e)}shouldShow(){const e=this.appService.runtimeSnapshot.showRobotSleepAnimation,i=this.parent,s=i?i.visible:!1,r=i&&(i.x!==0||i.y!==0);return e&&s&&!!r}updateVisibility(){const e=this.shouldShow();e&&!this.visible?(this.visible=!0,this.textures&&this.textures.length>0&&this.play()):!e&&this.visible?(this.visible=!1,this.stop()):!e&&this.playing&&this.stop()}updateOffset(){}draw(e){const i=this.appService.getApp().toFixedSize(this.appService.robotConfig.sleepAnimation.offsetX),s=this.appService.getApp().toFixedSize(this.appService.robotConfig.sleepAnimation.offsetY),r={...e,x:e.x+i,y:e.y+s};super.draw(r,()=>this.shouldShow()),this.updateVisibility()}onRobotVisibilityChanged(){this.updateVisibility()}set visible(e){const i=super.visible;super.visible=e,e&&!i&&this.textures&&this.textures.length>0?this.play():!e&&i&&this.playing&&this.stop()}get visible(){return super.visible}destroy(e){this.appService.emitter.off("antiScale",this.throttledUpdateOffset),this.unsubscribeFns.forEach(i=>i()),this.unsubscribeFns=[],this.stop(),super.destroy(e)}}class jx extends H{constructor(e){super();f(this,"currentPosition",null);f(this,"animationStartTime",0);f(this,"isAnimating",!1);f(this,"handleScaleChange",()=>{this.redraw()});f(this,"updateAnimation",()=>{if(!this.currentPosition||!this.isAnimating||!this.visible)return;const e=this.appService,i=e.robotConfig.pulseCircle,r=(Date.now()-this.animationStartTime)%i.duration/i.duration,{minScale:o,maxScale:a,minAlpha:h,maxAlpha:l}=i,c=o+(a-o)*(Math.sin(r*Math.PI*2)*.5+.5),d=l-(l-h)*(c-o)/(a-o);super.clear();const{size:u,color:p,strokeWidth:g,strokeColor:y,sizeFixed:m}=i,S=(m?e.getApp().toFixedSize(u/2):u/2)*c,v=e.getApp().toFixedSize(g);this.setFillStyle({color:p,alpha:d}),this.circle(this.currentPosition.x,this.currentPosition.y,S).fill().stroke({color:y,width:v,alpha:d,cap:"round",join:"round"})});this.appService=e,this.setupAntiScaleListener()}setupAntiScaleListener(){this.appService.emitter.on("antiScale",this.handleScaleChange)}draw(e){this.currentPosition=e,this.isAnimating||this.startAnimation(),this.redraw()}startAnimation(){const e=this.appService;this.isAnimating||(this.isAnimating=!0,this.animationStartTime=Date.now(),e.getApp().ticker.add(this.updateAnimation,this),e.getApp().requestRender("pulse-circle-animation",!0))}stopAnimation(){const e=this.appService;this.isAnimating&&(this.isAnimating=!1,e.getApp().ticker.remove(this.updateAnimation,this),e.getApp().stopRender("pulse-circle-animation"))}redraw(){this.currentPosition&&this.isAnimating&&this.updateAnimation()}clearCircle(){super.clear()}remove(){this.stopAnimation(),this.clearCircle(),this.currentPosition=null}destroy(){this.stopAnimation(),this.appService.emitter.off("antiScale",this.handleScaleChange),super.destroy()}}class Zx extends W{constructor(e){super();f(this,"robot");f(this,"ring");f(this,"pulseCircle");f(this,"sleepAnimation",null);f(this,"unsubscribeFns",[]);f(this,"clickHandler");f(this,"targetPosition",null);f(this,"targetRotation",null);f(this,"isMoving",!1);f(this,"pathQueue",[]);f(this,"lastPosition",null);f(this,"currentPathType");f(this,"lastUpdateTime",0);f(this,"isCleared",!1);this.appService=e,e.appContainer.addToLayer(Rc,this),this.visible=e.runtime.showRobot,this.ring=new kc(this.appService,{config:this.appService.robotConfig.ring}),this.ring.visible=this.appService.runtime.showRobotRing,this.addChild(this.ring),this.pulseCircle=new jx(this.appService),this.pulseCircle.visible=e.runtime.showRobotPulseCircle,this.addChild(this.pulseCircle),this.robot=new Xx(this.appService),this.addChild(this.robot),this.lastUpdateTime=Date.now(),this.appService.robotConfig.speed>0&&this.appService.getApp().ticker.add(this.update,this);const s=G(this.appService.runtime,"showRobotRing",o=>{w.log(`[runtime] showRobotRing: ${o}`),this.ring.visible=o});this.unsubscribeFns.push(s);const r=G(this.appService.runtime,"showRobotPulseCircle",o=>{w.log(`[runtime] showRobotPulseCircle: ${o}`),o?(this.lastPosition&&this.pulseCircle.draw(this.lastPosition),this.pulseCircle.visible=!0):(this.pulseCircle.remove(),this.pulseCircle.visible=!1)});this.unsubscribeFns.push(r),this.initClickInteraction()}async initializeSleepAnimation(){try{this.sleepAnimation=await Vr.create(this.appService),this.addChild(this.sleepAnimation),w.log("Sleep animation added to robot")}catch(e){w.error("Failed to initialize sleep animation:",e)}}updatePositionByOrigin(e,i){this.position.set(e,i)}async draw({x:e,y:i,rotation:s}){this.isCleared&&(this.robot.visible=!0,this.ring.visible=this.appService.runtime.showRobotRing,this.pulseCircle.visible=this.appService.runtime.showRobotPulseCircle,this.sleepAnimation&&(this.sleepAnimation.visible=!0),this.isCleared=!1),this.ring.draw({x:e,y:i}),this.pulseCircle.draw({x:e,y:i}),await this.robot.draw({x:e,y:i,rotation:s}),this.sleepAnimation||await this.initializeSleepAnimation(),this.sleepAnimation.draw({x:e,y:i}),this.lastPosition={x:e,y:i},this.sleepAnimation.draw({x:e,y:i}),this.lastPosition={x:e,y:i}}initClickInteraction(){const{enableRobotClick:e}=this.appService.interactionConfig;e?this.clickHandler||(this.clickHandler=new vt(this.robot,{onClick:()=>{var s;const i=this.getCurrentPosition();i&&((s=this.appService.events)!=null&&s.onClickRobot)&&this.appService.events.onClickRobot({...i,rotation:this.robot.rotation})}})):this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=void 0,this.robot.interactive=!1,this.robot.eventMode="none")}getCurrentPosition(){return this.lastPosition?this.appService.fixPrecision({...this.lastPosition}):null}moveTo(e){this.pathQueue.push(e),this.isMoving||this.processNextPathPoint()}batchProcessQueue(e=!1){if(this.pathQueue.length===0)return;const i=[...this.pathQueue];if(e){const s=i[i.length-1];this.robot.position.set(s.x,s.y),s.rotation!==void 0&&(this.robot.rotation=s.rotation),this.lastPosition={x:s.x,y:s.y},this.pathQueue=[],this.isMoving=!1,this.targetPosition=null}else this.pathQueue.splice(0,i.length),this.pathQueue.length===0?(this.isMoving=!1,this.targetPosition=null):this.processNextPathPoint()}processNextPathPoint(){if(this.pathQueue.length===0){this.isMoving=!1,this.currentPathType=void 0,this.stopRobotAnimation(),this.appService.emitter.emit("robotAnimationComplete");return}this.isMoving||this.startRobotAnimation(),this.isMoving=!0;const e=this.pathQueue[0];this.targetPosition={x:e.x,y:e.y},this.currentPathType=e.type,e.rotation!==void 0&&(this.targetRotation=e.rotation),this.lastPosition||(this.lastPosition={x:this.robot.x,y:this.robot.y})}update(){const e=Date.now();if(this.lastUpdateTime===0){this.lastUpdateTime=e;return}let i=e-this.lastUpdateTime;if(this.lastUpdateTime=e,i>500&&(i=16.67),this.targetPosition){const s=this.targetPosition.x-this.robot.x,r=this.targetPosition.y-this.robot.y,o=Math.sqrt(s*s+r*r),a=this.appService.robotConfig.speed,h=this.appService.coords.toPixels(ut(a));if(a===0){this.robot.position.set(this.targetPosition.x,this.targetPosition.y),this.targetRotation!==null&&(this.robot.rotation=this.targetRotation,this.targetRotation=null),this.targetPosition=null,this.lastPosition={x:this.robot.x,y:this.robot.y},this.pathQueue.shift(),this.processNextPathPoint();return}const l=h*(i/1e3);o<l?(this.robot.position.set(this.targetPosition.x,this.targetPosition.y),this.targetRotation!==null&&(this.robot.rotation=this.targetRotation,this.targetRotation=null),this.targetPosition=null,this.lastPosition={x:this.robot.x,y:this.robot.y},this.pathQueue.shift(),this.processNextPathPoint()):(this.robot.x+=s*(l/o),this.robot.y+=r*(l/o),this.appService.emitter.emit("robotPositionUpdate",{x:this.robot.x,y:this.robot.y,pathType:this.currentPathType}),this.lastPosition={x:this.robot.x,y:this.robot.y})}}startRobotAnimation(){this.appService.getApp().requestRender("robot-animation",!0)}set visible(e){super.visible=e,this.sleepAnimation&&this.sleepAnimation.onRobotVisibilityChanged()}get visible(){return super.visible}stopRobotAnimation(){this.appService.getApp().stopRender("robot-animation")}remove(){this.pathQueue=[],this.isMoving=!1,this.targetPosition=null,this.stopRobotAnimation()}clear(){this.remove(),this.robot.visible=!1,this.ring.visible=!1,this.pulseCircle.remove(),this.sleepAnimation&&(this.sleepAnimation.visible=!1),this.lastPosition=null,this.isCleared=!0}destroy(e){this.unsubscribeFns.forEach(s=>s()),this.unsubscribeFns=[],this.stopRobotAnimation(),this.appService.robotConfig.speed>0&&this.appService.getApp().ticker.remove(this.update,this),this.ring.destroy(),this.pulseCircle.destroy(),this.clickHandler&&this.clickHandler.destroy(),super.destroy(e)}}class qx{constructor(t){f(this,"path");f(this,"robot");f(this,"unsubscribeFns",[]);f(this,"lastDrawnPathData",null);this.appService=t,this.path=new Yx(this.appService),this.robot=new Zx(this.appService);const e=G(t.runtime,"showPath",s=>{w.log(`[runtime] showPath: ${s}`),this.path.visible=s}),i=G(t.runtime,"showRobot",s=>{w.log(`[runtime] showRobot: ${s}`),this.robot.visible=s});this.unsubscribeFns.push(e,i)}draw(t){var s,r,o;const e=(s=t.pathHeader)==null?void 0:s.pathId,i=(o=(r=this.lastDrawnPathData)==null?void 0:r.pathHeader)==null?void 0:o.pathId;this.lastDrawnPathData&&e!==i&&(this.path.clear(),this.lastDrawnPathData=null),this.shouldUseIncrementalDraw(t)?this.incrementalDraw(t):this.fullDraw(t),this.lastDrawnPathData=t}shouldUseIncrementalDraw(t){var h,l,c,d;if(!this.lastDrawnPathData)return!1;const e=(h=t.pathHeader)==null?void 0:h.pathId,i=(l=this.lastDrawnPathData.pathHeader)==null?void 0:l.pathId;if(e!==i)return!1;const s=((c=t.pathPoints)==null?void 0:c.length)||0,r=((d=this.lastDrawnPathData.pathPoints)==null?void 0:d.length)||0,o=s-r,a=this.appService.pathConfig.incrementalThreshold;return!(o<=0||o>a)}fullDraw(t){if(this.path.stopRealTimeDrawing(),this.path.drawFull(t),t.pathPoints&&t.pathPoints.length>0){const e=t.pathPoints[t.pathPoints.length-1];this.moveRobotToPoint(e,t.pathHeader.direction,!1)}else this.robot.clear()}convertToRobotPoint(t,e){const i=e+this.appService.robotConfig.rotationCorrection;return{x:t.x,y:t.y,rotation:i*Math.PI/180,type:t.type}}moveRobotToPoint(t,e,i=!0){const s=this.convertToRobotPoint(t,e);i?this.robot.moveTo(s):(this.robot.remove(),this.robot.draw(s))}incrementalDraw(t){var o;if(!this.lastDrawnPathData||!t.pathPoints)return;this.path.drawIncremental(t);const e=((o=this.lastDrawnPathData.pathPoints)==null?void 0:o.length)||0,i=t.pathPoints.slice(e);if(i.length===0)return;if(this.appService.robotConfig.speed>0)i.forEach(a=>{this.moveRobotToPoint(a,t.pathHeader.direction,!0)});else{const a=i[i.length-1];this.moveRobotToPoint(a,t.pathHeader.direction,!1)}}batchProcessRobotQueue(t=!1){this.robot.batchProcessQueue(t)}updatePositionByOrigin(t,e){this.path.updatePositionByOrigin(t,e),this.robot.updatePositionByOrigin(t,e)}clear(){this.lastDrawnPathData=null,this.path.clear(),this.robot.clear()}destroy(){this.unsubscribeFns.forEach(t=>t()),this.unsubscribeFns=[],this.path.destroy(),this.robot.destroy()}}class Kx extends W{constructor(e){super();f(this,"colorGradients",[]);f(this,"cellSize",2);this.appService=e,this.appService.appContainer.addToLayer(Pc,this);const i=this.appService.heatMapConfig;this.colorGradients=i.colorGradients.map(s=>new nt(s).toArray().slice(0,3).join(",")),this.cellSize=i.cellSize}draw(e,i=.8){this.removeChildren();const{useGradient:s}=this.appService.heatMapConfig,r=s?this.gradientDrawing(e):this.gridDrawing(e);this.croppingHeatmap(r),r.alpha=i,this.addChild(r)}croppingHeatmap(e){var a;const i=((a=this.appService.mapState)==null?void 0:a.origin)||{x:0,y:0},r=this.appService.mapManager.roomFill.children.filter(h=>h instanceof H),o=new H;for(const h of r)o.context.instructions.push(...h.context.instructions);o.context.dirty=!0,o.position.set(-i.x,-i.y),e.setMask({mask:o}),this.addChild(o)}gridDrawing(e){const i=[],s=[],r=e.length,o=e[0].length;for(let c=0;c<r;c++)for(let d=0;d<o;d++){const u=e[c][d],p=this.cellSize/2,g=u.x-p,y=u.y-p,m=u.x+p,x=u.y+p;i.push(g,y),s.push(u.signal),i.push(m,y),s.push(u.signal),i.push(m,x),s.push(u.signal),i.push(g,y),s.push(u.signal),i.push(m,x),s.push(u.signal),i.push(g,x),s.push(u.signal)}const a=new Bi({attributes:{aPosition:new Float32Array(i),aSignal:new Float32Array(s)}}),h=new De({glProgram:new ti({vertex:`
503
+ in vec2 aPosition;
504
+ in float aSignal;
505
+ uniform mat3 uProjectionMatrix;
506
+ uniform mat3 uWorldTransformMatrix;
507
+ uniform mat3 uTransformMatrix;
508
+
509
+ out float vSignal;
510
+
511
+ void main() {
512
+ mat3 mvp = uProjectionMatrix * uWorldTransformMatrix * uTransformMatrix;
513
+ gl_Position = vec4((mvp * vec3(aPosition, 1.0)).xy, 0.0, 1.0);
514
+ vSignal = aSignal;
515
+ }
516
+ `,fragment:`
517
+ precision mediump float;
518
+
519
+ in float vSignal;
520
+
521
+ void main() {
522
+ vec3 color;
523
+
524
+ if (vSignal > 0.875) {
525
+ color = vec3(${this.colorGradients[0]});
526
+ } else if (vSignal > 0.75) {
527
+ color = vec3(${this.colorGradients[1]});
528
+ } else if (vSignal > 0.625) {
529
+ color = vec3(${this.colorGradients[2]});
530
+ } else if (vSignal > 0.5) {
531
+ color = vec3(${this.colorGradients[3]});
532
+ } else if (vSignal > 0.375) {
533
+ color = vec3(${this.colorGradients[4]});
534
+ } else if (vSignal > 0.25) {
535
+ color = vec3(${this.colorGradients[5]});
536
+ } else if (vSignal > 0.125) {
537
+ color = vec3(${this.colorGradients[6]});
538
+ } else {
539
+ color = vec3(${this.colorGradients[7]});
540
+ }
541
+ gl_FragColor = vec4(color, 1.0);
542
+ }
543
+ `}),gpuProgram:new he({vertex:{source:`
544
+ struct GlobalUniforms {
545
+ uProjectionMatrix: mat3x3<f32>,
546
+ uWorldTransformMatrix: mat3x3<f32>,
547
+ uWorldColorAlpha: vec4<f32>,
548
+ uResolution: vec2<f32>,
549
+ };
550
+
551
+ struct LocalUniforms {
552
+ uTransformMatrix: mat3x3<f32>,
553
+ uColor: vec4<f32>,
554
+ uRound: f32,
555
+ };
556
+
557
+ @group(0) @binding(0) var<uniform> globalUniforms: GlobalUniforms;
558
+ @group(1) @binding(0) var<uniform> localUniforms: LocalUniforms;
559
+
560
+ struct VSOutput {
561
+ @builtin(position) position: vec4<f32>,
562
+ @location(0) vSignal: f32,
563
+ };
564
+
565
+ @vertex
566
+ fn main(
567
+ @location(0) aPosition: vec2<f32>,
568
+ @location(1) aSignal: f32
569
+ ) -> VSOutput {
570
+ var output: VSOutput;
571
+ let mvp = globalUniforms.uProjectionMatrix * globalUniforms.uWorldTransformMatrix * localUniforms.uTransformMatrix;
572
+ output.position = vec4((mvp * vec3<f32>(aPosition, 1.0)).xy, 0.0, 1.0);
573
+ output.vSignal = aSignal;
574
+ return output;
575
+ }
576
+ `,entryPoint:"main"},fragment:{source:`
577
+ @fragment
578
+ fn main(@location(0) vSignal: f32) -> @location(0) vec4<f32> {
579
+ var color: vec3<f32>;
580
+
581
+ if (vSignal > 0.875) {
582
+ color = vec3<f32>(${this.colorGradients[0]});
583
+ } else if (vSignal > 0.75) {
584
+ color = vec3<f32>(${this.colorGradients[1]});
585
+ } else if (vSignal > 0.625) {
586
+ color = vec3<f32>(${this.colorGradients[2]});
587
+ } else if (vSignal > 0.5) {
588
+ color = vec3<f32>(${this.colorGradients[3]});
589
+ } else if (vSignal > 0.375) {
590
+ color = vec3<f32>(${this.colorGradients[4]});
591
+ } else if (vSignal > 0.25) {
592
+ color = vec3<f32>(${this.colorGradients[5]});
593
+ } else if (vSignal > 0.125) {
594
+ color = vec3<f32>(${this.colorGradients[6]});
595
+ } else {
596
+ color = vec3<f32>(${this.colorGradients[7]});
597
+ }
598
+
599
+ return vec4<f32>(color, 1.0);
600
+ }
601
+ `,entryPoint:"main"}})}),l=new Aa({geometry:a,shader:h});return l.alpha=.8,l}gradientDrawing(e){const i=[],s=[],r=e.length,o=e[0].length;for(let c=0;c<r;c++)for(let d=0;d<o;d++){const u=e[c][d],p=this.cellSize/2,g=(_,R)=>_<0||_>=r||R<0||R>=o?u.signal:e[_][R].signal,y=(g(c-1,d-1)+g(c-1,d)+g(c,d-1)+u.signal)/4,m=(g(c-1,d)+g(c-1,d+1)+u.signal+g(c,d+1))/4,x=(u.signal+g(c,d+1)+g(c+1,d)+g(c+1,d+1))/4,S=(g(c,d-1)+u.signal+g(c+1,d-1)+g(c+1,d))/4,v=u.x-p,b=u.y-p,P=u.x+p,C=u.y+p;i.push(v,b,P,b,P,C),s.push(y,m,x),i.push(v,b,P,C,v,C),s.push(y,x,S)}const a=new Bi({attributes:{aPosition:new Float32Array(i),aSignal:new Float32Array(s)}}),h=new De({glProgram:new ti({vertex:`
602
+ in vec2 aPosition;
603
+ in float aSignal;
604
+ uniform mat3 uProjectionMatrix;
605
+ uniform mat3 uWorldTransformMatrix;
606
+ uniform mat3 uTransformMatrix;
607
+
608
+ out float vSignal;
609
+
610
+ void main() {
611
+ mat3 mvp = uProjectionMatrix * uWorldTransformMatrix * uTransformMatrix;
612
+ gl_Position = vec4((mvp * vec3(aPosition, 1.0)).xy, 0.0, 1.0);
613
+ vSignal = aSignal;
614
+ }
615
+ `,fragment:`
616
+ precision mediump float;
617
+
618
+ in float vSignal;
619
+
620
+ // 颜色插值函数
621
+ vec3 interpolateColor(vec3 color1, vec3 color2, float t) {
622
+ return mix(color1, color2, t);
623
+ }
624
+
625
+ void main() {
626
+ vec3 color;
627
+ float signal = clamp(vSignal, 0.0, 1.0);
628
+
629
+ vec3 color1 = vec3(${this.colorGradients[7]});
630
+ vec3 color2 = vec3(${this.colorGradients[6]});
631
+ vec3 color3 = vec3(${this.colorGradients[5]});
632
+ vec3 color4 = vec3(${this.colorGradients[4]});
633
+ vec3 color5 = vec3(${this.colorGradients[3]});
634
+ vec3 color6 = vec3(${this.colorGradients[2]});
635
+ vec3 color7 = vec3(${this.colorGradients[1]});
636
+ vec3 color8 = vec3(${this.colorGradients[0]});
637
+
638
+ if (signal <= 0.125) {
639
+ float t = signal / 0.125;
640
+ color = interpolateColor(color1, color2, t);
641
+ } else if (signal <= 0.25) {
642
+ float t = (signal - 0.125) / 0.125;
643
+ color = interpolateColor(color2, color3, t);
644
+ } else if (signal <= 0.375) {
645
+ float t = (signal - 0.25) / 0.125;
646
+ color = interpolateColor(color3, color4, t);
647
+ } else if (signal <= 0.5) {
648
+ float t = (signal - 0.375) / 0.125;
649
+ color = interpolateColor(color4, color5, t);
650
+ } else if (signal <= 0.625) {
651
+ float t = (signal - 0.5) / 0.125;
652
+ color = interpolateColor(color5, color6, t);
653
+ } else if (signal <= 0.75) {
654
+ float t = (signal - 0.625) / 0.125;
655
+ color = interpolateColor(color6, color7, t);
656
+ } else if (signal <= 0.875) {
657
+ float t = (signal - 0.75) / 0.125;
658
+ color = interpolateColor(color7, color8, t);
659
+ } else {
660
+ color = color8;
661
+ }
662
+
663
+ gl_FragColor = vec4(color, 1.0);
664
+ }
665
+ `}),gpuProgram:new he({vertex:{source:`
666
+ struct GlobalUniforms {
667
+ uProjectionMatrix: mat3x3<f32>,
668
+ uWorldTransformMatrix: mat3x3<f32>,
669
+ uWorldColorAlpha: vec4<f32>,
670
+ uResolution: vec2<f32>,
671
+ };
672
+
673
+ struct LocalUniforms {
674
+ uTransformMatrix: mat3x3<f32>,
675
+ uColor: vec4<f32>,
676
+ uRound: f32,
677
+ };
678
+
679
+ @group(0) @binding(0) var<uniform> globalUniforms: GlobalUniforms;
680
+ @group(1) @binding(0) var<uniform> localUniforms: LocalUniforms;
681
+
682
+ struct VSOutput {
683
+ @builtin(position) position: vec4<f32>,
684
+ @location(0) vSignal: f32,
685
+ };
686
+
687
+ @vertex
688
+ fn main(
689
+ @location(0) aPosition: vec2<f32>,
690
+ @location(1) aSignal: f32
691
+ ) -> VSOutput {
692
+ var output: VSOutput;
693
+ let mvp = globalUniforms.uProjectionMatrix * globalUniforms.uWorldTransformMatrix * localUniforms.uTransformMatrix;
694
+ output.position = vec4((mvp * vec3<f32>(aPosition, 1.0)).xy, 0.0, 1.0);
695
+ output.vSignal = aSignal;
696
+ return output;
697
+ }
698
+ `,entryPoint:"main"},fragment:{source:`
699
+ fn interpolateColor(color1: vec3<f32>, color2: vec3<f32>, t: f32) -> vec3<f32> {
700
+ return mix(color1, color2, t);
701
+ }
702
+
703
+ @fragment
704
+ fn main(@location(0) vSignal: f32) -> @location(0) vec4<f32> {
705
+ var color: vec3<f32>;
706
+ let signal = clamp(vSignal, 0.0, 1.0);
707
+
708
+ let color1 = vec3<f32>(${this.colorGradients[7]});
709
+ let color2 = vec3<f32>(${this.colorGradients[6]});
710
+ let color3 = vec3<f32>(${this.colorGradients[5]});
711
+ let color4 = vec3<f32>(${this.colorGradients[4]});
712
+ let color5 = vec3<f32>(${this.colorGradients[3]});
713
+ let color6 = vec3<f32>(${this.colorGradients[2]});
714
+ let color7 = vec3<f32>(${this.colorGradients[1]});
715
+ let color8 = vec3<f32>(${this.colorGradients[0]});
716
+
717
+ if (signal <= 0.125) {
718
+ let t = signal / 0.125;
719
+ color = interpolateColor(color1, color2, t);
720
+ } else if (signal <= 0.25) {
721
+ let t = (signal - 0.125) / 0.125;
722
+ color = interpolateColor(color2, color3, t);
723
+ } else if (signal <= 0.375) {
724
+ let t = (signal - 0.25) / 0.125;
725
+ color = interpolateColor(color3, color4, t);
726
+ } else if (signal <= 0.5) {
727
+ let t = (signal - 0.375) / 0.125;
728
+ color = interpolateColor(color4, color5, t);
729
+ } else if (signal <= 0.625) {
730
+ let t = (signal - 0.5) / 0.125;
731
+ color = interpolateColor(color5, color6, t);
732
+ } else if (signal <= 0.75) {
733
+ let t = (signal - 0.625) / 0.125;
734
+ color = interpolateColor(color6, color7, t);
735
+ } else if (signal <= 0.875) {
736
+ let t = (signal - 0.75) / 0.125;
737
+ color = interpolateColor(color7, color8, t);
738
+ } else {
739
+ color = color8;
740
+ }
741
+
742
+ return vec4<f32>(color, 1.0);
743
+ }
744
+ `,entryPoint:"main"}})}),l=new Aa({geometry:a,shader:h});return l.alpha=.8,l}updatePositionByOrigin(e,i){this.position.set(e,i)}clear(){this.removeChildren()}destroy(){this.removeChildren(),this.cacheAsTexture(!1)}}class Qx{constructor(t){f(this,"heatmap");f(this,"pointsTopLeftOrigin",[]);f(this,"signalGrid",[]);f(this,"cellSize",2);f(this,"maxDistance",14);f(this,"smoothIterations",10);f(this,"heatmapAlpha",.8);f(this,"isHeatmapDrawn",!1);f(this,"loadTimer",null);f(this,"pendingPoints",null);this.appService=t,this.heatmap=new Kx(t);const e=t.heatMapConfig;this.cellSize=e.cellSize,this.maxDistance=e.maxDistance,this.smoothIterations=e.smoothIterations,this.heatmapAlpha=e.heatmapAlpha}draw(t){if(t.length===0){this.clear();return}const e=this.appService;if(!e.isMapDrawn){this.pendingPoints=t;return}this.pendingPoints=null;const{minX:i,minY:s}=e.mapManager.mapBounds,r=t.map(o=>({x:+(o.x-i).toFixed(0),y:+(o.y-s).toFixed(0),signal:o.signal}));this.signalGrid=this.calculateInterpolatedSignal(r),this.heatmap.draw(this.signalGrid,this.heatmapAlpha),this.isHeatmapDrawn=!0}clear(){this.pendingPoints=null,this.pointsTopLeftOrigin=[],this.signalGrid=[],this.heatmap.clear(),this.isHeatmapDrawn=!1}onMapLoaded(){this.loadTimer||(this.pendingPoints&&this.draw(this.pendingPoints),this.loadTimer=setTimeout(()=>{this.loadTimer=null},200))}calculateInterpolatedSignal(t){var p;const e=this.appService,i=((p=e.mapState)==null?void 0:p.origin)||{x:0,y:0};let{minX:s,minY:r,maxX:o,maxY:a}=e.mapManager.mapBounds;r=r-i.y,s=s-i.x,a=a-i.y,o=o-i.x;const h=Math.ceil((a-r)/this.cellSize),l=Math.ceil((o-s)/this.cellSize),c=Array(h).fill(null).map(()=>Array(l).fill(null));for(let g=0;g<h;g++){const y=r+g*this.cellSize+this.cellSize/2,m=Math.min(this.cellSize,a-(y-this.cellSize/2));for(let x=0;x<l;x++){const S=s+x*this.cellSize+this.cellSize/2,v=Math.min(this.cellSize,o-(S-this.cellSize/2));let b=0,P=!1;for(let C=0;C<t.length;C++){const _=t[C];if(Math.abs(S-_.x)<=v/2&&Math.abs(y-_.y)<=m/2){const R=1-_.signal/7;b=Math.round(Math.max(b,R)*10)/10,P=!0}}c[g][x]={x:S,y,signal:b,hasPoint:P}}}const d=(g,y)=>{if(t.length===0)return 0;let m=0,x=0;for(const S of t){const v=Math.sqrt((g-S.x)**2+(y-S.y)**2);if(v<=this.maxDistance){const b=1/(1+v),P=1-S.signal/7;x+=b*P,m+=b}}return m===0?0:Math.round(x/m*1e3)/1e3},u=(g,y=1)=>{for(let m=0;m<y;m++){const x=g.map(S=>[...S]);for(let S=1;S<h-1;S++)for(let v=1;v<l-1;v++)if(!g[S][v].hasPoint){let b=0,P=0;const C=4;for(let _=-C;_<=C;_++)for(let R=-C;R<=C;R++){if(_===0&&R===0)continue;const M=S+_,A=v+R;if(M>=0&&M<h&&A>=0&&A<l){const I=1/(1+Math.sqrt(_*_+R*R)*.3);b+=g[M][A].signal*I,P+=I}}if(P>0){const _=b/P,R=.6,M=.4;x[S][v].signal=g[S][v].signal*R+_*M,x[S][v].signal>.1&&(x[S][v].signal=Math.max(x[S][v].signal,.2))}}for(let S=0;S<h;S++)for(let v=0;v<l;v++)g[S][v].signal=x[S][v].signal}};for(let g=0;g<h;g++)for(let y=0;y<l;y++){const m=c[g][y];m.hasPoint||(m.signal=d(m.x,m.y))}return u(c,this.smoothIterations),c}updatePositionByOrigin(t,e){this.heatmap.updatePositionByOrigin(t,e)}destroy(){this.heatmap.destroy()}}class $r extends H{constructor(e,i){super();f(this,"fillOptions");f(this,"isDragging",!1);f(this,"dragStartPosition",null);f(this,"gestureSession",null);f(this,"handlePointerDown",e=>{e.stopPropagation(),this.startDragging(e)});f(this,"handleDragPointerMove",e=>{var i,s;!this.isDragging||!this.dragStartPosition||(s=(i=this.fillOptions).onDragMove)==null||s.call(i,e)});f(this,"handleDragPointerUp",()=>{var e,i;this.gestureSession=null,this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null,(i=(e=this.fillOptions).onDragEnd)==null||i.call(e))});this.appService=e,this.fillOptions=i,this.setupInteraction(),this.draw()}setupInteraction(){this.fillOptions.enableInteraction&&(this.eventMode="static",this.on("pointerdown",this.handlePointerDown))}startDragging(e){var s,r;this.isDragging=!0;const i=this.parent.toLocal(e.global);this.dragStartPosition={x:i.x,y:i.y},(r=(s=this.fillOptions).onDragStart)==null||r.call(s,e),this.gestureSession=this.appService.gestureController.hijack(e),this.gestureSession.onMove(this.handleDragPointerMove),this.gestureSession.onEnd(this.handleDragPointerUp)}draw(){const{points:e,fillColor:i}=this.fillOptions;if(e.length<3)return;this.clear();const s=e.flatMap(r=>[r.x,r.y]);this.setFillStyle({color:i}).poly(s).fill()}getDragStartPosition(){return this.dragStartPosition}updateOptions(e){this.fillOptions={...this.fillOptions,...e},e.enableInteraction!==void 0&&(this.off("pointerdown",this.handlePointerDown),this.setupInteraction()),this.draw()}updatePoints(e){this.fillOptions.points=e,this.draw()}updateFillColor(e){this.fillOptions.fillColor=e,this.draw()}stopDragging(){var e;this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null,(e=this.gestureSession)==null||e.cancel(),this.gestureSession=null)}isCurrentlyDragging(){return this.isDragging}setInteractionEnabled(e){this.fillOptions.enableInteraction=e,e?(this.eventMode="static",this.on("pointerdown",this.handlePointerDown)):(this.eventMode="auto",this.off("pointerdown",this.handlePointerDown),this.isDragging&&this.stopDragging())}destroy(){this.stopDragging(),this.gestureSession=null,this.off("pointerdown",this.handlePointerDown),super.destroy()}}class si extends W{constructor(e,i){super();f(this,"borderOptions");f(this,"solidLine",null);f(this,"dashGraphics",null);f(this,"fillGraphics",null);f(this,"handleAntiScale",()=>{this.drawBorder()});this.appService=e,this.borderOptions={...i},this.drawBorder(),this.setupAntiScaleListener(),this.eventMode="none"}setupAntiScaleListener(){this.appService.emitter.on("antiScale",this.handleAntiScale)}drawBorder(){const{points:e=[],closePath:i=!1,style:s}=this.borderOptions;e.length<2||(this.clearBorder(),s.fillColor!==void 0&&i&&this.drawFill(e,s),s.isDashed?this.drawContinuousDashedBorder(e,i,s):this.drawSolidBorder(e,i,s))}drawFill(e,i){if(!(!i.fillColor||e.length<3)){this.fillGraphics&&(this.removeChild(this.fillGraphics),this.fillGraphics.destroy()),this.fillGraphics=new H,this.fillGraphics.setFillStyle({color:i.fillColor}),this.fillGraphics.moveTo(e[0].x,e[0].y);for(let s=1;s<e.length;s++)this.fillGraphics.lineTo(e[s].x,e[s].y);this.fillGraphics.closePath(),this.fillGraphics.fill(),this.addChild(this.fillGraphics)}}drawSolidBorder(e,i,s){const r=this.appService;this.solidLine&&(this.removeChild(this.solidLine),this.solidLine.destroy()),this.solidLine=new H;const o=r.getApp().toFixedSize(s.width);this.solidLine.setStrokeStyle({color:s.color,width:o}),this.solidLine.moveTo(e[0].x,e[0].y);for(let a=1;a<e.length;a++)this.solidLine.lineTo(e[a].x,e[a].y);i&&this.solidLine.lineTo(e[0].x,e[0].y),this.solidLine.stroke(),this.addChild(this.solidLine)}drawContinuousDashedBorder(e,i,s){if(e.length<2)return;if(!s.dashArray||s.dashArray.length!==2||s.dashArray[0]<=0||s.dashArray[1]<=0){w.warn("Invalid dashArray:",s.dashArray);return}const r=this.appService;this.dashGraphics=new H;const o=r.getApp().toFixedSize(s.width);this.dashGraphics.setStrokeStyle({color:s.color,width:o});const a=Math.max(r.getApp().toFixedSize(s.dashArray[0]),1),h=Math.max(r.getApp().toFixedSize(s.dashArray[1]),1),l=i?[...e,e[0]]:e;this.drawContinuousPathDashes(this.dashGraphics,l,a,h),this.dashGraphics.stroke(),this.addChild(this.dashGraphics)}drawContinuousPathDashes(e,i,s,r){if(i.length<2)return;if(s<=0||r<=0){w.warn("Invalid dash parameters:",{dashLength:s,gapLength:r});return}const o=this.calculatePathSegments(i),a=o.reduce((c,d)=>c+d.length,0);if(a===0)return;const h=s+r;let l=0;for(;l<a;){const c=l+s;c<=a?this.drawContinuousDashSegment(e,o,l,c):this.drawContinuousDashSegment(e,o,l,a),l+=h}}calculatePathSegments(e){const i=[];for(let s=0;s<e.length-1;s++){const r=e[s],o=e[s+1],a=o.x-r.x,h=o.y-r.y,l=Math.sqrt(a*a+h*h);i.push({start:r,end:o,length:l})}return i}drawContinuousDashSegment(e,i,s,r){if(s>=r)return;let o=0,a=!1,h=null;for(const l of i){const c=o,d=o+l.length;if(d>s&&c<r){const u=Math.max(s,c),p=Math.min(r,d),g=(u-c)/l.length,y=(p-c)/l.length,m={x:l.start.x+(l.end.x-l.start.x)*g,y:l.start.y+(l.end.y-l.start.y)*g},x={x:l.start.x+(l.end.x-l.start.x)*y,y:l.start.y+(l.end.y-l.start.y)*y};a?h&&Math.sqrt(Math.pow(m.x-h.x,2)+Math.pow(m.y-h.y,2))>.1&&e.lineTo(m.x,m.y):(e.moveTo(m.x,m.y),a=!0),e.lineTo(x.x,x.y),h=x}if(o+=l.length,o>=r)break}}clearBorder(){this.fillGraphics&&(this.removeChild(this.fillGraphics),this.fillGraphics.destroy(),this.fillGraphics=null),this.solidLine&&(this.removeChild(this.solidLine),this.solidLine.destroy(),this.solidLine=null),this.dashGraphics&&(this.removeChild(this.dashGraphics),this.dashGraphics.destroy(),this.dashGraphics=null)}updateStyle(e){this.borderOptions.style={...this.borderOptions.style,...e},this.drawBorder()}updatePoints(e){this.borderOptions.points=e,this.drawBorder()}setClosePath(e){this.borderOptions.closePath=e,this.drawBorder()}getOptions(){return{...this.borderOptions}}destroy(){this.appService.emitter.off("antiScale",this.handleAntiScale),this.clearBorder(),super.destroy()}}class Yr{constructor(t){f(this,"id",null);f(this,"layer",null);f(this,"editingState",{});f(this,"idleState",{});f(this,"host",null);f(this,"onHostDestroyed",null);f(this,"detached",!1);this.deps=t}attach(t,e){this.layer&&this.detach(),this.detached=!1,this.host=t,this.id=e.id,this.editingState=e.editingState,this.idleState=e.idleState??{},this.layer=this.deps.editControls.registerEditControl(e.id,e.layerOptions);const i=()=>this.detach();return this.onHostDestroyed=i,t.once("destroyed",i),this.layer}detach(){this.detached||(this.detached=!0,this.host&&this.onHostDestroyed&&this.host.off("destroyed",this.onHostDestroyed),this.onHostDestroyed=null,this.host=null,this.id!=null&&this.deps.editControls.unregisterEditControl(this.id),this.id=null,this.layer=null)}setEditing(t){if(this.id==null){w.warn("[EditableShape] setEditing called before attach; ignoring");return}this.deps.editControls.updateEditState(this.id,t?this.editingState:this.idleState)}applyEditState(t){if(this.id==null){w.warn("[EditableShape] applyEditState called before attach; ignoring");return}this.deps.editControls.updateEditState(this.id,t)}updatePoints(t,e=!0){var i;(i=this.layer)==null||i.updatePoints(t,e)}getLayer(){return this.layer}getMoveButton(){var t;return((t=this.layer)==null?void 0:t.getMoveButton())??null}}class As extends Bs{constructor(e,{text:i,style:s}){super({text:i,style:s});f(this,"throttledUpdateScale");this.appService=e,this.throttledUpdateScale=_t(this.updateScale.bind(this),20,{leading:!0,trailing:!0}),this.registerScaleListener(),this.updateScale(this.appService.currentScale)}registerScaleListener(){this.appService.emitter.on("antiScale",this.throttledUpdateScale)}updateScale(e){e<=0||this.scale.set(1/e)}setBaseFontSize(e){this.style.fontSize=e}updateText(e){this.text=e}destroy(e){this.appService.emitter.off("antiScale",this.throttledUpdateScale),super.destroy(e)}}class Ec extends W{constructor(e){super();f(this,"throttledUpdateScale");this.appService=e,this.throttledUpdateScale=_t(this.updateScale.bind(this),30,{leading:!0,trailing:!0}),this.updateScale(this.appService.currentScale),this.registerScaleListener()}registerScaleListener(){this.appService.emitter.on("antiScale",this.throttledUpdateScale)}updateScale(e){e!==0&&this.scale.set(1/e)}destroy(e){this.appService.emitter.off("antiScale",this.throttledUpdateScale),super.destroy(e)}}class Os extends Ec{constructor(e,i){super(e);f(this,"background");f(this,"icon");f(this,"options");this.appService=e,this.options=i,this.background=new H,this.addChild(this.background),this.icon=new Xt(e),this.addChild(this.icon),this.eventMode="static",this.render(),this.setupHitArea(),this.setupEvents()}setupHitArea(){const e=this.appService,i=this.options.config||e.controlsConfig,s=8,r=i.iconWrapperWidth+s*2,o=i.iconWrapperHeight+s*2;this.hitArea=new J(-r/2,-o/2,r,o)}async render(){this.renderBackground(),this.renderIcon()}renderBackground(){const e=this.appService,i=this.options.config||e.controlsConfig;this.background.clear(),this.background.roundRect(-i.iconWrapperWidth/2,-i.iconWrapperHeight/2,i.iconWrapperWidth,i.iconWrapperHeight,i.iconWrapperBorderRadius).fill(this.options.backgroundColor)}async renderIcon(){try{const e=this.appService,i=this.options.config||e.controlsConfig;await this.icon.loadTextureAndSetSize(this.options.iconAlias,{width:i.iconWidth,height:i.iconHeight,sizeFixed:!1}),this.icon.visible=!0}catch(e){w.error(`Failed to load icon: ${this.options.iconAlias}`,e)}}destroy(){super.destroy()}}class Ic extends Os{constructor(e,i){super(e,i);f(this,"isMoving",!1);f(this,"dragStartPosition",null);f(this,"gestureSession",null);f(this,"handleMovePointerMove",e=>{var i,s;!this.isMoving||!this.dragStartPosition||(s=(i=this.options).onMoveMove)==null||s.call(i,e)});f(this,"handleMovePointerUp",()=>{var e,i;this.gestureSession=null,this.isMoving&&(this.isMoving=!1,this.dragStartPosition=null,(i=(e=this.options).onMoveEnd)==null||i.call(e))});this.appService=e}setupEvents(){this.on("pointerdown",this.handlePointerDown.bind(this))}handlePointerDown(e){e.stopPropagation(),this.startMoving(e)}startMoving(e){var i,s;this.isMoving=!0,this.dragStartPosition=this.parent.toLocal(e.global),(s=(i=this.options).onMoveStart)==null||s.call(i),this.gestureSession=this.appService.gestureController.hijack(e),this.gestureSession.onMove(this.handleMovePointerMove),this.gestureSession.onEnd(this.handleMovePointerUp)}isCurrentlyMoving(){return this.isMoving}getDragStartPosition(){return this.dragStartPosition?{...this.dragStartPosition}:null}stopMoving(){var e,i;this.isMoving&&(this.gestureSession?this.gestureSession.cancel():(this.isMoving=!1,this.dragStartPosition=null,(i=(e=this.options).onMoveEnd)==null||i.call(e)))}destroy(){this.stopMoving(),this.gestureSession=null,this.off("pointerdown",this.handlePointerDown),super.destroy()}}class Dc extends Os{constructor(e,i){super(e,i);f(this,"clickHandler",null);this.appService=e}setupEvents(){this.clickHandler=new vt(this,{onClick:this.options.onClick,stopPropagation:!0})}destroy(){var e;(e=this.clickHandler)==null||e.destroy(),super.destroy()}}class Jx extends Os{constructor(e,i){super(e,i);f(this,"isRotating",!1);f(this,"hasRotated",!1);f(this,"rotationCenter",{x:0,y:0});f(this,"lastAngle",0);f(this,"clickHandler",null);f(this,"gestureSession",null);f(this,"handleRotationPointerMove",e=>{var o,a;if(!this.isRotating)return;this.hasRotated=!0;const i=this.parent.toLocal(e.global),s=Math.atan2(i.y-this.rotationCenter.y,i.x-this.rotationCenter.x),r=s-this.lastAngle;(a=(o=this.options).onRotationMove)==null||a.call(o,r),this.lastAngle=s});f(this,"handleRotationPointerUp",()=>{var e,i;this.gestureSession=null,this.isRotating&&(this.isRotating=!1,this.hasRotated&&((i=(e=this.options).onRotationEnd)==null||i.call(e)),this.hasRotated=!1)});this.appService=e}setupEvents(){this.options.onClick&&(this.clickHandler=new vt(this,{onClick:()=>{var e,i;this.hasRotated||(i=(e=this.options).onClick)==null||i.call(e)},stopPropagation:!1})),this.on("pointerdown",this.handlePointerDown.bind(this))}handlePointerDown(e){e.stopPropagation(),this.startRotation(e)}startRotation(e){var r,o;this.isRotating=!0,this.hasRotated=!1;const i=this.options.getTargetPoints();this.rotationCenter=Le(i);const s=this.parent.toLocal(e.global);this.lastAngle=Math.atan2(s.y-this.rotationCenter.y,s.x-this.rotationCenter.x),(o=(r=this.options).onRotationStart)==null||o.call(r,this.rotationCenter),this.gestureSession=this.appService.gestureController.hijack(e),this.gestureSession.onMove(this.handleRotationPointerMove),this.gestureSession.onEnd(this.handleRotationPointerUp)}isCurrentlyRotating(){return this.isRotating}stopRotation(){var e,i;this.isRotating&&(this.gestureSession?this.gestureSession.cancel():(this.isRotating=!1,this.hasRotated&&((i=(e=this.options).onRotationEnd)==null||i.call(e)),this.hasRotated=!1))}destroy(){var e;this.stopRotation(),this.gestureSession=null,(e=this.clickHandler)==null||e.destroy(),this.off("pointerdown",this.handlePointerDown),super.destroy()}}class ys extends Os{constructor(e,i){super(e,i);f(this,"isScaling",!1);f(this,"initialButtonPosition",null);f(this,"dragStartPosition",null);f(this,"gestureSession",null);f(this,"handleScalePointerMove",e=>{var o,a;if(!this.isScaling||!this.initialButtonPosition||!this.dragStartPosition)return;const i=this.parent.toLocal(e.global),s=i.x-this.dragStartPosition.x,r=i.y-this.dragStartPosition.y;(a=(o=this.options).onScaleMove)==null||a.call(o,{deltaX:s,deltaY:r})});f(this,"handleScalePointerUp",()=>{var e,i;this.gestureSession=null,this.isScaling&&(this.isScaling=!1,this.initialButtonPosition=null,this.dragStartPosition=null,(i=(e=this.options).onScaleEnd)==null||i.call(e))});this.appService=e}setupEvents(){this.on("pointerdown",this.handlePointerDown.bind(this))}handlePointerDown(e){e.stopPropagation(),this.startScaling(e)}startScaling(e){var i,s,r,o;if(this.isScaling=!0,this.dragStartPosition=this.parent.toLocal(e.global),"initialButtonPosition"in this.options)this.initialButtonPosition={x:this.position.x,y:this.position.y},(s=(i=this.options).onScaleStart)==null||s.call(i);else{const a=this.options.getTargetPoints(),h=this.options.getButtonIndex();h>=0&&h<a.length&&(this.initialButtonPosition={...a[h]}),(o=(r=this.options).onScaleStart)==null||o.call(r,h)}this.gestureSession=this.appService.gestureController.hijack(e),this.gestureSession.onMove(this.handleScalePointerMove),this.gestureSession.onEnd(this.handleScalePointerUp)}isCurrentlyScaling(){return this.isScaling}stopScaling(){var e,i;this.isScaling&&(this.gestureSession?this.gestureSession.cancel():(this.isScaling=!1,this.initialButtonPosition=null,this.dragStartPosition=null,(i=(e=this.options).onScaleEnd)==null||i.call(e)))}destroy(){this.stopScaling(),this.gestureSession=null,this.off("pointerdown",this.handlePointerDown),super.destroy()}}const pt={REMOVE:0,ROTATE:1,SCALE:2,MOVE:3};class tS extends W{constructor(e,i){super();f(this,"config");f(this,"events");f(this,"zonePoints",[]);f(this,"outlinePoints");f(this,"minSize",.1);f(this,"maxSize");f(this,"sizeConstraintPerEdge");f(this,"initialZonePoints",[]);f(this,"scaleCache",null);f(this,"rotationCache",null);f(this,"outlineBorder");f(this,"moveLine");f(this,"sizeText");f(this,"controlButtons");f(this,"deleteButton",null);f(this,"rotateButton",null);f(this,"scaleButton",null);f(this,"moveButton",null);f(this,"horizontalScaleButton",null);f(this,"verticalScaleButton",null);f(this,"horizontalScaleInitialPosition",null);f(this,"verticalScaleInitialPosition",null);f(this,"clickHandler",null);f(this,"throttledUpdateOutline");this.appService=e,this.zonePoints=i.zonePoints,this.config={...i.config,showScaleButton:i.config.showScaleButton!==void 0?i.config.showScaleButton:!0,showRadialScaleButton:i.config.showRadialScaleButton!==void 0?i.config.showRadialScaleButton:!0,showDeleteButton:i.config.showDeleteButton!==void 0?i.config.showDeleteButton:!0,showMoveButton:i.config.showMoveButton!==void 0?i.config.showMoveButton:!0,showRotateButton:i.config.showRotateButton!==void 0?i.config.showRotateButton:!0,rotateMode:i.config.rotateMode??"step",scaleMode:i.config.scaleMode??"free"},this.events=i.events||{},this.minSize=i.minSize??.1,this.maxSize=i.maxSize,this.sizeConstraintPerEdge=i.sizeConstraintPerEdge,this.throttledUpdateOutline=_t(this.updateOutlineForScale.bind(this),30,{leading:!0,trailing:!0}),this.initializeComponents(),this.registerScaleListener()}initializeComponents(){this.outlinePoints=this.calculateOutlinePoints(),this.outlineBorder=this.createOutlineBorder(),this.addChild(this.outlineBorder),this.moveLine=this.createMoveLine(),this.addChild(this.moveLine),this.moveLine.visible=this.config.showMoveButton||!1,this.sizeText=this.createSizeText(),this.addChild(this.sizeText),this.controlButtons=new W,this.addChild(this.controlButtons),this.createControlButtons(),this.setupClickHandler()}createOutlineBorder(){const{outlineStrokeColor:e,outlineStrokeWidth:i,outlineDashed:s,outlineDashArray:r,outlineFillColor:o}=this.config;return new si(this.appService,{points:this.outlinePoints,closePath:!0,style:{color:e,width:i,isDashed:s,dashArray:r,fillColor:o}})}createMoveLine(){const{outlineStrokeColor:e,outlineStrokeWidth:i,outlineDashed:s,outlineDashArray:r}=this.config,o=this.calculateMoveLinePoints();return new si(this.appService,{points:o,closePath:!1,style:{color:e,width:i,isDashed:s,dashArray:r}})}createSizeText(){const e=this.calculateSizeText(),i=new As(this.appService,{text:e,style:{fontSize:this.config.textFontSize,fontFamily:this.config.textFontFamily,fontWeight:this.config.textFontWeight,fill:this.config.textColor,align:"center"}});i.anchor.set(.5);const s=this.calculateSizeTextPosition();i.position.set(s.x,s.y);const r=this.calculateSizeTextRotation();return i.rotation=r,i.eventMode="none",i}createDeleteButton(){const e=new Dc(this.appService,{iconAlias:"deleteIcon",backgroundColor:this.config.deleteIconWrapperFillColor??this.config.iconWrapperFillColor,onClick:()=>{var i,s;return(s=(i=this.events).onRemove)==null?void 0:s.call(i)}});return e.position.set(this.outlinePoints[pt.REMOVE].x,this.outlinePoints[pt.REMOVE].y),e}createRotateButton(){const e=this.config.rotateMode==="step",i=new Jx(this.appService,{iconAlias:"rotateIcon",backgroundColor:this.config.iconWrapperFillColor,getTargetPoints:()=>this.zonePoints,onRotationStart:s=>{var r,o;this.initializeRotationCache(s),(o=(r=this.events).onRotateStart)==null||o.call(r,s)},onRotationMove:e?void 0:s=>{var o,a;const r=this.handleInternalRotationMove(s);(a=(o=this.events).onRotateMove)==null||a.call(o,r??void 0)},onClick:e?()=>{var o,a,h,l;const s=this.config.stepRotateAngle??Math.PI/2,r=this.onClickRotateButton(s);(a=(o=this.events).onRotateMove)==null||a.call(o,r??void 0),(l=(h=this.events).onClickRotate)==null||l.call(h,r??void 0)}:void 0,onRotationEnd:()=>{var s,r;this.resetRotationState(),(r=(s=this.events).onRotateEnd)==null||r.call(s)}});return i.position.set(this.outlinePoints[pt.ROTATE].x,this.outlinePoints[pt.ROTATE].y),i}onClickRotateButton(e){const i=this.handleInternalRotationMove(e)??[];return this.resetRotationState(),i}createScaleButton(){const e=new ys(this.appService,{iconAlias:"scaleIcon",backgroundColor:this.config.iconWrapperFillColor,initialButtonPosition:this.outlinePoints[pt.SCALE],onScaleStart:()=>{var i,s;this.initializeScaleCache(),(s=(i=this.events).onScaleStart)==null||s.call(i)},onScaleMove:({deltaX:i,deltaY:s})=>{var o,a;const r=this.handleInternalScaleMove(i,s);(a=(o=this.events).onScaleMove)==null||a.call(o,r??void 0)},onScaleEnd:()=>{var i,s;this.resetScaleState(),this.initialZonePoints=[],(s=(i=this.events).onScaleEnd)==null||s.call(i)}});return e.position.set(this.outlinePoints[pt.SCALE].x,this.outlinePoints[pt.SCALE].y),e}createHorizontalScaleButton(){const[,e,i]=this.outlinePoints,s=this.getEdgeCenter(e,i),r=new ys(this.appService,{iconAlias:"horizontalScaleIcon",backgroundColor:this.config.iconWrapperFillColor,config:{iconWrapperWidth:18,iconWrapperHeight:18,iconWrapperBorderRadius:18,iconWidth:10,iconHeight:8},initialButtonPosition:s,onScaleStart:()=>{var h,l;const[,o,a]=this.zonePoints;this.horizontalScaleInitialPosition=this.getEdgeCenter(o,a),this.initializeScaleCache(),(l=(h=this.events).onScaleStart)==null||l.call(h)},onScaleMove:({deltaX:o,deltaY:a})=>{var l,c;const h=this.handleInternalHorizontalScaleMove(o,a);(c=(l=this.events).onScaleMoveHorizontal)==null||c.call(l,h??void 0)},onScaleEnd:()=>{var o,a;this.resetScaleState(),this.initialZonePoints=[],this.horizontalScaleInitialPosition=null,(a=(o=this.events).onScaleEnd)==null||a.call(o)}});return r.position.set(s.x,s.y),r}createVerticalScaleButton(){const[,,e,i]=this.outlinePoints,s=this.getEdgeCenter(e,i),r=new ys(this.appService,{iconAlias:"verticalScaleIcon",backgroundColor:this.config.iconWrapperFillColor,config:{iconWrapperWidth:18,iconWrapperHeight:18,iconWrapperBorderRadius:18,iconWidth:8,iconHeight:10},initialButtonPosition:s,onScaleStart:()=>{var h,l;const[,,o,a]=this.zonePoints;this.verticalScaleInitialPosition=this.getEdgeCenter(o,a),this.initializeScaleCache(),(l=(h=this.events).onScaleStart)==null||l.call(h)},onScaleMove:({deltaX:o,deltaY:a})=>{var l,c;const h=this.handleInternalVerticalScaleMove(o,a);(c=(l=this.events).onScaleMoveVertical)==null||c.call(l,h??void 0)},onScaleEnd:()=>{var o,a;this.resetScaleState(),this.initialZonePoints=[],this.verticalScaleInitialPosition=null,(a=(o=this.events).onScaleEnd)==null||a.call(o)}});return r.position.set(s.x,s.y),r}createMoveButton(){const e=this.calculateMoveButtonPosition(),i=new Ic(this.appService,{iconAlias:"moveIcon",backgroundColor:this.config.iconWrapperFillColor,onMoveStart:()=>{var s,r;return(r=(s=this.events).onMoveStart)==null?void 0:r.call(s)},onMoveMove:s=>{var r,o;return(o=(r=this.events).onMoveMove)==null?void 0:o.call(r,s)},onMoveEnd:()=>{var s,r;return(r=(s=this.events).onMoveEnd)==null?void 0:r.call(s)}});return i.position.set(e.x,e.y),i}createAndAddButton(e,i){return e.visible=i,this.controlButtons.addChild(e),e}createControlButtons(){this.outlinePoints.length<4||(this.deleteButton=this.createAndAddButton(this.createDeleteButton(),this.config.showDeleteButton??!1),this.moveButton=this.createAndAddButton(this.createMoveButton(),this.config.showMoveButton??!1),this.rotateButton=this.createAndAddButton(this.createRotateButton(),this.config.showRotateButton??!1),this.scaleButton=this.createAndAddButton(this.createScaleButton(),this.config.showScaleButton??!1),this.horizontalScaleButton=this.createAndAddButton(this.createHorizontalScaleButton(),this.config.showRadialScaleButton??!1),this.verticalScaleButton=this.createAndAddButton(this.createVerticalScaleButton(),this.config.showRadialScaleButton??!1))}calculateOutlinePoints(){const e=this.zonePoints;if(e.length<4)return e;const s=this.appService.getApp().toFixedSize(this.config.outlineOffset);return Jy(e,s)}calculateMoveButtonPosition(){const e=this.calculateOutlinePoints();if(e.length<4)return{x:0,y:0};const s=this.appService.getApp().toFixedSize(this.config.moveButtonOffset),r=e[pt.MOVE],o=e[pt.SCALE],a=e[pt.REMOVE];return yc(r,o,a,s)}calculateMoveLinePoints(){const e=this.calculateOutlinePoints();if(e.length<4)return[];const i=e[pt.MOVE],s=this.calculateMoveButtonPosition();return[i,s]}calculateSizeText(){const e=this.zonePoints;if(e.length<4)return"0m*0m";const[i,s,,r]=e,o=tt(i,s),a=tt(i,r),{coords:h}=this.appService,l=h.toMeters(Ft(o)),c=h.toMeters(Ft(a)),d=h.toDisplayUnit(l),u=h.toDisplayUnit(c),p=this.appService.runtimeSnapshot.unitLabel;return`${d.toFixed(1)}${p}*${u.toFixed(1)}${p}`}getEdgeCenter(e,i){return{x:(e.x+i.x)/2,y:(e.y+i.y)/2}}calculatePerpendicularOffset(e,i,s,r=!1){const o=It(St(i,e)),a=r?{x:-o.y,y:o.x}:{x:o.y,y:-o.x};return{x:a.x*s,y:a.y*s}}calculateSizeTextPosition(){if(this.zonePoints.length<4)return{x:0,y:0};const i=this.calculateOutlinePoints(),[s,r,o,a]=i,{textPosition:h,textOffset:l}=this.config,d=this.appService.getApp().toFixedSize(l);let u,p;switch(h){case"top":u=this.getEdgeCenter(s,r),p=this.calculatePerpendicularOffset(r,s,d);break;case"right":u=this.getEdgeCenter(r,o),p=this.calculatePerpendicularOffset(r,o,d);break;case"bottom":u=this.getEdgeCenter(a,o),p=this.calculatePerpendicularOffset(a,o,d,!0);break;case"left":u=this.getEdgeCenter(s,a),p=this.calculatePerpendicularOffset(a,s,d);break;default:u=this.getEdgeCenter(s,r),p={x:0,y:d};break}return{x:u.x+p.x,y:u.y+p.y}}calculateSizeTextRotation(){const e=this.zonePoints;if(e.length<4)return 0;const[i,s,r,o]=e,{textPosition:a}=this.config;let h,l;switch(a){case"top":h=i,l=s;break;case"right":h=s,l=r;break;case"bottom":h=r,l=o;break;case"left":h=o,l=i;break;default:h=i,l=s;break}const c=this.appService.appContainer.getMapRotationRadians();return ms(h,l,c)}calculateHorizontalScaleButtonRotation(){const e=this.zonePoints;if(e.length<4)return 0;const[,i,s]=e,r=this.appService.appContainer.getMapRotationRadians();return ms(i,s,r)+Math.PI/2}calculateVerticalScaleButtonRotation(){const e=this.zonePoints;if(e.length<4)return 0;const[,,i,s]=e,r=this.appService.appContainer.getMapRotationRadians();return ms(s,i,r)}updatePoints(e,i=!0){this.zonePoints=e,this.updateOutlineBorder(),this.moveLine&&this.updateMoveLine(),this.updateControlButtonsPosition(),this.updateSizeText(i)}updateOutlineBorder(){const e=this.calculateOutlinePoints();this.outlinePoints=e,this.outlineBorder.updatePoints(e)}updateMoveLine(){if(!this.moveLine)return;const e=this.calculateMoveLinePoints();this.moveLine.updatePoints(e)}updateSizeText(e=!0){if(this.sizeText){if(e){const i=this.calculateSizeText();this.sizeText.updateText(i)}this.updateSizeTextPosition()}}updateSizeTextPosition(){if(!this.sizeText)return;const e=this.calculateSizeTextPosition();this.sizeText.position.set(e.x,e.y);const i=this.calculateSizeTextRotation();this.sizeText.rotation=i}updateControlButtonsPosition(){if(!this.deleteButton||!this.scaleButton||!this.moveButton)return;const e=this.calculateOutlinePoints();if(e.length<4)return;const i=this.calculateMoveButtonPosition(),s=[{button:this.deleteButton,point:e[pt.REMOVE]},{button:this.scaleButton,point:e[pt.SCALE]},{button:this.moveButton,point:i}];if(this.rotateButton&&s.push({button:this.rotateButton,point:e[pt.ROTATE]}),this.horizontalScaleButton){const r=e[pt.ROTATE],o=e[pt.SCALE],a=gc(r,o,0);s.push({button:this.horizontalScaleButton,point:a})}if(this.verticalScaleButton){const r=e[pt.SCALE],o=e[pt.MOVE],a=this.getEdgeCenter(r,o);s.push({button:this.verticalScaleButton,point:a})}s.forEach(({button:r,point:o})=>r.position.set(o.x,o.y)),this.horizontalScaleButton&&(this.horizontalScaleButton.rotation=this.calculateHorizontalScaleButtonRotation()),this.verticalScaleButton&&(this.verticalScaleButton.rotation=this.calculateVerticalScaleButtonRotation()),this.scaleButton&&this.scaleButton.visible&&(this.scaleButton.rotation=this.calculateVerticalScaleButtonRotation())}setupClickHandler(){this.clickHandler=new vt(this,{onClick:()=>{var e,i;(i=(e=this.events).onClick)==null||i.call(e)},stopPropagation:!1})}registerScaleListener(){this.appService.emitter.on("antiScale",this.throttledUpdateOutline),this.appService.emitter.on("mapRotationUpdate",this.throttledUpdateOutline)}updateOutlineForScale(){(this.outlineBorder.visible||this.controlButtons.visible)&&(this.updateOutlineBorder(),this.moveLine&&this.updateMoveLine(),this.updateControlButtonsPosition(),this.updateSizeTextPosition())}initializeScaleCache(){if(this.initialZonePoints.length===0&&(this.initialZonePoints=this.zonePoints.map(p=>({...p}))),this.initialZonePoints.length<4)return;const e={...this.initialZonePoints[pt.SCALE]};if(!e)return;const i=pt.REMOVE,{x:s,y:r}=this.initialZonePoints[i],[,o,,a]=this.initialZonePoints,h={x:s,y:r},l=St(h,o),c=St(h,a),d=Oi(l),u=Oi(c);d===0||u===0||(this.scaleCache={fixedPoint:h,edge1:l,edge2:c,edge1Len:d,edge2Len:u,initialButtonPosition:e})}sizeConstraintPixels(){const{coords:e}=this.appService,i=(r,o)=>({minSizePixels:e.toPixels(ut(r)),maxSizePixels:o!=null?e.toPixels(ut(o)):void 0});if(this.sizeConstraintPerEdge){const{edge1:r,edge2:o}=this.sizeConstraintPerEdge();return{edge1:i(r.min,r.max),edge2:i(o.min,o.max)}}const s=i(this.minSize,this.maxSize);return{edge1:s,edge2:s}}handleInternalScaleMove(e,i){if(this.initialZonePoints.length!==4||!this.scaleCache)return null;const{edge1:s,edge2:r}=this.sizeConstraintPixels(),{fixedPoint:o,edge1:a,edge2:h,edge1Len:l,edge2Len:c,initialButtonPosition:d}=this.scaleCache,u={x:d.x+e,y:d.y+i},p=St(o,u);let g=cs(p,a,l,s.minSizePixels,s.maxSizePixels),y=cs(p,h,c,r.minSizePixels,r.maxSizePixels);if(this.config.scaleMode==="ratioLocked"){const m=Math.min(g,y);g=m,y=m}return this.calculatePointsFromScale(o,a,h,g,y)}resetScaleState(){this.scaleCache=null}handleInternalHorizontalScaleMove(e,i){if(this.initialZonePoints.length!==4||!this.scaleCache||!this.horizontalScaleInitialPosition)return null;const{fixedPoint:s,edge1:r,edge2:o,edge1Len:a}=this.scaleCache,{edge1:h}=this.sizeConstraintPixels(),l={x:this.horizontalScaleInitialPosition.x+e,y:this.horizontalScaleInitialPosition.y+i},c=St(s,l),d=cs(c,r,a,h.minSizePixels,h.maxSizePixels);return this.calculatePointsFromScale(s,r,o,d,1)}handleInternalVerticalScaleMove(e,i){if(this.initialZonePoints.length!==4||!this.scaleCache||!this.verticalScaleInitialPosition)return null;const{fixedPoint:s,edge1:r,edge2:o,edge2Len:a}=this.scaleCache,{edge2:h}=this.sizeConstraintPixels(),l={x:this.verticalScaleInitialPosition.x+e,y:this.verticalScaleInitialPosition.y+i},c=St(s,l),d=1,u=cs(c,o,a,h.minSizePixels,h.maxSizePixels);return this.calculatePointsFromScale(s,r,o,d,u)}calculatePointsFromScale(e,i,s,r,o){const{x:a,y:h}=e;return[e,{x:a+i.x*r,y:h+i.y*r},{x:a+i.x*r+s.x*o,y:h+i.y*r+s.y*o},{x:a+s.x*o,y:h+s.y*o}]}initializeRotationCache(e){this.zonePoints.length<3||(this.rotationCache={rotationCenter:e,initialPoints:this.zonePoints.map(i=>({...i})),totalAngle:0})}handleInternalRotationMove(e){if(!this.rotationCache||this.rotationCache.initialPoints.length<3)return null;const{rotationCenter:i,initialPoints:s}=this.rotationCache;return this.rotationCache.totalAngle+=e,Ky(s,i,this.rotationCache.totalAngle)}resetRotationState(){this.rotationCache=null}calculateRotationCenter(){return this.zonePoints.length===0?{x:0,y:0}:Le(this.zonePoints)}updateEditState({showRotateButton:e=!1,showScaleButton:i=!1,showRadialScaleButton:s=!1,showDeleteButton:r=!1,showMoveButton:o=!1,showBorder:a=!1,showSizeText:h=!1,borderStyle:l}){this.rotateButton&&(this.rotateButton.visible=e),this.scaleButton&&(this.scaleButton.visible=i),this.horizontalScaleButton&&(this.horizontalScaleButton.visible=s),this.verticalScaleButton&&(this.verticalScaleButton.visible=s),this.deleteButton&&(this.deleteButton.visible=r),this.moveButton&&(this.moveButton.visible=o);const c=e||i||s||r||o;this.controlButtons.visible=c,!c&&this.getOperationState().hasAnyOperation&&this.stopAllOperations(),this.outlineBorder.visible=a,this.moveLine&&(this.moveLine.visible=o),this.sizeText&&(this.sizeText.visible=h),a&&(this.updateOutlineBorder(),c&&(this.moveLine&&o&&this.updateMoveLine(),this.updateControlButtonsPosition()),h&&this.updateSizeTextPosition()),l&&this.outlineBorder.updateStyle({isDashed:l.isDashed,dashArray:l.dashArray})}getOperationState(){var r,o,a;const e=((r=this.scaleButton)==null?void 0:r.isCurrentlyScaling())||!1,i=((o=this.rotateButton)==null?void 0:o.isCurrentlyRotating())||!1,s=((a=this.moveButton)==null?void 0:a.isCurrentlyMoving())||!1;return{isDragging:!1,isScaling:e,isRotating:i,isMoving:s,hasAnyOperation:e||i||s}}stopAllOperations(){var e,i,s;(e=this.scaleButton)==null||e.stopScaling(),(i=this.rotateButton)==null||i.stopRotation(),(s=this.moveButton)==null||s.stopMoving()}getControlButtonsContainer(){return this.controlButtons}getMoveButton(){return this.moveButton}calculateEdgeMidpoint(e,i){const s=this.calculateOutlinePoints();if(s.length<4)return{x:0,y:0};const r=s[e],o=s[i];return{x:(r.x+o.x)/2,y:(r.y+o.y)/2}}destroy(){var e,i,s,r,o,a,h,l,c,d,u;this.appService.emitter.off("antiScale",this.throttledUpdateOutline),this.appService.emitter.off("mapRotationUpdate",this.throttledUpdateOutline),(e=this.clickHandler)==null||e.destroy(),this.clickHandler=null,(i=this.deleteButton)==null||i.destroy(),(s=this.rotateButton)==null||s.destroy(),(r=this.scaleButton)==null||r.destroy(),(o=this.moveButton)==null||o.destroy(),(a=this.horizontalScaleButton)==null||a.destroy(),(h=this.verticalScaleButton)==null||h.destroy(),this.deleteButton=null,this.rotateButton=null,this.scaleButton=null,this.moveButton=null,this.horizontalScaleButton=null,this.verticalScaleButton=null,(l=this.outlineBorder)==null||l.destroy(),(c=this.moveLine)==null||c.destroy(),(d=this.sizeText)==null||d.destroy(),(u=this.controlButtons)==null||u.destroy(),super.destroy()}}function eS(n,t,e){return{outlineStrokeColor:String(n.outlineStrokeColor),outlineStrokeWidth:n.outlineStrokeWidth,outlineDashed:n.outlineDashed,outlineDashArray:n.outlineDashArray,outlineFillColor:n.outlineFillColor?String(n.outlineFillColor):void 0,outlineOffset:n.outlineOffset,iconWrapperFillColor:String(n.iconWrapperFillColor),deleteIconWrapperFillColor:"deleteIconWrapperFillColor"in n&&n.deleteIconWrapperFillColor!==void 0?String(n.deleteIconWrapperFillColor):void 0,showRotateButton:(e==null?void 0:e.showRotateButton)??n.showRotateButton,showScaleButton:(e==null?void 0:e.showScaleButton)??!0,showRadialScaleButton:e==null?void 0:e.showRadialScaleButton,showDeleteButton:(e==null?void 0:e.showDeleteButton)??!0,showMoveButton:(e==null?void 0:e.showMoveButton)??!0,rotateMode:e==null?void 0:e.rotateMode,scaleMode:"free",textColor:String(n.textColor),textPosition:n.textPosition,textOffset:n.textOffset,moveButtonOffset:t.moveButtonOffset,textFontSize:t.textFontSize,textFontFamily:t.textFontFamily,textFontWeight:t.textFontWeight}}function Ws(n,t){return{coords:n.coords,editControls:n.editControlManager,getZoneConfig:e=>iS(n,e),controlsConfig:n.getConfig().controls,makeControlFill:e=>new $r(n,e),makeBorder:e=>new si(n,e),render:{request:e=>n.getApp().requestRender(e,!0),stop:e=>n.getApp().stopRender(e)},events:t}}function iS(n,t){var i;const e=n.getConfig();if(Ne(t)){const s=e.controls[t];if(s)return s}else{const s=(i=e.customZoneTypes)==null?void 0:i[t];if(s)return s}return gh.cleanZone}class Gs extends W{constructor(e){super();f(this,"zoneData");f(this,"zoneType");f(this,"zoneConfig");f(this,"controlsConfig");f(this,"zoneEvents");f(this,"deps");f(this,"controlFill");f(this,"zoneBorder");f(this,"editableShape");f(this,"clickHandler",null);f(this,"initialZonePoints",[]);f(this,"dragStartPosition",null);f(this,"editing",!1);f(this,"resolvedMaxSizeCache",null);f(this,"handleDragStart",()=>{this.editing&&(this.initialZonePoints=this.zoneData.points.map(e=>({...e})),this.dragStartPosition=this.controlFill.getDragStartPosition(),this.deps.render.request("zone-drag"))});f(this,"handleDragMove",e=>{if(!this.editing||this.initialZonePoints.length===0||!this.dragStartPosition)return;const i=this.parent.toLocal(e.global),s=i.x-this.dragStartPosition.x,r=i.y-this.dragStartPosition.y;this.applyTranslation(s,r)});f(this,"handleDragEnd",()=>{var e,i;this.initialZonePoints=[],this.dragStartPosition=null,this.deps.render.stop("zone-drag"),(i=(e=this.zoneEvents).onUpdate)==null||i.call(e,this.getZoneData())});f(this,"handleRotationStart",()=>{this.deps.render.request("zone-rotate")});f(this,"handleRotationMove",e=>{e&&(this.zoneData.points=e,this.drawZone(!1))});f(this,"handleScaleStart",()=>{this.deps.render.request("zone-scale")});f(this,"handleScaleMove",e=>{e&&(this.zoneData.points=e,this.drawZone())});f(this,"handleMoveStart",()=>{this.initialZonePoints=this.zoneData.points.map(e=>({...e})),this.deps.render.request("zone-move")});f(this,"handleMove",e=>{var a;if(!this.editing||this.initialZonePoints.length===0)return;const i=this.parent.toLocal(e.global),s=(a=this.editableShape.getMoveButton())==null?void 0:a.getDragStartPosition();if(!s)return;const r=i.x-s.x,o=i.y-s.y;this.applyTranslation(r,o)});f(this,"handleMoveEnd",()=>{var e,i;this.initialZonePoints=[],this.deps.render.stop("zone-move"),(i=(e=this.zoneEvents).onUpdate)==null||i.call(e,this.getZoneData())});f(this,"handleTransformEnd",()=>{var e,i;this.initialZonePoints=[],this.deps.render.stop("zone-rotate"),this.deps.render.stop("zone-scale"),(i=(e=this.zoneEvents).onUpdate)==null||i.call(e,this.getZoneData())});f(this,"handleDelete",()=>{var e,i;(i=(e=this.zoneEvents).onRemove)==null||i.call(e,this.zoneData.id)});f(this,"handleClick",()=>{var e,i;this.editing||(i=(e=this.zoneEvents)==null?void 0:e.onClick)==null||i.call(e,this.getZoneData())});const{deps:i,zoneData:s,zoneType:r}=e;this.deps=i,this.zoneType=r,this.zoneEvents=i.events,this.zoneConfig=i.getZoneConfig(r),this.controlsConfig=i.controlsConfig;const o=this.validateZoneShape(s.points);this.zoneData={...s,points:o},this.initializeComponents(),this.createEditControlLayer(),this.setupClickHandler(),this.applyEditing()}getResolvedMaxSize(){const e=this.zoneConfig.maxSize;if(this.resolvedMaxSizeCache&&this.resolvedMaxSizeCache.key===e)return this.resolvedMaxSizeCache.value;const i=zs(this.zoneConfig.minSize,e,this.zoneType);return this.resolvedMaxSizeCache={key:e,value:i},i}validateZoneShape(e){if(e.length<4)return e;const i=this.getResolvedMaxSize();return this.deps.coords.validateShape(lc(e),{minSize:ut(this.zoneConfig.minSize),maxSize:i!=null?ut(i):void 0})}initializeComponents(){this.controlFill=this.createControlFill(),this.addChild(this.controlFill),this.zoneBorder=this.createBorder(),this.addChild(this.zoneBorder)}createControlFill(){return this.deps.makeControlFill({points:this.zoneData.points,fillColor:this.zoneConfig.fillColor,enableInteraction:this.editing,onDragStart:this.handleDragStart,onDragMove:this.handleDragMove,onDragEnd:this.handleDragEnd})}createBorder(){const e=this.editing?this.zoneConfig.editing:this.zoneConfig.normal;return this.deps.makeBorder({points:this.zoneData.points,closePath:!0,style:{color:this.zoneConfig.strokeColor,width:this.zoneConfig.strokeWidth,isDashed:e.isDashed,dashArray:e.dashArray}})}createEditControlLayer(){const e=eS(this.zoneConfig,this.controlsConfig,{showRotateButton:this.zoneConfig.showRotateButton,showRadialScaleButton:!1,rotateMode:"free"});this.editableShape=new Yr({editControls:this.deps.editControls});const i=this.getResolvedMaxSize(),s={config:e,zonePoints:this.zoneData.points,minSize:this.zoneConfig.minSize,maxSize:i??void 0,contentLayer:Ae,events:{onRemove:this.handleDelete,onRotateStart:this.handleRotationStart,onRotateMove:this.handleRotationMove,onRotateEnd:this.handleTransformEnd,onScaleStart:this.handleScaleStart,onScaleMove:this.handleScaleMove,onScaleEnd:this.handleTransformEnd,onMoveStart:this.handleMoveStart,onMoveMove:this.handleMove,onMoveEnd:this.handleMoveEnd,onClick:this.handleClick}};this.editableShape.attach(this,{id:this.zoneData.id,topology:"quad",layerOptions:s,editingState:{showRotateButton:this.zoneConfig.showRotateButton,showScaleButton:!0,showRadialScaleButton:!1,showDeleteButton:!0,showMoveButton:!0,showBorder:!0,showSizeText:!0,borderStyle:this.zoneConfig.editing},idleState:{showRotateButton:!1,showScaleButton:!1,showRadialScaleButton:!1,showDeleteButton:!1,showMoveButton:!1,showBorder:!1,showSizeText:!1}})}applyTranslation(e,i){this.zoneData.points=this.initialZonePoints.map(s=>({x:s.x+e,y:s.y+i})),this.drawZone()}setupClickHandler(){this.interactiveChildren=!0,this.clickHandler=new vt(this,{onClick:this.handleClick,stopPropagation:!1})}drawZone(e=!0){const{points:i}=this.zoneData;i.length<4||(this.controlFill.updatePoints(i),this.zoneBorder.updatePoints(i),this.editableShape.updatePoints(i,e))}applyEditing(){this.controlFill.setInteractionEnabled(this.editing),this.updateBorderStyle(this.editing?this.zoneConfig.editing:this.zoneConfig.normal),this.editableShape.setEditing(this.editing),this.zIndex=this.editing?1e3:0}updateBorderStyle(e){this.zoneBorder.updateStyle({isDashed:e.isDashed,dashArray:e.dashArray})}setEditing(e){this.editing!==e&&(this.editing=e,this.applyEditing())}isEditing(){return this.editing}updateZoneData(e){const i=this.validateZoneShape(e.points);this.zoneData={...e,points:i},this.drawZone()}getZoneData(){return{...this.zoneData}}refreshDisplay(){this.drawZone()}destroy(){var e,i,s;this.editableShape.detach(),(e=this.clickHandler)==null||e.destroy(),this.clickHandler=null,(i=this.zoneBorder)==null||i.destroy(),(s=this.controlFill)==null||s.destroy(),super.destroy()}}class Xr extends Gs{constructor(t,e){super({deps:Ws(t,{onRemove:i=>{var s,r;(r=(s=t.events)==null?void 0:s.onRemoveForbiddenSweepZone)==null||r.call(s,i)},onUpdate:i=>{var s,r;(r=(s=t.events)==null?void 0:s.onUpdateForbiddenSweepZone)==null||r.call(s,i)},onClick:i=>{var s,r;(r=(s=t.events)==null?void 0:s.onClickForbiddenSweepZone)==null||r.call(s,i)}}),zoneData:e.zoneData,zoneType:"forbiddenSweepZone"})}static create(t,e){return new Xr(t,{zoneData:e})}}class jr extends Gs{constructor(t,e){super({deps:Ws(t,{onRemove:i=>{var s,r;(r=(s=t.events)==null?void 0:s.onRemoveForbiddenMopZone)==null||r.call(s,i)},onUpdate:i=>{var s,r;(r=(s=t.events)==null?void 0:s.onUpdateForbiddenMopZone)==null||r.call(s,i)},onClick:i=>{var s,r;(r=(s=t.events)==null?void 0:s.onClickForbiddenMopZone)==null||r.call(s,i)}}),zoneData:e.zoneData,zoneType:"forbiddenMopZone"})}static create(t,e){return new jr(t,{zoneData:e})}}class Zr extends Gs{constructor(t,e){super({deps:Ws(t,{onRemove:i=>{var s,r;(r=(s=t.events)==null?void 0:s.onRemoveCleanZone)==null||r.call(s,i)},onUpdate:i=>{var s,r;(r=(s=t.events)==null?void 0:s.onUpdateCleanZone)==null||r.call(s,i)},onClick:i=>{var s,r;(r=(s=t.events)==null?void 0:s.onClickCleanZone)==null||r.call(s,i)}}),zoneData:e.zoneData,zoneType:"cleanZone"})}static create(t,e){return new Zr(t,{zoneData:e})}}class He extends H{constructor(e,i){super();f(this,"lineOptions");f(this,"strokeContext",null);f(this,"drawDashLine",()=>{const{start:e,end:i,style:s}=this.lineOptions;this.clear(),this.strokeContext&&this.strokeContext.destroy();const r=this.appService;this.strokeContext=new gt;const o=r.getApp().toFixedSize(s.width);this.strokeContext.setStrokeStyle({color:s.color,width:o}),this.drawDashedLineToContext(this.strokeContext,e.x,e.y,i.x,i.y,s.dashArray[0],s.dashArray[1]),this.strokeContext.stroke(),this.context=this.strokeContext});this.appService=e,this.lineOptions={...i},this.eventMode="static",this.drawDashLine(),this.setupAntiScaleListener()}setupAntiScaleListener(){this.appService.emitter.on("antiScale",this.drawDashLine)}drawDashedLineToContext(e,i,s,r,o,a,h){const l=r-i,c=o-s,d=Math.sqrt(l*l+c*c);if(d===0)return;const u=this.appService,p=u.getApp().toFixedSize(a),g=u.getApp().toFixedSize(h),y=p+g,m=d/y,x=Math.round(m);if(x===0){e.moveTo(i,s),e.lineTo(r,o);return}const S=d/x,v=S*(p/y),b=l/d,P=c/d;for(let C=0;C<x;C++){const _=C*S,R=_+v;if(_>=d)break;const M=Math.min(R,d),A=i+_*b,T=s+_*P,I=i+M*b,D=s+M*P;e.moveTo(A,T),e.lineTo(I,D)}}updatePoints(e,i){this.lineOptions.start=e,this.lineOptions.end=i,this.drawDashLine()}updateStyle(e){this.lineOptions.style={...this.lineOptions.style,...e},this.drawDashLine()}getOptions(){return{...this.lineOptions}}destroy(){this.appService.emitter.off("antiScale",this.drawDashLine),this.strokeContext&&this.strokeContext.destroy(),super.destroy()}}const Vt=class Vt extends W{constructor(e){super();f(this,"wallData");f(this,"wallConfig");f(this,"controlsConfig");f(this,"wallEvents");f(this,"appService");f(this,"wallLine");f(this,"outlineBorder");f(this,"moveLine");f(this,"lengthText");f(this,"controlButtons");f(this,"removeButton",null);f(this,"scaleButton",null);f(this,"moveButton",null);f(this,"initialWallPoints",[]);f(this,"initialButtonPosition",null);f(this,"isDragging",!1);f(this,"dragStartPosition",null);f(this,"gestureSession",null);f(this,"resolvedMaxWidthCache",null);f(this,"throttledUpdateOutline");f(this,"throttledHandleScaleChange");f(this,"wallLineClickHandler",null);f(this,"handleRemove",()=>{var e,i;(i=(e=this.wallEvents).onRemove)==null||i.call(e,this.wallData.id)});f(this,"initializeOperation",()=>{this.initialWallPoints=this.wallData.points.map(e=>({...e}))});f(this,"finalizeOperation",()=>{var e,i;this.initialWallPoints=[],(i=(e=this.wallEvents).onUpdate)==null||i.call(e,this.getWallData())});f(this,"handleScaleStart",()=>{this.initializeOperation();const e=this.calculateOutlinePoints();e.length>Vt.BUTTON_INDICES.SCALE&&(this.initialButtonPosition={...e[Vt.BUTTON_INDICES.SCALE]}),this.appService.getApp().requestRender("virtualwall-scale",!0)});f(this,"handleScaleMove",({deltaX:e,deltaY:i})=>{if(this.initialWallPoints.length===0||!this.initialButtonPosition)return;const s={x:this.initialButtonPosition.x+e,y:this.initialButtonPosition.y+i};this.applyScaleAndRotation(s)});f(this,"handleScaleEnd",()=>{this.finalizeOperation(),this.initialButtonPosition=null,this.appService.getApp().stopRender("virtualwall-scale")});f(this,"handleMoveStart",()=>{this.initializeOperation(),this.appService.getApp().requestRender("virtualwall-move",!0)});f(this,"handleMove",e=>{var a;if(this.initialWallPoints.length===0)return;const i=this.parent.toLocal(e.global),s=this.getDragStartPosition()||((a=this.moveButton)==null?void 0:a.getDragStartPosition());if(!s)return;const r=i.x-s.x,o=i.y-s.y;this.applyTranslation(r,o)});f(this,"handleMoveEnd",()=>{this.finalizeOperation(),this.appService.getApp().stopRender("virtualwall-move")});f(this,"handleScaleChange",()=>{this.redrawSolidLine(),this.setupWallLineHitArea()});f(this,"handleWallLinePointerDown",e=>{this.isEditingEnabled()&&(e.stopPropagation(),this.startDragging(e))});f(this,"handleDragPointerMove",e=>{!this.isDragging||!this.dragStartPosition||this.handleMove(e)});f(this,"handleDragPointerUp",()=>{this.gestureSession=null,this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null,this.appService.getApp().stopRender("virtualwall-drag"),this.finalizeOperation())});const{appService:i,wallData:s,events:r={}}=e;this.appService=i,this.wallEvents=r,this.wallConfig=this.appService.controlsConfig.virtualWall,this.controlsConfig=this.appService.controlsConfig,this.wallData={...s,points:this.validateAndCorrectWallLength(s.points)},this.throttledHandleScaleChange=_t(this.handleScaleChange.bind(this),30,{leading:!0,trailing:!0}),this.throttledUpdateOutline=_t(this.updateOutlineForScale.bind(this),30,{leading:!0,trailing:!0}),this.initializeComponents(),this.updateEditState(),this.registerScaleListener()}registerScaleListener(){this.appService.emitter.on("antiScale",this.throttledUpdateOutline),this.appService.emitter.on("antiScale",this.throttledHandleScaleChange),this.appService.emitter.on("mapRotationUpdate",this.throttledUpdateOutline)}getResolvedMaxWidth(){const e=this.wallConfig.maxWidth;if(this.resolvedMaxWidthCache&&this.resolvedMaxWidthCache.key===e)return this.resolvedMaxWidthCache.value;const i=zs(this.wallConfig.minWidth,e,"virtualWall");return this.resolvedMaxWidthCache={key:e,value:i},i}validateAndCorrectWallLength(e){if(e.length<2)return e;const[i,s]=e,{coords:r}=this.appService,o=r.toPixels(ut(this.wallConfig.minWidth)),a=this.getResolvedMaxWidth(),h=a!=null?r.toPixels(ut(a)):void 0,l=tt(i,s),c=l<o,d=h!=null&&l>h;if(!c&&!d)return e;if(l===0)return[i,{x:i.x+o,y:i.y}];const u=It(St(i,s));let p=l;return h!=null&&(p=Math.min(p,h)),p=Math.max(p,o),[i,{x:i.x+u.x*p,y:i.y+u.y*p}]}isEditingEnabled(){return this.appService.runtimeSnapshot.editingVirtualWallIds.includes(this.wallData.id)}updateOutlineForScale(){this.isEditingEnabled()&&(this.updateOutlineComponents(),this.updateControlButtonsPosition(),this.updateLengthTextPosition())}initializeComponents(){this.outlineBorder=this.createOutlineBorder(),this.addChild(this.outlineBorder),this.createWallLine(!1),this.addChild(this.wallLine),this.lengthText=this.createLengthText(),this.addChild(this.lengthText),this.moveLine=this.createMoveLine(),this.addChild(this.moveLine),this.controlButtons=new W,this.controlButtons.visible=this.isEditingEnabled(),this.addChild(this.controlButtons),this.createControlButtons()}createWallLine(e=!0){const{points:i}=this.wallData;if(i.length<2)return;const{lineWidth:s,lineColor:r,editing:o,normal:a}=this.wallConfig,l=this.isEditingEnabled()?o:a;l.isDashed?this.wallLine=new He(this.appService,{start:i[0],end:i[1],style:{color:r.toString(),width:s,dashArray:l.dashArray}}):this.wallLine=this.createSolidLine(i[0],i[1],s,r.toString()),e&&this.setupWallLineInteraction()}createLengthText(){const e=this.calculateWallLengthInMeters(),i=this.formatLengthText(e),s=new As(this.appService,{text:i,style:{fontSize:this.controlsConfig.textFontSize,fontFamily:this.controlsConfig.textFontFamily,fontWeight:this.controlsConfig.textFontWeight,fill:this.wallConfig.textColor,align:"center"}});s.anchor.set(.5);const r=this.calculateTextPosition();s.position.set(r.x,r.y);const o=this.calculateTextRotation();return s.rotation=o,s.eventMode="none",s}calculateWallLengthInMeters(){const{points:e}=this.wallData;if(e.length<2)return 0;const i=tt(e[0],e[1]);return this.appService.coords.toMeters(Ft(i))}formatLengthText(e){const i=this.appService.coords.toDisplayUnit(ut(e)),s=this.appService.runtimeSnapshot.unitLabel;return`${i.toFixed(1)}${s}`}calculateTextPosition(){const{points:e}=this.wallData;if(e.length<2)return{x:0,y:0};const[i,s]=e,r=this.appService.getApp().toFixedSize(this.wallConfig.textOffset);return gc(i,s,r)}calculateTextRotation(){const{points:e}=this.wallData;if(e.length<2)return 0;const[i,s]=e,r=this.appService.appContainer.getMapRotationRadians();return ms(i,s,r)}getOutlineStyle(){return{color:this.wallConfig.outlineStrokeColor,width:this.wallConfig.outlineStrokeWidth,isDashed:this.wallConfig.outlineDashed,dashArray:this.wallConfig.outlineDashArray,fillColor:this.wallConfig.outlineFillColor}}createOutlineBorder(){const e=this.calculateOutlinePoints();return new si(this.appService,{points:e,closePath:!0,style:this.getOutlineStyle()})}createMoveLine(){const e=this.calculateOutlinePoints(),i=this.calculateMoveLinePoints(e);return new si(this.appService,{points:i,closePath:!1,style:this.getOutlineStyle()})}calculateOutlinePoints(e){const i=e||this.wallData.points;if(i.length<2)return i;const s=this.appService.getApp().toFixedSize(this.wallConfig.outlineOffset),r=Qy(i[0],i[1],s);return[r[3],r[2],r[1],r[0]]}calculateMoveLinePoints(e){if(e.length<4)return[];const{MOVE:i}=Vt.BUTTON_INDICES,s=e[i],r=this.calculateMoveButtonPosition();return[s,r]}calculateMoveButtonPosition(){const{moveButtonOffset:e}=this.controlsConfig,i=this.calculateOutlinePoints();if(i.length<4)return{x:0,y:0};const{MOVE:s}=Vt.BUTTON_INDICES,r=i[s],o=i[(s+3)%4],a=i[(s+1)%4],h=this.appService.getApp().toFixedSize(e);return yc(r,a,o,h)}createControlButtons(){const e=this.calculateOutlinePoints();if(e.length<4)return;const{REMOVE:i,SCALE:s}=Vt.BUTTON_INDICES;this.removeButton=new Dc(this.appService,{iconAlias:"deleteIcon",backgroundColor:this.wallConfig.iconWrapperFillColor,onClick:this.handleRemove}),this.removeButton.position.set(e[i].x,e[i].y),this.scaleButton=new ys(this.appService,{iconAlias:"scaleIcon",backgroundColor:this.wallConfig.iconWrapperFillColor,getTargetPoints:()=>this.calculateOutlinePoints(),getButtonIndex:()=>s,onScaleStart:this.handleScaleStart,onScaleMove:this.handleScaleMove,onScaleEnd:this.handleScaleEnd}),this.scaleButton.position.set(e[s].x,e[s].y);const r=this.calculateMoveButtonPosition();this.moveButton=new Ic(this.appService,{iconAlias:"moveIcon",backgroundColor:this.wallConfig.iconWrapperFillColor,onMoveStart:this.handleMoveStart,onMoveMove:this.handleMove,onMoveEnd:this.handleMoveEnd}),this.moveButton.position.set(r.x,r.y),this.controlButtons.addChild(this.removeButton),this.controlButtons.addChild(this.scaleButton),this.controlButtons.addChild(this.moveButton)}applyScaleAndRotation(e){if(this.initialWallPoints.length<2)return;const[i,s]=this.initialWallPoints,r=i,o=this.calculateOutlinePoints(this.initialWallPoints);if(o.length<4)return;const a=o[Vt.BUTTON_INDICES.SCALE],l=St(s,a),c={x:e.x-l.x,y:e.y-l.y},d=St(r,c),u=tt(r,c),{coords:p}=this.appService,g=p.toPixels(ut(this.wallConfig.minWidth)),y=this.getResolvedMaxWidth(),m=y!=null?p.toPixels(ut(y)):void 0;let x;if(u<g)if(u===0)x={x:r.x+g,y:r.y};else{const S=It(d);x={x:r.x+S.x*g,y:r.y+S.y*g}}else if(m!=null&&u>m){const S=It(d);x={x:r.x+S.x*m,y:r.y+S.y*m}}else x=c;this.wallData.points=[r,x],this.drawVirtualWall(),this.updateControlButtonsPosition()}applyTranslation(e,i){this.wallData.points=this.initialWallPoints.map(s=>({x:s.x+e,y:s.y+i})),this.drawVirtualWall(),this.updateControlButtonsPosition()}drawVirtualWall(){this.updateWallLine(),this.updateLengthText(),this.updateOutlineComponents()}updateWallLine(){const{points:e}=this.wallData;e.length<2||(this.wallLine instanceof He?this.wallLine.updatePoints(e[0],e[1]):this.redrawSolidLine(),this.setupWallLineHitArea())}updateLengthText(){if(!this.lengthText)return;const e=this.calculateWallLengthInMeters(),i=this.formatLengthText(e);this.lengthText.updateText(i),this.updateLengthTextPosition()}updateLengthTextPosition(){if(!this.lengthText)return;const e=this.calculateTextPosition();this.lengthText.position.set(e.x,e.y);const i=this.calculateTextRotation();this.lengthText.rotation=i}updateOutlineComponents(){const e=this.calculateOutlinePoints();this.outlineBorder.updatePoints(e);const i=this.calculateMoveLinePoints(e);this.moveLine.updatePoints(i)}updateControlButtonsPosition(){if(!this.removeButton||!this.scaleButton||!this.moveButton)return;const e=this.calculateOutlinePoints();if(e.length<4)return;const{REMOVE:i,SCALE:s}=Vt.BUTTON_INDICES,r=this.calculateMoveButtonPosition();this.removeButton.position.set(e[i].x,e[i].y),this.scaleButton.position.set(e[s].x,e[s].y),this.moveButton.position.set(r.x,r.y)}updateEditState(){const e=this.isEditingEnabled();this.controlButtons.visible=e,this.outlineBorder.visible=e,this.moveLine.visible=e,this.lengthText&&(this.lengthText.visible=e),e&&(this.updateOutlineComponents(),this.updateControlButtonsPosition(),this.updateLengthTextPosition()),this.updateWallLineStyle(),this.setupWallLineInteraction(),this.zIndex=e?1e3:0}createSolidLine(e,i,s,r){const o=new H;o.eventMode="static";const a=this.appService.getApp().toFixedSize(s);return o.moveTo(e.x,e.y),o.lineTo(i.x,i.y),o.stroke({color:r,width:a}),o}updateWallLineStyle(){const e=this.isEditingEnabled(),{editing:i,normal:s,lineWidth:r,lineColor:o}=this.wallConfig,a=e?i:s;this.wallLine instanceof He!==a.isDashed?(this.removeChild(this.wallLine),this.wallLine.destroy(),this.createWallLine(!1),this.addChild(this.wallLine)):this.wallLine instanceof He?this.wallLine.updateStyle({color:o.toString(),width:r,dashArray:a.dashArray}):this.redrawSolidLine()}redrawSolidLine(){const e=this.appService;if(!this.wallLine||this.wallLine instanceof He)return;const{points:i}=this.wallData;if(i.length<2)return;const{lineWidth:s,lineColor:r}=this.wallConfig,o=e.getApp().toFixedSize(s);this.wallLine.clear(),this.wallLine.setStrokeStyle({color:r.toString(),width:o}).moveTo(i[0].x,i[0].y).lineTo(i[1].x,i[1].y).stroke()}setupWallLineInteraction(){var i;if(!this.wallLine)return;this.setupWallLineHitArea();const e=this.isEditingEnabled();(i=this.wallLineClickHandler)==null||i.destroy(),this.wallLineClickHandler=null,this.wallLine.off("pointerdown",this.handleWallLinePointerDown),e?this.wallLine.on("pointerdown",this.handleWallLinePointerDown):this.wallLineClickHandler=new vt(this.wallLine,{onClick:()=>{var s,r;this.appService.gestureController.suppressMapClick(),(r=(s=this.wallEvents)==null?void 0:s.onClick)==null||r.call(s,this.getWallData())},stopPropagation:!1})}startDragging(e){const i=this.appService;this.isDragging=!0;const s=this.parent.toLocal(e.global);this.dragStartPosition={x:s.x,y:s.y},this.initializeOperation(),i.getApp().requestRender("virtualwall-drag",!0),this.gestureSession=this.appService.gestureController.hijack(e),this.gestureSession.onMove(this.handleDragPointerMove),this.gestureSession.onEnd(this.handleDragPointerUp)}getDragStartPosition(){return this.dragStartPosition}setupWallLineHitArea(){if(!this.wallLine)return;const{points:e}=this.wallData;if(e.length<2)return;const{hitAreaThickness:i}=this.wallConfig,s=this.appService.getApp().toFixedSize(i),r=mc(e[0],e[1],s);if(r.length===0)return;const o=new Te(r);this.wallLine.hitArea=o}getWallData(){return{...this.wallData}}updateWallData(e){this.wallData={...e,points:this.validateAndCorrectWallLength(e.points)},this.drawVirtualWall(),this.updateControlButtonsPosition()}updateEditingState(){this.updateEditState()}refreshDisplay(){this.drawVirtualWall()}destroy(){var e,i,s,r,o,a,h,l,c,d;this.appService.emitter.off("antiScale",this.throttledUpdateOutline),this.appService.emitter.off("antiScale",this.throttledHandleScaleChange),this.appService.emitter.off("mapRotationUpdate",this.throttledUpdateOutline),this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null),(e=this.gestureSession)==null||e.cancel(),this.gestureSession=null,this.wallLine&&this.wallLine.off("pointerdown",this.handleWallLinePointerDown),(i=this.wallLineClickHandler)==null||i.destroy(),this.wallLineClickHandler=null,(s=this.wallLine)==null||s.destroy(),(r=this.lengthText)==null||r.destroy(),(o=this.outlineBorder)==null||o.destroy(),(a=this.moveLine)==null||a.destroy(),(h=this.controlButtons)==null||h.destroy(),(l=this.removeButton)==null||l.destroy(),(c=this.scaleButton)==null||c.destroy(),(d=this.moveButton)==null||d.destroy(),this.removeButton=null,this.scaleButton=null,this.moveButton=null,super.destroy()}};f(Vt,"BUTTON_INDICES",{REMOVE:0,SCALE:2,MOVE:3});let dr=Vt;const sS={fontSize:12,fontFamily:"system-ui, -apple-system, sans-serif",fontWeight:"400",color:"#5d68fe",position:"top",offset:-8,editing:{visible:!0},normal:{visible:!0}};class qr extends W{constructor(e){super();f(this,"spotData");f(this,"spotConfig");f(this,"controlsConfig");f(this,"spotEvents");f(this,"appService");f(this,"controlFill");f(this,"spotBorder");f(this,"centerIcon");f(this,"sizeText");f(this,"nameText");f(this,"clickHandler",null);f(this,"initialSpotPoint",null);f(this,"dragStartMousePosition",null);f(this,"throttledUpdateScale");f(this,"unsubscribeMapRotation",null);f(this,"handleDragStart",e=>{this.isEditingEnabled()&&(this.initialSpotPoint={...this.spotData.point},this.dragStartMousePosition=this.parent.toLocal(e.global),this.appService.getApp().requestRender("spot-drag",!0))});f(this,"handleDragMove",e=>{if(!this.isEditingEnabled()||!this.initialSpotPoint||!this.dragStartMousePosition||!this.controlFill)return;const i=this.parent.toLocal(e.global),s=i.x-this.dragStartMousePosition.x,r=i.y-this.dragStartMousePosition.y;this.applyTranslation(s,r)});f(this,"handleDragEnd",()=>{var e,i;this.initialSpotPoint=null,this.dragStartMousePosition=null,this.appService.getApp().stopRender("spot-drag"),(i=(e=this.spotEvents).onUpdate)==null||i.call(e,this.getSpotData())});const{appService:i,spotData:s,events:r={}}=e;this.appService=i,this.spotData=s,this.spotEvents=r,this.controlsConfig=this.appService.controlsConfig,this.spotConfig=this.appService.controlsConfig.spot,this.position.set(s.point.x,s.point.y),this.throttledUpdateScale=_t(this.updateScale.bind(this),30,{leading:!0,trailing:!0}),this.initializeComponents(),this.updateEditState(),this.setupClickHandler(),this.registerScaleListener()}registerScaleListener(){this.appService.emitter.on("antiScale",this.throttledUpdateScale)}updateScale(){this.isEditingEnabled()&&this.sizeText&&this.updateSizeTextPosition(),this.nameText&&this.updateNameTextPosition()}isEditingEnabled(){return this.appService.runtimeSnapshot.editingSpotIds.includes(this.spotData.id)}shouldShowIcon(){return(this.isEditingEnabled()?this.spotConfig.editing:this.spotConfig.normal).showIcon}calculateRectanglePoints(){const{size:e}=this.spotConfig;if(e===0)return[{x:0,y:0},{x:0,y:0},{x:0,y:0},{x:0,y:0}];const s=this.appService.coords.toPixels(ut(e))/2;return[{x:-s,y:-s},{x:s,y:-s},{x:s,y:s},{x:-s,y:s}]}initializeComponents(){const e=this.calculateRectanglePoints();this.spotConfig.size>0&&(this.controlFill=this.createControlFill(e),this.addChild(this.controlFill),this.spotBorder=this.createBorder(e),this.addChild(this.spotBorder)),this.centerIcon=this.createCenterIcon(),this.addChild(this.centerIcon),this.spotConfig.showText&&(this.sizeText=this.createSizeText(),this.addChild(this.sizeText)),this.calculateSpotNameText()&&(this.nameText=this.createNameText(),this.addChild(this.nameText)),this.drawSpot()}createControlFill(e){const i=this.isEditingEnabled();return new $r(this.appService,{points:e,fillColor:this.spotConfig.fillColor,enableInteraction:i,onDragStart:this.handleDragStart,onDragMove:this.handleDragMove,onDragEnd:this.handleDragEnd})}createBorder(e){const s=this.isEditingEnabled()?this.spotConfig.editing:this.spotConfig.normal;return new si(this.appService,{points:e,closePath:!0,style:{color:this.spotConfig.strokeColor,width:this.spotConfig.strokeWidth,isDashed:s.isDashed,dashArray:s.dashArray}})}createCenterIcon(){const e=new Xt(this.appService);return this.loadIconTexture(e),e.position.set(0,0),e.eventMode="static",this.setupIconDrag(e),e.visible=!1,e}async loadIconTexture(e){const{iconSize:i,iconSizeFixed:s}=this.spotConfig;await e.loadTextureAndSetSize("spotIcon",{width:i,height:i,sizeFixed:s}),this.applyAntiRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation||(this.unsubscribeMapRotation=G(this.appService.runtime,"mapRotation",r=>{this.applyAntiRotation(r)})),e.visible=this.shouldShowIcon()}applyAntiRotation(e){const i=-e*Math.PI/180;this.rotation=i}setupIconDrag(e){let i=null,s=!1;const r=a=>{if(!s||!this.initialSpotPoint||!i)return;const h=this.parent.toLocal(a.global),l=h.x-i.x,c=h.y-i.y;this.applyTranslation(l,c)},o=()=>{var a,h;s&&(s=!1,this.initialSpotPoint=null,i=null,this.appService.getApp().stopRender("spot-drag"),(h=(a=this.spotEvents).onUpdate)==null||h.call(a,this.getSpotData()))};e.on("pointerdown",a=>{if(!this.isEditingEnabled())return;a.stopPropagation(),s=!0,this.initialSpotPoint={...this.spotData.point},i=this.parent.toLocal(a.global),this.appService.getApp().requestRender("spot-drag",!0);const h=this.appService.gestureController.hijack(a);h.onMove(r),h.onEnd(o)})}createSizeText(){const e=this.calculateSpotSizeText(),i=new As(this.appService,{text:e,style:{fontSize:this.controlsConfig.textFontSize,fontFamily:this.controlsConfig.textFontFamily,fontWeight:this.controlsConfig.textFontWeight,fill:this.spotConfig.textColor,align:"center"}});i.anchor.set(.5);const s=this.calculateSizeTextPosition();return i.position.set(s.x,s.y),i.eventMode="none",i}calculateSpotSizeText(){const{size:e}=this.spotConfig,i=this.appService.coords.toDisplayUnit(ut(e)),s=this.appService.runtimeSnapshot.unitLabel;return`${i.toFixed(1)}${s}*${i.toFixed(1)}${s}`}calculateSizeTextPosition(){const{textPosition:e,textOffset:i}=this.spotConfig;return this.calculateTextPosition(e,i)}calculateTextPosition(e,i){const s=this.calculateRectanglePoints();if(s.length<4)return{x:0,y:0};const[r,o,a,h]=s,l=this.appService.getApp().toFixedSize(i);let c,d;switch(e){case"top":{c={x:(r.x+o.x)/2,y:(r.y+o.y)/2},d={x:c.x,y:c.y+l};break}case"right":{c={x:(o.x+a.x)/2,y:(o.y+a.y)/2},d={x:c.x+l,y:c.y};break}case"bottom":{c={x:(h.x+a.x)/2,y:(h.y+a.y)/2},d={x:c.x,y:c.y+l};break}case"left":{c={x:(r.x+h.x)/2,y:(r.y+h.y)/2},d={x:c.x-l,y:c.y};break}default:{c={x:(r.x+o.x)/2,y:(r.y+o.y)/2},d={x:c.x,y:c.y+l};break}}return d}getNameLabelConfig(){return this.spotConfig.nameLabel??sS}createNameText(){const e=this.getNameLabelConfig(),i=new As(this.appService,{text:this.calculateSpotNameText(),style:{fontSize:e.fontSize,fontFamily:e.fontFamily,fontWeight:e.fontWeight,fill:e.color,align:"center"}});i.anchor.set(.5);const s=this.calculateNameTextPosition();return i.position.set(s.x,s.y),i.eventMode="none",i}calculateSpotNameText(){var e;return((e=this.spotData.name)==null?void 0:e.trim())??""}calculateNameTextPosition(){const{position:e,offset:i}=this.getNameLabelConfig();return this.calculateTextPosition(e,i)}shouldShowNameText(){if(!this.calculateSpotNameText())return!1;const i=this.isEditingEnabled(),s=this.getNameLabelConfig();return(i?s.editing:s.normal).visible}applyTranslation(e,i){this.initialSpotPoint&&(this.spotData.point={x:this.initialSpotPoint.x+e,y:this.initialSpotPoint.y+i},this.drawSpot())}setupClickHandler(){const e=this.spotConfig.size>0?this:this.centerIcon;this.clickHandler=new vt(e,{onClick:()=>{var i,s;this.isEditingEnabled()||(this.appService.gestureController.suppressMapClick(),(s=(i=this.spotEvents)==null?void 0:i.onClick)==null||s.call(i,this.getSpotData()))},stopPropagation:!1}),this.eventMode="static"}drawSpot(){const e=this.calculateRectanglePoints();this.position.set(this.spotData.point.x,this.spotData.point.y),this.spotConfig.size>0&&(this.controlFill&&this.controlFill.updatePoints(e),this.spotBorder&&this.spotBorder.updatePoints(e)),this.spotConfig.showText&&this.sizeText&&this.updateSizeText(),this.nameText&&this.updateNameText()}updateSizeText(){if(!this.sizeText)return;const e=this.calculateSpotSizeText();this.sizeText.updateText(e),this.updateSizeTextPosition()}updateSizeTextPosition(){if(!this.sizeText)return;const e=this.calculateSizeTextPosition();this.sizeText.position.set(e.x,e.y)}updateNameText(){this.nameText&&(this.nameText.updateText(this.calculateSpotNameText()),this.updateNameTextPosition())}updateNameTextPosition(){if(!this.nameText)return;const e=this.calculateNameTextPosition();this.nameText.position.set(e.x,e.y)}updateEditState(){const e=this.isEditingEnabled(),i=e?this.spotConfig.editing:this.spotConfig.normal;this.sizeText&&(this.sizeText.visible=e&&this.spotConfig.showText),this.nameText&&(this.nameText.visible=this.shouldShowNameText()),this.centerIcon&&(this.centerIcon.visible=this.shouldShowIcon()),this.controlFill&&(this.controlFill.setInteractionEnabled(e),this.controlFill.visible=i.showFrame),this.spotBorder&&(this.spotBorder.updateStyle({isDashed:i.isDashed,dashArray:i.dashArray}),this.spotBorder.visible=i.showFrame),this.zIndex=e?1e3:0}updateSpotData(e){this.spotData={...e},!this.nameText&&this.calculateSpotNameText()&&(this.nameText=this.createNameText(),this.addChild(this.nameText)),this.drawSpot(),this.updateEditState()}getSpotData(){return{...this.spotData}}refreshDisplay(){this.drawSpot()}destroy(){var e,i,s,r,o,a;this.appService.emitter.off("antiScale",this.throttledUpdateScale),this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),(e=this.clickHandler)==null||e.destroy(),this.clickHandler=null,this.centerIcon&&this.spotConfig.size===0&&this.centerIcon.removeAllListeners(),(i=this.controlFill)==null||i.destroy(),(s=this.spotBorder)==null||s.destroy(),(r=this.centerIcon)==null||r.destroy(),(o=this.sizeText)==null||o.destroy(),(a=this.nameText)==null||a.destroy(),super.destroy()}static create(e,i){return new qr({appService:e,spotData:i,events:{onUpdate:s=>{var r,o;(o=(r=e.events)==null?void 0:r.onUpdateSpot)==null||o.call(r,s)},onClick:s=>{var r,o;(o=(r=e.events)==null?void 0:r.onClickSpot)==null||o.call(r,s)}}})}}class nS extends Ec{constructor(e){const{appService:i,wayPointData:s,order:r,events:o={}}=e;super(i);f(this,"wayPointData");f(this,"order");f(this,"wayPointConfig");f(this,"controlsConfig");f(this,"wayPointEvents");f(this,"icon");f(this,"orderContainer");f(this,"orderBackground");f(this,"orderText");f(this,"clickHandler",null);f(this,"initialWayPointPoint",null);f(this,"unsubscribeMapRotation",null);this.wayPointData=s,this.order=r,this.wayPointEvents=o,this.controlsConfig=this.appService.controlsConfig,this.wayPointConfig=this.appService.controlsConfig.wayPoint,this.position.set(s.point.x,s.point.y),this.initializeComponents(),this.updateEditState(),this.setupClickHandler()}isEditingEnabled(){return(this.appService.runtimeSnapshot.editingWayPointIds||[]).includes(this.wayPointData.id)}initializeComponents(){this.icon=this.createIcon(),this.addChild(this.icon),this.wayPointConfig.showOrder&&(this.createOrderContainer(),this.addChild(this.orderContainer))}createIcon(){const e=new Xt(this.appService);return this.loadIconTexture(e),e.position.set(0,0),e.anchor.set(.5,1),e.eventMode="static",this.setupIconDrag(e),e}async loadIconTexture(e){const i=this.isEditingEnabled(),s=i?this.wayPointConfig.editing:this.wayPointConfig.normal,{iconSize:r}=s,o=i?"wayPointActive":"wayPoint";await e.loadTextureAndSetSize(o,{width:r,height:r,sizeFixed:!1}),this.applyAntiRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation||(this.unsubscribeMapRotation=G(this.appService.runtime,"mapRotation",a=>{this.applyAntiRotation(a)})),e.visible=!0,this.orderContainer&&this.updateOrderPosition()}applyAntiRotation(e){const i=-e*Math.PI/180;this.rotation=i}createOrderContainer(){const i=this.isEditingEnabled()?this.wayPointConfig.editing:this.wayPointConfig.normal,{orderContainer:s,orderText:r}=i;this.orderContainer=new W,this.orderBackground=new H,this.orderText=new Bs({text:this.order.toString(),style:new le({fontSize:r.fontSize,fontFamily:r.fontFamily,fontWeight:r.fontWeight,fill:r.color,align:"center",trim:!0})}),this.orderBackground.clear(),this.orderBackground.circle(0,0,s.size/2),this.orderBackground.fill({color:s.backgroundColor}),this.orderText.anchor.set(.5,.5),this.orderContainer.addChild(this.orderBackground),this.orderContainer.addChild(this.orderText),this.orderContainer.eventMode="none",this.orderContainer.visible=this.wayPointConfig.showOrder,this.updateOrderPosition()}updateOrderPosition(){if(!this.orderContainer)return;const i=this.isEditingEnabled()?this.wayPointConfig.editing:this.wayPointConfig.normal,{offsetX:s,offsetY:r}=i.orderContainer;this.orderContainer.position.set(s,-r)}setupIconDrag(e){let i=null,s=null,r=!1;const o=h=>{if(!(!r||!i||!s)&&this.parent){const l=this.parent.toLocal(h.global),c=l.x-i.x,d=l.y-i.y,u={x:s.x+c,y:s.y+d};this.wayPointData.point=u,this.position.set(u.x,u.y),this.orderContainer&&this.updateOrderPosition()}},a=()=>{var h,l;r&&(r=!1,i=null,s=null,(l=(h=this.wayPointEvents).onUpdate)==null||l.call(h,this.wayPointData))};e.on("pointerdown",h=>{if(this.isEditingEnabled()&&(h.stopPropagation(),s={...this.wayPointData.point},this.parent&&(i=this.parent.toLocal(h.global)),r=!0,this.parent)){const l=this.appService.gestureController.hijack(h);l.onMove(o),l.onEnd(a)}})}setupClickHandler(){this.clickHandler=new vt(this.icon,{stopPropagation:!1,onClick:()=>{var e,i;this.appService.gestureController.suppressMapClick(),(i=(e=this.wayPointEvents).onClick)==null||i.call(e,this.wayPointData)}})}updateWayPoint(e){this.wayPointData=e,this.drawWayPoint()}updateOrder(e){this.order=e,this.orderText&&(this.orderText.text=e.toString())}getWayPointData(){return{...this.wayPointData}}drawWayPoint(){this.position.set(this.wayPointData.point.x,this.wayPointData.point.y),this.orderContainer&&this.updateOrderPosition()}updateEditState(){if(this.loadIconTexture(this.icon),this.orderContainer&&this.orderText&&this.orderBackground){const i=this.isEditingEnabled()?this.wayPointConfig.editing:this.wayPointConfig.normal;this.orderText.style=new le({fontSize:i.orderText.fontSize,fontFamily:i.orderText.fontFamily,fontWeight:i.orderText.fontWeight,fill:i.orderText.color,align:"center",trim:!0});const{size:s,backgroundColor:r}=i.orderContainer;this.orderBackground.clear(),this.orderBackground.circle(0,0,s/2).fill(r),this.orderContainer.visible=this.wayPointConfig.showOrder,this.updateOrderPosition()}}onEditStateChange(){this.updateEditState()}destroy(){this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null),this.icon&&this.icon.removeAllListeners(),super.destroy()}}class ih extends H{constructor(e,i){super();f(this,"isDragging",!1);f(this,"dragStartPosition",null);f(this,"initialPosition");f(this,"gestureSession",null);f(this,"handleDragPointerMove",e=>{var a,h;if(!this.isDragging||!this.dragStartPosition)return;const i=this.parent.toLocal(e.global),s=i.x-this.dragStartPosition.x,r=i.y-this.dragStartPosition.y,o={x:this.initialPosition.x+s,y:this.initialPosition.y+r};this.position.set(o.x,o.y),(h=(a=this.options).onDragMove)==null||h.call(a,o)});f(this,"handleDragPointerUp",()=>{var i,s;if(this.gestureSession=null,!this.isDragging)return;const e=this.appService;this.isDragging=!1,this.dragStartPosition=null,e.getApp().stopRender("endpoint-drag"),(s=(i=this.options).onDragEnd)==null||s.call(i)});this.appService=e,this.options=i,this.initialPosition={...i.position},this.position.set(i.position.x,i.position.y),this.eventMode="static",this.cursor="pointer",this.setupEvents(),this.draw()}draw(){const e=this.appService,{config:i}=this.options,s=e.getApp().toFixedSize(i.endPointSize),r=e.getApp().toFixedSize(i.endPointStrokeWidth);this.clear(),this.circle(0,0,s/2),this.fill({color:i.endPointColor}),this.stroke({color:i.endPointStrokeColor,width:r}),this.setupHitArea()}setupHitArea(){const e=this.appService,{config:i}=this.options,s=Math.max(i.endPointSize/2+10,20),r=e.getApp().toFixedSize(s);this.hitArea=new Is(0,0,r)}setupEvents(){this.on("pointerdown",this.handlePointerDown.bind(this))}handlePointerDown(e){e.stopPropagation(),this.startDragging(e)}startDragging(e){var s,r;const i=this.appService;this.isDragging=!0,this.dragStartPosition=this.parent.toLocal(e.global),this.initialPosition={x:this.x,y:this.y},(r=(s=this.options).onDragStart)==null||r.call(s),i.getApp().requestRender("endpoint-drag",!0),this.gestureSession=this.appService.gestureController.hijack(e),this.gestureSession.onMove(this.handleDragPointerMove),this.gestureSession.onEnd(this.handleDragPointerUp)}updatePosition(e){this.position.set(e.x,e.y),this.initialPosition={...e}}getPosition(){return{x:this.x,y:this.y}}redraw(){this.draw()}destroy(){var e;this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null),(e=this.gestureSession)==null||e.cancel(),this.gestureSession=null,this.off("pointerdown",this.handlePointerDown),super.destroy()}}class rS extends W{constructor(e){super();f(this,"endPoints");f(this,"dividerConfig");f(this,"dividerEvents");f(this,"roomId");f(this,"appService");f(this,"roomGeometry",null);f(this,"dashLine");f(this,"solidLine",null);f(this,"startEndPoint");f(this,"endEndPoint");f(this,"solidLinePoints",null);f(this,"initialDividerPoints",[]);f(this,"isDragging",!1);f(this,"dragStartPosition",null);f(this,"gestureSession",null);f(this,"throttledHandleScaleChange");f(this,"handleEndPointDragStart",()=>{this.initialDividerPoints=this.endPoints.map(e=>({...e})),this.clearSolidLine(),this.appService.getApp().requestRender("divider-endpoint-drag",!0)});f(this,"handleEndPointDragMove",(e,i)=>{this.initialDividerPoints.length!==0&&(this.endPoints[e]=i,this.updateDashLine(),this.updateSolidLine(),this.setupDashLineHitArea())});f(this,"handleEndPointDragEnd",()=>{var e,i;this.initialDividerPoints=[],this.appService.getApp().stopRender("divider-endpoint-drag"),this.calculateAndCreateSolidLine(),this.checkAndResetIfOutOfRoom(),(i=(e=this.dividerEvents).onUpdate)==null||i.call(e,this.getDividerEndPoints())});f(this,"handleDashLinePointerDown",e=>{e.stopPropagation(),this.startDragging(e)});f(this,"handleDragPointerMove",e=>{if(!this.isDragging||!this.dragStartPosition||this.initialDividerPoints.length===0)return;const i=this.parent.toLocal(e.global),s=i.x-this.dragStartPosition.x,r=i.y-this.dragStartPosition.y;this.endPoints=this.initialDividerPoints.map(o=>({x:o.x+s,y:o.y+r})),this.updateAllComponents()});f(this,"handleDragPointerUp",()=>{var e,i;this.gestureSession=null,this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null,this.initialDividerPoints=[],this.appService.getApp().stopRender("divider-drag"),this.calculateAndCreateSolidLine(),this.checkAndResetIfOutOfRoom(),(i=(e=this.dividerEvents).onUpdate)==null||i.call(e,this.getDividerEndPoints()))});f(this,"handleScaleChange",()=>{var e,i;(e=this.startEndPoint)==null||e.redraw(),(i=this.endEndPoint)==null||i.redraw(),this.updateSolidLine(),this.setupDashLineHitArea()});const{appService:i,endPoints:s,roomId:r,events:o={}}=e;this.appService=i,this.dividerEvents=o,this.roomId=r,this.dividerConfig=this.appService.dividerConfig,this.roomGeometry=this.appService.mapManager.getRoomById(this.roomId)||null,s?this.endPoints=this.validateDividerPoints(s):this.endPoints=this.createDefaultdividerPoints(),this.throttledHandleScaleChange=_t(this.handleScaleChange.bind(this),30,{leading:!0,trailing:!0}),this.initializeComponents(),this.calculateAndCreateSolidLine(),this.registerScaleListener()}validateDividerPoints(e){if(e.length>=2)return e.slice(0,2);const i=e[0]||{x:0,y:0},s={x:i.x+50,y:i.y};return[i,s]}createDefaultdividerPoints(){if(!this.roomGeometry)return w.warn("Room geometry not available, creating fallback divider"),[{x:0,y:0},{x:100,y:0}];const e=this.appService.getApp().mapState;if(!e)return w.warn("Map state not available, creating fallback divider"),[{x:0,y:0},{x:100,y:0}];const{boundingBox:i}=this.roomGeometry,s=this.appService.getApp().toFixedSize(this.dividerConfig.defaultExtension),r=this.dividerConfig.defaultDirection,o=i.x+i.width/2,a=i.y+i.height/2,h=r==="horizontal"?i.width+2*s:i.height+2*s;return ax(o,a,h,r).map(c=>({x:c.x-e.origin.x,y:c.y-e.origin.y}))}initializeComponents(){this.createDashLine(),this.addChild(this.dashLine),this.createEndPoints(),this.addChild(this.startEndPoint),this.addChild(this.endEndPoint),this.setupDashLineInteraction()}createDashLine(){const e=this.endPoints;if(e.length<2)return;const{dashLineWidth:i,dashLineDashArray:s,lineColor:r}=this.dividerConfig;this.dashLine=new He(this.appService,{start:e[0],end:e[1],style:{color:r.toString(),width:i,dashArray:s}})}createEndPoints(){const e=this.endPoints;this.startEndPoint=new ih(this.appService,{position:e[0],config:this.dividerConfig,onDragStart:this.handleEndPointDragStart,onDragMove:i=>this.handleEndPointDragMove(0,i),onDragEnd:this.handleEndPointDragEnd}),this.endEndPoint=new ih(this.appService,{position:e[1],config:this.dividerConfig,onDragStart:this.handleEndPointDragStart,onDragMove:i=>this.handleEndPointDragMove(1,i),onDragEnd:this.handleEndPointDragEnd})}setupDashLineInteraction(){this.dashLine&&(this.setupDashLineHitArea(),this.dashLine.off("pointerdown",this.handleDashLinePointerDown),this.dashLine.on("pointerdown",this.handleDashLinePointerDown))}setupDashLineHitArea(){if(!this.dashLine)return;const e=this.endPoints;if(e.length<2)return;const{hitAreaThickness:i}=this.dividerConfig,s=this.appService.getApp().toFixedSize(i),r=mc(e[0],e[1],s);if(r.length===0)return;const o=new Te(r);this.dashLine.hitArea=o}startDragging(e){this.isDragging=!0;const i=this.parent.toLocal(e.global);this.dragStartPosition={x:i.x,y:i.y},this.initialDividerPoints=this.endPoints.map(s=>({...s})),this.clearSolidLine(),this.appService.getApp().requestRender("divider-drag",!0),this.gestureSession=this.appService.gestureController.hijack(e),this.gestureSession.onMove(this.handleDragPointerMove),this.gestureSession.onEnd(this.handleDragPointerUp)}updateAllComponents(){this.updateDashLine(),this.updateSolidLine(),this.updateEndPoints(),this.setupDashLineHitArea()}updateDashLine(){const e=this.endPoints;e.length<2||!this.dashLine||this.dashLine.updatePoints(e[0],e[1])}updateSolidLine(){if(!this.solidLine||!this.solidLinePoints)return;const{solidLineWidth:e,lineColor:i}=this.dividerConfig,s=this.appService.getApp().toFixedSize(e);this.solidLine.clear(),this.solidLine.setStrokeStyle({color:i.toString(),width:s}).moveTo(this.solidLinePoints[0].x,this.solidLinePoints[0].y).lineTo(this.solidLinePoints[1].x,this.solidLinePoints[1].y).stroke()}updateEndPoints(){const e=this.endPoints;this.startEndPoint&&this.startEndPoint.updatePosition(e[0]),this.endEndPoint&&this.endEndPoint.updatePosition(e[1])}registerScaleListener(){const{emitter:e}=this.appService;e.on("antiScale",this.throttledHandleScaleChange)}getDividerEndPoints(){return[...this.endPoints]}getEffectiveDividerPoints(){return this.solidLinePoints?[...this.solidLinePoints]:null}calculateAndCreateSolidLine(){if(this.clearSolidLine(),typeof this.roomId!="number"||!this.getRoomGraphics())return;const i=this.calculateLineRoomIntersection();i&&i.length>=2&&(this.solidLinePoints=[i[0],i[i.length-1]],this.createSolidLine())}getRoomGraphics(){const e=this.appService.mapManager.roomFill;return!e||typeof this.roomId!="number"?null:e.getRoomGraphicsMap().get(this.roomId)||null}calculateLineRoomIntersection(){const e=this.endPoints;if(e.length<2||typeof this.roomId!="number")return null;const[i,s]=e,r=this.isPointInRoomFill(i),o=this.isPointInRoomFill(s);if(r||o)return null;const a=Vy(i,s),h=[];for(const p of a)this.isPointInRoomFill(p)&&h.push(p);if(h.length===0)return null;const l=h[0],c=h[h.length-1];return tt(l,c)<3?null:hx(l,c,.5)}isPointInRoomFill(e){if(typeof this.roomId!="number")return!1;const i=this.appService.getApp().mapState;if(!i)return!1;const s={x:e.x+i.origin.x,y:e.y+i.origin.y};return i.mapType==="raster"?this.isPointInRasterRoomFill(s):this.isPointInStructuredRoomFill(s)}isPointInRasterRoomFill(e){e.x-=.5,e.y-=.5;const i=this.appService.getApp().mapState,s=this.appService.mapManager.roomFill;if(!i||!s)return!1;const r=s.getRasterRoomData(this.roomId);if(!r)return!1;const o=s.getMapWidth();if(o===0)return!1;const a=Math.round(e.x),h=Math.round(e.y);if(a<0||h<0||a>=o)return!1;const l=h*o+a;for(let c=0;c<r.pixelIndices.length;c++)if(r.pixelIndices[c]===l)return!0;return!1}isPointInStructuredRoomFill(e){const i={x:Math.round(e.x),y:Math.round(e.y)},s=this.appService.getApp().mapState,r=this.appService.mapManager.getRoomById(this.roomId);return!s||!r||!r.outlinePoints?!1:kt(i,r.outlinePoints,!0)}isDividerCompletelyOutOfRoom(){if(!this.roomGeometry)return!1;const{boundingBox:e}=this.roomGeometry,i=this.endPoints;if(i.length<2)return!1;const s=this.appService.getApp().mapState;if(!s)return!1;const r={x:i[0].x+s.origin.x,y:i[0].y+s.origin.y},o={x:i[1].x+s.origin.x,y:i[1].y+s.origin.y};return!ox(r,o,e.x,e.y,e.width,e.height)}checkAndResetIfOutOfRoom(){const{resetDividerWhenOutOfRoom:e}=this.appService.dividerConfig;e&&this.isDividerCompletelyOutOfRoom()&&this.resetToDefaultState()}resetToDefaultState(){var e,i;this.endPoints=this.createDefaultdividerPoints(),this.calculateAndCreateSolidLine(),this.updateComponents(),(i=(e=this.dividerEvents).onUpdate)==null||i.call(e,this.endPoints)}updateComponents(){const e=this.endPoints;e.length>=2&&(this.dashLine.updatePoints(e[0],e[1]),this.startEndPoint.position.set(e[0].x,e[0].y),this.endEndPoint.position.set(e[1].x,e[1].y),this.setupDashLineInteraction())}createSolidLine(){if(!this.solidLinePoints)return;const{solidLineWidth:e,lineColor:i}=this.dividerConfig;this.solidLine=new H,this.solidLine.eventMode="none";const s=this.appService.getApp().toFixedSize(e);this.solidLine.setStrokeStyle({color:i.toString(),width:s}).moveTo(this.solidLinePoints[0].x,this.solidLinePoints[0].y).lineTo(this.solidLinePoints[1].x,this.solidLinePoints[1].y).stroke(),this.addChildAt(this.solidLine,0)}clearSolidLine(){this.solidLine&&(this.removeChild(this.solidLine),this.solidLine.destroy(),this.solidLine=null),this.solidLinePoints=null}updatedividerPoints(e){this.endPoints=this.validateDividerPoints(e),this.updateAllComponents(),this.calculateAndCreateSolidLine()}destroy(){var e,i,s,r;this.appService.emitter.off("antiScale",this.throttledHandleScaleChange),this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null,this.initialDividerPoints=[]),(e=this.gestureSession)==null||e.cancel(),this.gestureSession=null,this.dashLine&&this.dashLine.off("pointerdown",this.handleDashLinePointerDown),this.clearSolidLine(),(i=this.dashLine)==null||i.destroy(),(s=this.startEndPoint)==null||s.destroy(),(r=this.endEndPoint)==null||r.destroy(),super.destroy()}}const ur=["forbiddenSweepZone","forbiddenMopZone","cleanZone","virtualWall","spot","wayPoint","divider"];function oS(n){if(!n||n.length===0)return[...ur];const t=new Set,e=[];for(const i of n)t.has(i)||(t.add(i),e.push(i));for(const i of ur)t.has(i)||e.push(i);return e}class aS{constructor(t){f(this,"zoneMaps",new Map);f(this,"virtualWallMap",new Map);f(this,"spotMap",new Map);f(this,"wayPointMap",new Map);f(this,"divider",null);f(this,"controlContainers",new Map);f(this,"unsubscribeFns",[]);f(this,"builtinZoneFactories",{forbiddenSweepZone:t=>Xr.create(this.appService,t),forbiddenMopZone:t=>jr.create(this.appService,t),cleanZone:t=>Zr.create(this.appService,t)});this.appService=t,this.initializeControlContainers();const e=G(t.runtime,"editingForbiddenSweepZoneIds",u=>{w.log(`[runtime] editingForbiddenSweepZoneIds: ${u}`);const p=this.zoneMaps.get("forbiddenSweepZone");p&&this.updateZonesEditState("forbiddenSweepZone",p)}),i=G(t.runtime,"editingForbiddenMopZoneIds",u=>{w.log(`[runtime] editingForbiddenMopZoneIds: ${u}`);const p=this.zoneMaps.get("forbiddenMopZone");p&&this.updateZonesEditState("forbiddenMopZone",p)}),s=G(t.runtime,"editingCleanZoneIds",u=>{w.log(`[runtime] editingCleanZoneIds: ${u}`);const p=this.zoneMaps.get("cleanZone");p&&this.updateZonesEditState("cleanZone",p)}),r=G(t.runtime,"editingCustomZoneIds",u=>{w.log(`[runtime] editingCustomZoneIds: ${JSON.stringify(u??{})}`);for(const[p,g]of this.zoneMaps)Ne(p)||g.size&&this.updateZonesEditState(p,g)}),o=G(t.runtime,"editingVirtualWallIds",u=>{w.log(`[runtime] editingVirtualWallIds: ${u}`),this.updateVirtualWallsEditState(this.virtualWallMap)}),a=G(t.runtime,"editingSpotIds",u=>{w.log(`[runtime] editingSpotIds: ${u}`),this.updateSpotsEditState(this.spotMap)}),h=G(t.runtime,"editingWayPointIds",u=>{w.log(`[runtime] editingWayPointIds: ${u}`),this.updateWayPointsEditState(this.wayPointMap)}),l=G(t.runtime,"dividingRoomId",u=>{w.log(`[runtime] dividingRoomId: ${u}`),this.handleDividingRoomIdChange(u)}),c=G(t.runtime,"unit",u=>{w.log(`[runtime] unit changed: ${u}`),this.handleUnitChange()}),d=G(t.runtime,"unitLabel",u=>{w.log(`[runtime] unitLabel changed: ${u}`),this.handleUnitChange()});this.unsubscribeFns.push(e,i,s,r,o,a,h,l,c,d)}updateRenderOrder(){this.applyRenderOrder()}initializeControlContainers(){const t=this.appService.appContainer.getLayer(Ae);if(!t){w.warn("[ControlsManager] LAYER_CONTROLS not found during init");return}for(const e of ur){const i=new W;i.label=`controls:${e}`,this.controlContainers.set(e,i),t.addChild(i)}this.applyRenderOrder()}applyRenderOrder(){const t=this.appService.appContainer.getLayer(Ae);if(!t)return;oS(this.appService.getConfig().controls.renderOrder).forEach((i,s)=>{const r=this.controlContainers.get(i);r&&(r.zIndex=s)}),t.sortableChildren=!0,t.sortChildren()}addToControlLayer(t,e){let i=this.controlContainers.get(t);if(!i){const s=this.appService.appContainer.getLayer(Ae);if(!s){w.warn("[ControlsManager] LAYER_CONTROLS not found");return}i=new W,i.label=`controls:${t}`,this.controlContainers.set(t,i),s.addChild(i),this.applyRenderOrder()}i.addChild(e)}drawForbiddenSweepZones(t){this.drawZonesByType("forbiddenSweepZone",t)}getForbiddenSweepZones(){return this.getZonesDataByType("forbiddenSweepZone")}clearAllForbiddenSweepZones(){this.clearAllZonesByType("forbiddenSweepZone")}drawForbiddenMopZones(t){this.drawZonesByType("forbiddenMopZone",t)}getForbiddenMopZones(){return this.getZonesDataByType("forbiddenMopZone")}clearAllForbiddenMopZones(){this.clearAllZonesByType("forbiddenMopZone")}drawCleanZones(t){this.drawZonesByType("cleanZone",t)}getCleanZones(){return this.getZonesDataByType("cleanZone")}clearAllCleanZones(){this.clearAllZonesByType("cleanZone")}drawVirtualWalls(t){var r;const e=this.appService,i=this.virtualWallMap,s=new Set(t.map(o=>o.id));for(const[o,a]of i)s.has(o)||((r=a.parent)==null||r.removeChild(a),a.destroy(),i.delete(o));t.forEach(o=>{const a=i.get(o.id);if(a)this.isWallDataEqual(a.getWallData(),o)||a.updateWallData(o);else{const h=new dr({appService:e,wallData:o,events:{onRemove:l=>{var c,d;(d=(c=e.events)==null?void 0:c.onRemoveVirtualWall)==null||d.call(c,l)},onUpdate:l=>{var c,d;(d=(c=e.events)==null?void 0:c.onUpdateVirtualWall)==null||d.call(c,l)},onClick:l=>{var c,d;(d=(c=e.events)==null?void 0:c.onClickVirtualWall)==null||d.call(c,l)}}});i.set(o.id,h),this.addToControlLayer("virtualWall",h)}})}getVirtualWalls(){return this.getWallsData(this.virtualWallMap)}clearAllVirtualWalls(){this.clearAllWalls(this.virtualWallMap)}drawSpots(t){const e=this.spotMap;if(!t||t.length===0){this.clearAllSpotsInternal(e);return}const i=new Set(e.keys()),s=new Set(t.map(r=>r.id));for(const r of i)s.has(r)||this.removeSpot(r,e);t.forEach(r=>{const o=e.get(r.id);o?this.isSpotDataEqual(o.getSpotData(),r)||o.updateSpotData(r):this.addNewSpot(r,e)})}getSpots(){return this.getSpotsData(this.spotMap)}clearAllSpots(){this.clearAllSpotsInternal(this.spotMap)}getZoneMap(t){let e=this.zoneMaps.get(t);return e||(e=new Map,this.zoneMaps.set(t,e)),e}resolveZoneFactory(t){var s;const e=this.builtinZoneFactories[t];return e||((s=this.appService.getConfig().customZoneTypes)!=null&&s[t]?r=>new Gs({deps:Ws(this.appService,{onRemove:o=>{var a,h;return(h=(a=this.appService.events)==null?void 0:a.onRemoveCustomZone)==null?void 0:h.call(a,t,o)},onUpdate:o=>{var a,h;return(h=(a=this.appService.events)==null?void 0:a.onUpdateCustomZone)==null?void 0:h.call(a,t,o)},onClick:o=>{var a,h;return(h=(a=this.appService.events)==null?void 0:a.onClickCustomZone)==null?void 0:h.call(a,t,o)}}),zoneData:r,zoneType:t}):null)}drawCustomZones(t,e){this.drawZonesByType(t,e)}getCustomZones(t){return this.getZonesDataByType(t)}clearCustomZones(t){this.clearAllZonesByType(t)}drawZonesByType(t,e){const i=this.resolveZoneFactory(t);if(!i){w.warn(`[ControlsManager] Unknown zone type: ${t}`);return}const s=this.getZoneMap(t);this.drawZonesImpl(e,s,i,t)}getZonesDataByType(t){const e=this.zoneMaps.get(t);return e?this.getZonesData(e):[]}clearAllZonesByType(t){const e=this.zoneMaps.get(t);e&&this.clearAllZones(e)}drawZonesImpl(t,e,i,s){if(!t||t.length===0){this.clearAllZones(e);return}const r=new Set(e.keys()),o=new Set(t.map(a=>a.id));for(const a of r)o.has(a)||this.removeZone(a,e);t.forEach(a=>{const h=e.get(a.id);h?this.isZoneDataEqual(h.getZoneData(),a)||h.updateZoneData(a):this.addNewZone(a,e,i,s)})}addNewZone(t,e,i,s){const r=i(t);e.set(t.id,r),this.addToControlLayer(s,r),r.setEditing(this.getEditingZoneIds(String(s)).includes(t.id))}removeZone(t,e){var s;const i=e.get(t);i&&((s=i.parent)==null||s.removeChild(i),i.destroy(),e.delete(t))}getZonesData(t){const e=[];return t.forEach(i=>{e.push(i.getZoneData())}),e}clearAllZones(t){t.forEach((e,i)=>{var r;const s=t.get(i);s&&((r=s.parent)==null||r.removeChild(s),s.destroy())}),t.clear()}getEditingZoneIds(t){var i;const e=this.appService.runtimeSnapshot;switch(t){case"forbiddenSweepZone":return e.editingForbiddenSweepZoneIds;case"forbiddenMopZone":return e.editingForbiddenMopZoneIds;case"cleanZone":return e.editingCleanZoneIds;default:return((i=e.editingCustomZoneIds)==null?void 0:i[t])??[]}}updateZonesEditState(t,e){const i=this.getEditingZoneIds(t);e.forEach((s,r)=>{s.setEditing(i.includes(r))})}updateVirtualWallsEditState(t){t.forEach(e=>{e.updateEditingState()})}isZoneDataEqual(t,e){if(t.id!==e.id||t.points.length!==e.points.length)return!1;for(let i=0;i<t.points.length;i++){const s=t.points[i],r=e.points[i];if(Math.abs(s.x-r.x)>.1||Math.abs(s.y-r.y)>.1)return!1}return!0}getWallsData(t){return Array.from(t.values()).map(e=>e.getWallData())}clearAllWalls(t){for(const e of t.values())e.destroy();t.clear()}isWallDataEqual(t,e){if(t.id!==e.id||t.points.length!==e.points.length)return!1;for(let i=0;i<t.points.length;i++){const s=t.points[i],r=e.points[i];if(Math.abs(s.x-r.x)>.1||Math.abs(s.y-r.y)>.1)return!1}return!0}addNewSpot(t,e){const i=qr.create(this.appService,t);e.set(t.id,i),this.addToControlLayer("spot",i)}removeSpot(t,e){var s;const i=e.get(t);i&&((s=i.parent)==null||s.removeChild(i),i.destroy(),e.delete(t))}getSpotsData(t){const e=[];return t.forEach(i=>{e.push(i.getSpotData())}),e}clearAllSpotsInternal(t){t.forEach((e,i)=>{var r;const s=t.get(i);s&&((r=s.parent)==null||r.removeChild(s),s.destroy())}),t.clear()}updateSpotsEditState(t){t.forEach(e=>{e.updateEditState()})}isSpotDataEqual(t,e){if(t.id!==e.id)return!1;const i=t.point,s=e.point;return Math.abs(i.x-s.x)>.1||Math.abs(i.y-s.y)>.1?!1:t.name===e.name}drawWayPoints(t){w.log("[ControlsManager] drawWayPoints",t);const e=Array.from(this.wayPointMap.keys()),i=t.map(r=>r.id);e.filter(r=>!i.includes(r)).forEach(r=>{this.removeWayPoint(r,this.wayPointMap)}),t.forEach((r,o)=>{const a=o+1,h=this.wayPointMap.get(r.id);h?(this.isWayPointDataEqual(h.getWayPointData(),r)||h.updateWayPoint(r),h.updateOrder(a)):this.addNewWayPoint(r,a,this.wayPointMap)})}clearAllWayPoints(){w.log("[ControlsManager] clearAllWayPoints"),this.clearAllWayPointsInternal(this.wayPointMap)}getWayPoints(){return this.getWayPointsData(this.wayPointMap)}addNewWayPoint(t,e,i){var o,a;const s=this.appService,r=new nS({appService:s,wayPointData:t,order:e,events:{onUpdate:(o=s.events)==null?void 0:o.onUpdateWayPoint,onClick:(a=s.events)==null?void 0:a.onClickWayPoint}});i.set(t.id,r),this.addToControlLayer("wayPoint",r)}removeWayPoint(t,e){var s;const i=e.get(t);i&&((s=i.parent)==null||s.removeChild(i),i.destroy(),e.delete(t))}getWayPointsData(t){const e=[];return t.forEach(i=>{e.push(i.getWayPointData())}),e}clearAllWayPointsInternal(t){t.forEach((e,i)=>{var r;const s=t.get(i);s&&((r=s.parent)==null||r.removeChild(s),s.destroy())}),t.clear()}updateWayPointsEditState(t){t.forEach(e=>{e.onEditStateChange()})}isWayPointDataEqual(t,e){if(t.id!==e.id)return!1;const i=t.point,s=e.point;return!(Math.abs(i.x-s.x)>.1||Math.abs(i.y-s.y)>.1)}handleDividingRoomIdChange(t){if(t==null||t===-1){this.clearDivider();return}if(!this.getRoomGeometry(t)){this.clearDivider();return}this.createDefaultDivider(t)}getRoomGeometry(t){return this.appService.mapManager.getRoomById(t)}createDefaultDivider(t){const e=this.appService;this.clearDivider(),this.divider=new rS({appService:this.appService,roomId:t,events:{onUpdate:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onUpdateDivider)==null||r.call(s,i)}}}),this.addToControlLayer("divider",this.divider)}clearDivider(){var t;this.divider&&((t=this.divider.parent)==null||t.removeChild(this.divider),this.divider.destroy(),this.divider=null)}getDividerEndPoints(){return this.divider?this.divider.getDividerEndPoints():null}getEffectiveDividerPoints(){return this.divider?this.divider.getEffectiveDividerPoints():null}handleUnitChange(){w.debug("[ControlsManager] Unit changed, refreshing all size texts");for(const t of this.zoneMaps.values())t.forEach(e=>{e.refreshDisplay()});this.virtualWallMap.forEach(t=>{t.refreshDisplay()}),this.spotMap.forEach(t=>{t.refreshDisplay()})}destroy(){this.unsubscribeFns.forEach(t=>t()),this.unsubscribeFns=[];for(const t of this.zoneMaps.keys())this.clearAllZonesByType(t);this.clearAllVirtualWalls(),this.clearAllSpots(),this.clearDivider(),this.controlContainers.forEach(t=>{t.removeFromParent(),t.destroy({children:!0})}),this.controlContainers.clear()}}class hS extends Xt{constructor(e,i){super(e);f(this,"objectData");f(this,"clickHandler",null);f(this,"unsubscribeMapRotation",null);this.appService=e,this.objectData=i}async initializeSprite(){const e=this.appService.detectedObjectConfig,i=this.objectData.width||e.width,s=this.objectData.height||e.height;await this.loadTextureAndSetSize(this.objectData.src,{width:i,height:s}),this.anchor.set(e.anchor.x,e.anchor.y),this.position.set(this.objectData.x,this.objectData.y),this.visible=!0,this.applyAntiRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation=G(this.appService.runtime,"mapRotation",r=>{this.applyAntiRotation(r)}),e.interactive?this.setupClickHandler():this.eventMode="none"}applyAntiRotation(e){const i=-e*Math.PI/180;this.rotation=i}setupClickHandler(){this.clickHandler&&this.clickHandler.destroy(),this.clickHandler=new vt(this,{onClick:()=>this.handleClick(),stopPropagation:!1})}handleClick(){var e,i;(i=(e=this.appService.events)==null?void 0:e.onClickDetectedObject)==null||i.call(e,this.getObjectData())}getObjectData(){return{...this.objectData}}async updateObjectData(e){const i=this.objectData;this.objectData=e;const s=this.appService.detectedObjectConfig;if(i.src!==e.src){const r=e.width||s.width,o=e.height||s.height;await this.loadTextureAndSetSize(e.src,{width:r,height:o})}if(i.width!==e.width||i.height!==e.height){const r=e.width||s.width,o=e.height||s.height;this.setFixedSize(r,o)}this.position.set(e.x,e.y),s.interactive?this.clickHandler||this.setupClickHandler():this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null)}isSameData(e){return this.objectData.id===e.id&&this.objectData.src===e.src&&this.objectData.x===e.x&&this.objectData.y===e.y&&this.objectData.width===e.width&&this.objectData.height===e.height}destroy(){this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null),super.destroy()}}class lS{constructor(t){f(this,"detectedObjectMap",new Map);f(this,"unsubscribeShowDetectedObjects",null);this.appService=t,this.applyLayerVisibility(this.appService.runtime.showDetectedObjects),this.unsubscribeShowDetectedObjects=G(this.appService.runtime,"showDetectedObjects",e=>{this.applyLayerVisibility(e)})}async drawDetectedObjects(t){if(!t||t.length===0){this.clearAllDetectedObjects();return}const e=new Set(t.map(s=>s.id)),i=Array.from(this.detectedObjectMap.keys());for(const s of i)e.has(s)||this.removeDetectedObject(s);for(const s of t){const r=this.detectedObjectMap.get(s.id);r?r.isSameData(s)||await r.updateObjectData(s):await this.addNewDetectedObject(s)}}applyLayerVisibility(t){const e=this.appService.appContainer.getLayer(Ye);e&&(e.visible=t)}clearAllDetectedObjects(){const t=this.appService;this.detectedObjectMap.forEach(e=>{t.appContainer.removeFromLayer(Ye,e),e.destroy()}),this.detectedObjectMap.clear()}async addNewDetectedObject(t){const e=this.appService,i=new hS(this.appService,t);await i.initializeSprite(),this.detectedObjectMap.set(t.id,i),e.appContainer.addToLayer(Ye,i)}removeDetectedObject(t){const e=this.appService,i=this.detectedObjectMap.get(t);i&&(e.appContainer.removeFromLayer(Ye,i),i.destroy(),this.detectedObjectMap.delete(t))}destroy(){this.unsubscribeShowDetectedObjects&&(this.unsubscribeShowDetectedObjects(),this.unsubscribeShowDetectedObjects=null),this.clearAllDetectedObjects()}}var ke={},Fc={},ee={};Object.defineProperty(ee,"__esModule",{value:!0});ee.loop=ee.conditional=ee.parse=void 0;var cS=function n(t,e){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:i;if(Array.isArray(e))e.forEach(function(o){return n(t,o,i,s)});else if(typeof e=="function")e(t,i,s,n);else{var r=Object.keys(e)[0];Array.isArray(e[r])?(s[r]={},n(t,e[r],i,s[r])):s[r]=e[r](t,i,s,n)}return i};ee.parse=cS;var dS=function(t,e){return function(i,s,r,o){e(i,s,r)&&o(i,t,s,r)}};ee.conditional=dS;var uS=function(t,e){return function(i,s,r,o){for(var a=[],h=i.pos;e(i,s,r);){var l={};if(o(i,t,s,l),i.pos===h)break;h=i.pos,a.push(l)}return a}};ee.loop=uS;var dt={};Object.defineProperty(dt,"__esModule",{value:!0});dt.readBits=dt.readArray=dt.readUnsigned=dt.readString=dt.peekBytes=dt.readBytes=dt.peekByte=dt.readByte=dt.buildStream=void 0;var pS=function(t){return{data:t,pos:0}};dt.buildStream=pS;var Bc=function(){return function(t){return t.data[t.pos++]}};dt.readByte=Bc;var fS=function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return function(e){return e.data[e.pos+t]}};dt.peekByte=fS;var Us=function(t){return function(e){return e.data.subarray(e.pos,e.pos+=t)}};dt.readBytes=Us;var gS=function(t){return function(e){return e.data.subarray(e.pos,e.pos+t)}};dt.peekBytes=gS;var mS=function(t){return function(e){return Array.from(Us(t)(e)).map(function(i){return String.fromCharCode(i)}).join("")}};dt.readString=mS;var yS=function(t){return function(e){var i=Us(2)(e);return t?(i[1]<<8)+i[0]:(i[0]<<8)+i[1]}};dt.readUnsigned=yS;var xS=function(t,e){return function(i,s,r){for(var o=typeof e=="function"?e(i,s,r):e,a=Us(t),h=new Array(o),l=0;l<o;l++)h[l]=a(i);return h}};dt.readArray=xS;var SS=function(t,e,i){for(var s=0,r=0;r<i;r++)s+=t[e+r]&&Math.pow(2,i-r-1);return s},vS=function(t){return function(e){for(var i=Bc()(e),s=new Array(8),r=0;r<8;r++)s[7-r]=!!(i&1<<r);return Object.keys(t).reduce(function(o,a){var h=t[a];return h.length?o[a]=SS(s,h.index,h.length):o[a]=s[h.index],o},{})}};dt.readBits=vS;(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var t=ee,e=dt,i={blocks:function(u){for(var p=0,g=[],y=u.data.length,m=0,x=(0,e.readByte)()(u);x!==p&&x;x=(0,e.readByte)()(u)){if(u.pos+x>=y){var S=y-u.pos;g.push((0,e.readBytes)(S)(u)),m+=S;break}g.push((0,e.readBytes)(x)(u)),m+=x}for(var v=new Uint8Array(m),b=0,P=0;P<g.length;P++)v.set(g[P],b),b+=g[P].length;return v}},s=(0,t.conditional)({gce:[{codes:(0,e.readBytes)(2)},{byteSize:(0,e.readByte)()},{extras:(0,e.readBits)({future:{index:0,length:3},disposal:{index:3,length:3},userInput:{index:6},transparentColorGiven:{index:7}})},{delay:(0,e.readUnsigned)(!0)},{transparentColorIndex:(0,e.readByte)()},{terminator:(0,e.readByte)()}]},function(d){var u=(0,e.peekBytes)(2)(d);return u[0]===33&&u[1]===249}),r=(0,t.conditional)({image:[{code:(0,e.readByte)()},{descriptor:[{left:(0,e.readUnsigned)(!0)},{top:(0,e.readUnsigned)(!0)},{width:(0,e.readUnsigned)(!0)},{height:(0,e.readUnsigned)(!0)},{lct:(0,e.readBits)({exists:{index:0},interlaced:{index:1},sort:{index:2},future:{index:3,length:2},size:{index:5,length:3}})}]},(0,t.conditional)({lct:(0,e.readArray)(3,function(d,u,p){return Math.pow(2,p.descriptor.lct.size+1)})},function(d,u,p){return p.descriptor.lct.exists}),{data:[{minCodeSize:(0,e.readByte)()},i]}]},function(d){return(0,e.peekByte)()(d)===44}),o=(0,t.conditional)({text:[{codes:(0,e.readBytes)(2)},{blockSize:(0,e.readByte)()},{preData:function(u,p,g){return(0,e.readBytes)(g.text.blockSize)(u)}},i]},function(d){var u=(0,e.peekBytes)(2)(d);return u[0]===33&&u[1]===1}),a=(0,t.conditional)({application:[{codes:(0,e.readBytes)(2)},{blockSize:(0,e.readByte)()},{id:function(u,p,g){return(0,e.readString)(g.blockSize)(u)}},i]},function(d){var u=(0,e.peekBytes)(2)(d);return u[0]===33&&u[1]===255}),h=(0,t.conditional)({comment:[{codes:(0,e.readBytes)(2)},i]},function(d){var u=(0,e.peekBytes)(2)(d);return u[0]===33&&u[1]===254}),l=[{header:[{signature:(0,e.readString)(3)},{version:(0,e.readString)(3)}]},{lsd:[{width:(0,e.readUnsigned)(!0)},{height:(0,e.readUnsigned)(!0)},{gct:(0,e.readBits)({exists:{index:0},resolution:{index:1,length:3},sort:{index:4},size:{index:5,length:3}})},{backgroundColorIndex:(0,e.readByte)()},{pixelAspectRatio:(0,e.readByte)()}]},(0,t.conditional)({gct:(0,e.readArray)(3,function(d,u){return Math.pow(2,u.lsd.gct.size+1)})},function(d,u){return u.lsd.gct.exists}),{frames:(0,t.loop)([s,a,h,r,o],function(d){var u=(0,e.peekByte)()(d);return u===33||u===44})}],c=l;n.default=c})(Fc);var Hs={};Object.defineProperty(Hs,"__esModule",{value:!0});Hs.deinterlace=void 0;var bS=function(t,e){for(var i=new Array(t.length),s=t.length/e,r=function(u,p){var g=t.slice(p*e,(p+1)*e);i.splice.apply(i,[u*e,e].concat(g))},o=[0,4,2,1],a=[8,8,4,2],h=0,l=0;l<4;l++)for(var c=o[l];c<s;c+=a[l])r(c,h),h++;return i};Hs.deinterlace=bS;var Ns={};Object.defineProperty(Ns,"__esModule",{value:!0});Ns.lzw=void 0;var wS=function(t,e,i){var s=4096,r=-1,o=i,a,h,l,c,d,u,p,C,g,y,P,m,_,R,A,M,x=new Array(i),S=new Array(s),v=new Array(s),b=new Array(s+1);for(m=t,h=1<<m,d=h+1,a=h+2,p=r,c=m+1,l=(1<<c)-1,g=0;g<h;g++)S[g]=0,v[g]=g;var P,C,_,R,M,A;for(P=C=_=R=M=A=0,y=0;y<o;){if(R===0){if(C<c){P+=e[A]<<C,C+=8,A++;continue}if(g=P&l,P>>=c,C-=c,g>a||g==d)break;if(g==h){c=m+1,l=(1<<c)-1,a=h+2,p=r;continue}if(p==r){b[R++]=v[g],p=g,_=g;continue}for(u=g,g==a&&(b[R++]=_,g=p);g>h;)b[R++]=v[g],g=S[g];_=v[g]&255,b[R++]=_,a<s&&(S[a]=p,v[a]=_,a++,!(a&l)&&a<s&&(c++,l+=a)),p=u}R--,x[M++]=b[R],y++}for(y=M;y<o;y++)x[y]=0;return x};Ns.lzw=wS;Object.defineProperty(ke,"__esModule",{value:!0});var Lc=ke.decompressFrames=ke.decompressFrame=zc=ke.parseGIF=void 0,CS=AS(Fc),_S=ee,PS=dt,MS=Hs,TS=Ns;function AS(n){return n&&n.__esModule?n:{default:n}}var RS=function(t){var e=new Uint8Array(t);return(0,_S.parse)((0,PS.buildStream)(e),CS.default)},zc=ke.parseGIF=RS,kS=function(t){for(var e=t.pixels.length,i=new Uint8ClampedArray(e*4),s=0;s<e;s++){var r=s*4,o=t.pixels[s],a=t.colorTable[o]||[0,0,0];i[r]=a[0],i[r+1]=a[1],i[r+2]=a[2],i[r+3]=o!==t.transparentIndex?255:0}return i},Oc=function(t,e,i){if(!t.image){console.warn("gif frame does not have associated image.");return}var s=t.image,r=s.descriptor.width*s.descriptor.height,o=(0,TS.lzw)(s.data.minCodeSize,s.data.blocks,r);s.descriptor.lct.interlaced&&(o=(0,MS.deinterlace)(o,s.descriptor.width));var a={pixels:o,dims:{top:t.image.descriptor.top,left:t.image.descriptor.left,width:t.image.descriptor.width,height:t.image.descriptor.height}};return s.descriptor.lct&&s.descriptor.lct.exists?a.colorTable=s.lct:a.colorTable=e,t.gce&&(a.delay=(t.gce.delay||10)*10,a.disposalType=t.gce.extras.disposal,t.gce.extras.transparentColorGiven&&(a.transparentIndex=t.gce.transparentColorIndex)),i&&(a.patch=kS(a)),a};ke.decompressFrame=Oc;var ES=function(t,e){return t.frames.filter(function(i){return i.image}).map(function(i){return Oc(i,t.gct,e)})};Lc=ke.decompressFrames=ES;class Vs{constructor(t){if(!t||!t.length)throw new Error("Invalid frames");const[{texture:{width:e,height:i}}]=t;this.width=e,this.height=i,this.frames=t,this.textures=this.frames.map(s=>s.texture),this.totalFrames=this.frames.length,this.duration=this.frames[this.totalFrames-1].end}destroy(){for(const t of this.textures)t.destroy(!0);for(const t of this.frames)t.texture=null;this.frames.length=0,this.textures.length=0,Object.assign(this,{frames:null,textures:null,width:0,height:0,duration:0,totalFrames:0})}static from(t,e){if(!t||t.byteLength===0)throw new Error("Invalid buffer");const i=S=>{let v=null;for(const b of S.frames)v=b.gce??v,"image"in b&&!("gce"in b)&&(b.gce=v)},s=zc(t);i(s);const r=Lc(s,!0),o=[],a=s.lsd.width,h=s.lsd.height,l=$.get().createCanvas(a,h),c=l.getContext("2d",{willReadFrequently:!0}),d=$.get().createCanvas(),u=d.getContext("2d");let p=0,g=null;const{fps:y=30,...m}=e??{},x=1e3/y;for(let S=0;S<r.length;S++){const{disposalType:v=2,delay:b=x,patch:P,dims:{width:C,height:_,left:R,top:M}}=r[S];d.width=C,d.height=_,u.clearRect(0,0,C,_);const A=u.createImageData(C,_);A.data.set(P),u.putImageData(A,0,0),v===3&&(g=c.getImageData(0,0,a,h)),c.drawImage(d,R,M);const T=c.getImageData(0,0,a,h);v===2?c.clearRect(0,0,a,h):v===3&&c.putImageData(g,0,0);const I=$.get().createCanvas(T.width,T.height);I.getContext("2d").putImageData(T,0,0),o.push({start:p,end:p+b,texture:new O({source:new vr({resource:I,...m})})}),p+=b}return l.width=l.height=0,d.width=d.height=0,new Vs(o)}}const IS={extension:E.Asset,detection:{test:async()=>!0,add:async n=>[...n,"gif"],remove:async n=>n.filter(t=>t!=="gif")},loader:{name:"gifLoader",id:"gif",test:n=>Pt.extname(n)===".gif"||n.startsWith("data:image/gif"),load:async(n,t)=>{const i=await(await $.get().fetch(n)).arrayBuffer();return Vs.from(i,t==null?void 0:t.data)},unload:async n=>{n.destroy()}}},Wc=class pr extends $t{constructor(...t){const e=t[0]instanceof Vs?{source:t[0]}:t[0],{source:i,fps:s,loop:r,animationSpeed:o,autoPlay:a,autoUpdate:h,onComplete:l,onFrameChange:c,onLoop:d,...u}=Object.assign({},pr.defaultOptions,e);super({texture:O.EMPTY,...u}),this.animationSpeed=1,this.loop=!0,this.duration=0,this.autoPlay=!0,this.dirty=!1,this._currentFrame=0,this._autoUpdate=!1,this._isConnectedToTicker=!1,this._playing=!1,this._currentTime=0,this.onRender=()=>this._updateFrame(),this.texture=i.textures[0],this.duration=i.frames[i.frames.length-1].end,this._source=i,this._playing=!1,this._currentTime=0,this._isConnectedToTicker=!1,Object.assign(this,{fps:s,loop:r,animationSpeed:o,autoPlay:a,autoUpdate:h,onComplete:l,onFrameChange:c,onLoop:d}),this.currentFrame=0,a&&this.play()}stop(){this._playing&&(this._playing=!1,this._autoUpdate&&this._isConnectedToTicker&&(mt.shared.remove(this.update,this),this._isConnectedToTicker=!1))}play(){this._playing||(this._playing=!0,this._autoUpdate&&!this._isConnectedToTicker&&(mt.shared.add(this.update,this,Ie.HIGH),this._isConnectedToTicker=!0),!this.loop&&this.currentFrame===this._source.frames.length-1&&(this._currentTime=0))}get progress(){return this._currentTime/this.duration}get playing(){return this._playing}update(t){var o,a;if(!this._playing)return;const e=this.animationSpeed*t.deltaTime/mt.targetFPMS,i=this._currentTime+e,s=i%this.duration,r=this._source.frames.findIndex(h=>h.start<=s&&h.end>s);i>=this.duration?this.loop?(this._currentTime=s,this._updateFrameIndex(r),(o=this.onLoop)==null||o.call(this)):(this._currentTime=this.duration,this._updateFrameIndex(this.totalFrames-1),(a=this.onComplete)==null||a.call(this),this.stop()):(this._currentTime=s,this._updateFrameIndex(r))}_updateFrame(){this.dirty&&(this.texture=this._source.frames[this._currentFrame].texture,this.dirty=!1)}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){t!==this._autoUpdate&&(this._autoUpdate=t,!this._autoUpdate&&this._isConnectedToTicker?(mt.shared.remove(this.update,this),this._isConnectedToTicker=!1):this._autoUpdate&&!this._isConnectedToTicker&&this._playing&&(mt.shared.add(this.update,this),this._isConnectedToTicker=!0))}get currentFrame(){return this._currentFrame}set currentFrame(t){this._updateFrameIndex(t),this._currentTime=this._source.frames[t].start}get source(){return this._source}_updateFrameIndex(t){var e;if(t<0||t>=this.totalFrames)throw new Error(`Frame index out of range, expecting 0 to ${this.totalFrames}, got ${t}`);this._currentFrame!==t&&(this._currentFrame=t,this.dirty=!0,(e=this.onFrameChange)==null||e.call(this,t))}get totalFrames(){return this._source.totalFrames}destroy(t=!1){this.stop(),super.destroy(),t&&this._source.destroy();const e=null;this._source=e,this.onComplete=e,this.onFrameChange=e,this.onLoop=e}clone(){const t=new pr({source:this._source,autoUpdate:this._autoUpdate,loop:this.loop,autoPlay:this.autoPlay,animationSpeed:this.animationSpeed,onComplete:this.onComplete,onFrameChange:this.onFrameChange,onLoop:this.onLoop});return t.dirty=!0,t}};Wc.defaultOptions={fps:30,loop:!0,animationSpeed:1,autoPlay:!0,autoUpdate:!0,onComplete:null,onFrameChange:null,onLoop:null};let DS=Wc;q.add(IS);class Kr extends DS{constructor(e,i){super(i);f(this,"throttledUpdateScale");f(this,"fixedWidth",0);f(this,"fixedHeight",0);f(this,"isFixedSizeSet",!1);f(this,"sizeFixed",!0);f(this,"baselineScale",1);this.appService=e,this.anchor.set(.5),this.visible=!1,this.throttledUpdateScale=_t(this.updateScale.bind(this),30,{leading:!0,trailing:!0}),this.registerScaleListener()}setFixedSize(e,i){this.fixedWidth=e,this.fixedHeight=i,this.isFixedSizeSet=!0,this.applySize()}setSizeFixed(e){this.sizeFixed=e,this.baselineScale=1,e&&this.isFixedSizeSet?this.applySize():!e&&this.isFixedSizeSet&&this.applySize()}set width(e){if(this.isFixedSizeSet){w.warn("EnhancedGifSprite: 使用 setFixedSize() 方法来设置宽度");return}this.setFixedSize(e,this.fixedHeight||e)}set height(e){if(this.isFixedSizeSet){w.warn("EnhancedGifSprite: 使用 setFixedSize() 方法来设置高度");return}this.setFixedSize(this.fixedWidth||e,e)}get width(){return this.fixedWidth||super.width}get height(){return this.fixedHeight||super.height}registerScaleListener(){this.appService.emitter.on("antiScale",this.throttledUpdateScale)}applySize(){if(!this.isFixedSizeSet||!this.texture||this.texture.width===0||this.texture.height===0)return;const e=this.fixedWidth/this.texture.width,i=this.fixedHeight/this.texture.height;if(this.sizeFixed){const s=this.appService.currentScale;if(s===0)return;const r=e/s,o=i/s;super.scale.set(r,o)}else super.scale.set(e/this.baselineScale,i/this.baselineScale)}updateScale(e){this.sizeFixed&&(this.isFixedSizeSet?this.applySize():e!==0&&super.scale.set(1/e))}static async createFromSrc(e,i,s){try{const r=await V.load(i),o=new Kr(e,{source:r});return s.sizeFixed!==void 0&&o.setSizeFixed(s.sizeFixed),o.setFixedSize(s.width,s.height),o}catch(r){throw w.error(`Failed to load GIF "${i}":`,r),r}}draw(e,i){const{x:s,y:r,rotation:o=0}=e;i&&!this.visible?this.visible=i():!i&&!this.visible&&(this.visible=!0),this.rotation=o,this.position.set(s,r)}destroy(e){this.appService.emitter.off("antiScale",this.throttledUpdateScale),super.destroy(e)}}class Ue extends Kr{constructor(e,i,s){super(e,{source:i});f(this,"elementData");f(this,"clickHandler",null);f(this,"unsubscribeMapRotation",null);f(this,"userRotation",0);this.elementData=s}async initialize(){this.elementData.sizeFixed!==void 0&&this.setSizeFixed(this.elementData.sizeFixed),this.setFixedSize(this.elementData.width,this.elementData.height);const e=this.elementData.anchor||{x:.5,y:.5};this.anchor.set(e.x,e.y),this.position.set(this.elementData.x,this.elementData.y),this.elementData.rotation!==void 0&&(this.userRotation=this.elementData.rotation),this.elementData.opacity!==void 0&&(this.alpha=this.elementData.opacity),this.applyRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation=G(this.appService.runtime,"mapRotation",i=>{this.applyRotation(i)}),this.visible=!0,this.elementData.interactive?this.setupClickHandler():this.eventMode="none"}applyRotation(e){const i=-e*Math.PI/180;this.rotation=this.userRotation+i}setupClickHandler(){this.clickHandler&&this.clickHandler.destroy(),this.clickHandler=new vt(this,{onClick:()=>this.handleClick(),stopPropagation:!1})}handleClick(){var e,i;(i=(e=this.appService.events)==null?void 0:e.onClickCustomElement)==null||i.call(e,this.getElementData())}getElementData(){return{...this.elementData}}async updateElementData(e){const i=this.elementData;if(this.elementData=e,i.src!==e.src)throw new Error("GIF source change requires recreation of instance");i.sizeFixed!==e.sizeFixed&&e.sizeFixed!==void 0&&this.setSizeFixed(e.sizeFixed),(i.width!==e.width||i.height!==e.height)&&this.setFixedSize(e.width,e.height);const s=e.anchor||{x:.5,y:.5},r=i.anchor||{x:.5,y:.5};(s.x!==r.x||s.y!==r.y)&&this.anchor.set(s.x,s.y),this.position.set(e.x,e.y),e.rotation!==void 0&&(this.userRotation=e.rotation,this.applyRotation(this.appService.runtime.mapRotation)),e.opacity!==void 0&&(this.alpha=e.opacity),e.interactive?this.clickHandler||this.setupClickHandler():(this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null),this.eventMode="none")}isSameData(e){const i=this.elementData.anchor||{x:.5,y:.5},s=e.anchor||{x:.5,y:.5};return this.elementData.id===e.id&&this.elementData.type===e.type&&this.elementData.src===e.src&&this.elementData.x===e.x&&this.elementData.y===e.y&&this.elementData.width===e.width&&this.elementData.height===e.height&&this.elementData.rotation===e.rotation&&this.elementData.opacity===e.opacity&&this.elementData.interactive===e.interactive&&this.elementData.sizeFixed===e.sizeFixed&&i.x===s.x&&i.y===s.y}destroy(){this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null),super.destroy()}}class Fn extends Xt{constructor(e,i){super(e);f(this,"elementData");f(this,"clickHandler",null);f(this,"unsubscribeMapRotation",null);f(this,"userRotation",0);this.appService=e,this.elementData=i}async initialize(){await this.loadTextureAndSetSize(this.elementData.src,{width:this.elementData.width,height:this.elementData.height,sizeFixed:this.elementData.sizeFixed});const e=this.elementData.anchor||{x:.5,y:.5};this.anchor.set(e.x,e.y),this.position.set(this.elementData.x,this.elementData.y),this.elementData.rotation!==void 0&&(this.userRotation=this.elementData.rotation),this.elementData.opacity!==void 0&&(this.alpha=this.elementData.opacity),this.applyRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation=G(this.appService.runtime,"mapRotation",i=>{this.applyRotation(i)}),this.visible=!0,this.elementData.interactive?this.setupClickHandler():this.eventMode="none"}applyRotation(e){const i=-e*Math.PI/180;this.rotation=this.userRotation+i}setupClickHandler(){this.clickHandler&&this.clickHandler.destroy(),this.clickHandler=new vt(this,{onClick:()=>this.handleClick(),stopPropagation:!1})}handleClick(){var e,i;(i=(e=this.appService.events)==null?void 0:e.onClickCustomElement)==null||i.call(e,this.getElementData())}getElementData(){return{...this.elementData}}async updateElementData(e){const i=this.elementData;this.elementData=e,i.src!==e.src?await this.loadTextureAndSetSize(e.src,{width:e.width,height:e.height,sizeFixed:e.sizeFixed}):(i.sizeFixed!==e.sizeFixed&&e.sizeFixed!==void 0&&this.setSizeFixed(e.sizeFixed),(i.width!==e.width||i.height!==e.height)&&this.setFixedSize(e.width,e.height));const s=e.anchor||{x:.5,y:.5},r=i.anchor||{x:.5,y:.5};(s.x!==r.x||s.y!==r.y)&&this.anchor.set(s.x,s.y),this.position.set(e.x,e.y),e.rotation!==void 0&&(this.userRotation=e.rotation,this.applyRotation(this.appService.runtime.mapRotation)),e.opacity!==void 0&&(this.alpha=e.opacity),e.interactive?this.clickHandler||this.setupClickHandler():(this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null),this.eventMode="none")}isSameData(e){const i=this.elementData.anchor||{x:.5,y:.5},s=e.anchor||{x:.5,y:.5};return this.elementData.id===e.id&&this.elementData.type===e.type&&this.elementData.src===e.src&&this.elementData.x===e.x&&this.elementData.y===e.y&&this.elementData.width===e.width&&this.elementData.height===e.height&&this.elementData.rotation===e.rotation&&this.elementData.opacity===e.opacity&&this.elementData.interactive===e.interactive&&this.elementData.sizeFixed===e.sizeFixed&&i.x===s.x&&i.y===s.y}destroy(){this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null),super.destroy()}}class FS extends im{constructor(e,i){super(i);f(this,"throttledUpdateScale");f(this,"fixedWidth",0);f(this,"fixedHeight",0);f(this,"isFixedSizeSet",!1);f(this,"userCenterX",0);f(this,"userCenterY",0);f(this,"sizeFixed",!0);this.appService=e,this.anchor.set(0,0),this.throttledUpdateScale=_t(this.updateScale.bind(this),30,{leading:!0,trailing:!0}),this.registerScaleListener()}setFixedSize(e,i){this.fixedWidth=e,this.fixedHeight=i,this.isFixedSizeSet=!0,this.applyFixedSize(),this.updatePositionFromCenter()}setCenterPosition(e,i){this.userCenterX=e,this.userCenterY=i,this.updatePositionFromCenter()}setSizeFixed(e){this.sizeFixed=e,this.isFixedSizeSet&&(this.applyFixedSize(),this.updatePositionFromCenter())}getIsFixedSizeSet(){return this.isFixedSizeSet}updatePositionFromCenter(){if(!this.isFixedSizeSet){this.position.set(this.userCenterX,this.userCenterY);return}const i=this.appService.currentScale;let s,r;this.sizeFixed?(s=this.fixedWidth/2/i,r=this.fixedHeight/2/i):(s=this.fixedWidth/2,r=this.fixedHeight/2),this.position.set(this.userCenterX-s,this.userCenterY-r)}registerScaleListener(){this.appService.emitter.on("antiScale",this.throttledUpdateScale)}applyFixedSize(){if(!this.isFixedSizeSet)return;const i=this.appService.currentScale;if(i!==0){if(this.sizeFixed){const s=1/i;this.scale.set(s)}else this.scale.set(1);this.element&&(this.element.style.width=`${this.fixedWidth}px`,this.element.style.height=`${this.fixedHeight}px`)}}updateScale(e){this.isFixedSizeSet&&e!==0&&(this.applyFixedSize(),this.updatePositionFromCenter())}updateTransform(e){return super.updateTransform(e)}destroy(e){this.appService.emitter.off("antiScale",this.throttledUpdateScale),super.destroy(e)}}class ki extends FS{constructor(e,i){const s=document.createElement("div");ki.setupDefaultStyles(s,i),s.innerHTML=i.htmlContent;super(e,{element:s});f(this,"elementData");f(this,"domClickHandler",null);f(this,"resizeObserver",null);f(this,"debugMarker",null);f(this,"unsubscribeMapRotation",null);f(this,"userRotation",0);this.elementData=i}async initialize(){this.alpha=0,this.elementData.width&&this.elementData.height?(this.setFixedSize(this.elementData.width,this.elementData.height),this.setCenterPosition(this.elementData.x,this.elementData.y),this.setSizeFixed(this.elementData.sizeFixed??!0),this.waitForElementInsertion()):(this.position.set(this.elementData.x,this.elementData.y),this.setupAutoSize()),this.elementData.rotation!==void 0&&(this.userRotation=this.elementData.rotation),this.applyRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation=G(this.appService.runtime,"mapRotation",e=>{this.applyRotation(e)}),this.elementData.interactive?this.setupClickHandler():this.eventMode="none"}applyRotation(e){const i=-e*Math.PI/180;this.rotation=this.userRotation+i}setupAutoSize(){this.element&&(this.element.style.width="auto",this.element.style.height="auto",this.waitForElementDimensions())}waitForElementInsertion(){if(!this.element)return;const e=()=>{this.element&&(this.element.isConnected?this.showElement():requestAnimationFrame(e))};requestAnimationFrame(e)}waitForElementDimensions(){this.element&&(typeof ResizeObserver<"u"?(this.resizeObserver=new ResizeObserver(e=>{var s;const i=e[0];i&&i.contentRect.width>0&&i.contentRect.height>0&&(this.setFixedSize(i.contentRect.width,i.contentRect.height),this.setCenterPosition(this.elementData.x,this.elementData.y),this.setSizeFixed(this.elementData.sizeFixed??!0),this.alpha===0&&this.showElement(),(s=this.resizeObserver)==null||s.disconnect(),this.resizeObserver=null)}),this.resizeObserver.observe(this.element)):this.pollForElementDimensions())}pollForElementDimensions(){if(!this.element)return;const e=()=>{if(!this.element)return;if(!this.element.isConnected){requestAnimationFrame(e);return}const i=this.element.getBoundingClientRect();i.width>0&&i.height>0?(this.setFixedSize(i.width,i.height),this.setCenterPosition(this.elementData.x,this.elementData.y),this.setSizeFixed(this.elementData.sizeFixed??!0),this.alpha===0&&this.showElement()):requestAnimationFrame(e)};requestAnimationFrame(e)}showElement(){this.alpha=this.elementData.opacity??1,this.element.style.pointerEvents=this.elementData.interactive?"auto":"none",this.interactive=this.elementData.interactive??!1,this.elementData.interactive&&this.element&&(this.element.style.setProperty("-webkit-tap-highlight-color","transparent"),this.element.style.setProperty("-webkit-touch-callout","none")),this.appService.getApp().renderOnceNextFrame()}setupClickHandler(){this.element&&(this.domClickHandler=e=>{e.preventDefault(),e.stopPropagation(),this.handleClick()},this.element.addEventListener("click",this.domClickHandler))}handleClick(){var e,i;(i=(e=this.appService.events)==null?void 0:e.onClickCustomElement)==null||i.call(e,this.getElementData())}getElementData(){return{...this.elementData}}async updateElementData(e){const i=this.elementData;this.elementData=e,i.htmlContent!==e.htmlContent&&this.element&&(this.element.innerHTML=e.htmlContent,(!e.width||!e.height)&&this.waitForElementDimensions()),(i.width!==e.width||i.height!==e.height)&&(e.width&&e.height?(this.setFixedSize(e.width,e.height),this.element&&(this.element.style.width=`${e.width}px`,this.element.style.height=`${e.height}px`)):this.setupAutoSize()),e.width&&e.height?this.setCenterPosition(e.x,e.y):this.getIsFixedSizeSet()?this.setCenterPosition(e.x,e.y):this.position.set(e.x,e.y),i.sizeFixed!==e.sizeFixed&&e.sizeFixed!==void 0&&this.setSizeFixed(e.sizeFixed),this.userRotation=e.rotation??0,this.applyRotation(this.appService.runtime.mapRotation),this.alpha=e.opacity??1,e.interactive?this.domClickHandler||this.setupClickHandler():(this.eventMode="none",this.domClickHandler&&this.element&&(this.element.removeEventListener("click",this.domClickHandler),this.domClickHandler=null))}isSameData(e){return this.elementData.id===e.id&&this.elementData.type===e.type&&this.elementData.htmlContent===e.htmlContent&&this.elementData.x===e.x&&this.elementData.y===e.y&&this.elementData.width===e.width&&this.elementData.height===e.height&&this.elementData.rotation===e.rotation&&this.elementData.opacity===e.opacity&&this.elementData.interactive===e.interactive&&this.elementData.sizeFixed===e.sizeFixed}static setupDefaultStyles(e,i){const s={position:"relative",boxSizing:"border-box",webkitFontSmoothing:"antialiased",textRendering:"optimizeLegibility",background:"transparent",userSelect:"auto",webkitUserSelect:"auto"};i.width&&i.height?(s.width=`${i.width}px`,s.height=`${i.height}px`,s.overflow="hidden"):(s.width=i.width?`${i.width}px`:"auto",s.height=i.height?`${i.height}px`:"auto",s.overflow="visible"),Object.assign(e.style,s),e.style.setProperty("-webkit-tap-highlight-color","transparent"),e.style.setProperty("-webkit-touch-callout","none")}destroy(){this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.domClickHandler&&this.element&&(this.element.removeEventListener("click",this.domClickHandler),this.domClickHandler=null),this.debugMarker&&(this.debugMarker.destroy(),this.debugMarker=null),super.destroy()}}class BS{constructor(t){f(this,"customElementsMap",new Map);f(this,"gifTicker",null);f(this,"gifElements",new Set);this.appService=t}async drawCustomElements(t){if(!t||t.length===0){this.clearAllCustomElements();return}const e=new Set(t.map(r=>r.id)),i=Array.from(this.customElementsMap.keys());for(const r of i)e.has(r)||this.removeCustomElement(r);const s=t.map(async r=>{const o=this.customElementsMap.get(r.id);o?this.isSameData(o,r)||(r.type==="gif"&&o.getElementData().src!==r.src?(this.removeCustomElement(r.id),await this.addNewCustomElement(r)):await this.updateElementData(o,r)):await this.addNewCustomElement(r)});await Promise.all(s),this.updateGifTicker()}clearAllCustomElements(){const t=this.appService;this.customElementsMap.forEach(e=>{e instanceof Ue?t.appContainer.removeFromLayer(Ri,e):t.appContainer.removeFromLayer(Ai,e),e.destroy()}),this.customElementsMap.clear(),this.gifElements.clear(),this.stopGifTicker()}async addNewCustomElement(t){const e=this.appService;let i;switch(t.type){case"image":i=new Fn(this.appService,t);break;case"gif":{const s=await V.load(t.src);i=new Ue(this.appService,s,t);break}case"html":i=new ki(this.appService,t);break;default:throw new Error(`Unsupported custom element type: ${t.type}`)}await i.initialize(),this.customElementsMap.set(t.id,i),i instanceof Ue?(e.appContainer.addToLayer(Ri,i),this.gifElements.add(i)):e.appContainer.addToLayer(Ai,i)}removeCustomElement(t){const e=this.appService,i=this.customElementsMap.get(t);i&&(i instanceof Ue?(this.gifElements.delete(i),e.appContainer.removeFromLayer(Ri,i)):e.appContainer.removeFromLayer(Ai,i),i.destroy(),this.customElementsMap.delete(t))}isSameData(t,e){return t.getElementData().type!==e.type?!1:e.type==="image"&&t instanceof Fn||e.type==="gif"&&t instanceof Ue||e.type==="html"&&t instanceof ki?t.isSameData(e):!1}async updateElementData(t,e){if(e.type==="image"&&t instanceof Fn)await t.updateElementData(e);else if(e.type==="gif"&&t instanceof Ue)await t.updateElementData(e);else if(e.type==="html"&&t instanceof ki)await t.updateElementData(e);else throw new Error("Element type mismatch during update")}updateGifTicker(){this.gifElements.size>0?this.startGifTicker():this.stopGifTicker()}startGifTicker(){var t;(t=this.gifTicker)!=null&&t.started||(this.gifTicker?this.gifTicker.maxFPS=1:(this.gifTicker=new mt,this.gifTicker.maxFPS=1,this.gifTicker.add(()=>{this.renderGifContainer()})),this.gifTicker.start())}stopGifTicker(){var t;(t=this.gifTicker)!=null&&t.started&&(w.log("⏸️ [GifTicker] 停止 GIF 专用渲染"),this.gifTicker.stop())}renderGifContainer(){const t=this.appService;if(this.gifElements.size===0)return;const e=t.getApp();e.renderer.render(e.stage)}destroy(){this.stopGifTicker(),this.gifTicker&&(this.gifTicker.destroy(),this.gifTicker=null),this.clearAllCustomElements()}}class LS extends W{constructor(e,i){super();f(this,"roomId");f(this,"roomIndex");f(this,"appService");f(this,"nameText");f(this,"iconSprite",null);f(this,"iconWrapper",null);f(this,"iconBg",null);this.appService=e,this.roomId=i.id,this.roomIndex=i.index;const{nameLabel:s,type:r}=e.roomConfig,{showRoomType:o}=e.runtime,a=i.colorIndex??i.index,h=this.getRoomNameColor(a),l=new le({fontSize:s.fontSize,fontFamily:s.fontFamily,fontWeight:s.fontWeight,fill:h,align:"center"}),c=i.name||"Unknown";this.nameText=new Bs({text:c,style:l}),this.nameText.anchor.set(.5),o&&i.type!=null&&(r!=null&&r.assets)&&r.assets[i.type]&&this.createIcon(i.type,h),this.addChild(this.nameText),this.layout()}createIcon(e,i){const{type:s}=this.appService.roomConfig,r=s.iconSize||14;this.iconWrapper||(this.iconWrapper=new W,this.addChild(this.iconWrapper)),s.container.visible?(this.iconBg||(this.iconBg=new H,this.iconWrapper.addChild(this.iconBg)),this.drawIconBg(i)):this.iconBg&&(this.iconBg.destroy(),this.iconBg=null),this.iconSprite||(this.iconSprite=new Xt(this.appService),this.iconSprite.anchor.set(.5),this.iconWrapper.addChild(this.iconSprite)),this.iconSprite.visible=!0,this.iconSprite.tint=s.container.visible?"#ffffff":i,this.iconSprite.setFixedSize(r,r),this.iconSprite.loadTextureAndSetSize(s.assets[e],{width:r,height:r,sizeFixed:!1}).then(()=>{this.iconSprite&&(this.iconSprite.visible=this.appService.runtime.showRoomType,this.layout())}),s.container&&this.iconSprite.position.set(0,0)}drawIconBg(e){const{type:i}=this.appService.roomConfig;if(!this.iconBg||!i.container.visible)return;const{size:s,borderRadius:r}=i.container;this.iconBg.clear().roundRect(-s/2,-s/2,s,s,r).fill(e)}layout(){if(!this.iconWrapper||!this.iconWrapper.visible){this.nameText.position.set(0,0);return}if(!(this.iconSprite&&this.iconSprite.visible||this.iconBg&&this.iconBg.visible)){this.nameText.position.set(0,0);return}const{gap:i=4,position:s="left"}=this.appService.roomConfig.type,r=this.nameText.width,o=this.iconWrapper.width,h=-(o+i+r)/2;s==="left"?(this.iconWrapper.x=h+o/2,this.nameText.x=h+o+i+r/2):(this.nameText.x=h+r/2,this.iconWrapper.x=h+r+i+o/2),this.iconWrapper.y=0,this.nameText.y=0}updateName(e){this.nameText.text=e,this.layout()}refreshColor(e){const{type:i}=this.appService.roomConfig,s=this.appService.getRoomData(this.roomId),r=(s==null?void 0:s.colorIndex)??this.roomIndex,o=this.getRoomNameColor(r,e);this.nameText.style.fill=o,this.iconBg&&this.drawIconBg(o),this.iconSprite&&(this.iconSprite.tint=i.container.visible?"#ffffff":o)}getRoomNameColor(e,i){const{colors:s}=this.appService.roomConfig,{enableRoomSelection:r,selectRoomIds:o}=this.appService.runtime;if(i)return i;if(r)return!o.includes(this.roomId)&&s.nameInactive?s.nameInactive[e%s.nameInactive.length]:s.name[e%s.name.length];const a=s.nameNormal||s.name;return a[e%a.length]}async updateRoomType(e){const{type:i}=this.appService.roomConfig;if(!this.appService.runtime.showRoomType||e==null||!(i!=null&&i.assets)||!i.assets[e])this.iconWrapper&&(this.iconWrapper.visible=!1);else{const r=this.appService.getRoomData(this.roomId),o=(r==null?void 0:r.colorIndex)??this.roomIndex,a=this.getRoomNameColor(o);this.createIcon(e,a),this.iconWrapper&&(this.iconWrapper.visible=!0)}this.layout()}updateRoomTypeVisibility(e){if(this.iconWrapper)this.iconWrapper.visible=e,this.layout();else if(e){const i=this.appService.getRoomData(this.roomId);i&&this.updateRoomType(i.type??null)}}destroy(e){this.iconBg&&(this.iconBg.destroy(),this.iconBg=null),this.iconSprite&&(this.iconSprite.destroy(),this.iconSprite=null),this.iconWrapper&&(this.iconWrapper.destroy(),this.iconWrapper=null),super.destroy(e)}}class zS extends W{constructor(e,i){super();f(this,"background");f(this,"foldedIndicator");f(this,"propertyIcons",new Map);f(this,"orderContainer");f(this,"orderBackground");f(this,"orderText");f(this,"isFolded",!1);f(this,"roomId");f(this,"roomIndex");f(this,"isDestroyed",!1);this.appService=e;const s=this.appService.roomConfig;this.roomId=i.id,this.roomIndex=i.index,this.background=new H,this.foldedIndicator=new H,this.foldedIndicator.visible=!1;const{property:r}=s,o=i.colorIndex??i.index,a=this.getIconColor(o);this.initializePropertyIcons(r.displayOrders,a);const h=r.cleanOrder.color==="auto"?s.colors.active[o%s.colors.active.length]:r.cleanOrder.color;this.orderContainer=new W,this.orderBackground=new H,this.orderText=new Bs({text:"",style:new le({fontSize:r.cleanOrder.fontSize,fontFamily:r.cleanOrder.fontFamily,fontWeight:r.cleanOrder.fontWeight,fill:h,align:"center",trim:!0})}),this.orderText.anchor.set(.5,.5),this.orderContainer.addChild(this.orderBackground),this.orderContainer.addChild(this.orderText),this.addChild(this.background),this.addChild(this.foldedIndicator),this.propertyIcons.forEach(({sprite:l})=>{this.addChild(l)}),this.addChild(this.orderContainer),this.visible=this.appService.runtimeSnapshot.showRoomProperty}initializePropertyIcons(e,i){const s=["cleanMode","suction","cistern","cleanTimes"];e.forEach(r=>{const o=s.includes(r),a=new Xt(this.appService);a.tint=i,a.anchor.set(0,0),this.propertyIcons.set(r,{fieldName:r,sprite:a,isBuiltin:o})})}async updateProperty(e){this.isDestroyed||this.destroyed||(await this.updateIcons(e),!(this.isDestroyed||this.destroyed)&&this.updateBackground())}getFieldValue(e,i){if(["cleanMode","suction","cistern","cleanTimes"].includes(i))return e[i]??null;if(e.customData&&i in e.customData){const r=e.customData[i];return typeof r=="number"?r:null}return null}getAssetAlias(e,i){const s={cleanMode:r=>`cleanMode_${r}`,suction:r=>`fan_${r}`,cistern:r=>`water_${r}`,cleanTimes:r=>`cleanTimes${r}`};return e in s?s[e](i):`custom_${e}_${i}`}shouldShowField(e,i,s){const{showRoomProperty:r}=this.appService.runtimeSnapshot;return!(s===null||!r||i==="cleanTimes"&&s<=0)}getDisplayElements(e){const{displayOrders:i}=this.appService.roomConfig.property,{showRoomOrder:s}=this.appService.runtimeSnapshot,r=e.order||0,o=s&&r>0,a=[];return o&&a.push({element:this.orderContainer,show:!0,isOrder:!0,fieldName:"order"}),i.forEach(h=>{const l=this.propertyIcons.get(h);if(!l||!l.sprite)return;const c=this.getFieldValue(e,h);this.shouldShowField(e,h,c)&&c!==null&&a.push({element:l.sprite,show:!0,isOrder:!1,fieldName:h,value:c})}),{elementsToShow:a,orderValue:r}}async updateIcons(e){if(this.isDestroyed||this.destroyed||this.isFolded)return;const{iconWidth:i,iconHeight:s,container:r,cleanOrder:o,iconGap:a}=this.appService.roomConfig.property,{paddingHorizontal:h,paddingVertical:l}=r,{elementsToShow:c,orderValue:d}=this.getDisplayElements(e);this.orderContainer.visible=!1,this.propertyIcons.forEach(({sprite:g})=>{g.visible=!1});const u=[];if(c.forEach(g=>{if(g.isOrder){this.orderContainer.visible=!0,this.orderText.text=d.toString();const y=e.colorIndex??this.roomIndex,m=this.getIconColor(y);this.orderBackground.clear(),this.orderBackground.setFillStyle({color:m}),this.orderBackground.circle(i/2,s/2,i/2).fill();const x=this.resolveOrderTextColor(y);this.orderText.style.fill=x,this.orderText.position.set(i/2,s/2)}else{const y=this.propertyIcons.get(g.fieldName);if(y&&y.sprite){y.sprite.visible=!0;const m=this.getAssetAlias(g.fieldName,g.value);u.push(y.sprite.loadTextureAndSetSize(m,{width:i,height:s,sizeFixed:!1}))}}}),await Promise.all(u),this.isDestroyed||this.destroyed)return;let p=h;c.forEach((g,y)=>{const{element:m,isOrder:x}=g;!m||!m.position||(m.position.set(p,l),p+=i,y<c.length-1&&(x?p+=o.gapRight:p+=a))})}updateBackground(){if(this.isDestroyed||this.destroyed)return;const e=this.appService.roomConfig,{container:i,foldable:s}=e.property,{borderRadius:r,tailHeight:o,tailWidth:a,backgroundColor:h}=i,l=this.calculateContentWidth(),c=this.calculateContentHeight(),d=Math.min(r,l/2,c/2),u=d*.8,p=Math.max(l-u*2,a*.5),g=Math.min(a,l/2,p);if(this.background.clear(),this.background.setFillStyle({color:h}),s){const y=(l-g)/2,m=c+o;this.background.moveTo(d,0),this.background.lineTo(l-d,0),this.background.arcTo(l,0,l,d,d),this.background.lineTo(l,c-d),this.background.arcTo(l,c,l-d,c,d),this.background.lineTo(y+g,c),this.background.lineTo(y+g/2,m),this.background.lineTo(y,c),this.background.lineTo(d,c),this.background.arcTo(0,c,0,c-d,d),this.background.lineTo(0,d),this.background.arcTo(0,0,d,0,d),this.background.closePath()}else this.background.roundRect(0,0,l,c,d);this.background.fill()}calculateContentWidth(){const{iconWidth:e,container:i,cleanOrder:s,iconGap:r}=this.appService.roomConfig.property,{paddingHorizontal:o}=i,a=this.appService.getRoomData(this.roomId);if(!a)return o*2;const{elementsToShow:h}=this.getDisplayElements(a);let l=o;return h.forEach((c,d)=>{const{isOrder:u}=c;l+=e,d<h.length-1&&(u?l+=s.gapRight:l+=r)}),l+=o,l}calculateContentHeight(){const e=this.appService.roomConfig,{iconHeight:i,container:s}=e.property;return s.paddingVertical+i+s.paddingVertical}getTotalHeight(){const{foldable:e,container:i}=this.appService.roomConfig.property,{tailHeight:s}=i;return this.isFolded?s:this.calculateContentHeight()+(e?s:0)}getTotalWidth(){if(this.isFolded){const{tailWidth:i}=this.appService.roomConfig.property.container,s=this.calculateContentWidth();return Math.min(i,s/2)}return this.calculateContentWidth()}async setFolded(e){const{foldable:i}=this.appService.roomConfig.property;if(i)if(this.isFolded=e,e)this.background.visible=!1,this.orderContainer.visible=!1,this.propertyIcons.forEach(({sprite:s})=>{s.visible=!1}),this.foldedIndicator.visible=!0,this.updateFoldedIndicator();else{this.background.visible=!0,this.foldedIndicator.visible=!1,this.foldedIndicator.position.set(0,0),this.updateBackground();const s=this.appService.getRoomData(this.roomId);s&&await this.updateIcons(s)}}isFoldedState(){const{foldable:e}=this.appService.roomConfig.property;return e?this.isFolded:!1}updateFoldedIndicator(){const e=this.appService.roomConfig,{tailHeight:i,tailWidth:s,backgroundColor:r}=e.property.container,o=this.calculateContentWidth(),a=Math.min(s,o/2);this.foldedIndicator.clear(),this.foldedIndicator.setFillStyle({color:r}),this.foldedIndicator.poly([0,i,a,i,a/2,0]).fill(),this.foldedIndicator.position.set(0,0)}resolveOrderTextColor(e){const{property:i,colors:s}=this.appService.roomConfig,{enableRoomSelection:r}=this.appService.runtime;if(i.cleanOrder.color==="auto"){const o=r?s.active:s.normal||s.active;return o[e%o.length]}return i.cleanOrder.color}getIconColor(e){const{colors:i}=this.appService.roomConfig,{propertyTheme:s,propertyThemeInactive:r,propertyThemeNormal:o}=i,{enableRoomSelection:a,selectRoomIds:h}=this.appService.runtime;if(a)return!h.includes(this.roomId)&&r?r[e%r.length]:s[e%s.length];const l=o||s;return l[e%l.length]}refreshColor(){const e=this.appService.getRoomData(this.roomId),i=(e==null?void 0:e.colorIndex)??this.roomIndex,s=this.getIconColor(i);if(this.propertyIcons.forEach(({sprite:r})=>{r.tint=s}),this.orderBackground&&this.orderBackground.visible){const{property:r}=this.appService.roomConfig,o=r.iconWidth,a=r.iconHeight;this.orderBackground.clear(),this.orderBackground.setFillStyle({color:s}),this.orderBackground.circle(o/2,a/2,o/2).fill();const h=this.resolveOrderTextColor(i);this.orderText.style.fill=h}}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.propertyIcons.forEach(({sprite:e})=>{e.destroy()}),this.propertyIcons.clear(),super.destroy({children:!0}))}}class OS extends W{constructor(e,i){super();f(this,"background");f(this,"checkmarkIcon");f(this,"bubble");f(this,"roomIndex");f(this,"roomId");this.appService=e;const s=this.appService.roomConfig;this.roomId=i.id,this.roomIndex=i.index,this.background=new H,this.bubble=new H;const{colors:{selectionIndicatorIcon:r}}=s;this.checkmarkIcon=new Xt(this.appService);const o=i.colorIndex??i.index;this.checkmarkIcon.tint=r[o%r.length],this.checkmarkIcon.anchor.set(0,0),this.addChild(this.background),this.addChild(this.bubble),this.addChild(this.checkmarkIcon)}async updateIndicator(e){const{roomSelectionMode:i,enableRoomSelection:s,selectRoomIds:r}=this.appService.runtimeSnapshot;if(!s||i!=="checkmark"){this.visible=!1;return}const o=r.includes(e.id);await this.showCheckmarkMode(o),this.updateBackground()}async showCheckmarkMode(e){const{selectionIndicator:i}=this.appService.roomConfig,{iconWidth:s,iconHeight:r}=i;if(e){this.visible=!0,this.checkmarkIcon.visible=!0,await this.checkmarkIcon.loadTextureAndSetSize("checkmark",{width:s,height:r,sizeFixed:!1});const o=i.containerWidth/2,a=i.containerHeight/2;this.checkmarkIcon.position.set(o-s/2,a-r/2)}else this.visible=!1}updateBackground(){const{selectionIndicator:e,colors:i}=this.appService.roomConfig,{containerWidth:s,containerHeight:r,strokeWidth:o,strokeColor:a,borderRadius:h,tailHeight:l,tailWidth:c}=e,d=this.appService.getRoomData(this.roomId),u=(d==null?void 0:d.colorIndex)??this.roomIndex,p=i.selectionIndicatorBackground[u%i.selectionIndicatorBackground.length],g=a==="auto"?p:a;if(this.checkmarkIcon.tint=i.selectionIndicatorIcon[u%i.selectionIndicatorIcon.length],this.background.clear(),this.bubble.clear(),this.background.setFillStyle({color:p}).roundRect(0,0,s,r,h).fill().setStrokeStyle({color:g,width:o,alignment:0}).stroke(),l>0&&c>0){const y=(s-c)/2;this.bubble.setFillStyle({color:g});const m=r+o;this.bubble.poly([y,m-1,y+c,m-1,y+c/2,m+l]).fill()}}getTotalHeight(){const{selectionIndicator:e}=this.appService.roomConfig,{containerHeight:i,tailHeight:s,strokeWidth:r}=e;return i+r+(s>0?s:0)}getTotalWidth(){const{selectionIndicator:e}=this.appService.roomConfig;return e.containerWidth}async refreshColor(){const e=this.appService.getRoomData(this.roomId);e&&await this.updateIndicator(e)}destroy(){var e;(e=this.checkmarkIcon)==null||e.destroy(),super.destroy({children:!0})}}class WS extends W{constructor(e,i){super();f(this,"roomId");f(this,"roomName");f(this,"roomProperty",null);f(this,"roomSelectionIndicator",null);f(this,"clickHandler",null);f(this,"unsubscribeMapRotation",null);f(this,"targetElasticScale",1);f(this,"currentElasticScale",1);f(this,"isAnimatingScale",!1);f(this,"scaleAnimationBound",null);f(this,"updateScaleBound",null);this.appService=e,this.enableRenderGroup(),this.roomId=i.id,this.initializeElasticScale(e.currentScale),this.updateScaleBound=s=>this.updateScale(s),this.appService.emitter.on("antiScale",this.updateScaleBound),this.updateScale(this.appService.currentScale),i.centerPoint&&this.position.set(i.centerPoint.x,i.centerPoint.y),this.roomName=new LS(this.appService,i),this.roomName.visible=this.appService.runtimeSnapshot.showRoomName,this.applyAntiRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation=G(this.appService.runtime,"mapRotation",s=>{this.applyAntiRotation(s)}),this.clickHandler=new vt(this,{onClick:()=>{var s,r;(r=(s=this.appService.events)==null?void 0:s.onClickRoomProperties)==null||r.call(s,i)}})}async initialize(e){await this.createRoomProperty(e),await this.createRoomSelectionIndicator(e),this.updateLayout()}applyAntiRotation(e){const i=-e*Math.PI/180;this.rotation=i}initializeElasticScale(e){const{enableElasticScale:i,elasticMinScale:s,elasticMaxScale:r}=this.appService.roomConfig;if(!i)return;const o=1,a=5;let h;e<=o?h=s:e>=a?h=r:h=1,this.targetElasticScale=h,this.currentElasticScale=h}updateScale(e){const{enableElasticScale:i,elasticMinScale:s,elasticMaxScale:r}=this.appService.roomConfig;if(!i){e!==0&&this.scale.set(1/e);return}if(e===0)return;const o=1,a=5;let h;e<=o?h=s:e>=a?h=r:h=1;const c=1/e*h;Math.abs(this.targetElasticScale-h)>.01?(this.targetElasticScale=h,this.startScaleAnimation()):this.scale.set(c)}startScaleAnimation(){this.scaleAnimationBound||(this.scaleAnimationBound=this.animateScale.bind(this)),this.isAnimatingScale||(this.isAnimatingScale=!0,this.appService.getApp().ticker.add(this.scaleAnimationBound))}animateScale(){this.currentElasticScale+=(this.targetElasticScale-this.currentElasticScale)*.3;const r=1/this.appService.currentScale*this.currentElasticScale;this.scale.set(r),Math.abs(this.currentElasticScale-this.targetElasticScale)<.001&&(this.currentElasticScale=this.targetElasticScale,this.isAnimatingScale=!1,this.scaleAnimationBound&&this.appService.getApp().ticker.remove(this.scaleAnimationBound))}shouldShowRoomProperty(){const{showRoomOrder:e,showRoomProperty:i,selectRoomIds:s,enableRoomSelection:r,roomSelectionMode:o}=this.appService.runtimeSnapshot,a=this.appService.getRoomData(this.roomId);if(!a||r&&o==="checkmark"&&s.includes(this.roomId))return!1;const h=e&&(a.order||0)>0;let l=!1;if(i){const{displayOrders:c}=this.appService.roomConfig.property;l=c.some(d=>!!(d==="suction"&&a.suction!=null||d==="cistern"&&a.cistern!=null||d==="cleanMode"&&a.cleanMode!=null||d==="cleanTimes"&&a.cleanTimes>0||a.customData&&d in a.customData&&typeof a.customData[d]=="number"&&a.customData[d]!=null))}return h||l}shouldShowRoomSelectionIndicator(){const{enableRoomSelection:e,roomSelectionMode:i}=this.appService.runtimeSnapshot;return e&&i==="checkmark"}async updateRoomPropertyVisibility(){if(!this.roomProperty)return;if(!this.shouldShowRoomProperty())this.roomProperty.visible=!1;else{this.roomProperty.visible=!0;const i=this.appService.runtimeSnapshot.roomPropertyFoldIds.includes(this.roomId);await this.roomProperty.setFolded(i);const s=this.appService.getRoomData(this.roomId);s&&await this.roomProperty.updateProperty(s)}this.updateLayout()}async updateRoomSelectionIndicatorVisibility(){if(!this.roomSelectionIndicator)return;if(this.shouldShowRoomSelectionIndicator()){const i=this.appService.getRoomData(this.roomId);i&&await this.roomSelectionIndicator.updateIndicator(i)}else this.roomSelectionIndicator.visible=!1;this.updateLayout()}async createRoomProperty(e){this.roomProperty&&(this.removeChild(this.roomProperty),this.roomProperty.destroy()),this.roomProperty=new zS(this.appService,e),await this.roomProperty.updateProperty(e),this.addChild(this.roomProperty),this.addChild(this.roomName),await this.updateRoomPropertyVisibility(),this.updateLayout()}async createRoomSelectionIndicator(e){this.roomSelectionIndicator&&(this.removeChild(this.roomSelectionIndicator),this.roomSelectionIndicator.destroy()),this.roomSelectionIndicator=new OS(this.appService,e),await this.updateRoomSelectionIndicatorVisibility(),this.addChild(this.roomSelectionIndicator)}updateLayout(){var l,c,d,u,p,g;if(this.destroyed)return;const{property:{offsetY:e,offsetX:i},selectionIndicator:{offsetY:s,offsetX:r}}=this.appService.roomConfig,o=((l=this.roomProperty)==null?void 0:l.visible)||!1,a=((c=this.roomName)==null?void 0:c.visible)||!1,h=((d=this.roomSelectionIndicator)==null?void 0:d.visible)||!1;if(o&&this.roomProperty){const y=this.roomProperty.getTotalHeight(),m=this.roomProperty.getTotalWidth();if(this.roomProperty.isFoldedState()){const S=-m/2+i,v=-y/2-e;this.roomProperty.position.set(S,v)}else a&&((u=this.roomName)!=null&&u.position)?(this.roomProperty.position.set(-m/2+i,-e-y),this.roomName.position.set(0,0)):this.roomProperty.position.set(-m/2+i,-y/2-e)}if(h&&this.roomSelectionIndicator){const y=this.roomSelectionIndicator.getTotalHeight(),m=this.roomSelectionIndicator.getTotalWidth();a&&((p=this.roomName)!=null&&p.position)?(this.roomSelectionIndicator.position.set(-m/2+r,-s-y),this.roomName.position.set(0,0)):this.roomSelectionIndicator.position.set(-m/2+r,-y/2-s)}a&&!o&&!h&&((g=this.roomName)!=null&&g.position)&&this.roomName.position.set(0,0)}updateName(e){this.roomName.updateName(e)}async updateRoomType(e){await this.roomName.updateRoomType(e),this.updateLayout()}updateRoomNameVisibility(e){this.roomName.visible=e,this.updateLayout()}updateRoomTypeVisibility(e){this.roomName.updateRoomTypeVisibility(e),this.updateLayout()}updatePosition(e){this.position.set(e.x,e.y)}async refreshColor(){this.roomName&&this.roomName.refreshColor(),this.roomProperty&&this.roomProperty.refreshColor(),this.roomSelectionIndicator&&await this.roomSelectionIndicator.refreshColor()}destroy(){var e,i,s,r;(e=this.clickHandler)==null||e.destroy(),this.clickHandler=null,this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),this.isAnimatingScale&&this.scaleAnimationBound&&(this.appService.getApp().ticker.remove(this.scaleAnimationBound),this.isAnimatingScale=!1),this.scaleAnimationBound=null,this.updateScaleBound&&(this.appService.emitter.off("antiScale",this.updateScaleBound),this.updateScaleBound=null),(i=this.roomProperty)==null||i.destroy(),this.roomProperty=null,(s=this.roomSelectionIndicator)==null||s.destroy(),this.roomSelectionIndicator=null,(r=this.roomName)==null||r.destroy(),super.destroy()}}class GS extends W{constructor(e){super({isRenderGroup:!0});f(this,"floorTypeMap",new Map);f(this,"floorTypeMasks",new Map);f(this,"floorTypeContexts",new Map);f(this,"floorTypeToRooms",new Map);this.appService=e,this.appService.appContainer.addToLayer(Nr,this)}async createFloorTypes(e){if(!this.appService.runtimeSnapshot.showRoomFloorType)return;this.clearFloorTypes();const s=this.groupRoomsByFloorType(e),r=[];for(const[o,a]of s)r.push(this.createMergedFloorType(o,a));await Promise.all(r)}groupRoomsByFloorType(e){const i=new Map,s=this.appService;return e.forEach((r,o)=>{const a=s.getRoomData(o),h=(a==null?void 0:a.floorType)||0;h>=0&&(i.has(h)||i.set(h,[]),i.get(h).push({roomId:o,graphics:r}))}),i}async createMergedFloorType(e,i){const s=this.appService,{assets:r,opacity:o,scale:a}=s.roomConfig.floorType,h=e%r.length,l=`floorType${h}`;if(!r[h]){w.warn(`No texture asset configured for floorType: ${e}`);return}const c=await V.load(l);if(!c){w.warn(`Floor material texture not found: ${l}`);return}const d=i.map(({graphics:m})=>m.getLocalBounds()),u=nx(d),p=new Cs({texture:c,width:u.width,height:u.height});p.x=u.x,p.y=u.y,p.alpha=o,p.tileScale.set(a);const{maskContainer:g,contexts:y}=this.createMergedMask(i.map(({graphics:m})=>m));p.mask=g,this.addChild(p),this.floorTypeMap.set(e,p),this.floorTypeMasks.set(e,g),this.floorTypeContexts.set(e,y),this.floorTypeToRooms.set(e,new Set(i.map(({roomId:m})=>m)))}createMergedMask(e){const i=new W,s=[];return e.forEach(r=>{const o=new H,a=r.context.clone();o.context=a,s.push(a),i.addChild(o)}),{maskContainer:i,contexts:s}}clearFloorTypes(){this.floorTypeMasks.forEach(e=>{try{e.destroy({children:!0})}catch(i){w.warn("Error destroying floor mask:",i)}}),this.floorTypeMasks.clear(),this.floorTypeContexts.forEach(e=>{try{e.forEach(i=>{try{i.destroy()}catch(s){w.warn("Error destroying cloned graphics context:",s)}})}catch(i){w.warn("Error destroying graphics contexts:",i)}}),this.floorTypeContexts.clear(),this.floorTypeMap.forEach(e=>{try{this.removeChild(e),e.destroy()}catch(i){w.warn("Error destroying floor material:",i)}}),this.floorTypeMap.clear(),this.floorTypeToRooms.clear()}destroy(){this.clearFloorTypes(),super.destroy()}}const Bn=(n,t)=>n&&t?{x:n.x-t.x,y:n.y-t.y}:null;class US{constructor(t){f(this,"unsubscribeFns",[]);f(this,"roomInfoContainer",new W);f(this,"roomInfoMap",new Map);f(this,"roomDisplayMap",new Map);f(this,"roomFloorType");this.appService=t,this.roomFloorType=new GS(t),t.appContainer.addToLayer(Tc,this.roomInfoContainer);const e=G(t.runtime,"showRoomFloorType",d=>{w.log(`[runtime] showRoomFloorType: ${d}`),d?this.updateFloorTypes():this.roomFloorType.clearFloorTypes()}),i=G(t.runtime,"showRoomProperty",d=>{w.log(`[runtime] showRoomProperty: ${d}`),this.updateAllRoomPropertyVisibility()}),s=G(t.runtime,"showRoomOrder",d=>{w.log(`[runtime] showRoomOrder: ${d}`),this.updateAllRoomPropertyVisibility()}),r=G(t.runtime,"roomPropertyFoldIds",d=>{w.log(`[runtime] roomPropertyFoldIds: ${d}`),this.updateAllRoomPropertyVisibility()}),o=G(t.runtime,"showRoomName",d=>{w.log(`[runtime] showRoomName: ${d}`),this.updateAllRoomNameVisibility(d)}),a=G(t.runtime,"showRoomType",d=>{w.log(`[runtime] showRoomType: ${d}`),this.updateAllRoomTypeVisibility(d)}),h=G(t.runtime,"enableRoomSelection",d=>{w.log(`[runtime] enableRoomSelection: ${d}`),this.updateAllRoomPropertyVisibility(),this.updateAllRoomSelectionIndicatorVisibility(),this.refreshAllRoomColors()}),l=G(t.runtime,"selectRoomIds",d=>{w.log(`[runtime] selectRoomIds: ${d}`),this.updateAllRoomPropertyVisibility(),this.updateAllRoomSelectionIndicatorVisibility(),this.refreshAllRoomColors()}),c=G(t.runtime,"roomSelectionMode",d=>{w.log(`[runtime] roomSelectionMode: ${d}`),this.updateAllRoomPropertyVisibility(),this.updateAllRoomSelectionIndicatorVisibility(),this.refreshAllRoomColors()});this.unsubscribeFns.push(e,i,s,r,o,a,h,l,c)}async drawRoomProperty(t){var s;const e=this.appService;this.roomDisplayMap.clear();const i=((s=e.getApp().mapState)==null?void 0:s.origin)??null;return t.forEach((r,o)=>{const a=e.mapManager.getRoomById(r.id),h=(a==null?void 0:a.centerPoint)||null,l={...r,centerPoint:h,relativeCenterPoint:Bn(h,i),index:o,colorIndex:a==null?void 0:a.colorIndex};this.roomDisplayMap.set(r.id,l)}),await this.updateRoomInfoDisplay(),await this.updateFloorTypes(),!0}async updateRoomInfoDisplay(){if(this.roomDisplayMap.size===0){this.appService.mapManager.getAllRooms().length===0&&this.clearRoomInfos();return}const t=Array.from(this.roomDisplayMap.values()).filter(e=>e.centerPoint!==null);this.clearRoomInfos(),await Promise.all(t.map(e=>this.createRoomInfo(e)))}async createRoomInfo(t){const e=new WS(this.appService,t);this.roomInfoContainer.addChild(e),this.roomInfoMap.set(t.id,e),await e.initialize(t)}updateRoomName(t,e){const i=this.roomInfoMap.get(t);i&&i.updateName(e)}async updateRoomType(t,e){const i=this.roomDisplayMap.get(t);i&&(i.type=e);const s=this.roomInfoMap.get(t);s&&await s.updateRoomType(e)}updateRoomPosition(t,e){var r;const i=this.roomDisplayMap.get(t);if(i){i.centerPoint=e;const o=((r=this.appService.getApp().mapState)==null?void 0:r.origin)??null;i.relativeCenterPoint=Bn(e,o)}const s=this.roomInfoMap.get(t);s&&s.updatePosition(e)}clearRoomInfos(){if(this.roomInfoMap.size===0)return;const t=Array.from(this.roomInfoMap.values());this.roomInfoContainer.removeChildren(),t.forEach(e=>{try{e.destroy()}catch(i){w.warn(`[RoomManager] Error destroying RoomInfo for room ${e.roomId}:`,i)}}),this.roomInfoMap.clear()}getRoomPropertyById(t){return this.roomDisplayMap.get(t)}async refresh(){var i;const t=this.appService;this.roomFloorType.clearFloorTypes();const e=((i=t.getApp().mapState)==null?void 0:i.origin)??null;this.roomDisplayMap.forEach((s,r)=>{const o=t.mapManager.getRoomById(r),a=(o==null?void 0:o.centerPoint)||null;if(s.centerPoint!==a){s.centerPoint=a,s.relativeCenterPoint=Bn(a,e);const l=this.roomInfoMap.get(r);l&&a&&l.updatePosition(a)}const h=o==null?void 0:o.colorIndex;if(s.colorIndex!==h&&h!==void 0){s.colorIndex=h;const l=this.roomInfoMap.get(r);l&&l.refreshColor()}}),await this.updateRoomInfoDisplay(),await this.updateFloorTypes()}async updateAllRoomPropertyVisibility(){this.roomInfoMap.size!==0&&await Promise.all(Array.from(this.roomInfoMap.values()).map(async t=>{try{await t.updateRoomPropertyVisibility()}catch(e){console.warn(`[RoomManager] Failed to update room property visibility for room ${t.roomId}`,e)}}))}updateAllRoomNameVisibility(t){this.roomInfoMap.size!==0&&this.roomInfoMap.forEach(e=>{e.updateRoomNameVisibility(t)})}updateAllRoomTypeVisibility(t){this.roomInfoMap.size!==0&&this.roomInfoMap.forEach(e=>{e.updateRoomTypeVisibility(t)})}updateAllRoomSelectionIndicatorVisibility(){this.roomInfoMap.size!==0&&this.roomInfoMap.forEach(t=>{t.updateRoomSelectionIndicatorVisibility()})}refreshAllRoomColors(){this.roomInfoMap.size!==0&&this.roomInfoMap.forEach(t=>{t.refreshColor()})}async updateFloorTypes(){const t=this.appService,e=t.mapManager.roomFill.getRoomGraphicsMap();e.size>0?(await this.roomFloorType.createFloorTypes(e),t.getApp().renderOnceNextFrame()):t.mapManager.getAllRooms().length===0&&this.roomFloorType.clearFloorTypes()}clear(){this.clearRoomInfos(),this.roomInfoContainer.removeChildren(),this.roomInfoMap.clear(),this.roomDisplayMap.clear(),this.roomFloorType.clearFloorTypes()}destroy(){this.unsubscribeFns.forEach(t=>t()),this.unsubscribeFns=[],this.clearRoomInfos(),this.roomInfoContainer.destroy(),this.roomFloorType.destroy()}}var ah,hh;(ah=navigator==null?void 0:navigator.userAgent)!=null&&ah.includes("tuya-ark-ide")||((hh=navigator==null?void 0:navigator.userAgent)==null||hh.includes("miniProgram"));const HS=()=>{var i,s;if(!Pu.any)return!0;const n=navigator.userAgent.toLowerCase(),t=()=>{const r=navigator.deviceMemory;return r?r>=4:!0};let e=!1;if(/iphone|ipad|ipod/.test(n)){const r=(i=n.match(/os (\d+)_/))==null?void 0:i[1];e=(r?parseInt(r):0)>=12}else if(/android/.test(n)){const r=(s=n.match(/android (\d+)/))==null?void 0:s[1];e=(r?parseInt(r):0)>=10}return e&&t()};class NS extends W{constructor(e,i,s){super();f(this,"graphics");f(this,"sprite",null);f(this,"viewportBounds");f(this,"lastConfig",null);f(this,"onImageLoaded");this.label="background",this.viewportBounds=i,this.onImageLoaded=s,this.graphics=new H,this.graphics.label="backgroundGraphics",this.addChild(this.graphics),this.render(e)}async render(e){if(this.lastConfig=e,this.clear(),e.backgroundImage){await this.renderImage(e.backgroundImage,e.backgroundAlpha);return}if(e.backgroundGradient){this.renderGradient(e.backgroundGradient);return}if(e.backgroundColor!==void 0){this.renderSolidColor(e.backgroundColor,e.backgroundAlpha);return}w.warn("[Background] No background configuration provided")}clear(){this.graphics.clear(),this.sprite&&(this.removeChild(this.sprite),this.sprite.destroy(),this.sprite=null)}renderSolidColor(e,i){this.graphics.clear(),this.graphics.rect(0,0,this.viewportBounds.width,this.viewportBounds.height).fill({color:e,alpha:i}),w.debug("[Background] Rendered solid color background",{color:e,alpha:i})}renderGradient(e){const{width:i,height:s}=this.viewportBounds;if(this.graphics.clear(),e.type==="linear"){const r=e.x0??0,o=e.y0??0,a=e.x1??1,h=e.y1??1,l=new Wt({type:"linear",start:{x:r,y:o},end:{x:a,y:h},colorStops:e.colorStops});this.graphics.rect(0,0,i,s).fill(l),w.debug("[Background] Rendered linear gradient background",{x0:r,y0:o,x1:a,y1:h,colorStops:e.colorStops.length})}else if(e.type==="radial"){const r=e.cx??.5,o=e.cy??.5,a=e.r??.5,h=new Wt({type:"radial",center:{x:r,y:o},innerRadius:0,outerCenter:{x:r,y:o},outerRadius:a,colorStops:e.colorStops});this.graphics.rect(0,0,i,s).fill(h),w.debug("[Background] Rendered radial gradient background",{cx:r,cy:o,r:a,colorStops:e.colorStops.length})}}async renderImage(e,i){var s,r,o,a;try{const h=await V.load(e.src);if(!h){w.error("[Background] Failed to load image:",e.src),(s=this.lastConfig)!=null&&s.backgroundColor&&this.renderSolidColor(this.lastConfig.backgroundColor,i);return}this.sprite=new $t(h),this.sprite.label="backgroundSprite",this.sprite.alpha=i;const{width:l,height:c}=this.viewportBounds,d=e.fit||"cover",u=((r=e.position)==null?void 0:r.x)??.5,p=((o=e.position)==null?void 0:o.y)??.5,g=h.width,y=h.height,m=g/y,x=l/c;switch(d){case"fill":this.sprite.width=l,this.sprite.height=c,this.sprite.x=0,this.sprite.y=0;break;case"contain":m>x?(this.sprite.width=l,this.sprite.height=l/m):(this.sprite.height=c,this.sprite.width=c*m),this.sprite.x=(l-this.sprite.width)*u,this.sprite.y=(c-this.sprite.height)*p;break;case"cover":m>x?(this.sprite.height=c,this.sprite.width=c*m):(this.sprite.width=l,this.sprite.height=l/m),this.sprite.x=(l-this.sprite.width)*u,this.sprite.y=(c-this.sprite.height)*p;break;case"none":this.sprite.width=g,this.sprite.height=y,this.sprite.x=(l-g)*u,this.sprite.y=(c-y)*p;break}e.repeat&&w.warn("[Background] Repeat mode not yet implemented"),this.addChild(this.sprite),w.debug("[Background] Rendered image background",{src:e.src,fit:d,position:{x:u,y:p},spriteSize:{width:this.sprite.width,height:this.sprite.height}}),this.onImageLoaded&&this.onImageLoaded()}catch(h){w.error("[Background] Error loading background image:",h),(a=this.lastConfig)!=null&&a.backgroundColor&&this.renderSolidColor(this.lastConfig.backgroundColor,i)}}async update(e){await this.render(e)}async updateViewportBounds(e){this.viewportBounds=e,this.lastConfig&&await this.render(this.lastConfig)}destroy(){this.clear(),super.destroy()}}class VS extends W{constructor(e){super();f(this,"carpetData");f(this,"carpetConfig");f(this,"controlsConfig");f(this,"carpetEvents");f(this,"appService");f(this,"controlFill");f(this,"editableShape");f(this,"clickHandler",null);f(this,"maskContainer",null);f(this,"maskGraphics",null);f(this,"texture",null);f(this,"textureMap",new Map);f(this,"tilingSprite",null);f(this,"initialZonePoints",[]);f(this,"unsubscribeFns",[]);f(this,"resolvedMaxSizeCache",null);f(this,"handleDragStart",()=>{this.isEditingEnabled()&&(this.carpetData.points&&this.carpetData.points.length>0?this.initialZonePoints=this.carpetData.points.map(e=>({...e})):this.initialZonePoints=[],this.appService.getApp().requestRender("zone-drag",!0))});f(this,"handleDragMove",e=>{if(!this.isEditingEnabled()||this.initialZonePoints.length===0||this.carpetData.shape==="custom")return;const i=this.parent.toLocal(e.global),s=this.controlFill.getDragStartPosition();if(!s)return;const r=i.x-s.x,o=i.y-s.y;this.applyTranslation(r,o)});f(this,"handleDragEnd",()=>{var e,i;this.initialZonePoints=[],this.appService.getApp().stopRender("zone-drag"),(i=(e=this.carpetEvents).onUpdate)==null||i.call(e,this.getCarpetData())});f(this,"handleMoveStart",()=>{this.carpetData.points&&this.carpetData.points.length>0?this.initialZonePoints=this.carpetData.points.map(e=>({...e})):this.initialZonePoints=[],this.appService.getApp().requestRender("zone-move",!0)});f(this,"handleMove",e=>{var a,h;if(!this.isEditingEnabled()||this.initialZonePoints.length===0)return;const i=this.parent.toLocal(e.global),s=(h=(a=this.editableShape)==null?void 0:a.getMoveButton())==null?void 0:h.getDragStartPosition();if(!s)return;const r=i.x-s.x,o=i.y-s.y;this.applyTranslation(r,o)});f(this,"handleMoveEnd",()=>{var e,i;this.initialZonePoints=[],this.appService.getApp().stopRender("zone-move"),(i=(e=this.carpetEvents).onUpdate)==null||i.call(e,this.getCarpetData())});f(this,"handleRotationStart",()=>{this.appService.getApp().requestRender("zone-rotate",!0)});f(this,"handleRotationMove",e=>{e&&(this.carpetData.points=e,this.drawCarpet())});f(this,"handleRotationEnd",()=>{var e,i;this.appService.getApp().stopRender("zone-rotate"),(i=(e=this.carpetEvents).onUpdate)==null||i.call(e,this.getCarpetData())});f(this,"handleScaleStart",()=>{this.appService.getApp().requestRender("zone-scale",!0)});f(this,"handleScaleMove",e=>{e&&(this.carpetData.points=e,this.drawCarpet())});f(this,"handleScaleMoveHorizontal",e=>{e&&(this.carpetData.points=e,this.drawCarpet())});f(this,"handleScaleMoveVertical",e=>{e&&(this.carpetData.points=e,this.drawCarpet())});f(this,"handleScaleEnd",()=>{var e,i;this.appService.getApp().stopRender("zone-scale"),(i=(e=this.carpetEvents).onUpdate)==null||i.call(e,this.getCarpetData())});f(this,"handleDelete",()=>{var e,i;(i=(e=this.carpetEvents).onRemove)==null||i.call(e,this.carpetData.id)});f(this,"handleClick",()=>{var e,i;this.isEditingEnabled()||(i=(e=this.carpetEvents)==null?void 0:e.onClick)==null||i.call(e,this.getCarpetData())});f(this,"handlePointsUpdate",e=>{this.carpetData.points=e,this.drawCarpet()});const{appService:i,carpetData:s,events:r={},textureMap:o}=e;this.appService=i,this.textureMap=o,this.carpetEvents=r,this.controlsConfig=this.getControlsConfig(),this.carpetConfig=this.controlsConfig.carpet,this.processCarpetData(s),this.initializeComponents(),this.createEditControlLayer(),this.setupClickHandler(),this.setupEnableRoomSelectionListener(),this.updateEditState(),this.loadTexture()}getResolvedMaxSize(){const e=this.carpetConfig.maxSize;if(this.resolvedMaxSizeCache&&this.resolvedMaxSizeCache.key===e)return this.resolvedMaxSizeCache.value;const i=zs(this.carpetConfig.minSize,e,"carpet");return this.resolvedMaxSizeCache={key:e,value:i},i}validateCarpetShape(e){const i=this.getResolvedMaxSize();return this.appService.coords.validateShape(lc(e),{minSize:ut(this.carpetConfig.minSize),maxSize:i!=null?ut(i):void 0})}processCarpetData(e){if(e.points&&e.points.length>=2)if(e.shape==="custom")this.carpetData={...e,points:e.points};else{const s=this.validateCarpetShape(e.points);this.carpetData={...e,points:s}}else this.carpetData={...e,points:[],shape:e.shape||"rectangle"}}getControlsConfig(){const{controls:e}=this.appService.getConfig();return e}isEditingEnabled(){return this.appService.runtimeSnapshot.editingCarpetIds.includes(this.carpetData.id)}isSelected(){return this.appService.runtimeSnapshot.selectedCarpetIds.includes(this.carpetData.id)}shouldShowEditControl(){return this.isEditingEnabled()||this.isSelected()}initializeComponents(){this.maskContainer=this.createMaskContainer(),this.controlFill=this.createControlFill(),this.addChild(this.maskContainer),this.addChild(this.controlFill),this.drawCarpet()}createMaskContainer(){const e=new W;return this.maskGraphics=new H,this.updateMaskShape(),e.addChild(this.maskGraphics),e.mask=this.maskGraphics,e}createControlFill(){const e=this.isEditingEnabled();return new $r(this.appService,{points:this.carpetData.points||[],fillColor:this.carpetConfig.fillColor,enableInteraction:e,onDragStart:this.handleDragStart,onDragMove:this.handleDragMove,onDragEnd:this.handleDragEnd})}createEditControlLayer(){const e=this.isEditingEnabled(),i=this.carpetData.shape==="custom",s=!!e&&!i&&this.carpetConfig.scaleMode==="ratioLocked",r={...An(this.carpetConfig,["outlineStrokeWidth","outlineDashed","outlineDashArray","outlineFillColor","outlineOffset","outlineStrokeColor"]),...An(this.carpetConfig,["textColor","textPosition","textOffset"]),...An(this.controlsConfig,["textFontSize","textFontFamily","textFontWeight"]),showRotateButton:!!e&&!i&&this.carpetConfig.showRotateButton,showScaleButton:!!e&&!i,showDeleteButton:!!e,showMoveButton:!!e&&!i,showRadialScaleButton:s,iconWrapperFillColor:this.carpetConfig.iconWrapperFillColor,deleteIconWrapperFillColor:this.carpetConfig.deleteIconWrapperFillColor,rotateMode:this.carpetConfig.rotateMode,scaleMode:this.carpetConfig.scaleMode,moveButtonOffset:this.controlsConfig.moveButtonOffset},o=i?this.calculateBoundingRectanglePoints():this.carpetData.points||[];this.editableShape=new Yr({editControls:this.appService.editControlManager});const a=this.getResolvedMaxSize();this.editableShape.attach(this,{id:this.carpetData.id,topology:"quad",layerOptions:{config:r,zonePoints:o,minSize:this.carpetConfig.minSize,maxSize:a??void 0,contentLayer:Ze,events:{onRemove:this.handleDelete,onRotateStart:this.handleRotationStart,onRotateMove:this.handleRotationMove,onRotateEnd:this.handleRotationEnd,onScaleStart:this.handleScaleStart,onScaleMove:this.handleScaleMove,onScaleMoveHorizontal:this.handleScaleMoveHorizontal,onScaleMoveVertical:this.handleScaleMoveVertical,onScaleEnd:this.handleScaleEnd,onMoveStart:this.handleMoveStart,onMoveMove:this.handleMove,onMoveEnd:this.handleMoveEnd,onClick:this.handleClick,onPointsUpdate:this.handlePointsUpdate}},editingState:{showRotateButton:!i&&this.carpetConfig.showRotateButton,showScaleButton:!i,showDeleteButton:!0,showMoveButton:!i,showBorder:!0,showSizeText:!0,borderStyle:this.carpetConfig.editing,showRadialScaleButton:!i&&this.carpetConfig.scaleMode==="ratioLocked"},idleState:{showRotateButton:!1,showScaleButton:!1,showDeleteButton:!1,showMoveButton:!1,showBorder:!1,showSizeText:!1}})}setupClickHandler(){this.interactiveChildren=!0,this.clickHandler=new vt(this,{onClick:()=>{var e,i;this.isEditingEnabled()||(i=(e=this.carpetEvents)==null?void 0:e.onClick)==null||i.call(e,this.getCarpetData())},stopPropagation:!1})}setupEnableRoomSelectionListener(){const e=G(this.appService.runtime,"enableRoomSelection",s=>{this.updateClickHandlerState(s)});this.unsubscribeFns.push(e);const i=this.appService.runtimeSnapshot.enableRoomSelection;this.updateClickHandlerState(i)}isRoomSelectionEnabled(){return this.appService.runtimeSnapshot.enableRoomSelection}updateClickHandlerState(e){if(e){if(this.eventMode="none",this.clickHandler){const i=this.clickHandler.getTarget();i.eventMode="none"}}else if(this.eventMode="static",this.clickHandler){const i=this.clickHandler.getTarget();i.eventMode="static"}}calculateBounds(){const{points:e}=this.carpetData;let i=1/0,s=1/0,r=-1/0,o=-1/0;if(e&&e.length>0)for(const a of e)i=Math.min(i,a.x),s=Math.min(s,a.y),r=Math.max(r,a.x),o=Math.max(o,a.y);return{minX:i,minY:s,maxX:r,maxY:o}}calculateBoundingRectanglePoints(){const{points:e}=this.carpetData;if(!e||e.length===0)return[];const{minX:i,minY:s,maxX:r,maxY:o}=_s(e);return[{x:i,y:s},{x:r,y:s},{x:r,y:o},{x:i,y:o}]}updateMaskShape(){if(!this.maskGraphics)return;this.maskGraphics.clear();const{points:e,shape:i}=this.carpetData;if(!(!e||!Array.isArray(e)||e.length<2)){if(i==="round"){if(e.length<4)return;const r=Le(e),[o,a,,h]=e,l=tt(o,a),c=tt(o,h),d=Math.atan2(a.y-o.y,a.x-o.x);this.maskGraphics.position.set(r.x,r.y),this.maskGraphics.rotation=d,this.maskGraphics.ellipse(0,0,l/2,c/2)}else{const r=e.flatMap(o=>[o.x,o.y]);this.maskGraphics.poly(r),this.maskGraphics.position.set(0,0),this.maskGraphics.rotation=0}this.maskGraphics.fill(16777215)}}loadTexture(){const{opacity:e,scale:i}=this.appService.carpetConfig,{type:s}=this.carpetData;try{this.texture=this.textureMap.get(s)||this.textureMap.get(-1)||null,this.texture&&this.maskContainer&&(this.tilingSprite&&(this.maskContainer.removeChild(this.tilingSprite),this.tilingSprite.destroy(),this.tilingSprite=null),this.createTilingSprite(i,e),this.appService.getApp().renderOnce())}catch(r){console.warn("Failed to load carpet texture:",r)}}createTilingSprite(e,i){if(!this.texture||!this.maskContainer)return;const s=this.calculateBounds();this.tilingSprite=new Cs({texture:this.texture,width:s.maxX-s.minX+100,height:s.maxY-s.minY+100}),this.tilingSprite.position.set(s.minX-50,s.minY-50),this.tilingSprite.tileScale.set(e),this.tilingSprite.alpha=i,this.maskContainer.addChild(this.tilingSprite)}updateTilingSprite(){if(!this.tilingSprite)return;const e=this.calculateBounds();this.tilingSprite.position.set(e.minX-50,e.minY-50),this.tilingSprite.width=e.maxX-e.minX+100,this.tilingSprite.height=e.maxY-e.minY+100}applyTranslation(e,i){this.carpetData.points=this.initialZonePoints.map(s=>({x:s.x+e,y:s.y+i})),this.drawCarpet()}drawCarpet(){const{points:e}=this.carpetData;if(!(!e||e.length<2)&&(this.updateMaskShape(),this.updateTilingSprite(),this.controlFill.updatePoints(e),this.editableShape)){const r=this.carpetData.shape==="custom"?this.calculateBoundingRectanglePoints():e;this.editableShape.updatePoints(r)}}updateEditState(){const e=this.isEditingEnabled(),i=this.isSelected(),s=this.shouldShowEditControl();this.controlFill.setInteractionEnabled(e),this.editableShape&&(i&&!e?this.editableShape.applyEditState({showRotateButton:!1,showScaleButton:!1,showDeleteButton:!1,showMoveButton:!1,showBorder:!0,showSizeText:!1,borderStyle:this.carpetConfig.normal}):this.editableShape.setEditing(e)),this.zIndex=s?1e3:0}refreshConfig(){this.controlsConfig=this.getControlsConfig(),this.carpetConfig=this.controlsConfig.carpet,this.resolvedMaxSizeCache=null,this.controlFill.updateFillColor(this.carpetConfig.fillColor),this.editableShape.detach(),this.createEditControlLayer(),this.drawCarpet(),this.updateEditState()}updateCarpetData(e){const s=this.carpetData.type;if(e.points&&e.points.length>=2)if(e.shape==="custom")this.carpetData={...e,points:e.points};else{const r=this.validateCarpetShape(e.points);this.carpetData={...e,points:r}}else this.carpetData={...e,points:e.points||[]};s!==this.carpetData.type&&this.loadTexture(),this.drawCarpet(),this.updateEditState()}getCarpetData(){return{...this.carpetData}}refreshDisplay(){this.drawCarpet()}destroy(){var e,i,s,r,o;this.editableShape.detach(),this.unsubscribeFns.forEach(a=>a()),this.unsubscribeFns=[],(e=this.tilingSprite)==null||e.destroy(),(i=this.maskGraphics)==null||i.destroy(),(s=this.maskContainer)==null||s.destroy(),this.tilingSprite=null,this.maskGraphics=null,this.maskContainer=null,this.texture=null,(r=this.controlFill)==null||r.destroy(),(o=this.clickHandler)==null||o.destroy(),super.destroy()}}class $S{constructor(t){f(this,"customCarpetMap",new Map);f(this,"unsubscribeFns",[]);f(this,"textureMap",new Map);f(this,"texturesLoaded",!1);f(this,"texturesLoadingPromise",null);this.appService=t,this.applyLayerVisibility(t.runtime.showCustomCarpets);const e=G(t.runtime,"editingCarpetIds",r=>{w.log(`[runtime] editingCarpetIds: ${r}`),this.updateCarpetsEditState()}),i=G(t.runtime,"selectedCarpetIds",r=>{w.log(`[runtime] selectedCarpetIds: ${r}`),this.updateCarpetsEditState()}),s=G(t.runtime,"showCustomCarpets",r=>{w.log(`[runtime] showCustomCarpets: ${r}`),this.applyLayerVisibility(r)});this.unsubscribeFns.push(e,i,s)}async loadTextures(){if(!this.texturesLoaded){if(this.texturesLoadingPromise)return this.texturesLoadingPromise;this.texturesLoadingPromise=this._loadTextures(),await this.texturesLoadingPromise,this.texturesLoaded=!0,this.texturesLoadingPromise=null}}async _loadTextures(){const t=this.appService,{material:e,src:i}=t.carpetConfig;if(e)for(const s of e){const r=await V.load(s.src);this.textureMap.set(s.type,r)}if(i){const s=await V.load(i);this.textureMap.set(-1,s)}}async drawCustomCarpets(t){if(await this.loadTextures(),!t||t.length===0){this.clearAllCustomCarpets();return}const e=new Set(this.customCarpetMap.keys()),i=new Set(t.map(s=>s.id));for(const s of e)i.has(s)||this.removeCustomCarpet(s);t.forEach(s=>{const r=this.customCarpetMap.get(s.id.toString());r?this.isCarpetDataEqual(r.getCarpetData(),s)||r.updateCarpetData(s):this.addNewCustomCarpet(s)})}getCustomCarpets(){const t=[];return this.customCarpetMap.forEach(e=>{t.push(e.getCarpetData())}),t}getCustomCarpetById(t){return this.customCarpetMap.get(t)}clearAllCustomCarpets(){this.customCarpetMap.forEach((t,e)=>{var s;const i=this.customCarpetMap.get(e);i&&((s=i.parent)==null||s.removeChild(i),i.destroy())}),this.customCarpetMap.clear()}addNewCustomCarpet(t){const e=this.appService,i=new VS({appService:e,carpetData:t,textureMap:this.textureMap,events:{onRemove:s=>{var r,o;(o=(r=e.events)==null?void 0:r.onDeleteCustomCarpet)==null||o.call(r,{id:s})},onUpdate:s=>{var r,o;(o=(r=e.events)==null?void 0:r.onUpdateCustomCarpet)==null||o.call(r,s)},onClick:s=>{var r,o;(o=(r=e.events)==null?void 0:r.onClickCarpet)==null||o.call(r,{id:s.id})}}});this.customCarpetMap.set(t.id.toString(),i),e.appContainer.addToLayer(Ze,i)}removeCustomCarpet(t){const e=this.appService,i=this.customCarpetMap.get(t);i&&(e.appContainer.removeFromLayer(Ze,i),i.destroy(),this.customCarpetMap.delete(t))}updateCarpetsEditState(){this.customCarpetMap.forEach(t=>{t.updateEditState()})}applyLayerVisibility(t){const e=this.appService.appContainer.getLayer(Ze);e&&(e.visible=t)}isCarpetDataEqual(t,e){if(t.id!==e.id||t.type!==e.type||t.shape!==e.shape)return!1;const i=t.points||[],s=e.points||[];if(i.length!==s.length)return!1;for(let r=0;r<i.length;r++){const o=i[r],a=s[r];if(Math.abs(o.x-a.x)>.1||Math.abs(o.y-a.y)>.1)return!1}return!0}refreshDisplay(){this.customCarpetMap.forEach(t=>{t.refreshDisplay()})}refreshConfig(){this.customCarpetMap.forEach(t=>{t.refreshConfig()})}destroy(){this.unsubscribeFns.forEach(t=>t()),this.unsubscribeFns=[],this.clearAllCustomCarpets()}}function YS(n,t){return{coords:n.coords,editControls:n.editControlManager,furnitureConfig:n.furnitureConfig,controlsConfig:n.controlsConfig,gestures:n.gestureController,render:{request:e=>n.getApp().requestRender(e,!0),stop:e=>n.getApp().stopRender(e)},events:t}}const sh="furniture-drag",nh="furniture-scale",rh="furniture-move",oh="furniture-rotate";class XS extends W{constructor(e){super();f(this,"deps");f(this,"config");f(this,"controlsConfig");f(this,"furnitureEvents");f(this,"data");f(this,"textureAlias");f(this,"sprite");f(this,"editableShape");f(this,"editing",!1);f(this,"clickHandler",null);f(this,"dragStartPosition",null);f(this,"initialPoints",[]);f(this,"isDragging",!1);f(this,"gestureSession",null);f(this,"originalSizeMeters",null);f(this,"resolveSizeConstraintPerEdge",()=>{var o,a;const{minScaleRatio:e,maxScaleRatio:i}=this.config,s=i===1/0||i==null?void 0:i,r=h=>{if(!h||h<=0)return{min:.1,max:void 0};const l=h*(e||0);return{min:l>0?l:.1,max:s!=null?h*s:void 0}};return{edge1:r((o=this.originalSizeMeters)==null?void 0:o.width),edge2:r((a=this.originalSizeMeters)==null?void 0:a.height)}});f(this,"onDragStart",e=>{if(!this.editing||!this.parent||e.target!==this&&e.target!==this.sprite)return;e.stopPropagation();const i=this.parent.toLocal(e.global);this.dragStartPosition={x:i.x,y:i.y},this.initialPoints=this.data.points.map(s=>({...s})),this.isDragging=!1,this.gestureSession=this.deps.gestures.hijack(e),this.gestureSession.onMove(this.onDragMove),this.gestureSession.onEnd(this.onDragEnd)});f(this,"onDragMove",e=>{if(!this.dragStartPosition||!this.parent)return;const i=this.parent.toLocal(e.global),s=i.x-this.dragStartPosition.x,r=i.y-this.dragStartPosition.y;!this.isDragging&&Math.abs(s)+Math.abs(r)<3||(this.isDragging||(this.isDragging=!0,this.deps.render.request(sh)),this.data.points=this.initialPoints.map(o=>({x:o.x+s,y:o.y+r})),this.redraw())});f(this,"onDragEnd",()=>{var e,i;this.gestureSession=null,this.dragStartPosition&&(this.isDragging&&((i=(e=this.furnitureEvents).onUpdate)==null||i.call(e,this.getData()),this.deps.render.stop(sh)),this.dragStartPosition=null,this.initialPoints=[],this.isDragging=!1)});f(this,"handleRotateStart",()=>{this.deps.render.request(oh)});f(this,"handleRotateMove",e=>{e&&(this.data.points=e,this.redraw())});f(this,"handleTapRotate",e=>{var i,s;e&&(this.data.points=e,this.redraw()),this.captureOriginalSize(),(s=(i=this.furnitureEvents).onUpdate)==null||s.call(i,this.getData())});f(this,"handleScaleStart",()=>{this.deps.render.request(nh)});f(this,"handleScaleMove",e=>{e&&(this.data.points=e,this.redraw())});f(this,"handleMoveStart",()=>{this.initialPoints=this.data.points.map(e=>({...e})),this.deps.render.request(rh)});f(this,"handleMove",e=>{var a;if(!this.editing||this.initialPoints.length===0||!this.parent)return;const i=this.parent.toLocal(e.global),s=(a=this.editableShape.getMoveButton())==null?void 0:a.getDragStartPosition();if(!s)return;const r=i.x-s.x,o=i.y-s.y;this.data.points=this.initialPoints.map(h=>({x:h.x+r,y:h.y+o})),this.redraw()});f(this,"handleMoveEnd",()=>{var e,i;this.initialPoints=[],this.deps.render.stop(rh),(i=(e=this.furnitureEvents).onUpdate)==null||i.call(e,this.getData())});f(this,"handleTransformEnd",()=>{var e,i;this.deps.render.stop(oh),this.deps.render.stop(nh),(i=(e=this.furnitureEvents).onUpdate)==null||i.call(e,this.getData())});f(this,"handleDelete",()=>{var e,i;(i=(e=this.furnitureEvents).onRemove)==null||i.call(e,this.data.id)});f(this,"handleClick",()=>{var e,i;this.editing||(i=(e=this.furnitureEvents).onClick)==null||i.call(e,this.getData())});const{deps:i,data:s,textureAlias:r}=e;this.deps=i,this.config=i.furnitureConfig,this.controlsConfig=i.controlsConfig,this.furnitureEvents=i.events,this.data={...s,points:s.points.map(o=>({...o}))},this.textureAlias=r,this.captureOriginalSize(),this.createSprite(),this.updateSpriteTransform(),this.createEditControlLayer(),this.eventMode="static",this.cursor="pointer",this.setupInteraction(),this.applyEditing()}captureOriginalSize(){const e=this.data.points;if(e.length<4){this.originalSizeMeters=null;return}const i=tt(e[0],e[1]),s=tt(e[1],e[2]);this.originalSizeMeters={width:this.deps.coords.toMeters(Ft(i)),height:this.deps.coords.toMeters(Ft(s))}}createSprite(){const e=V.get(this.textureAlias);this.sprite=new $t(e),this.sprite.anchor.set(.5),this.sprite.alpha=this.config.opacity,this.sprite.eventMode="passive",this.addChild(this.sprite)}updateSpriteTransform(){const e=this.data.points;if(e.length<4)return;const i=Le(e),s=e[1].x-e[0].x,r=e[1].y-e[0].y,o=Math.atan2(r,s),a=tt(e[0],e[1]),h=tt(e[1],e[2]);this.sprite.position.set(i.x,i.y),this.sprite.rotation=o,this.sprite.width=a,this.sprite.height=h}createEditControlLayer(){const e={outlineStrokeColor:String(this.config.outlineStrokeColor),outlineStrokeWidth:this.config.outlineStrokeWidth,outlineDashed:this.config.outlineDashed,outlineDashArray:this.config.outlineDashArray,outlineFillColor:this.config.outlineFillColor?String(this.config.outlineFillColor):void 0,outlineOffset:this.config.outlineOffset,iconWrapperFillColor:String(this.config.iconWrapperFillColor),showRotateButton:!0,showScaleButton:!0,showRadialScaleButton:!1,showDeleteButton:!0,showMoveButton:!0,rotateMode:"step",stepRotateAngle:this.config.rotateDirection==="ccw"?-Math.PI/2:Math.PI/2,scaleMode:this.config.lockAspectRatio?"ratioLocked":"free",textColor:String(this.config.textColor),textPosition:this.config.textPosition,textOffset:this.config.textOffset,moveButtonOffset:this.controlsConfig.moveButtonOffset,textFontSize:this.controlsConfig.textFontSize,textFontFamily:this.controlsConfig.textFontFamily,textFontWeight:this.controlsConfig.textFontWeight};this.editableShape=new Yr({editControls:this.deps.editControls});const i={config:e,zonePoints:this.data.points,sizeConstraintPerEdge:this.resolveSizeConstraintPerEdge,contentLayer:Pe,events:{onRemove:this.handleDelete,onRotateStart:this.handleRotateStart,onRotateMove:this.handleRotateMove,onClickRotate:this.handleTapRotate,onRotateEnd:this.handleTransformEnd,onScaleStart:this.handleScaleStart,onScaleMove:this.handleScaleMove,onScaleEnd:this.handleTransformEnd,onMoveStart:this.handleMoveStart,onMoveMove:this.handleMove,onMoveEnd:this.handleMoveEnd,onClick:this.handleClick}};this.editableShape.attach(this,{id:this.data.id,topology:"quad",layerOptions:i,editingState:{showRotateButton:!0,showScaleButton:!0,showRadialScaleButton:!1,showDeleteButton:!0,showMoveButton:!0,showBorder:!0,showSizeText:this.config.showSizeText},idleState:{showRotateButton:!1,showScaleButton:!1,showRadialScaleButton:!1,showDeleteButton:!1,showMoveButton:!1,showBorder:!1,showSizeText:!1}})}setupInteraction(){this.clickHandler=new vt(this,{onClick:e=>{!this.isDragging&&((e==null?void 0:e.target)===this||(e==null?void 0:e.target)===this.sprite)&&this.handleClick()}}),this.on("pointerdown",this.onDragStart,this)}redraw(){this.data.points.length<4||(this.updateSpriteTransform(),this.editableShape.updatePoints(this.data.points))}applyEditing(){this.editableShape.setEditing(this.editing),this.zIndex=this.editing?1e3:0}updateEditState(e){this.editing!==e&&(this.editing=e,this.applyEditing())}isEditing(){return this.editing}getData(){return{id:this.data.id,furnitureType:this.data.furnitureType,points:this.data.points.map(e=>({...e}))}}updateData(e){this.data={...e,points:e.points.map(i=>({...i}))},this.captureOriginalSize(),this.data.points.length>=4&&(this.updateSpriteTransform(),this.editableShape.updatePoints(this.data.points))}destroy(){var e,i,s;(e=this.editableShape)==null||e.detach(),(i=this.gestureSession)==null||i.cancel(),this.gestureSession=null,(s=this.clickHandler)==null||s.destroy(),this.clickHandler=null,super.destroy({children:!0})}}class jS{constructor(t){f(this,"furnitureMap",new Map);f(this,"unsubscribeFns",[]);this.appService=t,this.applyLayerVisibility(t.runtime.showFurnitures);const e=G(t.runtime,"editingFurnitureIds",s=>{w.log(`[runtime] editingFurnitureIds: ${s}`),this.updateEditState()}),i=G(t.runtime,"showFurnitures",s=>{w.log(`[runtime] showFurnitures: ${s}`),this.applyLayerVisibility(s)});this.unsubscribeFns.push(e,i)}async drawFurnitures(t){if(!t||t.length===0){this.clearAll();return}const e=new Set(this.furnitureMap.keys()),i=new Set(t.map(r=>r.id));for(const r of e)i.has(r)||this.removeFurniture(r);const s=[];for(const r of t){const o=this.furnitureMap.get(r.id);o?this.isDataEqual(o.getData(),r)||o.updateData(r):s.push(this.addFurniture(r))}await Promise.all(s)}async addFurniture(t){const e=this.appService;if(!e.furnitureConfig.assets.find(l=>l.type===t.furnitureType)){w.warn(`[FurnitureManager] No asset found for furnitureType: ${t.furnitureType}`);return}const r=`furniture_${t.furnitureType}`;await V.load(r);const o=YS(e,{onRemove:l=>{var c,d;(d=(c=e.events)==null?void 0:c.onRemoveFurniture)==null||d.call(c,l)},onUpdate:l=>{var c,d;(d=(c=e.events)==null?void 0:c.onUpdateFurniture)==null||d.call(c,l)},onClick:l=>{var c,d;(d=(c=e.events)==null?void 0:c.onClickFurniture)==null||d.call(c,l)}}),a=new XS({deps:o,data:t,textureAlias:r});this.furnitureMap.set(t.id,a),e.appContainer.addToLayer(Pe,a),e.runtime.editingFurnitureIds.includes(t.id)&&(a.updateEditState(!0),this.moveToEditLayer(a))}removeFurniture(t){var i;const e=this.furnitureMap.get(t);e&&((i=e.parent)==null||i.removeChild(e),e.destroy(),this.furnitureMap.delete(t))}clearAll(){var t;for(const[,e]of this.furnitureMap)(t=e.parent)==null||t.removeChild(e),e.destroy();this.furnitureMap.clear()}applyLayerVisibility(t){const e=this.appService.appContainer.getLayer(Pe);e&&(e.visible=t),this.furnitureMap.forEach(i=>{i.visible=t})}updateEditState(){const t=this.appService.runtime.editingFurnitureIds,{appContainer:e}=this.appService,i=e.getLayer(Pe);this.furnitureMap.forEach((s,r)=>{const o=t.includes(r);s.updateEditState(o),o?this.moveToEditLayer(s):s.parent!==i&&this.moveToFurnitureLayer(s)})}moveToEditLayer(t){var e;(e=t.parent)==null||e.removeChild(t),this.appService.appContainer.addToLayer(Re,t)}moveToFurnitureLayer(t){var e;(e=t.parent)==null||e.removeChild(t),this.appService.appContainer.addToLayer(Pe,t)}getFurnitures(){const t=[];return this.furnitureMap.forEach(e=>{t.push(e.getData())}),t}isDataEqual(t,e){if(t.id!==e.id||t.furnitureType!==e.furnitureType||t.points.length!==e.points.length)return!1;for(let i=0;i<t.points.length;i++)if(Math.abs(t.points[i].x-e.points[i].x)>.1||Math.abs(t.points[i].y-e.points[i].y)>.1)return!1;return!0}destroy(){this.unsubscribeFns.forEach(t=>t()),this.unsubscribeFns=[],this.clearAll()}}class ZS{constructor(t){f(this,"editControlLayers",new Map);this.appService=t}registerEditControl(t,e){const i=this.appService;this.editControlLayers.has(t)&&this.unregisterEditControl(t);const s=new tS(i,e);if(!i.appContainer.addToLayer(Re,s))throw w.warn(`[EditControlManager] Failed to add edit control layer for id: ${t}`),s.destroy(),new Error(`Failed to register edit control for id: ${t}`);if(this.editControlLayers.set(t,s),e.contentLayer){const o=i.appContainer.getLayer(Re),a=i.appContainer.getLayer(e.contentLayer);o&&a&&(o.position.x!==a.position.x||o.position.y!==a.position.y)&&w.warn(`[EditControlManager] Edit layer position does not match content layer "${e.contentLayer}" position — edit controls will appear misaligned. Ensure "${e.contentLayer}" is in ORIGIN_TRACKED_LAYERS.`,{edit:o.position,content:a.position})}return s}unregisterEditControl(t){const e=this.editControlLayers.get(t);if(!e)return;this.appService.appContainer.removeFromLayer(Re,e),e.destroy(),this.editControlLayers.delete(t)}getEditControl(t){return this.editControlLayers.get(t)}updateEditState(t,e){const i=this.editControlLayers.get(t);i&&i.updateEditState(e)}clearAll(){Array.from(this.editControlLayers.keys()).forEach(e=>this.unregisterEditControl(e))}getAllEditControls(){return Array.from(this.editControlLayers.values())}hasEditControl(t){return this.editControlLayers.has(t)}}function ds(n){return n.charAt(0).toUpperCase()+n.slice(1)}const Ei=class Ei extends ul{constructor(e=no){super();f(this,"mapState",null);f(this,"components",{});f(this,"managers",{});f(this,"config",so);f(this,"runtime");f(this,"appService");f(this,"coords");f(this,"scaleMin",.5);f(this,"scaleMax",5);f(this,"events",{});f(this,"instanceKey");f(this,"debugInstanceId");f(this,"previousLoggerRuntimeState",null);f(this,"isDestroying",!1);f(this,"hasActiveContextLoss",!1);f(this,"createdAtMs",Date.now());f(this,"lastMapDataAtMs",null);f(this,"lastMapDrawAtMs",null);f(this,"lastPathDataAtMs",null);f(this,"lastVisibilityChangeAtMs",null);f(this,"containerElement");f(this,"onWebGLContextLost",e=>{var r;const i=e;if((r=i.preventDefault)==null||r.call(i),this.hasActiveContextLoss)return;this.hasActiveContextLoss=!0;const s=this.getContextLossDiagnostics(e);w.error("[Pixi] WebGL context lost",s.summary),w.error("[Pixi] WebGL context lost tail",s.recentLifecycleTail),this.recordDebugLifecycleEvent("webglcontextlost",{eventType:e.type,statusMessage:i.statusMessage??null})});f(this,"onWebGLContextRestored",e=>{this.hasActiveContextLoss=!1,w.warn("[Pixi] WebGL context restored, scheduling render",this.getRendererDiagnostics({eventType:e.type})),this.recordDebugLifecycleEvent("webglcontextrestored",{eventType:e.type}),this.renderOnceNextFrame()});f(this,"emitter",bx());f(this,"tickerState",{renderReasons:new Set,renderTimer:null,lastRequestReason:null,lastStopReason:null});f(this,"customCarpetResolvedMaxSizeCache",null);f(this,"pendingAsyncRender",!1);f(this,"isFirstMapDraw",!0);f(this,"isMapDrawn",!1);f(this,"onVisibilityChange",()=>{var i;this.lastVisibilityChangeAtMs=Date.now(),document.visibilityState==="visible"||(i=this.components.interaction)==null||i.clearTouches()});f(this,"onRendererResize",()=>{var e,i;this.isDestroying||((e=this.components.viewportContainer)==null||e.updateViewport(this.config),(i=this.components.background)==null||i.updateViewportBounds(this.getViewportBounds()),this.renderOnceNextFrame())});this.instanceKey=e,this.debugInstanceId=Qa(),this.coords=new Bx(()=>{var i;return((i=this.runtime)==null?void 0:i.unit)??"meter"}),this.appService=new vc(this),globalThis.__PIXI_APP__=this,this.recordDebugLifecycleEvent("app:create",{instanceKey:e})}getRendererDiagnostics(e={}){var r,o,a,h,l,c,d,u,p,g,y;const i=this.containerElement&&"getBoundingClientRect"in this.containerElement&&typeof this.containerElement.getBoundingClientRect=="function"?this.containerElement.getBoundingClientRect():null,s=((r=this.renderer)==null?void 0:r.type)===Qt.WEBGPU?"webgpu":((o=this.renderer)==null?void 0:o.type)===Qt.WEBGL?"webgl":"unknown";return{sessionId:In().getSessionId(),instanceId:this.debugInstanceId,requestedPreference:this.config.global.rendererPreference,rendererType:s,rendererWidth:((a=this.renderer)==null?void 0:a.width)??null,rendererHeight:((h=this.renderer)==null?void 0:h.height)??null,canvasWidth:((l=this.canvas)==null?void 0:l.width)??null,canvasHeight:((c=this.canvas)==null?void 0:c.height)??null,canvasClientWidth:((d=this.canvas)==null?void 0:d.clientWidth)??null,canvasClientHeight:((u=this.canvas)==null?void 0:u.clientHeight)??null,containerWidth:(i==null?void 0:i.width)??null,containerHeight:(i==null?void 0:i.height)??null,mapId:((p=this.mapState)==null?void 0:p.id)??null,mapWidth:((g=this.mapState)==null?void 0:g.width)??null,mapHeight:((y=this.mapState)==null?void 0:y.height)??null,isMapDrawn:this.isMapDrawn,visibilityState:document.visibilityState,...e}}getElapsedMsSince(e){return typeof e=="number"?Math.max(0,Date.now()-e):null}getDeviceDiagnostics(){const e=globalThis.navigator;return{devicePixelRatio:globalThis.devicePixelRatio??null,userAgent:(e==null?void 0:e.userAgent)??null,hardwareConcurrency:(e==null?void 0:e.hardwareConcurrency)??null,deviceMemory:(e==null?void 0:e.deviceMemory)??null,documentWasDiscarded:"wasDiscarded"in document?document.wasDiscarded:null}}getWebGLDiagnostics(){var r;const e=(r=this.renderer)==null?void 0:r.gl;if(!e)return{contextAttributes:null,isContextLost:null,drawingBufferWidth:null,drawingBufferHeight:null,vendor:null,renderer:null,version:null,shadingLanguageVersion:null,maxTextureSize:null,maxRenderbufferSize:null};const i=o=>{if(typeof o!="number"||typeof e.getParameter!="function")return null;try{return e.getParameter(o)??null}catch{return null}},s=typeof e.getExtension=="function"?e.getExtension("WEBGL_debug_renderer_info"):null;return{contextAttributes:typeof e.getContextAttributes=="function"?e.getContextAttributes()??null:null,isContextLost:typeof e.isContextLost=="function"?e.isContextLost():null,drawingBufferWidth:e.drawingBufferWidth??null,drawingBufferHeight:e.drawingBufferHeight??null,vendor:s&&typeof s.UNMASKED_VENDOR_WEBGL=="number"?i(s.UNMASKED_VENDOR_WEBGL):null,renderer:s&&typeof s.UNMASKED_RENDERER_WEBGL=="number"?i(s.UNMASKED_RENDERER_WEBGL):null,version:i(e.VERSION),shadingLanguageVersion:i(e.SHADING_LANGUAGE_VERSION),maxTextureSize:i(e.MAX_TEXTURE_SIZE),maxRenderbufferSize:i(e.MAX_RENDERBUFFER_SIZE)}}getRecentLifecycleTail(){return In().readCurrentSession().slice(-Ei.CONTEXT_LOSS_TAIL_SIZE).map(e=>({seq:e.seq,ts:e.ts,event:e.event,sessionId:e.sessionId,instanceId:e.instanceId??null,visibilityState:e.visibilityState??null,rendererType:e.rendererType??null,mapId:e.mapId??null,detail:e.detail}))}getContextLossDiagnostics(e){const i=e;return{summary:this.getRendererDiagnostics({eventType:e.type,statusMessage:i.statusMessage??null,uptimeMs:this.getElapsedMsSince(this.createdAtMs),timeSinceLastMapDataMs:this.getElapsedMsSince(this.lastMapDataAtMs),timeSinceLastMapDrawMs:this.getElapsedMsSince(this.lastMapDrawAtMs),timeSinceLastPathDataMs:this.getElapsedMsSince(this.lastPathDataAtMs),timeSinceLastVisibilityChangeMs:this.getElapsedMsSince(this.lastVisibilityChangeAtMs),device:this.getDeviceDiagnostics(),webgl:this.getWebGLDiagnostics()}),recentLifecycleTail:this.getRecentLifecycleTail()}}attachRendererDiagnostics(){var e,i;if(((e=this.renderer)==null?void 0:e.type)!==Qt.WEBGL||typeof((i=this.canvas)==null?void 0:i.addEventListener)!="function"){w.debug("[Pixi] Renderer diagnostics initialized",this.getRendererDiagnostics({contextListeners:!1}));return}this.canvas.addEventListener("webglcontextlost",this.onWebGLContextLost),this.canvas.addEventListener("webglcontextrestored",this.onWebGLContextRestored),w.debug("[Pixi] Renderer diagnostics initialized",this.getRendererDiagnostics({contextListeners:!0}))}detachRendererDiagnostics(){var e;typeof((e=this.canvas)==null?void 0:e.removeEventListener)=="function"&&(this.canvas.removeEventListener("webglcontextlost",this.onWebGLContextLost),this.canvas.removeEventListener("webglcontextrestored",this.onWebGLContextRestored))}getDebugRendererType(){var e,i;return((e=this.renderer)==null?void 0:e.type)===Qt.WEBGPU?"webgpu":((i=this.renderer)==null?void 0:i.type)===Qt.WEBGL?"webgl":"unknown"}recordDebugLifecycleEvent(e,i){var s;In().record({event:e,instanceId:this.debugInstanceId,visibilityState:typeof document<"u"?document.visibilityState:null,rendererType:this.getDebugRendererType(),mapId:((s=this.mapState)==null?void 0:s.id)??null,detail:i})}async initialize(e){const{resizeTo:i,events:s,config:r,runtime:o={},...a}=e;this.config=cr(La({},so,r??{},(g,y)=>{if(Array.isArray(y))return y})),this.validateCustomZoneTypes(this.config),this.previousLoggerRuntimeState=zy(),Ly({getLoggerConfig:()=>this.config.logger,getLegacyEnabled:()=>this.config.global.enableLogger}),w.log("Applying config",this.config,r),this.runtime=cr(Object.assign({},md,o));const h=this.instanceKey===no;this.containerElement=i;const l=h&&this.config.interaction.enable,c=this.config.global.performanceMode||!h,d={gcActive:!1,autoStart:!1,sharedTicker:c,eventFeatures:{move:l,globalMove:!1,click:l,wheel:l}},u={resizeTo:h?i:void 0,resolution:this.config.global.resolution,antialias:c?!1:HS(),depth:!c,autoDensity:!0,backgroundColor:0,backgroundAlpha:0,...d,...a},p=this.config.global.rendererPreference;if(p==="webgpu")try{await this.init({...u,preference:"webgpu"})}catch(g){w.warn("[Pixi] WebGPU initialization failed, falling back to WebGL:",g),await this.init({...u,preference:"webgl"})}else await this.init({...u,preference:p});this.attachRendererDiagnostics(),this.recordDebugLifecycleEvent("app:initialized",{isMainInstance:h,isPerformanceMode:c,requestedPreference:p}),w.debug("[Pixi] Renderer initialized",this.getRendererDiagnostics({isMainInstance:h,isPerformanceMode:c})),this.preloadAssets(),this.scaleMax=this.config.interaction.zoomRange.max,this.scaleMin=this.config.interaction.zoomRange.min,this.events=s,this.initializeViewportContainer(),this.initializeInteraction(),this.initializeAppContainer(),this.renderer.on("resize",this.onRendererResize),this.managers.mapManager=new $x(this.appService),this.managers.heatmapManager=new Qx(this.appService),this.managers.pathManager=new qx(this.appService),this.managers.controlsManager=new aS(this.appService),this.managers.detectedObjectManager=new lS(this.appService),this.managers.customElementsManager=new BS(this.appService),this.managers.roomsManager=new US(this.appService),this.managers.customCarpetManager=new $S(this.appService),this.managers.furnitureManager=new jS(this.appService),this.managers.editControlManager=new ZS(this.appService),this.setupMapRotationListener(),document.addEventListener("visibilitychange",this.onVisibilityChange)}async drawMap(e){var a,h,l,c,d,u,p;this.lastMapDataAtMs=Date.now(),this.isMapDrawn=!1,w.log("[Map] drawMap",e);const{size:i,resolution:s,origin:r,id:o}=e;((a=this.mapState)==null?void 0:a.id)!==void 0&&this.mapState.id!==o&&this.managers.pathManager.clear(),(r[0]!==((h=this.mapState)==null?void 0:h.origin.x)||r[1]!==((l=this.mapState)==null?void 0:l.origin.y))&&(this.appService.appContainer.updateOriginTrackedLayers(...r),this.managers.pathManager.updatePositionByOrigin(...r),this.managers.heatmapManager.updatePositionByOrigin(...r)),this.mapState={id:e.id,status:e.status===1,origin:{x:r[0],y:r[1]},charger:{x:e.charger.coordinate[0],y:e.charger.coordinate[1]},chargerDirection:e.charger.angle??0,resolution:s,width:i[0],height:i[1],mapType:"structured"},this.coords.setResolution(s),w.debug("[Map] Structured map state updated",{mapId:o,mapWidth:i[0],mapHeight:i[1],mapResolution:s,mapStatus:e.status===1,originX:r[0],originY:r[1]}),this.isFirstMapDraw&&(this.isFirstMapDraw=!1,(d=(c=this.events)==null?void 0:c.onMapFirstDrawed)==null||d.call(c,this.mapState)),(p=(u=this.events)==null?void 0:u.onMapDrawed)==null||p.call(u,this.mapState),this.emitter.emit("mapStateUpdate",this.mapState),await this.managers.mapManager.drawMap(e),i[0]===0||i[1]===0?(w.warn("[Map] Structured map cleared by incoming data",this.getRendererDiagnostics({mapId:o,mapWidth:i[0],mapHeight:i[1],mapResolution:s,mapStatus:e.status===1,originX:r[0],originY:r[1]})),this.managers.pathManager.clear(),this.managers.roomsManager.clear(),this.isMapDrawn=!1):(this.isMapDrawn=!0,this.lastMapDrawAtMs=Date.now(),this.managers.heatmapManager.onMapLoaded()),this.emitRoomsDrawed(),this.renderOnce()}async drawRasterMap(e){var a,h,l,c,d,u;this.lastMapDataAtMs=Date.now(),this.isMapDrawn=!1,w.log("[Map] drawRasterMap",e);const{mapHeader:i,mapData:s}=e,{originX:r,originY:o}=i;(r!==((a=this.mapState)==null?void 0:a.origin.x)||o!==((h=this.mapState)==null?void 0:h.origin.y))&&(this.appService.appContainer.updateOriginTrackedLayers(r,o),this.managers.pathManager.updatePositionByOrigin(r,o),this.managers.heatmapManager.updatePositionByOrigin(r,o)),this.mapState={id:i.id,status:i.mapStable,origin:{x:r,y:o},charger:{x:i.chargeX,y:i.chargeY},chargerDirection:i.chargeDirection??0,resolution:i.mapResolution*100,width:i.mapWidth,height:i.mapHeight,version:i.version,mapType:"raster"},this.coords.setResolution(i.mapResolution*100),w.debug("[Map] Raster map state updated",{mapId:i.id,mapWidth:i.mapWidth,mapHeight:i.mapHeight,mapResolution:i.mapResolution*100,mapStatus:i.mapStable,originX:r,originY:o,version:i.version??null}),this.isFirstMapDraw&&(this.isFirstMapDraw=!1,(c=(l=this.events)==null?void 0:l.onMapFirstDrawed)==null||c.call(l,this.mapState)),(u=(d=this.events)==null?void 0:d.onMapDrawed)==null||u.call(d,this.mapState),this.emitter.emit("mapStateUpdate",this.mapState),await this.managers.mapManager.drawRasterMap(s.parsed,this.mapState),i.mapWidth===0||i.mapHeight===0?(w.warn("[Map] Raster map cleared by incoming data",this.getRendererDiagnostics({mapId:i.id,mapWidth:i.mapWidth,mapHeight:i.mapHeight,mapResolution:i.mapResolution*100,mapStatus:i.mapStable,originX:r,originY:o,version:i.version??null})),this.managers.pathManager.clear(),this.managers.roomsManager.clear(),this.isMapDrawn=!1):(this.isMapDrawn=!0,this.lastMapDrawAtMs=Date.now(),this.managers.heatmapManager.onMapLoaded()),this.emitRoomsDrawed(),this.renderOnce()}emitRoomsDrawed(){var r,o;const e=(r=this.events)==null?void 0:r.onRoomsDrawed;if(!e)return;const i=((o=this.mapState)==null?void 0:o.origin)??{x:0,y:0},s=this.managers.mapManager.getAllRooms().map(a=>({id:a.id,centerPoint:a.centerPoint,relativeCenterPoint:{x:a.centerPoint.x-i.x,y:a.centerPoint.y-i.y}}));e(s)}drawPath(e){var i,s;this.lastPathDataAtMs=Date.now(),w.log("[Path] drawPath",e),(s=(i=this.events)==null?void 0:i.onPathDrawed)==null||s.call(i,{id:e.pathHeader.pathId,type:e.pathHeader.type,direction:e.pathHeader.direction,count:e.pathHeader.count,initFlag:e.pathHeader.initFlag,robotPosition:e.pathPoints[e.pathPoints.length-1]??null}),this.managers.pathManager.draw(e),this.renderOnce()}async drawRoomProperty(e){var i,s;w.log("[Room] drawRoomProperty",e),(s=(i=this.events)==null?void 0:i.onRoomPropertiesDrawed)==null||s.call(i,e),await this.managers.roomsManager.drawRoomProperty(e),this.renderOnceNextFrame()}async drawCustomCarpets(e){w.log("[CustomCarpets] drawCustomCarpets",e),await this.managers.customCarpetManager.drawCustomCarpets(e),this.renderOnceNextFrame()}async drawFurnitures(e){w.log("[Furniture] drawFurnitures",e),await this.managers.furnitureManager.drawFurnitures(e),this.renderOnceNextFrame()}drawHeatmap(e){w.log("[Heatmap] drawHeatmap",e),this.managers.heatmapManager.draw(e),this.renderOnce()}drawForbiddenSweepZones(e){w.log("[Controls] drawForbiddenSweepZones",e),this.managers.controlsManager.drawForbiddenSweepZones(e),this.renderOnceNextFrame()}drawForbiddenMopZones(e){w.log("[Controls] drawForbiddenMopZones",e),this.managers.controlsManager.drawForbiddenMopZones(e),this.renderOnceNextFrame()}drawCleanZones(e){w.log("[Controls] drawCleanZones",e),this.managers.controlsManager.drawCleanZones(e),this.renderOnceNextFrame()}drawCustomZones(e,i){if(Ne(e)){w.warn(`[MapApplication] drawCustomZones: '${e}' is a built-in type; use draw${ds(e)}s() instead`);return}w.log("[Controls] drawCustomZones",e,i),this.managers.controlsManager.drawCustomZones(e,i),this.renderOnceNextFrame()}getCustomZones(e){return Ne(e)?(w.warn(`[MapApplication] getCustomZones: '${e}' is a built-in type; use get${ds(e)}s() instead`),[]):this.managers.controlsManager.getCustomZones(e)}clearCustomZones(e){if(Ne(e)){w.warn(`[MapApplication] clearCustomZones: '${e}' is a built-in type; use clearAll${ds(e)}s() instead`);return}w.log("[Controls] clearCustomZones",e),this.managers.controlsManager.clearCustomZones(e),this.renderOnceNextFrame()}setEditingCustomZones(e,i){if(Ne(e)){w.warn(`[MapApplication] setEditingCustomZones: '${e}' is a built-in type; use runtime.editing${ds(e)}Ids instead`);return}this.runtime.editingCustomZoneIds={...this.runtime.editingCustomZoneIds??{},[e]:[...i]}}drawVirtualWalls(e){w.log("[Controls] drawVirtualWalls",e),this.managers.controlsManager.drawVirtualWalls(e),this.renderOnceNextFrame()}drawSpots(e){w.log("[Controls] drawSpots",e),this.managers.controlsManager.drawSpots(e),this.renderOnceNextFrame()}drawWayPoints(e){w.log("[Controls] drawWayPoints",e),this.managers.controlsManager.drawWayPoints(e),this.renderOnceNextFrame()}async drawDetectedObjects(e){w.log("[DetectedObject] drawDetectedObjects",e),await this.managers.detectedObjectManager.drawDetectedObjects(e),this.renderOnceNextFrame()}drawCustomCarpet(e){w.log("[CustomCarpet] drawCustomCarpet",e),this.managers.customCarpetManager.drawCustomCarpets(e),this.renderOnceNextFrame()}async drawCustomElements(e){w.log("[CustomElements] drawCustomElements",e),await this.managers.customElementsManager.drawCustomElements(e),this.renderOnceNextFrame()}getForbiddenSweepZones(){return this.managers.controlsManager.getForbiddenSweepZones()}getForbiddenMopZones(){return this.managers.controlsManager.getForbiddenMopZones()}getCleanZones(){return this.managers.controlsManager.getCleanZones()}getVirtualWalls(){return this.managers.controlsManager.getVirtualWalls()}getSpots(){return this.managers.controlsManager.getSpots()}getWayPoints(){return this.managers.controlsManager.getWayPoints()}getEffectiveDividerPoints(){return this.managers.controlsManager.getEffectiveDividerPoints()}getCustomCarpets(){return this.managers.customCarpetManager.getCustomCarpets()}getFurnitures(){return this.managers.furnitureManager.getFurnitures()}getDividerEndPoints(){return this.managers.controlsManager.getDividerEndPoints()}resetPanZoom(){this.components.interaction.setPanZoom()}forceEndGesture(){w.log("[Map] forceEndGesture"),this.components.interaction.forceEndGesture()}fitMapToView(e,i=!1){if(!e||e.minX===e.maxX||e.minY===e.maxY)return;const s=this.config.map.autoPaddingVerticalPercent,r=this.config.map.autoPaddingHorizontalPercent,o=this.getViewportBounds(),a=this.components.appContainer.getMapRotationRadians(),h=this.calculateRotatedBounds(e,a),l=h.maxX-h.minX,c=h.maxY-h.minY,d=o.width,u=o.height,p=d*(1-r*2),g=u*(1-s*2),y=p/l,m=g/c,x=Math.min(y,m),S=this.config.interaction.fitMinScale,v=this.config.interaction.fitMaxScale,b=Math.max(S,Math.min(v,x));this.setScaleBounds(this.config.interaction.zoomRange.min,this.config.interaction.zoomRange.max),b<this.scaleMin&&(this.setScaleBounds(b,this.scaleMax),w.debug("[MapApplication] scaleMin lowered for fit:",{configured:this.config.interaction.zoomRange.min,adjusted:b})),b>this.scaleMax&&(this.setScaleBounds(this.scaleMin,b),w.debug("[MapApplication] scaleMax raised for fit:",{configured:this.config.interaction.zoomRange.max,adjusted:b}));const P=e.minX+(e.maxX-e.minX)/2,C=e.minY+(e.maxY-e.minY)/2,_=this.config.map.autoFitOffset||{x:0,y:0},R=d/2+(_.x||0),M=u/2+(_.y||0),A=Math.cos(a),T=Math.sin(a),I=P*A-C*T,D=P*T+C*A,B=R-I*b,j=M-D*b;w.debug("[MapApplication] fitMapToView calculated:",{rotation:this.components.appContainer.getMapRotation(),originalBounds:e,rotatedBounds:h,finalScale:b,position:{x:B,y:j}}),this.components.interaction.setPanZoom({targetPosition:{x:B,y:j},targetScale:{x:b,y:b},setCenter:!0,setScale:!0},i)}setScaleBounds(e,i){this.scaleMin=e,this.scaleMax=i,this.components.interaction.scaleMin=e,this.components.interaction.scaleMax=i}validateCustomZoneTypes(e){const i=["minSize","strokeColor","strokeWidth","fillColor","outlineOffset","outlineStrokeColor","outlineStrokeWidth","outlineDashed","outlineDashArray","outlineFillColor","iconWrapperFillColor","textColor","textPosition","textOffset","showRotateButton","editing","normal"],s=e.customZoneTypes??{},r=gh.cleanZone;for(const[,o]of Object.entries(s))for(const a of i)o[a]===void 0&&(o[a]=r[a])}calculateRotatedBounds(e,i){if(i===0)return e;const s=(e.minX+e.maxX)/2,r=(e.minY+e.maxY)/2,o=[{x:e.minX-s,y:e.minY-r},{x:e.maxX-s,y:e.minY-r},{x:e.maxX-s,y:e.maxY-r},{x:e.minX-s,y:e.maxY-r}],a=Math.cos(i),h=Math.sin(i),l=o.map(g=>({x:g.x*a-g.y*h,y:g.x*h+g.y*a}));let c=1/0,d=1/0,u=-1/0,p=-1/0;return l.forEach(g=>{c=Math.min(c,g.x),d=Math.min(d,g.y),u=Math.max(u,g.x),p=Math.max(p,g.y)}),{minX:c+s,minY:d+r,maxX:u+s,maxY:p+r}}getViewportBounds(){var e;return((e=this.components.viewportContainer)==null?void 0:e.getViewportBounds())||{x:0,y:0,width:this.renderer.width,height:this.renderer.height}}updateRuntime(e){Object.assign(this.runtime,e),w.log("[runtime] runtime updated",e),this.renderOnceNextFrame()}updateConfig(e){var s,r,o;La(this.config,e,(a,h)=>{if(Array.isArray(h))return h}),e.customZoneTypes&&this.validateCustomZoneTypes(this.config),(s=this.managers.controlsManager)==null||s.updateRenderOrder(),((r=e.controls)==null?void 0:r.carpet)!==void 0&&((o=this.managers.customCarpetManager)==null||o.refreshConfig()),w.log("[Config] Configuration updated",e),this.renderOnceNextFrame()}metersToPixels(e){return this.coords.toPixels(ut(e))}pixelsToMeters(e){return this.coords.toMeters(Ft(e))}toFixedSize(e,i){const s=i??this.components.appContainer.scale.x;return e/s}fromFixedSize(e,i){const s=i??this.components.appContainer.scale.x;return e*s}getViewportCenterPoint(){if(!this.mapState)return w.warn("Map state not available, cannot calculate center point"),null;const e=this.getViewportBounds(),i=e.x+e.width/2,s=e.y+e.height/2,r=this.components.appContainer,o=r.scale.x,a=r.getMapRotationRadians(),h=i-r.x,l=s-r.y,c=h/o,d=l/o,u=Math.cos(a),p=Math.sin(a),g=c*u+d*p,y=-c*p+d*u,m=g-this.mapState.origin.x,x=y-this.mapState.origin.y;return{x:m,y:x}}getMapCenterPoint(){if(!this.mapState)return w.warn("Map state not available, cannot calculate map center point"),null;const e=this.managers.mapManager.mapBounds;if(e.minX===1/0||e.minY===1/0||e.maxX===-1/0||e.maxY===-1/0)return w.warn("Invalid map bounds, cannot calculate map center point"),null;const i=(e.minX+e.maxX)/2,s=(e.minY+e.maxY)/2,r=i-this.mapState.origin.x,o=s-this.mapState.origin.y;return{x:r,y:o}}getWallPointsByViewportCenter(e){var g;const{width:i=this.config.controls.virtualWall.minWidth,direction:s="horizontal",offsetX:r=0,offsetY:o=0}=e||{},a=this.getViewportCenterPoint()||{x:0,y:0},l=this.coords.toPixels(ut(i))/2,c=((g=this.components.appContainer)==null?void 0:g.getMapRotationRadians())||0,d=Math.cos(c),u=Math.sin(c);let p;return s==="horizontal"?p=[{vx:-l+r,vy:o},{vx:l+r,vy:o}]:p=[{vx:r,vy:-l+o},{vx:r,vy:l+o}],p.map(y=>({x:a.x+y.vx*d+y.vy*u,y:a.y-y.vx*u+y.vy*d}))}getForbiddenSweepZonePointsByViewportCenter(e){const i=this.config.controls.forbiddenSweepZone,{size:s=i.minSize,offsetX:r=0,offsetY:o=0}=e||{};return this.generateZonePoints(s,r,o)}getForbiddenMopZonePointsByViewportCenter(e){const i=this.config.controls.forbiddenMopZone,{size:s=i.minSize,offsetX:r=0,offsetY:o=0}=e||{};return this.generateZonePoints(s,r,o)}getCleanZonePointsByViewportCenter(e){const i=this.config.controls.cleanZone,{size:s=i.minSize,offsetX:r=0,offsetY:o=0}=e||{};return this.generateZonePoints(s,r,o)}getSpotPointByViewportCenter(e){const{offsetX:i=0,offsetY:s=0}=e||{},r=this.getViewportCenterPoint()||{x:0,y:0},o=r.x+i,a=r.y+s;return{x:o,y:a}}getFurniturePointsByViewportCenter(e){const{furnitureType:i=1,offsetX:s=0,offsetY:r=0}=e||{},o=this.config.furniture.assets.find(h=>h.type===i),a=this.getViewportCenterPoint()||{x:0,y:0};return this.buildRectPoints({center:a,widthMeters:(o==null?void 0:o.width)??1.8,heightMeters:(o==null?void 0:o.height)??2,applyMapRotation:!0,visualOffsetX:s,visualOffsetY:r})}getResolvedCustomCarpetMaxSize(){const e=this.config.controls.carpet.maxSize;if(this.customCarpetResolvedMaxSizeCache&&this.customCarpetResolvedMaxSizeCache.key===e)return this.customCarpetResolvedMaxSizeCache.value;const i=zs(this.config.controls.carpet.minSize,e,"carpet");return this.customCarpetResolvedMaxSizeCache={key:e,value:i},i}getCustomCarpetPointsByViewportCenter(e){const s=this.config.controls.carpet.minSize,r=this.getResolvedCustomCarpetMaxSize(),{offsetX:o=0,offsetY:a=0}=e||{},h=(g,y)=>{const m=typeof g=="number"&&Number.isFinite(g)?g:y;return r!=null?Math.min(Math.max(m,s),r):Math.max(m,s)},l=(e==null?void 0:e.width)??(e==null?void 0:e.height),c=(e==null?void 0:e.height)??(e==null?void 0:e.width),d=h(l,s),u=h(c,s),p=this.getViewportCenterPoint()||{x:0,y:0};return this.buildRectPoints({center:p,widthMeters:d,heightMeters:u,applyMapRotation:!0,visualOffsetX:o,visualOffsetY:a})}getRectPointsByCenter(e){const{center:i,width:s,height:r,applyMapRotation:o=!0}=e;return this.buildRectPoints({center:i,widthMeters:s,heightMeters:r,applyMapRotation:o})}areRoomsAdjacent(e){return!e||e.length===0?(w.warn("[Room] No room IDs provided"),!1):this.managers.mapManager.areRoomsAdjacent(e)}isPointInAnyRoom(e){return!e||typeof e.x!="number"||typeof e.y!="number"?(w.warn("[Room] Invalid point provided"),null):this.mapState?this.managers.mapManager.isPointInAnyRoom(e):(w.warn("[Room] Map state not available"),null)}isWallIntersectsAnyRoom(e){return!e||e.length!==2||!e[0]||!e[1]||typeof e[0].x!="number"||typeof e[0].y!="number"||typeof e[1].x!="number"||typeof e[1].y!="number"?(w.warn("[Room] Invalid wall points provided"),!1):this.mapState?this.managers.mapManager.isWallIntersectsAnyRoom(e):(w.warn("[Room] Map state not available"),!1)}isZoneIntersectsAnyRoom(e){return!e||e.length!==4||!e[0]||!e[1]||!e[2]||!e[3]||typeof e[0].x!="number"||typeof e[0].y!="number"||typeof e[1].x!="number"||typeof e[1].y!="number"||typeof e[2].x!="number"||typeof e[2].y!="number"||typeof e[3].x!="number"||typeof e[3].y!="number"?(w.warn("[Room] Invalid zone points provided"),!1):this.mapState?this.managers.mapManager.isZoneIntersectsAnyRoom(e):(w.warn("[Room] Map state not available"),!1)}isNearChargerOrRobot(e,i,s){var h,l;if(!e||e.length<1)return w.warn("[Distance] Invalid points array: must have at least 1 point"),!1;if(e.length!==1&&e.length!==2&&e.length!==4)return w.warn("[Distance] Invalid points array: must have exactly 1 (point), 2 (wall) or 4 (zone) points"),!1;if(i<=0)return w.warn("[Distance] Invalid threshold: must be greater than 0"),!1;if(!this.mapState)return w.warn("[Distance] Map state not available"),!1;const{checkCharger:r=!0,checkRobot:o=!1}=s||{};if(!r&&!o)return w.warn("[Distance] At least one of checkCharger or checkRobot must be true"),!1;const a=this.coords.toPixels(ut(i));if(r){const c=this.appService.getChargerPosition();if(c){const d=(h=this.mapState)==null?void 0:h.charger.x,u=(l=this.mapState)==null?void 0:l.charger.y;if(d===0&&u===0)return w.warn("[Distance] Charger position not available"),!1;const p=Ha(c,e);if(p<=a)return w.log(`[Distance] Too close to charger: ${p.toFixed(2)} pixels (threshold: ${a.toFixed(2)} pixels)`),!0}else w.warn("[Distance] Charger position not available")}if(o){const c=this.appService.getRobotPosition();if(c){const d=Ha(c,e);if(d<=a)return w.log(`[Distance] Too close to robot: ${d.toFixed(2)} pixels (threshold: ${a.toFixed(2)} pixels)`),!0}else w.warn("[Distance] Robot position not available")}return!1}async snapshot(e){this.render();const{snapshot:i,global:s}=this.config,r=(e==null?void 0:e.backgroundColor)??s.backgroundColor,o=this.components.appContainer,a=o.getSnapshotBounds(),h=Math.floor(a.x),l=Math.floor(a.y),c=Math.ceil(a.x+a.width)-h,d=Math.ceil(a.y+a.height)-l;if(c<=0||d<=0)return w.error("[MapApplication] Snapshot failed: invalid bounds",a),"";const u=i.resolution||window.devicePixelRatio||2,p=Or.create({width:c,height:d,resolution:u}),g=new H;g.rect(0,0,c,d).fill(r);const y=new U;y.translate(-h,-l);try{return this.renderer.render({container:g,target:p}),this.renderer.render({container:o,target:p,transform:y,clear:!1}),await this.renderer.extract.base64({target:p,format:i.format,quality:i.quality,antialias:i.antialias})}catch(m){return w.error("[MapApplication] Snapshot failed:",m),""}finally{g.destroy(),p.destroy(!0)}}async snapshotByData({map:e,path:i,roomProperties:s,customElements:r,forbiddenSweepZones:o,forbiddenMopZones:a,virtualWalls:h,detectedObjects:l,furnitures:c,carpets:d},u={},p){const g=`SNAPSHOT_${Qa()}`;w.log(`[MapApplication] ${g} snapshot start`);const y=new Ei(g);try{if(await y.initialize({config:this.config,runtime:u}),!e)throw new Error("Map data is required");if(e.startsWith("7b22")){const x=yd(e);await y.drawMap(x)}else{const x=xd(e,{pointsStructured:!0});if(x)await y.drawRasterMap(x);else throw new Error("Failed to decode raster map data")}if(i){const{decodePath:x}=await Me(async()=>{const{decodePath:v}=await import("./theme.DUpgtHaE.js").then(b=>b.f);return{decodePath:v}},__vite__mapDeps([4,2])),S=x(i);y.drawPath(S)}s&&s.length>0&&await y.drawRoomProperty(s),o&&o.length>0&&y.drawForbiddenSweepZones(o),a&&a.length>0&&y.drawForbiddenMopZones(a),h&&h.length>0&&y.drawVirtualWalls(h),d&&d.length>0&&await y.drawCustomCarpets(d),c&&c.length>0&&await y.drawFurnitures(c),l&&l.length>0&&await y.drawDetectedObjects(l),r&&r.length>0&&await y.drawCustomElements(r);const m=await y.snapshot(p);return w.log(`[MapApplication] ${g} snapshot completed successfully`),m}catch(m){throw w.error(`[MapApplication] ${g} snapshot other map failed:`,m),m}finally{w.log(`[MapApplication] ${g} destroy`),y.destroy()}}renderOnce(){w.debug("[Pixi] renderOnce");try{this.render()}catch(e){w.error("[Pixi] renderOnce failed",this.getRendererDiagnostics({error:e}))}}renderOnceNextFrame(){this.pendingAsyncRender||(this.pendingAsyncRender=!0,requestAnimationFrame(()=>{w.debug("[Pixi] renderOnceNextFrame");try{this.render()}catch(e){w.error("[Pixi] renderOnceNextFrame failed",this.getRendererDiagnostics({error:e}))}finally{this.pendingAsyncRender=!1}}))}requestRender(e,i=!1){if(this.tickerState.lastRequestReason=e,!i){this.renderOnceNextFrame(),this.emitRenderStateUpdate();return}this.tickerState.renderReasons.add(e),this.ticker.started||(w.debug(`🎬 [Ticker] START: ${e}`),this.ticker.start()),this.emitRenderStateUpdate()}stopRender(e){this.tickerState.lastStopReason=e,this.tickerState.renderReasons.delete(e),this.tickerState.renderReasons.size===0&&this.scheduleStopRender("final",100),this.emitRenderStateUpdate()}getRenderState(){var i;const e=!!((i=this.ticker)!=null&&i.started);return{continuous:e,fps:e?Math.round(this.ticker.FPS):0,lastRequestReason:this.tickerState.lastRequestReason,lastStopReason:this.tickerState.lastStopReason,activeReasons:[...this.tickerState.renderReasons]}}emitRenderStateUpdate(){this.emitter.emit("renderStateUpdate",this.getRenderState())}destroy(){var e,i,s,r,o,a,h,l,c,d,u,p,g;if(!this.isDestroying){this.isDestroying=!0,w.log("[MapApplication] destroy"),this.recordDebugLifecycleEvent("destroy:start");try{this.tickerState.renderTimer&&(clearTimeout(this.tickerState.renderTimer),this.tickerState.renderTimer=null),this.tickerState.renderReasons.clear(),this.emitter.all.clear(),(e=this.renderer)==null||e.off("resize",this.onRendererResize),document.removeEventListener("visibilitychange",this.onVisibilityChange),(i=this.managers.pathManager)==null||i.destroy(),(s=this.managers.mapManager)==null||s.destroy(),(r=this.managers.controlsManager)==null||r.destroy(),(o=this.managers.furnitureManager)==null||o.destroy(),(a=this.managers.detectedObjectManager)==null||a.destroy(),(h=this.managers.customElementsManager)==null||h.destroy(),(l=this.managers.roomsManager)==null||l.destroy(),(c=this.components.interaction)==null||c.destroy(),(d=this.components.background)==null||d.destroy(),(u=this.components.viewportContainer)==null||u.destroy(),(p=this.components.appContainer)==null||p.destroy(),(g=this.managers.heatmapManager)==null||g.destroy(),this.detachRendererDiagnostics(),Oy(this.previousLoggerRuntimeState),this.previousLoggerRuntimeState=null,globalThis.__PIXI_APP__===this&&delete globalThis.__PIXI_APP__,super.destroy({removeView:!0},{children:!0,texture:!0,textureSource:!0,context:!0})}finally{globalThis.__PIXI_APP__===this&&delete globalThis.__PIXI_APP__,this.recordDebugLifecycleEvent("destroy:end")}}}initializeViewportContainer(){this.components.viewportContainer=new zx(this.config,this.containerElement),this.stage.addChild(this.components.viewportContainer);const e=this.getViewportBounds();this.components.background=new NS(this.config.global,e,()=>{this.renderOnceNextFrame()}),this.components.viewportContainer.addChild(this.components.background),this.components.viewportContainer.setChildIndex(this.components.background,0),Ls(this.config.global,()=>{var i;(i=this.components.background)==null||i.update(this.config.global)})}initializeAppContainer(){this.components.appContainer=new Ux(this.appService),this.components.interaction.addChild(this.components.appContainer)}initializeInteraction(){this.components.interaction=new vx(this.appService),this.components.viewportContainer.addChild(this.components.interaction)}scheduleStopRender(e,i){this.tickerState.renderTimer&&clearTimeout(this.tickerState.renderTimer),this.tickerState.renderTimer=setTimeout(()=>{this.tickerState.renderReasons.delete(e),this.tickerState.renderReasons.size===0&&(w.debug("⏸️ [Ticker] STOP"),this.ticker&&(this.ticker.stop(),this.emitRenderStateUpdate()))},i)}generateZonePoints(e,i,s){const r=this.getViewportCenterPoint()||{x:0,y:0};return this.buildRectPoints({center:r,widthMeters:e,heightMeters:e,applyMapRotation:!0,visualOffsetX:i,visualOffsetY:s})}buildRectPoints(e){var y;const{center:i,widthMeters:s,heightMeters:r,applyMapRotation:o,visualOffsetX:a=0,visualOffsetY:h=0}=e,l=this.coords.toPixels(ut(s))/2,c=this.coords.toPixels(ut(r))/2,d=o&&((y=this.components.appContainer)==null?void 0:y.getMapRotationRadians())||0,u=Math.cos(d),p=Math.sin(d);return[{vx:-l+a,vy:-c+h},{vx:l+a,vy:-c+h},{vx:l+a,vy:c+h},{vx:-l+a,vy:c+h}].map(m=>({x:i.x+m.vx*u+m.vy*p,y:i.y-m.vx*p+m.vy*u}))}preloadAssets(){const e=this.config.robot.icon.src,i=this.config.chargingStation.icon.src,s=[];V.add({alias:"robot",src:e}),s.push("robot"),V.add({alias:"chargingStation",src:i}),s.push("chargingStation"),V.add({alias:"deleteIcon",src:this.config.controls.deleteIconSrc}),s.push("deleteIcon"),V.add({alias:"rotateIcon",src:this.config.controls.rotateIconSrc}),s.push("rotateIcon"),V.add({alias:"scaleIcon",src:this.config.controls.scaleIconSrc}),s.push("scaleIcon"),V.add({alias:"moveIcon",src:this.config.controls.moveIconSrc}),s.push("moveIcon"),V.add({alias:"checkmark",src:this.config.room.selectionIndicator.iconSrc}),s.push("checkmark"),V.add({alias:"spotIcon",src:this.config.controls.spot.iconSrc}),s.push("spotIcon"),V.add({alias:"wayPoint",src:this.config.controls.wayPoint.normal.iconSrc}),s.push("wayPoint"),V.add({alias:"wayPointActive",src:this.config.controls.wayPoint.editing.iconSrc}),s.push("wayPointActive"),V.add({alias:"horizontalScaleIcon",src:this.config.controls.horizontalScaleIconSrc}),s.push("horizontalScaleIcon"),V.add({alias:"verticalScaleIcon",src:this.config.controls.verticalScaleIconSrc}),s.push("verticalScaleIcon"),this.config.room.property.cleanMode.assets.forEach((r,o)=>{const a=`cleanMode_${o}`;V.add({alias:a,src:r}),s.push(a)}),this.config.room.property.suction.assets.forEach((r,o)=>{const a=`fan_${o}`;V.add({alias:a,src:r}),s.push(a)}),this.config.room.property.cistern.assets.forEach((r,o)=>{const a=`water_${o}`;V.add({alias:a,src:r}),s.push(a)}),this.config.room.property.cleanTimes.assets.forEach((r,o)=>{const a=`cleanTimes${o+1}`;V.add({alias:a,src:r}),s.push(a)}),this.config.room.floorType.assets.forEach((r,o)=>{if(!r)return;const a=`floorType${o}`;V.add({alias:a,src:r}),s.push(a)}),this.config.room.property.customAssets&&Object.entries(this.config.room.property.customAssets).forEach(([r,o])=>{o.forEach((a,h)=>{const l=`custom_${r}_${h}`;V.add({alias:l,src:a}),s.push(l)})}),this.config.furniture.assets.forEach(r=>{const o=`furniture_${r.type}`;V.add({alias:o,src:r.src}),s.push(o)}),V.backgroundLoad(s)}setupMapRotationListener(){this.applyMapRotation(this.runtime.mapRotation),G(this.runtime,"mapRotation",e=>{this.applyMapRotation(e)})}applyMapRotation(e){const i=(e%360+360)%360;w.log(`[MapApplication] Applying map rotation: ${i}°`),this.components.appContainer.setMapRotation(i);const s=this.managers.mapManager.mapBounds;s&&s.minX!==1/0&&s.maxX!==-1/0&&this.fitMapToView(s,!1),this.emitter.emit("mapRotationUpdate",i),this.renderOnce()}};f(Ei,"CONTEXT_LOSS_TAIL_SIZE",8);let fr=Ei;const sv=Object.freeze(Object.defineProperty({__proto__:null,AppService:vc,MapApplication:fr},Symbol.toStringTag,{value:"Module"}));export{Xo as $,wi as A,oe as B,se as C,xr as D,Yt as E,br as F,H as G,um as H,Je as I,tg as J,Ds as K,$f as L,U as M,Wt as N,Fs as O,Q as P,vr as Q,J as R,sf as S,O as T,Ie as U,$ as V,ol as W,Qt as X,Ui as Y,Jp as Z,ai as _,Ke as a,_i as a0,wr as a1,sl as a2,Bt as a3,ei as a4,bl as a5,kf as a6,Ff as a7,iv as a8,Cl as a9,Bi as aA,of as aB,wl as aC,Ef as aD,Lf as aE,pm as aF,_l as aG,zf as aH,nm as aI,sv as aJ,De as aa,ps as ab,Vu as ac,kd as ad,he as ae,ti as af,Of as ag,Mt as ah,Ah as ai,Dt as aj,Rs as ak,So as al,$t as am,Xm as an,au as ao,bo as ap,en as aq,wo as ar,lu as as,kh as at,Or as au,Fr as av,al as aw,Gi as ax,gp as ay,cp as az,rr as b,nt as c,N as d,le as e,or as f,os as g,yt as h,X as i,Fu as j,ft as k,Am as l,ct as m,Pu as n,wu as o,E as p,mt as q,Vd as r,sm as s,_a as t,Yu as u,K as v,st as w,q as x,W as y,it as z};