@ray-js/robot-map-sdk 0.1.0-beta.0 → 0.1.1-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-docs/404.html +2 -2
- package/dist-docs/assets/{app.DA7jnJ_k.js → app.DeVcN3v7.js} +1 -1
- package/dist-docs/assets/chunks/@localSearchIndexroot.DnGhpABz.js +1 -0
- package/dist-docs/assets/chunks/{BitmapFont.ga4S-mSe.js → BitmapFont.JB98v0Ym.js} +1 -1
- package/dist-docs/assets/chunks/{BufferResource.DaBoo8RA.js → BufferResource.BOpUIftr.js} +1 -1
- package/dist-docs/assets/chunks/{CanvasRenderer.vEsk0ehs.js → CanvasRenderer.CY93dSp-.js} +1 -1
- package/dist-docs/assets/chunks/{RenderTargetSystem.DokPFeg4.js → RenderTargetSystem.Dx7_01Io.js} +1 -1
- package/dist-docs/assets/chunks/{VPLocalSearchBox.nW9U6a8I.js → VPLocalSearchBox.AUOBcjB8.js} +1 -1
- package/dist-docs/assets/chunks/{WebGLRenderer.DDBDE-SE.js → WebGLRenderer.DRQ9GEc2.js} +1 -1
- package/dist-docs/assets/chunks/{WebGPURenderer.CrTlLNt7.js → WebGPURenderer.CNOqh8b3.js} +1 -1
- package/dist-docs/assets/chunks/{browserAll.ZTT3ke0G.js → browserAll.B4WDqSW_.js} +1 -1
- package/dist-docs/assets/chunks/{index.BD_SMmlU.js → index.DbAtgdYR.js} +4 -4
- package/dist-docs/assets/chunks/{theme.DhH3-Q9Y.js → theme.BEOFMcEN.js} +3 -3
- package/dist-docs/assets/chunks/{webworkerAll.n0O5aLP1.js → webworkerAll.DlWWJIZe.js} +1 -1
- package/dist-docs/assets/{guide_getting-started.md.DpcKgvcS.js → guide_getting-started.md.DlJAeJhY.js} +2 -2
- package/dist-docs/assets/guide_getting-started.md.DlJAeJhY.lean.js +1 -0
- package/dist-docs/guide/advanced-usage.html +3 -3
- package/dist-docs/guide/concepts.html +3 -3
- package/dist-docs/guide/getting-started.html +5 -5
- package/dist-docs/guide/mcp.html +3 -3
- package/dist-docs/guide/spot-room-binding.html +3 -3
- package/dist-docs/hashmap.json +1 -1
- package/dist-docs/index.html +3 -3
- package/dist-docs/plans/2026-03-04-detected-objects-visibility-design.html +3 -3
- package/dist-docs/plans/2026-03-04-show-detected-objects-implementation-plan.html +3 -3
- package/dist-docs/plans/2026-03-10-simulator-debug-design.html +3 -3
- package/dist-docs/plans/2026-03-10-simulator-events-console-design.html +3 -3
- package/dist-docs/plans/2026-03-10-simulator-events-console-implementation-plan.html +3 -3
- package/dist-docs/plans/2026-03-10-simulator-runtime-controls-design.html +3 -3
- package/dist-docs/plans/2026-03-10-simulator-runtime-controls-implementation-plan.html +3 -3
- package/dist-docs/plans/2026-03-10-testing-rollout-next-steps-plan.html +3 -3
- package/dist-docs/plans/2026-03-11-simulator-logger-dump-implementation-plan.html +3 -3
- package/dist-docs/reference/callbacks.html +3 -3
- package/dist-docs/reference/config.html +3 -3
- package/dist-docs/reference/data.html +3 -3
- package/dist-docs/reference/methods.html +3 -3
- package/dist-docs/reference/runtime.html +3 -3
- package/dist-docs/reference/types.html +3 -3
- package/dist-docs/reference/utils.html +3 -3
- package/dist-docs/simulator/index.html +3 -3
- package/package.json +1 -1
- package/dist-docs/assets/chunks/@localSearchIndexroot.C7PYZQrC.js +0 -1
- package/dist-docs/assets/guide_getting-started.md.DpcKgvcS.lean.js +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/chunks/browserAll.
|
|
2
|
-
var mp=Object.defineProperty;var yp=(n,e,t)=>e in n?mp(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var y=(n,e,t)=>yp(n,typeof e!="symbol"?e+"":e,t);import{V as je}from"./framework.CBLqO2Q1.js";import{L as lc,u as hc,m as cc,G as xp,E as Sp,d as Qe,y as bp,Q as vp,v as dc,H as wp,R as Cp,T as Mp,i as To,U as uc,V as _p,W as Pp,I as Ap,X as Tp,K as ua,Y as Rp,e as Ep,w as kp,l as Vr,f as Ip,a as Dp,x as pa,Z as Fp,h as Bp,_ as Lp,j as zp,$ as pc,a0 as Op,a1 as Wp,C as Gp,a2 as Up,N as $r,O as Hp,P as Np,M as fa}from"./mapValues.D2X8cRgC.js";import{a as Jt,N as Yn,i as Pe,D as fc,b as ga,M as ma,d as Vp,H as $p,e as Xp}from"./theme.DhH3-Q9Y.js";var B=(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))(B||{});const Xr=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},ks=(n,e)=>Xr(n).priority??e,Q={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...n){return n.map(Xr).forEach(e=>{e.type.forEach(t=>{var i,s;return(s=(i=this._removeHandlers)[t])==null?void 0:s.call(i,e)})}),this},add(...n){return n.map(Xr).forEach(e=>{e.type.forEach(t=>{var r,o;const i=this._addHandlers,s=this._queue;i[t]?(o=i[t])==null||o.call(i,e):(s[t]=s[t]||[],(r=s[t])==null||r.push(e))})}),this},handle(n,e,t){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]=e,s[n]=t;const r=this._queue;return r[n]&&((o=r[n])==null||o.forEach(a=>e(a)),delete r[n]),this},handleByMap(n,e){return this.handle(n,t=>{t.name&&(e[t.name]=t.ref)},t=>{t.name&&delete e[t.name]})},handleByNamedList(n,e,t=-1){return this.handle(n,i=>{e.findIndex(r=>r.name===i.name)>=0||(e.push({name:i.name,value:i.ref}),e.sort((r,o)=>ks(o.value,t)-ks(r.value,t)))},i=>{const s=e.findIndex(r=>r.name===i.name);s!==-1&&e.splice(s,1)})},handleByList(n,e,t=-1){return this.handle(n,i=>{e.includes(i.ref)||(e.push(i.ref),e.sort((s,r)=>ks(r,t)-ks(s,t)))},i=>{const s=e.indexOf(i.ref);s!==-1&&e.splice(s,1)})},mixin(n,...e){for(const t of e)Object.defineProperties(n.prototype,Object.getOwnPropertyDescriptors(t))}},Yp={extension:{type:B.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await je(()=>import("./browserAll.ZTT3ke0G.js"),__vite__mapDeps([0,1,2,3,4]))}},jp={extension:{type:B.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await je(()=>import("./webworkerAll.n0O5aLP1.js"),__vite__mapDeps([1,2,3,4]))}};class pt{constructor(e,t,i){this._x=t||0,this._y=i||0,this._observer=e}clone(e){return new pt(e??this._observer,this._x,this._y)}set(e=0,t=e){return(this._x!==e||this._y!==t)&&(this._x=e,this._y=t,this._observer._onUpdate(this)),this}copyFrom(e){return(this._x!==e.x||this._y!==e.y)&&(this._x=e.x,this._y=e.y,this._observer._onUpdate(this)),this}copyTo(e){return e.set(this._x,this._y),e}equals(e){return e.x===this._x&&e.y===this._y}toString(){return`[pixi.js/math:ObservablePoint x=${this._x} y=${this._y} scope=${this._observer}]`}get x(){return this._x}set x(e){this._x!==e&&(this._x=e,this._observer._onUpdate(this))}get y(){return this._y}set y(e){this._y!==e&&(this._y=e,this._observer._onUpdate(this))}}var gc={exports:{}};(function(n){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function s(l,h,c){this.fn=l,this.context=h,this.once=c||!1}function r(l,h,c,d,u){if(typeof c!="function")throw new TypeError("The listener must be a function");var p=new s(c,d||l,u),f=t?t+h:h;return l._events[f]?l._events[f].fn?l._events[f]=[l._events[f],p]:l._events[f].push(p):(l._events[f]=p,l._eventsCount++),l}function o(l,h){--l._eventsCount===0?l._events=new i:delete l._events[h]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var h=[],c,d;if(this._eventsCount===0)return h;for(d in c=this._events)e.call(c,d)&&h.push(t?d.slice(1):d);return Object.getOwnPropertySymbols?h.concat(Object.getOwnPropertySymbols(c)):h},a.prototype.listeners=function(h){var c=t?t+h:h,d=this._events[c];if(!d)return[];if(d.fn)return[d.fn];for(var u=0,p=d.length,f=new Array(p);u<p;u++)f[u]=d[u].fn;return f},a.prototype.listenerCount=function(h){var c=t?t+h:h,d=this._events[c];return d?d.fn?1:d.length:0},a.prototype.emit=function(h,c,d,u,p,f){var m=t?t+h:h;if(!this._events[m])return!1;var g=this._events[m],x=arguments.length,S,b;if(g.fn){switch(g.once&&this.removeListener(h,g.fn,void 0,!0),x){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,c),!0;case 3:return g.fn.call(g.context,c,d),!0;case 4:return g.fn.call(g.context,c,d,u),!0;case 5:return g.fn.call(g.context,c,d,u,p),!0;case 6:return g.fn.call(g.context,c,d,u,p,f),!0}for(b=1,S=new Array(x-1);b<x;b++)S[b-1]=arguments[b];g.fn.apply(g.context,S)}else{var w=g.length,_;for(b=0;b<w;b++)switch(g[b].once&&this.removeListener(h,g[b].fn,void 0,!0),x){case 1:g[b].fn.call(g[b].context);break;case 2:g[b].fn.call(g[b].context,c);break;case 3:g[b].fn.call(g[b].context,c,d);break;case 4:g[b].fn.call(g[b].context,c,d,u);break;default:if(!S)for(_=1,S=new Array(x-1);_<x;_++)S[_-1]=arguments[_];g[b].fn.apply(g[b].context,S)}}return!0},a.prototype.on=function(h,c,d){return r(this,h,c,d,!1)},a.prototype.once=function(h,c,d){return r(this,h,c,d,!0)},a.prototype.removeListener=function(h,c,d,u){var p=t?t+h:h;if(!this._events[p])return this;if(!c)return o(this,p),this;var f=this._events[p];if(f.fn)f.fn===c&&(!u||f.once)&&(!d||f.context===d)&&o(this,p);else{for(var m=0,g=[],x=f.length;m<x;m++)(f[m].fn!==c||u&&!f[m].once||d&&f[m].context!==d)&&g.push(f[m]);g.length?this._events[p]=g.length===1?g[0]:g:o(this,p)}return this},a.prototype.removeAllListeners=function(h){var c;return h?(c=t?t+h:h,this._events[c]&&o(this,c)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=t,a.EventEmitter=a,n.exports=a})(gc);var Zp=gc.exports;const ae=lc(Zp),qp=Math.PI*2,Kp=180/Math.PI,Qp=Math.PI/180;class it{constructor(e=0,t=0){this.x=0,this.y=0,this.x=e,this.y=t}clone(){return new it(this.x,this.y)}copyFrom(e){return this.set(e.x,e.y),this}copyTo(e){return e.set(this.x,this.y),e}equals(e){return e.x===this.x&&e.y===this.y}set(e=0,t=e){return this.x=e,this.y=t,this}toString(){return`[pixi.js/math:Point x=${this.x} y=${this.y}]`}static get shared(){return jn.x=0,jn.y=0,jn}}const jn=new it;class H{constructor(e=1,t=0,i=0,s=1,r=0,o=0){this.array=null,this.a=e,this.b=t,this.c=i,this.d=s,this.tx=r,this.ty=o}fromArray(e){this.a=e[0],this.b=e[1],this.c=e[3],this.d=e[4],this.tx=e[2],this.ty=e[5]}set(e,t,i,s,r,o){return this.a=e,this.b=t,this.c=i,this.d=s,this.tx=r,this.ty=o,this}toArray(e,t){this.array||(this.array=new Float32Array(9));const i=t||this.array;return e?(i[0]=this.a,i[1]=this.b,i[2]=0,i[3]=this.c,i[4]=this.d,i[5]=0,i[6]=this.tx,i[7]=this.ty,i[8]=1):(i[0]=this.a,i[1]=this.c,i[2]=this.tx,i[3]=this.b,i[4]=this.d,i[5]=this.ty,i[6]=0,i[7]=0,i[8]=1),i}apply(e,t){t=t||new it;const i=e.x,s=e.y;return t.x=this.a*i+this.c*s+this.tx,t.y=this.b*i+this.d*s+this.ty,t}applyInverse(e,t){t=t||new it;const i=this.a,s=this.b,r=this.c,o=this.d,a=this.tx,l=this.ty,h=1/(i*o+r*-s),c=e.x,d=e.y;return t.x=o*h*c+-r*h*d+(l*r-a*o)*h,t.y=i*h*d+-s*h*c+(-l*i+a*s)*h,t}translate(e,t){return this.tx+=e,this.ty+=t,this}scale(e,t){return this.a*=e,this.d*=t,this.c*=e,this.b*=t,this.tx*=e,this.ty*=t,this}rotate(e){const t=Math.cos(e),i=Math.sin(e),s=this.a,r=this.c,o=this.tx;return this.a=s*t-this.b*i,this.b=s*i+this.b*t,this.c=r*t-this.d*i,this.d=r*i+this.d*t,this.tx=o*t-this.ty*i,this.ty=o*i+this.ty*t,this}append(e){const t=this.a,i=this.b,s=this.c,r=this.d;return this.a=e.a*t+e.b*s,this.b=e.a*i+e.b*r,this.c=e.c*t+e.d*s,this.d=e.c*i+e.d*r,this.tx=e.tx*t+e.ty*s+this.tx,this.ty=e.tx*i+e.ty*r+this.ty,this}appendFrom(e,t){const i=e.a,s=e.b,r=e.c,o=e.d,a=e.tx,l=e.ty,h=t.a,c=t.b,d=t.c,u=t.d;return this.a=i*h+s*d,this.b=i*c+s*u,this.c=r*h+o*d,this.d=r*c+o*u,this.tx=a*h+l*d+t.tx,this.ty=a*c+l*u+t.ty,this}setTransform(e,t,i,s,r,o,a,l,h){return this.a=Math.cos(a+h)*r,this.b=Math.sin(a+h)*r,this.c=-Math.sin(a-l)*o,this.d=Math.cos(a-l)*o,this.tx=e-(i*this.a+s*this.c),this.ty=t-(i*this.b+s*this.d),this}prepend(e){const t=this.tx;if(e.a!==1||e.b!==0||e.c!==0||e.d!==1){const i=this.a,s=this.c;this.a=i*e.a+this.b*e.c,this.b=i*e.b+this.b*e.d,this.c=s*e.a+this.d*e.c,this.d=s*e.b+this.d*e.d}return this.tx=t*e.a+this.ty*e.c+e.tx,this.ty=t*e.b+this.ty*e.d+e.ty,this}decompose(e){const t=this.a,i=this.b,s=this.c,r=this.d,o=e.pivot,a=-Math.atan2(-s,r),l=Math.atan2(i,t),h=Math.abs(a+l);return h<1e-5||Math.abs(qp-h)<1e-5?(e.rotation=l,e.skew.x=e.skew.y=0):(e.rotation=0,e.skew.x=a,e.skew.y=l),e.scale.x=Math.sqrt(t*t+i*i),e.scale.y=Math.sqrt(s*s+r*r),e.position.x=this.tx+(o.x*t+o.y*s),e.position.y=this.ty+(o.x*i+o.y*r),e}invert(){const e=this.a,t=this.b,i=this.c,s=this.d,r=this.tx,o=e*s-t*i;return this.a=s/o,this.b=-t/o,this.c=-i/o,this.d=e/o,this.tx=(i*this.ty-s*r)/o,this.ty=-(e*this.ty-t*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 e=new H;return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e}copyTo(e){return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e}copyFrom(e){return this.a=e.a,this.b=e.b,this.c=e.c,this.d=e.d,this.tx=e.tx,this.ty=e.ty,this}equals(e){return e.a===this.a&&e.b===this.b&&e.c===this.c&&e.d===this.d&&e.tx===this.tx&&e.ty===this.ty}toString(){return`[pixi.js:Matrix a=${this.a} b=${this.b} c=${this.c} d=${this.d} tx=${this.tx} ty=${this.ty}]`}static get IDENTITY(){return tf.identity()}static get shared(){return Jp.identity()}}const Jp=new H,tf=new H,We=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],Ge=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],Ue=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],He=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],Yr=[],mc=[],Is=Math.sign;function ef(){for(let n=0;n<16;n++){const e=[];Yr.push(e);for(let t=0;t<16;t++){const i=Is(We[n]*We[t]+Ue[n]*Ge[t]),s=Is(Ge[n]*We[t]+He[n]*Ge[t]),r=Is(We[n]*Ue[t]+Ue[n]*He[t]),o=Is(Ge[n]*Ue[t]+He[n]*He[t]);for(let a=0;a<16;a++)if(We[a]===i&&Ge[a]===s&&Ue[a]===r&&He[a]===o){e.push(a);break}}}for(let n=0;n<16;n++){const e=new H;e.set(We[n],Ge[n],Ue[n],He[n],0,0),mc.push(e)}}ef();const K={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=>We[n],uY:n=>Ge[n],vX:n=>Ue[n],vY:n=>He[n],inv:n=>n&8?n&15:-n&7,add:(n,e)=>Yr[n][e],sub:(n,e)=>Yr[n][K.inv(e)],rotate180:n=>n^4,isVertical:n=>(n&3)===2,byDirection:(n,e)=>Math.abs(n)*2<=Math.abs(e)?e>=0?K.S:K.N:Math.abs(e)*2<=Math.abs(n)?n>0?K.E:K.W:e>0?n>0?K.SE:K.SW:n>0?K.NE:K.NW,matrixAppendRotationInv:(n,e,t=0,i=0,s=0,r=0)=>{const o=mc[K.inv(e)],a=o.a,l=o.b,h=o.c,c=o.d,d=t-Math.min(0,a*s,h*r,a*s+h*r),u=i-Math.min(0,l*s,c*r,l*s+c*r),p=n.a,f=n.b,m=n.c,g=n.d;n.a=a*p+l*m,n.b=a*f+l*g,n.c=h*p+c*m,n.d=h*f+c*g,n.tx=d*p+u*m+n.tx,n.ty=d*f+u*g+n.ty},transformRectCoords:(n,e,t,i)=>{const{x:s,y:r,width:o,height:a}=n,{x:l,y:h,width:c,height:d}=e;return t===K.E?(i.set(s+l,r+h,o,a),i):t===K.S?i.set(c-r-a+l,s+h,a,o):t===K.W?i.set(c-s-o+l,d-r-a+h,o,a):t===K.N?i.set(r+l,d-s-o+h,a,o):i.set(s+l,r+h,o,a)}},Ds=[new it,new it,new it,new it];class st{constructor(e=0,t=0,i=0,s=0){this.type="rectangle",this.x=Number(e),this.y=Number(t),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 st(0,0,0,0)}clone(){return new st(this.x,this.y,this.width,this.height)}copyFromBounds(e){return this.x=e.minX,this.y=e.minY,this.width=e.maxX-e.minX,this.height=e.maxY-e.minY,this}copyFrom(e){return this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height,this}copyTo(e){return e.copyFrom(this),e}contains(e,t){return this.width<=0||this.height<=0?!1:e>=this.x&&e<this.x+this.width&&t>=this.y&&t<this.y+this.height}strokeContains(e,t,i,s=.5){const{width:r,height:o}=this;if(r<=0||o<=0)return!1;const a=this.x,l=this.y,h=i*(1-s),c=i-h,d=a-h,u=a+r+h,p=l-h,f=l+o+h,m=a+c,g=a+r-c,x=l+c,S=l+o-c;return e>=d&&e<=u&&t>=p&&t<=f&&!(e>m&&e<g&&t>x&&t<S)}intersects(e,t){if(!t){const P=this.x<e.x?e.x:this.x;if((this.right>e.right?e.right:this.right)<=P)return!1;const R=this.y<e.y?e.y:this.y;return(this.bottom>e.bottom?e.bottom:this.bottom)>R}const i=this.left,s=this.right,r=this.top,o=this.bottom;if(s<=i||o<=r)return!1;const a=Ds[0].set(e.left,e.top),l=Ds[1].set(e.left,e.bottom),h=Ds[2].set(e.right,e.top),c=Ds[3].set(e.right,e.bottom);if(h.x<=a.x||l.y<=a.y)return!1;const d=Math.sign(t.a*t.d-t.b*t.c);if(d===0||(t.apply(a,a),t.apply(l,l),t.apply(h,h),t.apply(c,c),Math.max(a.x,l.x,h.x,c.x)<=i||Math.min(a.x,l.x,h.x,c.x)>=s||Math.max(a.y,l.y,h.y,c.y)<=r||Math.min(a.y,l.y,h.y,c.y)>=o))return!1;const u=d*(l.y-a.y),p=d*(a.x-l.x),f=u*i+p*r,m=u*s+p*r,g=u*i+p*o,x=u*s+p*o;if(Math.max(f,m,g,x)<=u*a.x+p*a.y||Math.min(f,m,g,x)>=u*c.x+p*c.y)return!1;const S=d*(a.y-h.y),b=d*(h.x-a.x),w=S*i+b*r,_=S*s+b*r,v=S*i+b*o,C=S*s+b*o;return!(Math.max(w,_,v,C)<=S*a.x+b*a.y||Math.min(w,_,v,C)>=S*c.x+b*c.y)}pad(e=0,t=e){return this.x-=e,this.y-=t,this.width+=e*2,this.height+=t*2,this}fit(e){const t=Math.max(this.x,e.x),i=Math.min(this.x+this.width,e.x+e.width),s=Math.max(this.y,e.y),r=Math.min(this.y+this.height,e.y+e.height);return this.x=t,this.width=Math.max(i-t,0),this.y=s,this.height=Math.max(r-s,0),this}ceil(e=1,t=.001){const i=Math.ceil((this.x+this.width-t)*e)/e,s=Math.ceil((this.y+this.height-t)*e)/e;return this.x=Math.floor((this.x+t)*e)/e,this.y=Math.floor((this.y+t)*e)/e,this.width=i-this.x,this.height=s-this.y,this}scale(e,t=e){return this.x*=e,this.y*=t,this.width*=e,this.height*=t,this}enlarge(e){const t=Math.min(this.x,e.x),i=Math.max(this.x+this.width,e.x+e.width),s=Math.min(this.y,e.y),r=Math.max(this.y+this.height,e.y+e.height);return this.x=t,this.width=i-t,this.y=s,this.height=r-s,this}getBounds(e){return e||(e=new st),e.copyFrom(this),e}containsRect(e){if(this.width<=0||this.height<=0)return!1;const t=e.x,i=e.y,s=e.x+e.width,r=e.y+e.height;return t>=this.x&&t<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(e,t,i,s){return this.x=e,this.y=t,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 Zn={default:-1};function ft(n="default"){return Zn[n]===void 0&&(Zn[n]=-1),++Zn[n]}const ya=new Set,tt="8.0.0",sf="8.3.4",di={quiet:!1,noColor:!1},X=(n,e,t=3)=>{if(di.quiet||ya.has(e))return;let i=new Error().stack;const s=`${e}
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/chunks/browserAll.B4WDqSW_.js","assets/chunks/webworkerAll.DlWWJIZe.js","assets/chunks/framework.CBLqO2Q1.js","assets/chunks/mapValues.D2X8cRgC.js","assets/chunks/theme.BEOFMcEN.js","assets/chunks/WebGPURenderer.CNOqh8b3.js","assets/chunks/BufferResource.BOpUIftr.js","assets/chunks/RenderTargetSystem.Dx7_01Io.js","assets/chunks/WebGLRenderer.DRQ9GEc2.js","assets/chunks/CanvasRenderer.CY93dSp-.js","assets/chunks/BitmapFont.JB98v0Ym.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var mp=Object.defineProperty;var yp=(n,e,t)=>e in n?mp(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var y=(n,e,t)=>yp(n,typeof e!="symbol"?e+"":e,t);import{V as je}from"./framework.CBLqO2Q1.js";import{L as lc,u as hc,m as cc,G as xp,E as Sp,d as Qe,y as bp,Q as vp,v as dc,H as wp,R as Cp,T as Mp,i as To,U as uc,V as _p,W as Pp,I as Ap,X as Tp,K as ua,Y as Rp,e as Ep,w as kp,l as Vr,f as Ip,a as Dp,x as pa,Z as Fp,h as Bp,_ as Lp,j as zp,$ as pc,a0 as Op,a1 as Wp,C as Gp,a2 as Up,N as $r,O as Hp,P as Np,M as fa}from"./mapValues.D2X8cRgC.js";import{a as Jt,N as Yn,i as Pe,D as fc,b as ga,M as ma,d as Vp,H as $p,e as Xp}from"./theme.BEOFMcEN.js";var B=(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))(B||{});const Xr=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},ks=(n,e)=>Xr(n).priority??e,Q={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...n){return n.map(Xr).forEach(e=>{e.type.forEach(t=>{var i,s;return(s=(i=this._removeHandlers)[t])==null?void 0:s.call(i,e)})}),this},add(...n){return n.map(Xr).forEach(e=>{e.type.forEach(t=>{var r,o;const i=this._addHandlers,s=this._queue;i[t]?(o=i[t])==null||o.call(i,e):(s[t]=s[t]||[],(r=s[t])==null||r.push(e))})}),this},handle(n,e,t){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]=e,s[n]=t;const r=this._queue;return r[n]&&((o=r[n])==null||o.forEach(a=>e(a)),delete r[n]),this},handleByMap(n,e){return this.handle(n,t=>{t.name&&(e[t.name]=t.ref)},t=>{t.name&&delete e[t.name]})},handleByNamedList(n,e,t=-1){return this.handle(n,i=>{e.findIndex(r=>r.name===i.name)>=0||(e.push({name:i.name,value:i.ref}),e.sort((r,o)=>ks(o.value,t)-ks(r.value,t)))},i=>{const s=e.findIndex(r=>r.name===i.name);s!==-1&&e.splice(s,1)})},handleByList(n,e,t=-1){return this.handle(n,i=>{e.includes(i.ref)||(e.push(i.ref),e.sort((s,r)=>ks(r,t)-ks(s,t)))},i=>{const s=e.indexOf(i.ref);s!==-1&&e.splice(s,1)})},mixin(n,...e){for(const t of e)Object.defineProperties(n.prototype,Object.getOwnPropertyDescriptors(t))}},Yp={extension:{type:B.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await je(()=>import("./browserAll.B4WDqSW_.js"),__vite__mapDeps([0,1,2,3,4]))}},jp={extension:{type:B.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await je(()=>import("./webworkerAll.DlWWJIZe.js"),__vite__mapDeps([1,2,3,4]))}};class pt{constructor(e,t,i){this._x=t||0,this._y=i||0,this._observer=e}clone(e){return new pt(e??this._observer,this._x,this._y)}set(e=0,t=e){return(this._x!==e||this._y!==t)&&(this._x=e,this._y=t,this._observer._onUpdate(this)),this}copyFrom(e){return(this._x!==e.x||this._y!==e.y)&&(this._x=e.x,this._y=e.y,this._observer._onUpdate(this)),this}copyTo(e){return e.set(this._x,this._y),e}equals(e){return e.x===this._x&&e.y===this._y}toString(){return`[pixi.js/math:ObservablePoint x=${this._x} y=${this._y} scope=${this._observer}]`}get x(){return this._x}set x(e){this._x!==e&&(this._x=e,this._observer._onUpdate(this))}get y(){return this._y}set y(e){this._y!==e&&(this._y=e,this._observer._onUpdate(this))}}var gc={exports:{}};(function(n){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function s(l,h,c){this.fn=l,this.context=h,this.once=c||!1}function r(l,h,c,d,u){if(typeof c!="function")throw new TypeError("The listener must be a function");var p=new s(c,d||l,u),f=t?t+h:h;return l._events[f]?l._events[f].fn?l._events[f]=[l._events[f],p]:l._events[f].push(p):(l._events[f]=p,l._eventsCount++),l}function o(l,h){--l._eventsCount===0?l._events=new i:delete l._events[h]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var h=[],c,d;if(this._eventsCount===0)return h;for(d in c=this._events)e.call(c,d)&&h.push(t?d.slice(1):d);return Object.getOwnPropertySymbols?h.concat(Object.getOwnPropertySymbols(c)):h},a.prototype.listeners=function(h){var c=t?t+h:h,d=this._events[c];if(!d)return[];if(d.fn)return[d.fn];for(var u=0,p=d.length,f=new Array(p);u<p;u++)f[u]=d[u].fn;return f},a.prototype.listenerCount=function(h){var c=t?t+h:h,d=this._events[c];return d?d.fn?1:d.length:0},a.prototype.emit=function(h,c,d,u,p,f){var m=t?t+h:h;if(!this._events[m])return!1;var g=this._events[m],x=arguments.length,S,b;if(g.fn){switch(g.once&&this.removeListener(h,g.fn,void 0,!0),x){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,c),!0;case 3:return g.fn.call(g.context,c,d),!0;case 4:return g.fn.call(g.context,c,d,u),!0;case 5:return g.fn.call(g.context,c,d,u,p),!0;case 6:return g.fn.call(g.context,c,d,u,p,f),!0}for(b=1,S=new Array(x-1);b<x;b++)S[b-1]=arguments[b];g.fn.apply(g.context,S)}else{var w=g.length,_;for(b=0;b<w;b++)switch(g[b].once&&this.removeListener(h,g[b].fn,void 0,!0),x){case 1:g[b].fn.call(g[b].context);break;case 2:g[b].fn.call(g[b].context,c);break;case 3:g[b].fn.call(g[b].context,c,d);break;case 4:g[b].fn.call(g[b].context,c,d,u);break;default:if(!S)for(_=1,S=new Array(x-1);_<x;_++)S[_-1]=arguments[_];g[b].fn.apply(g[b].context,S)}}return!0},a.prototype.on=function(h,c,d){return r(this,h,c,d,!1)},a.prototype.once=function(h,c,d){return r(this,h,c,d,!0)},a.prototype.removeListener=function(h,c,d,u){var p=t?t+h:h;if(!this._events[p])return this;if(!c)return o(this,p),this;var f=this._events[p];if(f.fn)f.fn===c&&(!u||f.once)&&(!d||f.context===d)&&o(this,p);else{for(var m=0,g=[],x=f.length;m<x;m++)(f[m].fn!==c||u&&!f[m].once||d&&f[m].context!==d)&&g.push(f[m]);g.length?this._events[p]=g.length===1?g[0]:g:o(this,p)}return this},a.prototype.removeAllListeners=function(h){var c;return h?(c=t?t+h:h,this._events[c]&&o(this,c)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=t,a.EventEmitter=a,n.exports=a})(gc);var Zp=gc.exports;const ae=lc(Zp),qp=Math.PI*2,Kp=180/Math.PI,Qp=Math.PI/180;class it{constructor(e=0,t=0){this.x=0,this.y=0,this.x=e,this.y=t}clone(){return new it(this.x,this.y)}copyFrom(e){return this.set(e.x,e.y),this}copyTo(e){return e.set(this.x,this.y),e}equals(e){return e.x===this.x&&e.y===this.y}set(e=0,t=e){return this.x=e,this.y=t,this}toString(){return`[pixi.js/math:Point x=${this.x} y=${this.y}]`}static get shared(){return jn.x=0,jn.y=0,jn}}const jn=new it;class H{constructor(e=1,t=0,i=0,s=1,r=0,o=0){this.array=null,this.a=e,this.b=t,this.c=i,this.d=s,this.tx=r,this.ty=o}fromArray(e){this.a=e[0],this.b=e[1],this.c=e[3],this.d=e[4],this.tx=e[2],this.ty=e[5]}set(e,t,i,s,r,o){return this.a=e,this.b=t,this.c=i,this.d=s,this.tx=r,this.ty=o,this}toArray(e,t){this.array||(this.array=new Float32Array(9));const i=t||this.array;return e?(i[0]=this.a,i[1]=this.b,i[2]=0,i[3]=this.c,i[4]=this.d,i[5]=0,i[6]=this.tx,i[7]=this.ty,i[8]=1):(i[0]=this.a,i[1]=this.c,i[2]=this.tx,i[3]=this.b,i[4]=this.d,i[5]=this.ty,i[6]=0,i[7]=0,i[8]=1),i}apply(e,t){t=t||new it;const i=e.x,s=e.y;return t.x=this.a*i+this.c*s+this.tx,t.y=this.b*i+this.d*s+this.ty,t}applyInverse(e,t){t=t||new it;const i=this.a,s=this.b,r=this.c,o=this.d,a=this.tx,l=this.ty,h=1/(i*o+r*-s),c=e.x,d=e.y;return t.x=o*h*c+-r*h*d+(l*r-a*o)*h,t.y=i*h*d+-s*h*c+(-l*i+a*s)*h,t}translate(e,t){return this.tx+=e,this.ty+=t,this}scale(e,t){return this.a*=e,this.d*=t,this.c*=e,this.b*=t,this.tx*=e,this.ty*=t,this}rotate(e){const t=Math.cos(e),i=Math.sin(e),s=this.a,r=this.c,o=this.tx;return this.a=s*t-this.b*i,this.b=s*i+this.b*t,this.c=r*t-this.d*i,this.d=r*i+this.d*t,this.tx=o*t-this.ty*i,this.ty=o*i+this.ty*t,this}append(e){const t=this.a,i=this.b,s=this.c,r=this.d;return this.a=e.a*t+e.b*s,this.b=e.a*i+e.b*r,this.c=e.c*t+e.d*s,this.d=e.c*i+e.d*r,this.tx=e.tx*t+e.ty*s+this.tx,this.ty=e.tx*i+e.ty*r+this.ty,this}appendFrom(e,t){const i=e.a,s=e.b,r=e.c,o=e.d,a=e.tx,l=e.ty,h=t.a,c=t.b,d=t.c,u=t.d;return this.a=i*h+s*d,this.b=i*c+s*u,this.c=r*h+o*d,this.d=r*c+o*u,this.tx=a*h+l*d+t.tx,this.ty=a*c+l*u+t.ty,this}setTransform(e,t,i,s,r,o,a,l,h){return this.a=Math.cos(a+h)*r,this.b=Math.sin(a+h)*r,this.c=-Math.sin(a-l)*o,this.d=Math.cos(a-l)*o,this.tx=e-(i*this.a+s*this.c),this.ty=t-(i*this.b+s*this.d),this}prepend(e){const t=this.tx;if(e.a!==1||e.b!==0||e.c!==0||e.d!==1){const i=this.a,s=this.c;this.a=i*e.a+this.b*e.c,this.b=i*e.b+this.b*e.d,this.c=s*e.a+this.d*e.c,this.d=s*e.b+this.d*e.d}return this.tx=t*e.a+this.ty*e.c+e.tx,this.ty=t*e.b+this.ty*e.d+e.ty,this}decompose(e){const t=this.a,i=this.b,s=this.c,r=this.d,o=e.pivot,a=-Math.atan2(-s,r),l=Math.atan2(i,t),h=Math.abs(a+l);return h<1e-5||Math.abs(qp-h)<1e-5?(e.rotation=l,e.skew.x=e.skew.y=0):(e.rotation=0,e.skew.x=a,e.skew.y=l),e.scale.x=Math.sqrt(t*t+i*i),e.scale.y=Math.sqrt(s*s+r*r),e.position.x=this.tx+(o.x*t+o.y*s),e.position.y=this.ty+(o.x*i+o.y*r),e}invert(){const e=this.a,t=this.b,i=this.c,s=this.d,r=this.tx,o=e*s-t*i;return this.a=s/o,this.b=-t/o,this.c=-i/o,this.d=e/o,this.tx=(i*this.ty-s*r)/o,this.ty=-(e*this.ty-t*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 e=new H;return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e}copyTo(e){return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e}copyFrom(e){return this.a=e.a,this.b=e.b,this.c=e.c,this.d=e.d,this.tx=e.tx,this.ty=e.ty,this}equals(e){return e.a===this.a&&e.b===this.b&&e.c===this.c&&e.d===this.d&&e.tx===this.tx&&e.ty===this.ty}toString(){return`[pixi.js:Matrix a=${this.a} b=${this.b} c=${this.c} d=${this.d} tx=${this.tx} ty=${this.ty}]`}static get IDENTITY(){return tf.identity()}static get shared(){return Jp.identity()}}const Jp=new H,tf=new H,We=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],Ge=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],Ue=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],He=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],Yr=[],mc=[],Is=Math.sign;function ef(){for(let n=0;n<16;n++){const e=[];Yr.push(e);for(let t=0;t<16;t++){const i=Is(We[n]*We[t]+Ue[n]*Ge[t]),s=Is(Ge[n]*We[t]+He[n]*Ge[t]),r=Is(We[n]*Ue[t]+Ue[n]*He[t]),o=Is(Ge[n]*Ue[t]+He[n]*He[t]);for(let a=0;a<16;a++)if(We[a]===i&&Ge[a]===s&&Ue[a]===r&&He[a]===o){e.push(a);break}}}for(let n=0;n<16;n++){const e=new H;e.set(We[n],Ge[n],Ue[n],He[n],0,0),mc.push(e)}}ef();const K={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=>We[n],uY:n=>Ge[n],vX:n=>Ue[n],vY:n=>He[n],inv:n=>n&8?n&15:-n&7,add:(n,e)=>Yr[n][e],sub:(n,e)=>Yr[n][K.inv(e)],rotate180:n=>n^4,isVertical:n=>(n&3)===2,byDirection:(n,e)=>Math.abs(n)*2<=Math.abs(e)?e>=0?K.S:K.N:Math.abs(e)*2<=Math.abs(n)?n>0?K.E:K.W:e>0?n>0?K.SE:K.SW:n>0?K.NE:K.NW,matrixAppendRotationInv:(n,e,t=0,i=0,s=0,r=0)=>{const o=mc[K.inv(e)],a=o.a,l=o.b,h=o.c,c=o.d,d=t-Math.min(0,a*s,h*r,a*s+h*r),u=i-Math.min(0,l*s,c*r,l*s+c*r),p=n.a,f=n.b,m=n.c,g=n.d;n.a=a*p+l*m,n.b=a*f+l*g,n.c=h*p+c*m,n.d=h*f+c*g,n.tx=d*p+u*m+n.tx,n.ty=d*f+u*g+n.ty},transformRectCoords:(n,e,t,i)=>{const{x:s,y:r,width:o,height:a}=n,{x:l,y:h,width:c,height:d}=e;return t===K.E?(i.set(s+l,r+h,o,a),i):t===K.S?i.set(c-r-a+l,s+h,a,o):t===K.W?i.set(c-s-o+l,d-r-a+h,o,a):t===K.N?i.set(r+l,d-s-o+h,a,o):i.set(s+l,r+h,o,a)}},Ds=[new it,new it,new it,new it];class st{constructor(e=0,t=0,i=0,s=0){this.type="rectangle",this.x=Number(e),this.y=Number(t),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 st(0,0,0,0)}clone(){return new st(this.x,this.y,this.width,this.height)}copyFromBounds(e){return this.x=e.minX,this.y=e.minY,this.width=e.maxX-e.minX,this.height=e.maxY-e.minY,this}copyFrom(e){return this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height,this}copyTo(e){return e.copyFrom(this),e}contains(e,t){return this.width<=0||this.height<=0?!1:e>=this.x&&e<this.x+this.width&&t>=this.y&&t<this.y+this.height}strokeContains(e,t,i,s=.5){const{width:r,height:o}=this;if(r<=0||o<=0)return!1;const a=this.x,l=this.y,h=i*(1-s),c=i-h,d=a-h,u=a+r+h,p=l-h,f=l+o+h,m=a+c,g=a+r-c,x=l+c,S=l+o-c;return e>=d&&e<=u&&t>=p&&t<=f&&!(e>m&&e<g&&t>x&&t<S)}intersects(e,t){if(!t){const P=this.x<e.x?e.x:this.x;if((this.right>e.right?e.right:this.right)<=P)return!1;const R=this.y<e.y?e.y:this.y;return(this.bottom>e.bottom?e.bottom:this.bottom)>R}const i=this.left,s=this.right,r=this.top,o=this.bottom;if(s<=i||o<=r)return!1;const a=Ds[0].set(e.left,e.top),l=Ds[1].set(e.left,e.bottom),h=Ds[2].set(e.right,e.top),c=Ds[3].set(e.right,e.bottom);if(h.x<=a.x||l.y<=a.y)return!1;const d=Math.sign(t.a*t.d-t.b*t.c);if(d===0||(t.apply(a,a),t.apply(l,l),t.apply(h,h),t.apply(c,c),Math.max(a.x,l.x,h.x,c.x)<=i||Math.min(a.x,l.x,h.x,c.x)>=s||Math.max(a.y,l.y,h.y,c.y)<=r||Math.min(a.y,l.y,h.y,c.y)>=o))return!1;const u=d*(l.y-a.y),p=d*(a.x-l.x),f=u*i+p*r,m=u*s+p*r,g=u*i+p*o,x=u*s+p*o;if(Math.max(f,m,g,x)<=u*a.x+p*a.y||Math.min(f,m,g,x)>=u*c.x+p*c.y)return!1;const S=d*(a.y-h.y),b=d*(h.x-a.x),w=S*i+b*r,_=S*s+b*r,v=S*i+b*o,C=S*s+b*o;return!(Math.max(w,_,v,C)<=S*a.x+b*a.y||Math.min(w,_,v,C)>=S*c.x+b*c.y)}pad(e=0,t=e){return this.x-=e,this.y-=t,this.width+=e*2,this.height+=t*2,this}fit(e){const t=Math.max(this.x,e.x),i=Math.min(this.x+this.width,e.x+e.width),s=Math.max(this.y,e.y),r=Math.min(this.y+this.height,e.y+e.height);return this.x=t,this.width=Math.max(i-t,0),this.y=s,this.height=Math.max(r-s,0),this}ceil(e=1,t=.001){const i=Math.ceil((this.x+this.width-t)*e)/e,s=Math.ceil((this.y+this.height-t)*e)/e;return this.x=Math.floor((this.x+t)*e)/e,this.y=Math.floor((this.y+t)*e)/e,this.width=i-this.x,this.height=s-this.y,this}scale(e,t=e){return this.x*=e,this.y*=t,this.width*=e,this.height*=t,this}enlarge(e){const t=Math.min(this.x,e.x),i=Math.max(this.x+this.width,e.x+e.width),s=Math.min(this.y,e.y),r=Math.max(this.y+this.height,e.y+e.height);return this.x=t,this.width=i-t,this.y=s,this.height=r-s,this}getBounds(e){return e||(e=new st),e.copyFrom(this),e}containsRect(e){if(this.width<=0||this.height<=0)return!1;const t=e.x,i=e.y,s=e.x+e.width,r=e.y+e.height;return t>=this.x&&t<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(e,t,i,s){return this.x=e,this.y=t,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 Zn={default:-1};function ft(n="default"){return Zn[n]===void 0&&(Zn[n]=-1),++Zn[n]}const ya=new Set,tt="8.0.0",sf="8.3.4",di={quiet:!1,noColor:!1},X=(n,e,t=3)=>{if(di.quiet||ya.has(e))return;let i=new Error().stack;const s=`${e}
|
|
3
3
|
Deprecated since v${n}`,r=typeof console.groupCollapsed=="function"&&!di.noColor;typeof i>"u"?console.warn("PixiJS Deprecation Warning: ",s):(i=i.split(`
|
|
4
4
|
`).splice(t).join(`
|
|
5
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))),ya.add(e)};Object.defineProperties(X,{quiet:{get:()=>di.quiet,set:n=>{di.quiet=n},enumerable:!0,configurable:!1},noColor:{get:()=>di.noColor,set:n=>{di.noColor=n},enumerable:!0,configurable:!1}});const yc=()=>{};function Si(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 xa(n){return!(n&n-1)&&!!n}function xc(n){const e={};for(const t in n)n[t]!==void 0&&(e[t]=n[t]);return e}const Sa=Object.create(null);function nf(n){const e=Sa[n];return e===void 0&&(Sa[n]=ft("resource")),e}const Sc=class bc extends ae{constructor(e={}){super(),this._resourceType="textureSampler",this._touched=0,this._maxAnisotropy=1,this.destroyed=!1,e={...bc.defaultOptions,...e},this.addressMode=e.addressMode,this.addressModeU=e.addressModeU??this.addressModeU,this.addressModeV=e.addressModeV??this.addressModeV,this.addressModeW=e.addressModeW??this.addressModeW,this.scaleMode=e.scaleMode,this.magFilter=e.magFilter??this.magFilter,this.minFilter=e.minFilter??this.minFilter,this.mipmapFilter=e.mipmapFilter??this.mipmapFilter,this.lodMinClamp=e.lodMinClamp,this.lodMaxClamp=e.lodMaxClamp,this.compare=e.compare,this.maxAnisotropy=e.maxAnisotropy??1}set addressMode(e){this.addressModeU=e,this.addressModeV=e,this.addressModeW=e}get addressMode(){return this.addressModeU}set wrapMode(e){X(tt,"TextureStyle.wrapMode is now TextureStyle.addressMode"),this.addressMode=e}get wrapMode(){return this.addressMode}set scaleMode(e){this.magFilter=e,this.minFilter=e,this.mipmapFilter=e}get scaleMode(){return this.magFilter}set maxAnisotropy(e){this._maxAnisotropy=Math.min(e,16),this._maxAnisotropy>1&&(this.scaleMode="linear")}get maxAnisotropy(){return this._maxAnisotropy}get _resourceId(){return this._sharedResourceId||this._generateResourceId()}update(){this._sharedResourceId=null,this.emit("change",this)}_generateResourceId(){const e=`${this.addressModeU}-${this.addressModeV}-${this.addressModeW}-${this.magFilter}-${this.minFilter}-${this.mipmapFilter}-${this.lodMinClamp}-${this.lodMaxClamp}-${this.compare}-${this._maxAnisotropy}`;return this._sharedResourceId=nf(e),this._resourceId}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this.removeAllListeners()}};Sc.defaultOptions={addressMode:"clamp-to-edge",scaleMode:"linear"};let bi=Sc;const vc=class wc extends ae{constructor(e={}){super(),this.options=e,this._gpuData=Object.create(null),this._gcLastUsed=-1,this.uid=ft("textureSource"),this._resourceType="textureSource",this._resourceId=ft("resource"),this.uploadMethodId="unknown",this._resolution=1,this.pixelWidth=1,this.pixelHeight=1,this.width=1,this.height=1,this.sampleCount=1,this.mipLevelCount=1,this.autoGenerateMipmaps=!1,this.format="rgba8unorm",this.dimension="2d",this.viewDimension="2d",this.arrayLayerCount=1,this.antialias=!1,this._touched=0,this._batchTick=-1,this._textureBindLocation=-1,e={...wc.defaultOptions,...e},this.label=e.label??"",this.resource=e.resource,this.autoGarbageCollect=e.autoGarbageCollect,this._resolution=e.resolution,e.width?this.pixelWidth=e.width*this._resolution:this.pixelWidth=this.resource?this.resourceWidth??1:1,e.height?this.pixelHeight=e.height*this._resolution:this.pixelHeight=this.resource?this.resourceHeight??1:1,this.width=this.pixelWidth/this._resolution,this.height=this.pixelHeight/this._resolution,this.format=e.format,this.dimension=e.dimensions,this.viewDimension=e.viewDimension??e.dimensions,this.arrayLayerCount=e.arrayLayerCount,this.mipLevelCount=e.mipLevelCount,this.autoGenerateMipmaps=e.autoGenerateMipmaps,this.sampleCount=e.sampleCount,this.antialias=e.antialias,this.alphaMode=e.alphaMode,this.style=new bi(xc(e)),this.destroyed=!1,this._refreshPOT()}get source(){return this}get style(){return this._style}set style(e){var t,i;this.style!==e&&((t=this._style)==null||t.off("change",this._onStyleChange,this),this._style=e,(i=this._style)==null||i.on("change",this._onStyleChange,this),this._onStyleChange())}set maxAnisotropy(e){this._style.maxAnisotropy=e}get maxAnisotropy(){return this._style.maxAnisotropy}get addressMode(){return this._style.addressMode}set addressMode(e){this._style.addressMode=e}get repeatMode(){return this._style.addressMode}set repeatMode(e){this._style.addressMode=e}get magFilter(){return this._style.magFilter}set magFilter(e){this._style.magFilter=e}get minFilter(){return this._style.minFilter}set minFilter(e){this._style.minFilter=e}get mipmapFilter(){return this._style.mipmapFilter}set mipmapFilter(e){this._style.mipmapFilter=e}get lodMinClamp(){return this._style.lodMinClamp}set lodMinClamp(e){this._style.lodMinClamp=e}get lodMaxClamp(){return this._style.lodMaxClamp}set lodMaxClamp(e){this._style.lodMaxClamp=e}_onStyleChange(){this.emit("styleChange",this)}update(){if(this.resource){const e=this._resolution;if(this.resize(this.resourceWidth/e,this.resourceHeight/e))return}this.emit("update",this)}destroy(){this.destroyed=!0,this.unload(),this.emit("destroy",this),this._style&&(this._style.destroy(),this._style=null),this.uploadMethodId=null,this.resource=null,this.removeAllListeners()}unload(){var e,t;this._resourceId=ft("resource"),this.emit("change",this),this.emit("unload",this);for(const i in this._gpuData)(t=(e=this._gpuData[i])==null?void 0:e.destroy)==null||t.call(e);this._gpuData=Object.create(null)}get resourceWidth(){const{resource:e}=this;return e.naturalWidth||e.videoWidth||e.displayWidth||e.width}get resourceHeight(){const{resource:e}=this;return e.naturalHeight||e.videoHeight||e.displayHeight||e.height}get resolution(){return this._resolution}set resolution(e){this._resolution!==e&&(this._resolution=e,this.width=this.pixelWidth/e,this.height=this.pixelHeight/e)}resize(e,t,i){i||(i=this._resolution),e||(e=this.width),t||(t=this.height);const s=Math.round(e*i),r=Math.round(t*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=ft("resource"),this.emit("change",this),!0)}updateMipmaps(){this.autoGenerateMipmaps&&this.mipLevelCount>1&&this.emit("updateMipmaps",this)}set wrapMode(e){this._style.wrapMode=e}get wrapMode(){return this._style.wrapMode}set scaleMode(e){this._style.scaleMode=e}get scaleMode(){return this._style.scaleMode}_refreshPOT(){this.isPowerOfTwo=xa(this.pixelWidth)&&xa(this.pixelHeight)}static test(e){throw new Error("Unimplemented")}};vc.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 Ut=vc;class Ro extends Ut{constructor(e){const t=e.resource||new Float32Array(e.width*e.height*4);let i=e.format;i||(t instanceof Float32Array?i="rgba32float":t instanceof Int32Array||t instanceof Uint32Array?i="rgba32uint":t instanceof Int16Array||t instanceof Uint16Array?i="rgba16uint":(t instanceof Int8Array,i="bgra8unorm")),super({...e,resource:t,format:i}),this.uploadMethodId="buffer"}static test(e){return e instanceof Int8Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array}}Ro.extension=B.TextureSource;const ba=new H;class rf{constructor(e,t){this.mapCoord=new H,this.uClampFrame=new Float32Array(4),this.uClampOffset=new Float32Array(2),this._textureID=-1,this._updateID=0,this.clampOffset=0,typeof t>"u"?this.clampMargin=e.width<10?0:.5:this.clampMargin=t,this.isSimple=!1,this.texture=e}get texture(){return this._texture}set texture(e){var t;this.texture!==e&&((t=this._texture)==null||t.removeListener("update",this.update,this),this._texture=e,this._texture.addListener("update",this.update,this),this.update())}multiplyUvs(e,t){t===void 0&&(t=e);const i=this.mapCoord;for(let s=0;s<e.length;s+=2){const r=e[s],o=e[s+1];t[s]=r*i.a+o*i.c+i.tx,t[s+1]=r*i.b+o*i.d+i.ty}return t}update(){const e=this._texture;this._updateID++;const t=e.uvs;this.mapCoord.set(t.x1-t.x0,t.y1-t.y0,t.x3-t.x0,t.y3-t.y0,t.x0,t.y0);const i=e.orig,s=e.trim;s&&(ba.set(i.width/s.width,0,0,i.height/s.height,-s.x/s.width,-s.y/s.height),this.mapCoord.append(ba));const r=e.source,o=this.uClampFrame,a=this.clampMargin/r._resolution,l=this.clampOffset/r._resolution;return o[0]=(e.frame.x+a+l)/r.width,o[1]=(e.frame.y+a+l)/r.height,o[2]=(e.frame.x+e.frame.width-a+l)/r.width,o[3]=(e.frame.y+e.frame.height-a+l)/r.height,this.uClampOffset[0]=this.clampOffset/r.pixelWidth,this.uClampOffset[1]=this.clampOffset/r.pixelHeight,this.isSimple=e.frame.width===r.width&&e.frame.height===r.height&&e.rotate===0,!0}}class U extends ae{constructor({source:e,label:t,frame:i,orig:s,trim:r,defaultAnchor:o,defaultBorders:a,rotate:l,dynamic:h}={}){if(super(),this.uid=ft("texture"),this.uvs={x0:0,y0:0,x1:0,y1:0,x2:0,y2:0,x3:0,y3:0},this.frame=new st,this.noFrame=!1,this.dynamic=!1,this.isTexture=!0,this.label=t,this.source=(e==null?void 0:e.source)??new Ut,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=l??0,this.defaultAnchor=o,this.defaultBorders=a,this.destroyed=!1,this.dynamic=h||!1,this.updateUvs()}set source(e){this._source&&this._source.off("resize",this.update,this),this._source=e,e.on("resize",this.update,this),this.emit("update",this)}get source(){return this._source}get textureMatrix(){return this._textureMatrix||(this._textureMatrix=new rf(this)),this._textureMatrix}get width(){return this.orig.width}get height(){return this.orig.height}updateUvs(){const{uvs:e,frame:t}=this,{width:i,height:s}=this._source,r=t.x/i,o=t.y/s,a=t.width/i,l=t.height/s;let h=this.rotate;if(h){const c=a/2,d=l/2,u=r+c,p=o+d;h=K.add(h,K.NW),e.x0=u+c*K.uX(h),e.y0=p+d*K.uY(h),h=K.add(h,2),e.x1=u+c*K.uX(h),e.y1=p+d*K.uY(h),h=K.add(h,2),e.x2=u+c*K.uX(h),e.y2=p+d*K.uY(h),h=K.add(h,2),e.x3=u+c*K.uX(h),e.y3=p+d*K.uY(h)}else e.x0=r,e.y0=o,e.x1=r+a,e.y1=o,e.x2=r+a,e.y2=o+l,e.x3=r,e.y3=o+l}destroy(e=!1){this._source&&(this._source.off("resize",this.update,this),e&&(this._source.destroy(),this._source=null)),this._textureMatrix=null,this.destroyed=!0,this.emit("destroy",this),this.removeAllListeners()}update(){this.noFrame&&(this.frame.width=this._source.width,this.frame.height=this._source.height),this.updateUvs(),this.emit("update",this)}get baseTexture(){return X(tt,"Texture.baseTexture is now Texture.source"),this._source}}U.EMPTY=new U({label:"EMPTY",source:new Ut({label:"EMPTY"})});U.EMPTY.destroy=yc;U.WHITE=new U({source:new Ro({resource:new Uint8Array([255,255,255,255]),width:1,height:1,alphaMode:"premultiply-alpha-on-upload",label:"WHITE"}),label:"WHITE"});U.WHITE.destroy=yc;function Cc(n,e,t){const{width:i,height:s}=t.orig,r=t.trim;if(r){const o=r.width,a=r.height;n.minX=r.x-e._x*i,n.maxX=n.minX+o,n.minY=r.y-e._y*s,n.maxY=n.minY+a}else n.minX=-e._x*i,n.maxX=n.minX+i,n.minY=-e._y*s,n.maxY=n.minY+s}const va=new H;class Wt{constructor(e=1/0,t=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=va,this.minX=e,this.minY=t,this.maxX=i,this.maxY=s}isEmpty(){return this.minX>this.maxX||this.minY>this.maxY}get rectangle(){this._rectangle||(this._rectangle=new st);const e=this._rectangle;return this.minX>this.maxX||this.minY>this.maxY?(e.x=0,e.y=0,e.width=0,e.height=0):e.copyFromBounds(this),e}clear(){return this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=va,this}set(e,t,i,s){this.minX=e,this.minY=t,this.maxX=i,this.maxY=s}addFrame(e,t,i,s,r){r||(r=this.matrix);const o=r.a,a=r.b,l=r.c,h=r.d,c=r.tx,d=r.ty;let u=this.minX,p=this.minY,f=this.maxX,m=this.maxY,g=o*e+l*t+c,x=a*e+h*t+d;g<u&&(u=g),x<p&&(p=x),g>f&&(f=g),x>m&&(m=x),g=o*i+l*t+c,x=a*i+h*t+d,g<u&&(u=g),x<p&&(p=x),g>f&&(f=g),x>m&&(m=x),g=o*e+l*s+c,x=a*e+h*s+d,g<u&&(u=g),x<p&&(p=x),g>f&&(f=g),x>m&&(m=x),g=o*i+l*s+c,x=a*i+h*s+d,g<u&&(u=g),x<p&&(p=x),g>f&&(f=g),x>m&&(m=x),this.minX=u,this.minY=p,this.maxX=f,this.maxY=m}addRect(e,t){this.addFrame(e.x,e.y,e.x+e.width,e.y+e.height,t)}addBounds(e,t){this.addFrame(e.minX,e.minY,e.maxX,e.maxY,t)}addBoundsMask(e){this.minX=this.minX>e.minX?this.minX:e.minX,this.minY=this.minY>e.minY?this.minY:e.minY,this.maxX=this.maxX<e.maxX?this.maxX:e.maxX,this.maxY=this.maxY<e.maxY?this.maxY:e.maxY}applyMatrix(e){const t=this.minX,i=this.minY,s=this.maxX,r=this.maxY,{a:o,b:a,c:l,d:h,tx:c,ty:d}=e;let u=o*t+l*i+c,p=a*t+h*i+d;this.minX=u,this.minY=p,this.maxX=u,this.maxY=p,u=o*s+l*i+c,p=a*s+h*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*t+l*r+c,p=a*t+h*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+l*r+c,p=a*s+h*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(e){return this.minX<e.left&&(this.minX=e.left),this.maxX>e.right&&(this.maxX=e.right),this.minY<e.top&&(this.minY=e.top),this.maxY>e.bottom&&(this.maxY=e.bottom),this}fitBounds(e,t,i,s){return this.minX<e&&(this.minX=e),this.maxX>t&&(this.maxX=t),this.minY<i&&(this.minY=i),this.maxY>s&&(this.maxY=s),this}pad(e,t=e){return this.minX-=e,this.maxX+=e,this.minY-=t,this.maxY+=t,this}ceil(){return this.minX=Math.floor(this.minX),this.minY=Math.floor(this.minY),this.maxX=Math.ceil(this.maxX),this.maxY=Math.ceil(this.maxY),this}clone(){return new Wt(this.minX,this.minY,this.maxX,this.maxY)}scale(e,t=e){return this.minX*=e,this.minY*=t,this.maxX*=e,this.maxY*=t,this}get x(){return this.minX}set x(e){const t=this.maxX-this.minX;this.minX=e,this.maxX=e+t}get y(){return this.minY}set y(e){const t=this.maxY-this.minY;this.minY=e,this.maxY=e+t}get width(){return this.maxX-this.minX}set width(e){this.maxX=this.minX+e}get height(){return this.maxY-this.minY}set height(e){this.maxY=this.minY+e}get left(){return this.minX}get right(){return this.maxX}get top(){return this.minY}get bottom(){return this.maxY}get isPositive(){return this.maxX-this.minX>0&&this.maxY-this.minY>0}get isValid(){return this.minX+this.minY!==1/0}addVertexData(e,t,i,s){let r=this.minX,o=this.minY,a=this.maxX,l=this.maxY;s||(s=this.matrix);const h=s.a,c=s.b,d=s.c,u=s.d,p=s.tx,f=s.ty;for(let m=t;m<i;m+=2){const g=e[m],x=e[m+1],S=h*g+d*x+p,b=c*g+u*x+f;r=S<r?S:r,o=b<o?b:o,a=S>a?S:a,l=b>l?b:l}this.minX=r,this.minY=o,this.maxX=a,this.maxY=l}containsPoint(e,t){return this.minX<=e&&this.minY<=t&&this.maxX>=e&&this.maxY>=t}toString(){return`[pixi.js:Bounds minX=${this.minX} minY=${this.minY} maxX=${this.maxX} maxY=${this.maxY} width=${this.width} height=${this.height}]`}copyFrom(e){return this.minX=e.minX,this.minY=e.minY,this.maxX=e.maxX,this.maxY=e.maxY,this}}var of={grad:.9,turn:360,rad:360/(2*Math.PI)},le=function(n){return typeof n=="string"?n.length>0:typeof n=="number"},Ct=function(n,e,t){return e===void 0&&(e=0),t===void 0&&(t=Math.pow(10,e)),Math.round(t*n)/t+0},Ot=function(n,e,t){return e===void 0&&(e=0),t===void 0&&(t=1),n>t?t:n>e?n:e},Mc=function(n){return(n=isFinite(n)?n%360:0)>0?n:n+360},wa=function(n){return{r:Ot(n.r,0,255),g:Ot(n.g,0,255),b:Ot(n.b,0,255),a:Ot(n.a)}},qn=function(n){return{r:Ct(n.r),g:Ct(n.g),b:Ct(n.b),a:Ct(n.a,3)}},af=/^#([0-9a-f]{3,8})$/i,Fs=function(n){var e=n.toString(16);return e.length<2?"0"+e:e},_c=function(n){var e=n.r,t=n.g,i=n.b,s=n.a,r=Math.max(e,t,i),o=r-Math.min(e,t,i),a=o?r===e?(t-i)/o:r===t?2+(i-e)/o:4+(e-t)/o:0;return{h:60*(a<0?a+6:a),s:r?o/r*100:0,v:r/255*100,a:s}},Pc=function(n){var e=n.h,t=n.s,i=n.v,s=n.a;e=e/360*6,t/=100,i/=100;var r=Math.floor(e),o=i*(1-t),a=i*(1-(e-r)*t),l=i*(1-(1-e+r)*t),h=r%6;return{r:255*[i,a,o,o,l,i][h],g:255*[l,i,i,a,o,o][h],b:255*[o,o,l,i,i,a][h],a:s}},Ca=function(n){return{h:Mc(n.h),s:Ot(n.s,0,100),l:Ot(n.l,0,100),a:Ot(n.a)}},Ma=function(n){return{h:Ct(n.h),s:Ct(n.s),l:Ct(n.l),a:Ct(n.a,3)}},_a=function(n){return Pc((t=(e=n).s,{h:e.h,s:(t*=((i=e.l)<50?i:100-i)/100)>0?2*t/(i+t)*100:0,v:i+t,a:e.a}));var e,t,i},ts=function(n){return{h:(e=_c(n)).h,s:(s=(200-(t=e.s))*(i=e.v)/100)>0&&s<200?t*i/100/(s<=100?s:200-s)*100:0,l:s/2,a:e.a};var e,t,i,s},lf=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,hf=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,cf=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,df=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,jr={string:[[function(n){var e=af.exec(n);return e?(n=e[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?Ct(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?Ct(parseInt(n.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(n){var e=cf.exec(n)||df.exec(n);return e?e[2]!==e[4]||e[4]!==e[6]?null:wa({r:Number(e[1])/(e[2]?100/255:1),g:Number(e[3])/(e[4]?100/255:1),b:Number(e[5])/(e[6]?100/255:1),a:e[7]===void 0?1:Number(e[7])/(e[8]?100:1)}):null},"rgb"],[function(n){var e=lf.exec(n)||hf.exec(n);if(!e)return null;var t,i,s=Ca({h:(t=e[1],i=e[2],i===void 0&&(i="deg"),Number(t)*(of[i]||1)),s:Number(e[3]),l:Number(e[4]),a:e[5]===void 0?1:Number(e[5])/(e[6]?100:1)});return _a(s)},"hsl"]],object:[[function(n){var e=n.r,t=n.g,i=n.b,s=n.a,r=s===void 0?1:s;return le(e)&&le(t)&&le(i)?wa({r:Number(e),g:Number(t),b:Number(i),a:Number(r)}):null},"rgb"],[function(n){var e=n.h,t=n.s,i=n.l,s=n.a,r=s===void 0?1:s;if(!le(e)||!le(t)||!le(i))return null;var o=Ca({h:Number(e),s:Number(t),l:Number(i),a:Number(r)});return _a(o)},"hsl"],[function(n){var e=n.h,t=n.s,i=n.v,s=n.a,r=s===void 0?1:s;if(!le(e)||!le(t)||!le(i))return null;var o=function(a){return{h:Mc(a.h),s:Ot(a.s,0,100),v:Ot(a.v,0,100),a:Ot(a.a)}}({h:Number(e),s:Number(t),v:Number(i),a:Number(r)});return Pc(o)},"hsv"]]},Pa=function(n,e){for(var t=0;t<e.length;t++){var i=e[t][0](n);if(i)return[i,e[t][1]]}return[null,void 0]},uf=function(n){return typeof n=="string"?Pa(n.trim(),jr.string):typeof n=="object"&&n!==null?Pa(n,jr.object):[null,void 0]},Kn=function(n,e){var t=ts(n);return{h:t.h,s:Ot(t.s+100*e,0,100),l:t.l,a:t.a}},Qn=function(n){return(299*n.r+587*n.g+114*n.b)/1e3/255},Aa=function(n,e){var t=ts(n);return{h:t.h,s:t.s,l:Ot(t.l+100*e,0,100),a:t.a}},Zr=function(){function n(e){this.parsed=uf(e)[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 Ct(Qn(this.rgba),2)},n.prototype.isDark=function(){return Qn(this.rgba)<.5},n.prototype.isLight=function(){return Qn(this.rgba)>=.5},n.prototype.toHex=function(){return e=qn(this.rgba),t=e.r,i=e.g,s=e.b,o=(r=e.a)<1?Fs(Ct(255*r)):"","#"+Fs(t)+Fs(i)+Fs(s)+o;var e,t,i,s,r,o},n.prototype.toRgb=function(){return qn(this.rgba)},n.prototype.toRgbString=function(){return e=qn(this.rgba),t=e.r,i=e.g,s=e.b,(r=e.a)<1?"rgba("+t+", "+i+", "+s+", "+r+")":"rgb("+t+", "+i+", "+s+")";var e,t,i,s,r},n.prototype.toHsl=function(){return Ma(ts(this.rgba))},n.prototype.toHslString=function(){return e=Ma(ts(this.rgba)),t=e.h,i=e.s,s=e.l,(r=e.a)<1?"hsla("+t+", "+i+"%, "+s+"%, "+r+")":"hsl("+t+", "+i+"%, "+s+"%)";var e,t,i,s,r},n.prototype.toHsv=function(){return e=_c(this.rgba),{h:Ct(e.h),s:Ct(e.s),v:Ct(e.v),a:Ct(e.a,3)};var e},n.prototype.invert=function(){return Kt({r:255-(e=this.rgba).r,g:255-e.g,b:255-e.b,a:e.a});var e},n.prototype.saturate=function(e){return e===void 0&&(e=.1),Kt(Kn(this.rgba,e))},n.prototype.desaturate=function(e){return e===void 0&&(e=.1),Kt(Kn(this.rgba,-e))},n.prototype.grayscale=function(){return Kt(Kn(this.rgba,-1))},n.prototype.lighten=function(e){return e===void 0&&(e=.1),Kt(Aa(this.rgba,e))},n.prototype.darken=function(e){return e===void 0&&(e=.1),Kt(Aa(this.rgba,-e))},n.prototype.rotate=function(e){return e===void 0&&(e=15),this.hue(this.hue()+e)},n.prototype.alpha=function(e){return typeof e=="number"?Kt({r:(t=this.rgba).r,g:t.g,b:t.b,a:e}):Ct(this.rgba.a,3);var t},n.prototype.hue=function(e){var t=ts(this.rgba);return typeof e=="number"?Kt({h:e,s:t.s,l:t.l,a:t.a}):Ct(t.h)},n.prototype.isEqual=function(e){return this.toHex()===Kt(e).toHex()},n}(),Kt=function(n){return n instanceof Zr?n:new Zr(n)},Ta=[],pf=function(n){n.forEach(function(e){Ta.indexOf(e)<0&&(e(Zr,jr),Ta.push(e))})};function ff(n,e){var t={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},i={};for(var s in t)i[t[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,l,h=i[this.toHex()];if(h)return h;if(o!=null&&o.closest){var c=this.toRgb(),d=1/0,u="black";if(!r.length)for(var p in t)r[p]=new n(t[p]).toRgb();for(var f in t){var m=(a=c,l=r[f],Math.pow(a.r-l.r,2)+Math.pow(a.g-l.g,2)+Math.pow(a.b-l.b,2));m<d&&(d=m,u=f)}return u}},e.string.push([function(o){var a=o.toLowerCase(),l=a==="transparent"?"#0000":t[a];return l?new n(l).toRgb():null},"name"])}pf([ff]);const vi=class Yi{constructor(e=16777215){this._value=null,this._components=new Float32Array(4),this._components.fill(1),this._int=16777215,this.value=e}get red(){return this._components[0]}get green(){return this._components[1]}get blue(){return this._components[2]}get alpha(){return this._components[3]}setValue(e){return this.value=e,this}set value(e){if(e instanceof Yi)this._value=this._cloneSource(e._value),this._int=e._int,this._components.set(e._components);else{if(e===null)throw new Error("Cannot set Color#value to null");(this._value===null||!this._isSourceEqual(this._value,e))&&(this._value=this._cloneSource(e),this._normalize(this._value))}}get value(){return this._value}_cloneSource(e){return typeof e=="string"||typeof e=="number"||e instanceof Number||e===null?e:Array.isArray(e)||ArrayBuffer.isView(e)?e.slice(0):typeof e=="object"&&e!==null?{...e}:e}_isSourceEqual(e,t){const i=typeof e;if(i!==typeof t)return!1;if(i==="number"||i==="string"||e instanceof Number)return e===t;if(Array.isArray(e)&&Array.isArray(t)||ArrayBuffer.isView(e)&&ArrayBuffer.isView(t))return e.length!==t.length?!1:e.every((r,o)=>r===t[o]);if(e!==null&&t!==null){const r=Object.keys(e),o=Object.keys(t);return r.length!==o.length?!1:r.every(a=>e[a]===t[a])}return e===t}toRgba(){const[e,t,i,s]=this._components;return{r:e,g:t,b:i,a:s}}toRgb(){const[e,t,i]=this._components;return{r:e,g:t,b:i}}toRgbaString(){const[e,t,i]=this.toUint8RgbArray();return`rgba(${e},${t},${i},${this.alpha})`}toUint8RgbArray(e){const[t,i,s]=this._components;return this._arrayRgb||(this._arrayRgb=[]),e||(e=this._arrayRgb),e[0]=Math.round(t*255),e[1]=Math.round(i*255),e[2]=Math.round(s*255),e}toArray(e){this._arrayRgba||(this._arrayRgba=[]),e||(e=this._arrayRgba);const[t,i,s,r]=this._components;return e[0]=t,e[1]=i,e[2]=s,e[3]=r,e}toRgbArray(e){this._arrayRgb||(this._arrayRgb=[]),e||(e=this._arrayRgb);const[t,i,s]=this._components;return e[0]=t,e[1]=i,e[2]=s,e}toNumber(){return this._int}toBgrNumber(){const[e,t,i]=this.toUint8RgbArray();return(i<<16)+(t<<8)+e}toLittleEndianNumber(){const e=this._int;return(e>>16)+(e&65280)+((e&255)<<16)}multiply(e){const[t,i,s,r]=Yi._temp.setValue(e)._components;return this._components[0]*=t,this._components[1]*=i,this._components[2]*=s,this._components[3]*=r,this._refreshInt(),this._value=null,this}premultiply(e,t=!0){return t&&(this._components[0]*=e,this._components[1]*=e,this._components[2]*=e),this._components[3]=e,this._refreshInt(),this._value=null,this}toPremultiplied(e,t=!0){if(e===1)return(255<<24)+this._int;if(e===0)return t?0:this._int;let i=this._int>>16&255,s=this._int>>8&255,r=this._int&255;return t&&(i=i*e+.5|0,s=s*e+.5|0,r=r*e+.5|0),(e*255<<24)+(i<<16)+(s<<8)+r}toHex(){const e=this._int.toString(16);return`#${"000000".substring(0,6-e.length)+e}`}toHexa(){const t=Math.round(this._components[3]*255).toString(16);return this.toHex()+"00".substring(0,2-t.length)+t}setAlpha(e){return this._components[3]=this._clamp(e),this}_normalize(e){let t,i,s,r;if((typeof e=="number"||e instanceof Number)&&e>=0&&e<=16777215){const o=e;t=(o>>16&255)/255,i=(o>>8&255)/255,s=(o&255)/255,r=1}else if((Array.isArray(e)||e instanceof Float32Array)&&e.length>=3&&e.length<=4)e=this._clamp(e),[t,i,s,r=1]=e;else if((e instanceof Uint8Array||e instanceof Uint8ClampedArray)&&e.length>=3&&e.length<=4)e=this._clamp(e,0,255),[t,i,s,r=255]=e,t/=255,i/=255,s/=255,r/=255;else if(typeof e=="string"||typeof e=="object"){if(typeof e=="string"){const a=Yi.HEX_PATTERN.exec(e);a&&(e=`#${a[2]}`)}const o=Kt(e);o.isValid()&&({r:t,g:i,b:s,a:r}=o.rgba,t/=255,i/=255,s/=255)}if(t!==void 0)this._components[0]=t,this._components[1]=i,this._components[2]=s,this._components[3]=r,this._refreshInt();else throw new Error(`Unable to convert color ${e}`)}_refreshInt(){this._clamp(this._components);const[e,t,i]=this._components;this._int=(e*255<<16)+(t*255<<8)+(i*255|0)}_clamp(e,t=0,i=1){return typeof e=="number"?Math.min(Math.max(e,t),i):(e.forEach((s,r)=>{e[r]=Math.min(Math.max(s,t),i)}),e)}static isColorLike(e){return typeof e=="number"||typeof e=="string"||e instanceof Number||e instanceof Yi||Array.isArray(e)||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Float32Array||e.r!==void 0&&e.g!==void 0&&e.b!==void 0||e.r!==void 0&&e.g!==void 0&&e.b!==void 0&&e.a!==void 0||e.h!==void 0&&e.s!==void 0&&e.l!==void 0||e.h!==void 0&&e.s!==void 0&&e.l!==void 0&&e.a!==void 0||e.h!==void 0&&e.s!==void 0&&e.v!==void 0||e.h!==void 0&&e.s!==void 0&&e.v!==void 0&&e.a!==void 0}};vi.shared=new vi;vi._temp=new vi;vi.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let ht=vi;const gf={cullArea:null,cullable:!1,cullableChildren:!0};let Jn=0;const Ra=500;function lt(...n){Jn!==Ra&&(Jn++,Jn===Ra?console.warn("PixiJS Warning: too many warnings, no more warnings will be reported to the console by PixiJS."):console.warn("PixiJS Warning: ",...n))}const _s={_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 mf{constructor(e,t){this._pool=[],this._count=0,this._index=0,this._classType=e,t&&this.prepopulate(t)}prepopulate(e){for(let t=0;t<e;t++)this._pool[this._index++]=new this._classType;this._count+=e}get(e){var i;let t;return this._index>0?t=this._pool[--this._index]:(t=new this._classType,this._count++),(i=t.init)==null||i.call(t,e),t}return(e){var t;(t=e.reset)==null||t.call(e),this._pool[this._index++]=e}get totalSize(){return this._count}get totalFree(){return this._index}get totalUsed(){return this._count-this._index}clear(){if(this._pool.length>0&&this._pool[0].destroy)for(let e=0;e<this._index;e++)this._pool[e].destroy();this._pool.length=0,this._count=0,this._index=0}}class yf{constructor(){this._poolsByClass=new Map}prepopulate(e,t){this.getPool(e).prepopulate(t)}get(e,t){return this.getPool(e).get(t)}return(e){this.getPool(e.constructor).return(e)}getPool(e){return this._poolsByClass.has(e)||this._poolsByClass.set(e,new mf(e)),this._poolsByClass.get(e)}stats(){const e={};return this._poolsByClass.forEach(t=>{const i=e[t._classType.name]?t._classType.name+t._classType.ID:t._classType.name;e[i]={free:t.totalFree,used:t.totalUsed,size:t.totalSize}}),e}clear(){this._poolsByClass.forEach(e=>e.clear()),this._poolsByClass.clear()}}const Ft=new yf;_s.register(Ft);const xf={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){X("v8.6.0","cacheAsBitmap is deprecated, use cacheAsTexture instead."),this.cacheAsTexture(n)}};function Sf(n,e,t){const i=n.length;let s;if(e>=i||t===0)return;t=e+t>i?i-e:t;const r=i-t;for(s=e;s<r;++s)n[s]=n[s+t];n.length=r}const bf={allowChildren:!0,removeChildren(n=0,e){var r;const t=e??this.children.length,i=t-n,s=[];if(i>0&&i<=t){for(let a=t-1;a>=n;a--){const l=this.children[a];l&&(s.push(l),l.parent=null)}Sf(this.children,n,t);const o=this.renderGroup||this.parentRenderGroup;o&&o.removeChildren(s);for(let a=0;a<s.length;++a){const l=s[a];(r=l.parentRenderLayer)==null||r.detach(l),this.emit("childRemoved",l,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 e=this.getChildAt(n);return this.removeChild(e)},getChildAt(n){if(n<0||n>=this.children.length)throw new Error(`getChildAt: Index (${n}) does not exist.`);return this.children[n]},setChildIndex(n,e){if(e<0||e>=this.children.length)throw new Error(`The index ${e} supplied is out of bounds ${this.children.length}`);this.getChildIndex(n),this.addChildAt(n,e)},getChildIndex(n){const e=this.children.indexOf(n);if(e===-1)throw new Error("The supplied Container must be a child of the caller");return e},addChildAt(n,e){this.allowChildren||X(tt,"addChildAt: Only Containers will be allowed to add children in v8.0.0");const{children:t}=this;if(e<0||e>t.length)throw new Error(`${n}addChildAt: The index ${e} supplied is out of bounds ${t.length}`);if(n.parent){const s=n.parent.children.indexOf(n);if(n.parent===this&&s===e)return n;s!==-1&&n.parent.children.splice(s,1)}e===t.length?t.push(n):t.splice(e,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,e),n.emit("added",this),n},swapChildren(n,e){if(n===e)return;const t=this.getChildIndex(n),i=this.getChildIndex(e);this.children[t]=e,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(e=>this.reparentChildAt(e,this.children.length)),n[0])},reparentChildAt(n,e){if(n.parent===this)return this.setChildIndex(n,e),n;const t=n.worldTransform.clone();n.removeFromParent(),this.addChildAt(n,e);const i=this.worldTransform.clone();return i.invert(),t.prepend(i),n.setFromMatrix(t),n},replaceChild(n,e){n.updateLocalTransform(),this.addChildAt(e,this.getChildIndex(n)),e.setFromMatrix(n.localTransform),e.updateLocalTransform(),this.removeChild(n)}},vf={collectRenderables(n,e,t){this.parentRenderLayer&&this.parentRenderLayer!==t||this.globalDisplayStatus<7||!this.includeInBuild||(this.sortableChildren&&this.sortChildren(),this.isSimple?this.collectRenderablesSimple(n,e,t):this.renderGroup?e.renderPipes.renderGroup.addRenderGroup(this.renderGroup,n):this.collectRenderablesWithEffects(n,e,t))},collectRenderablesSimple(n,e,t){const i=this.children,s=i.length;for(let r=0;r<s;r++)i[r].collectRenderables(n,e,t)},collectRenderablesWithEffects(n,e,t){const{renderPipes:i}=e;for(let s=0;s<this.effects.length;s++){const r=this.effects[s];i[r.pipe].push(r,this,n)}this.collectRenderablesSimple(n,e,t);for(let s=this.effects.length-1;s>=0;s--){const r=this.effects[s];i[r.pipe].pop(r,this,n)}}};class Ea{constructor(){this.pipe="filter",this.priority=1}destroy(){for(let e=0;e<this.filters.length;e++)this.filters[e].destroy();this.filters=null,this.filterArea=null}}class wf{constructor(){this._effectClasses=[],this._tests=[],this._initialized=!1}init(){this._initialized||(this._initialized=!0,this._effectClasses.forEach(e=>{this.add({test:e.test,maskClass:e})}))}add(e){this._tests.push(e)}getMaskEffect(e){this._initialized||this.init();for(let t=0;t<this._tests.length;t++){const i=this._tests[t];if(i.test(e))return Ft.get(i.maskClass,e)}return e}returnMaskEffect(e){Ft.return(e)}}const qr=new wf;Q.handleByList(B.MaskEffect,qr._effectClasses);const Cf={_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((t,i)=>t.priority-i.priority),this._markStructureAsChanged(),this._updateIsSimple())},removeEffect(n){const e=this.effects.indexOf(n);e!==-1&&(this.effects.splice(e,1),this._markStructureAsChanged(),this._updateIsSimple())},set mask(n){const e=this._maskEffect;(e==null?void 0:e.mask)!==n&&(e&&(this.removeEffect(e),qr.returnMaskEffect(e),this._maskEffect=null),n!=null&&(this._maskEffect=qr.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 e=this._filterEffect||(this._filterEffect=new Ea);n=n;const t=(n==null?void 0:n.length)>0,i=((r=e.filters)==null?void 0:r.length)>0,s=t!==i;n=Array.isArray(n)?n.slice(0):n,e.filters=Object.freeze(n),s&&(t?this.addEffect(e):(this.removeEffect(e),e.filters=n??null))},get filters(){var n;return(n=this._filterEffect)==null?void 0:n.filters},set filterArea(n){this._filterEffect||(this._filterEffect=new Ea),this._filterEffect.filterArea=n},get filterArea(){var n;return(n=this._filterEffect)==null?void 0:n.filterArea}},Mf={label:null,get name(){return X(tt,"Container.name property has been removed, use Container.label instead"),this.label},set name(n){X(tt,"Container.name property has been removed, use Container.label instead"),this.label=n},getChildByName(n,e=!1){return this.getChildByLabel(n,e)},getChildByLabel(n,e=!1){const t=this.children;for(let i=0;i<t.length;i++){const s=t[i];if(s.label===n||n instanceof RegExp&&n.test(s.label))return s}if(e)for(let i=0;i<t.length;i++){const r=t[i].getChildByLabel(n,!0);if(r)return r}return null},getChildrenByLabel(n,e=!1,t=[]){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))&&t.push(r)}if(e)for(let s=0;s<i.length;s++)i[s].getChildrenByLabel(n,!0,t);return t}},Rt=Ft.getPool(H),fe=Ft.getPool(Wt),_f=new H,Pf={getFastGlobalBounds(n,e){e||(e=new Wt),e.clear(),this._getGlobalBoundsRecursive(!!n,e,this.parentRenderLayer),e.isValid||e.set(0,0,0,0);const t=this.renderGroup||this.parentRenderGroup;return e.applyMatrix(t.worldTransform),e},_getGlobalBoundsRecursive(n,e,t){let i=e;if(n&&this.parentRenderLayer&&this.parentRenderLayer!==t||this.localDisplayStatus!==7||!this.measurable)return;const s=!!this.effects.length;if((this.renderGroup||s)&&(i=fe.get().clear()),this.boundsArea)e.addRect(this.boundsArea,this.worldTransform);else{if(this.renderPipeId){const o=this.bounds;i.addFrame(o.minX,o.minY,o.maxX,o.maxY,this.groupTransform)}const r=this.children;for(let o=0;o<r.length;o++)r[o]._getGlobalBoundsRecursive(n,i,t)}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(_f).invert()),e.addBounds(i),fe.return(i)}else this.renderGroup&&(e.addBounds(i,this.relativeGroupTransform),fe.return(i))}};function Ac(n,e,t){t.clear();let i,s;return n.parent?e?i=n.parent.worldTransform:(s=Rt.get().identity(),i=Eo(n,s)):i=H.IDENTITY,Tc(n,t,i,e),s&&Rt.return(s),t.isValid||t.set(0,0,0,0),t}function Tc(n,e,t,i){var a,l;if(!n.visible||!n.measurable)return;let s;i?s=n.worldTransform:(n.updateLocalTransform(),s=Rt.get(),s.appendFrom(n.localTransform,t));const r=e,o=!!n.effects.length;if(o&&(e=fe.get().clear()),n.boundsArea)e.addRect(n.boundsArea,s);else{const h=n.bounds;h&&!h.isEmpty()&&(e.matrix=s,e.addBounds(h));for(let c=0;c<n.children.length;c++)Tc(n.children[c],e,s,i)}if(o){for(let h=0;h<n.effects.length;h++)(l=(a=n.effects[h]).addBounds)==null||l.call(a,e);r.addBounds(e,H.IDENTITY),fe.return(e)}i||Rt.return(s)}function Eo(n,e){const t=n.parent;return t&&(Eo(t,e),t.updateLocalTransform(),e.append(t.localTransform)),e}function ko(n,e){if(n===16777215||!e)return e;if(e===16777215||!n)return n;const t=n>>16&255,i=n>>8&255,s=n&255,r=e>>16&255,o=e>>8&255,a=e&255,l=t*r/255|0,h=i*o/255|0,c=s*a/255|0;return(l<<16)+(h<<8)+c}const ka=16777215;function Ia(n,e){return n===ka?e:e===ka?n:ko(n,e)}function es(n){return((n&255)<<16)+(n&65280)+(n>>16&255)}const Af={getGlobalAlpha(n){if(n)return this.renderGroup?this.renderGroup.worldAlpha:this.parentRenderGroup?this.parentRenderGroup.worldAlpha*this.alpha:this.alpha;let e=this.alpha,t=this.parent;for(;t;)e*=t.alpha,t=t.parent;return e},getGlobalTransform(n=new H,e){if(e)return n.copyFrom(this.worldTransform);this.updateLocalTransform();const t=Eo(this,Rt.get().identity());return n.appendFrom(this.localTransform,t),Rt.return(t),n},getGlobalTint(n){if(n)return this.renderGroup?es(this.renderGroup.worldColor):this.parentRenderGroup?es(Ia(this.localColor,this.parentRenderGroup.worldColor)):this.tint;let e=this.localColor,t=this.parent;for(;t;)e=Ia(e,t.localColor),t=t.parent;return es(e)}};function Rc(n,e,t){return e.clear(),t||(t=H.IDENTITY),Ec(n,e,t,n,!0),e.isValid||e.set(0,0,0,0),e}function Ec(n,e,t,i,s){var l,h;let r;if(s)r=Rt.get(),r=t.copyTo(r);else{if(!n.visible||!n.measurable)return;n.updateLocalTransform();const c=n.localTransform;r=Rt.get(),r.appendFrom(c,t)}const o=e,a=!!n.effects.length;if(a&&(e=fe.get().clear()),n.boundsArea)e.addRect(n.boundsArea,r);else{n.renderPipeId&&(e.matrix=r,e.addBounds(n.bounds));const c=n.children;for(let d=0;d<c.length;d++)Ec(c[d],e,r,i,!1)}if(a){for(let c=0;c<n.effects.length;c++)(h=(l=n.effects[c]).addLocalBounds)==null||h.call(l,e,i);o.addBounds(e,H.IDENTITY),fe.return(e)}Rt.return(r)}function kc(n,e){const t=n.children;for(let i=0;i<t.length;i++){const s=t[i],r=s.uid,o=(s._didViewChangeTick&65535)<<16|s._didContainerChangeTick&65535,a=e.index;(e.data[a]!==r||e.data[a+1]!==o)&&(e.data[e.index]=r,e.data[e.index+1]=o,e.didChange=!0),e.index=a+2,s.children.length&&kc(s,e)}return e.didChange}const Tf=new H,Rf={_localBoundsCacheId:-1,_localBoundsCacheData:null,_setWidth(n,e){const t=Math.sign(this.scale.x)||1;e!==0?this.scale.x=n/e*t:this.scale.x=t},_setHeight(n,e){const t=Math.sign(this.scale.y)||1;e!==0?this.scale.y=n/e*t:this.scale.y=t},getLocalBounds(){this._localBoundsCacheData||(this._localBoundsCacheData={data:[],index:1,didChange:!1,localBounds:new Wt});const n=this._localBoundsCacheData;return n.index=1,n.didChange=!1,n.data[0]!==this._didViewChangeTick&&(n.didChange=!0,n.data[0]=this._didViewChangeTick),kc(this,n),n.didChange&&Rc(this,n.localBounds,Tf),n.localBounds},getBounds(n,e){return Ac(this,n,e||new Wt)}},Ef={_onRender:null,set onRender(n){const e=this.renderGroup||this.parentRenderGroup;if(!n){this._onRender&&(e==null||e.removeOnRender(this)),this._onRender=null;return}this._onRender||e==null||e.addOnRender(this),this._onRender=n},get onRender(){return this._onRender}},kf={_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(If))}};function If(n,e){return n._zIndex-e._zIndex}const Df={getGlobalPosition(n=new it,e=!1){return this.parent?this.parent.toGlobal(this._position,n,e):(n.x=this._position.x,n.y=this._position.y),n},toGlobal(n,e,t=!1){const i=this.getGlobalTransform(Rt.get(),t);return e=i.apply(n,e),Rt.return(i),e},toLocal(n,e,t,i){e&&(n=e.toGlobal(n,t,i));const s=this.getGlobalTransform(Rt.get(),i);return t=s.applyInverse(n,t),Rt.return(s),t}};class Io{constructor(){this.uid=ft("instructionSet"),this.instructions=[],this.instructionSize=0,this.renderables=[],this.gcTick=0}reset(){this.instructionSize=0}destroy(){this.instructions.length=0,this.renderables.length=0,this.renderPipes=null,this.gcTick=0}add(e){this.instructions[this.instructionSize++]=e}log(){this.instructions.length=this.instructionSize,console.table(this.instructions,["type","action"])}}let Ff=0;class Bf{constructor(e){this._poolKeyHash=Object.create(null),this._texturePool={},this.textureOptions=e||{},this.enableFullScreen=!1,this.textureStyle=new bi(this.textureOptions)}createTexture(e,t,i){const s=new Ut({...this.textureOptions,width:e,height:t,resolution:1,antialias:i,autoGarbageCollect:!1});return new U({source:s,label:`texturePool_${Ff++}`})}getOptimalTexture(e,t,i=1,s){let r=Math.ceil(e*i-1e-6),o=Math.ceil(t*i-1e-6);r=Si(r),o=Si(o);const a=(r<<17)+(o<<1)+(s?1:0);this._texturePool[a]||(this._texturePool[a]=[]);let l=this._texturePool[a].pop();return l||(l=this.createTexture(r,o,s)),l.source._resolution=i,l.source.width=r/i,l.source.height=o/i,l.source.pixelWidth=r,l.source.pixelHeight=o,l.frame.x=0,l.frame.y=0,l.frame.width=e,l.frame.height=t,l.updateUvs(),this._poolKeyHash[l.uid]=a,l}getSameSizeTexture(e,t=!1){const i=e.source;return this.getOptimalTexture(e.width,e.height,i._resolution,t)}returnTexture(e,t=!1){const i=this._poolKeyHash[e.uid];t&&(e.source.style=this.textureStyle),this._texturePool[i].push(e)}clear(e){if(e=e!==!1,e)for(const t in this._texturePool){const i=this._texturePool[t];if(i)for(let s=0;s<i.length;s++)i[s].destroy(!0)}this._texturePool={}}}const Rn=new Bf;_s.register(Rn);class Lf{constructor(){this.renderPipeId="renderGroup",this.root=null,this.canBundle=!1,this.renderGroupParent=null,this.renderGroupChildren=[],this.worldTransform=new H,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 Io,this._onRenderContainers=[],this.textureNeedsUpdate=!0,this.isCachedAsTexture=!1,this._matrixDirty=7}init(e){this.root=e,e._onRender&&this.addOnRender(e),e.didChange=!0;const t=e.children;for(let i=0;i<t.length;i++){const s=t[i];s._updateFlags=15,this.addChild(s)}}enableCacheAsTexture(e={}){this.textureOptions=e,this.isCachedAsTexture=!0,this.textureNeedsUpdate=!0}disableCacheAsTexture(){this.isCachedAsTexture=!1,this.texture&&(Rn.returnTexture(this.texture,!0),this.texture=null)}updateCacheTexture(){this.textureNeedsUpdate=!0;const e=this._parentCacheAsTextureRenderGroup;e&&!e.textureNeedsUpdate&&e.updateCacheTexture()}reset(){this.renderGroupChildren.length=0;for(const e in this.childrenToUpdate){const t=this.childrenToUpdate[e];t.list.fill(null),t.index=0}this.childrenRenderablesToUpdate.index=0,this.childrenRenderablesToUpdate.list.fill(null),this.root=null,this.updateTick=0,this.structureDidChange=!0,this._onRenderContainers.length=0,this.renderGroupParent=null,this.disableCacheAsTexture()}get localTransform(){return this.root.localTransform}addRenderGroupChild(e){e.renderGroupParent&&e.renderGroupParent._removeRenderGroupChild(e),e.renderGroupParent=this,this.renderGroupChildren.push(e)}_removeRenderGroupChild(e){const t=this.renderGroupChildren.indexOf(e);t>-1&&this.renderGroupChildren.splice(t,1),e.renderGroupParent=null}addChild(e){if(this.structureDidChange=!0,e.parentRenderGroup=this,e.updateTick=-1,e.parent===this.root?e.relativeRenderGroupDepth=1:e.relativeRenderGroupDepth=e.parent.relativeRenderGroupDepth+1,e.didChange=!0,this.onChildUpdate(e),e.renderGroup){this.addRenderGroupChild(e.renderGroup);return}e._onRender&&this.addOnRender(e);const t=e.children;for(let i=0;i<t.length;i++)this.addChild(t[i])}removeChild(e){if(this.structureDidChange=!0,e._onRender&&(e.renderGroup||this.removeOnRender(e)),e.parentRenderGroup=null,e.renderGroup){this._removeRenderGroupChild(e.renderGroup);return}const t=e.children;for(let i=0;i<t.length;i++)this.removeChild(t[i])}removeChildren(e){for(let t=0;t<e.length;t++)this.removeChild(e[t])}onChildUpdate(e){let t=this.childrenToUpdate[e.relativeRenderGroupDepth];t||(t=this.childrenToUpdate[e.relativeRenderGroupDepth]={index:0,list:[]}),t.list[t.index++]=e}updateRenderable(e){e.globalDisplayStatus<7||(this.instructionSet.renderPipes[e.renderPipeId].updateRenderable(e),e.didViewUpdate=!1)}onChildViewUpdate(e){this.childrenRenderablesToUpdate.list[this.childrenRenderablesToUpdate.index++]=e}get isRenderable(){return this.root.localDisplayStatus===7&&this.worldAlpha>0}addOnRender(e){this._onRenderContainers.push(e)}removeOnRender(e){this._onRenderContainers.splice(this._onRenderContainers.indexOf(e),1)}runOnRender(e){for(let t=0;t<this._onRenderContainers.length;t++)this._onRenderContainers[t]._onRender(e)}destroy(){this.disableCacheAsTexture(),this.renderGroupParent=null,this.root=null,this.childrenRenderablesToUpdate=null,this.childrenToUpdate=null,this.renderGroupChildren=null,this._onRenderContainers=null,this.instructionSet=null}getChildren(e=[]){const t=this.root.children;for(let i=0;i<t.length;i++)this._getChildren(t[i],e);return e}_getChildren(e,t=[]){if(t.push(e),e.renderGroup)return t;const i=e.children;for(let s=0;s<i.length;s++)this._getChildren(i[s],t);return t}invalidateMatrices(){this._matrixDirty=7}get inverseWorldTransform(){return this._matrixDirty&1?(this._matrixDirty&=-2,this._inverseWorldTransform||(this._inverseWorldTransform=new H),this._inverseWorldTransform.copyFrom(this.worldTransform).invert()):this._inverseWorldTransform}get textureOffsetInverseTransform(){return this._matrixDirty&2?(this._matrixDirty&=-3,this._textureOffsetInverseTransform||(this._textureOffsetInverseTransform=new H),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 e=this._parentCacheAsTextureRenderGroup;return e?(this._inverseParentTextureTransform||(this._inverseParentTextureTransform=new H),this._inverseParentTextureTransform.copyFrom(this.worldTransform).prepend(e.inverseWorldTransform).translate(-e._textureBounds.x,-e._textureBounds.y)):this.worldTransform}get cacheToLocalTransform(){return this.isCachedAsTexture?this.textureOffsetInverseTransform:this._parentCacheAsTextureRenderGroup?this._parentCacheAsTextureRenderGroup.textureOffsetInverseTransform:null}}function zf(n,e,t={}){for(const i in e)!t[i]&&e[i]!==void 0&&(n[i]=e[i])}const tr=new pt(null),Bs=new pt(null),er=new pt(null,1,1),Ls=new pt(null),Da=1,Of=2,ir=4;class O extends ae{constructor(e={}){var t,i;super(),this.uid=ft("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 H,this.relativeGroupTransform=new H,this.groupTransform=this.relativeGroupTransform,this.destroyed=!1,this._position=new pt(this,0,0),this._scale=er,this._pivot=Bs,this._origin=Ls,this._skew=tr,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=[],zf(this,e,{children:!0,parent:!0,effects:!0}),(t=e.children)==null||t.forEach(s=>this.addChild(s)),(i=e.parent)==null||i.addChild(this)}static mixin(e){X("8.8.0","Container.mixin is deprecated, please use extensions.mixin instead."),Q.mixin(O,e)}set _didChangeId(e){this._didViewChangeTick=e>>12&4095,this._didContainerChangeTick=e&4095}get _didChangeId(){return this._didContainerChangeTick&4095|(this._didViewChangeTick&4095)<<12}addChild(...e){if(this.allowChildren||X(tt,"addChild: Only Containers will be allowed to add children in v8.0.0"),e.length>1){for(let s=0;s<e.length;s++)this.addChild(e[s]);return e[0]}const t=e[0],i=this.renderGroup||this.parentRenderGroup;return t.parent===this?(this.children.splice(this.children.indexOf(t),1),this.children.push(t),i&&(i.structureDidChange=!0),t):(t.parent&&t.parent.removeChild(t),this.children.push(t),this.sortableChildren&&(this.sortDirty=!0),t.parent=this,t.didChange=!0,t._updateFlags=15,i&&i.addChild(t),this.emit("childAdded",t,this,this.children.length-1),t.emit("added",this),this._didViewChangeTick++,t._zIndex!==0&&t.depthOfChildModified(),t)}removeChild(...e){if(e.length>1){for(let s=0;s<e.length;s++)this.removeChild(e[s]);return e[0]}const t=e[0],i=this.children.indexOf(t);return i>-1&&(this._didViewChangeTick++,this.children.splice(i,1),this.renderGroup?this.renderGroup.removeChild(t):this.parentRenderGroup&&this.parentRenderGroup.removeChild(t),t.parentRenderLayer&&t.parentRenderLayer.detach(t),t.parent=null,this.emit("childRemoved",t,this,i),t.emit("removed",this)),t}_onUpdate(e){e&&e===this._skew&&this._updateSkew(),this._didContainerChangeTick++,!this.didChange&&(this.didChange=!0,this.parentRenderGroup&&this.parentRenderGroup.onChildUpdate(this))}set isRenderGroup(e){!!this.renderGroup!==e&&(e?this.enableRenderGroup():this.disableRenderGroup())}get isRenderGroup(){return!!this.renderGroup}enableRenderGroup(){if(this.renderGroup)return;const e=this.parentRenderGroup;e==null||e.removeChild(this),this.renderGroup=Ft.get(Lf,this),this.groupTransform=H.IDENTITY,e==null||e.addChild(this),this._updateIsSimple()}disableRenderGroup(){if(!this.renderGroup)return;const e=this.parentRenderGroup;e==null||e.removeChild(this),Ft.return(this.renderGroup),this.renderGroup=null,this.groupTransform=this.relativeGroupTransform,e==null||e.addChild(this),this._updateIsSimple()}_updateIsSimple(){this.isSimple=!this.renderGroup&&this.effects.length===0}get worldTransform(){return this._worldTransform||(this._worldTransform=new H),this.renderGroup?this._worldTransform.copyFrom(this.renderGroup.worldTransform):this.parentRenderGroup&&this._worldTransform.appendFrom(this.relativeGroupTransform,this.parentRenderGroup.worldTransform),this._worldTransform}get x(){return this._position.x}set x(e){this._position.x=e}get y(){return this._position.y}set y(e){this._position.y=e}get position(){return this._position}set position(e){this._position.copyFrom(e)}get rotation(){return this._rotation}set rotation(e){this._rotation!==e&&(this._rotation=e,this._onUpdate(this._skew))}get angle(){return this.rotation*Kp}set angle(e){this.rotation=e*Qp}get pivot(){return this._pivot===Bs&&(this._pivot=new pt(this,0,0)),this._pivot}set pivot(e){this._pivot===Bs&&(this._pivot=new pt(this,0,0),this._origin!==Ls&<("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof e=="number"?this._pivot.set(e):this._pivot.copyFrom(e)}get skew(){return this._skew===tr&&(this._skew=new pt(this,0,0)),this._skew}set skew(e){this._skew===tr&&(this._skew=new pt(this,0,0)),this._skew.copyFrom(e)}get scale(){return this._scale===er&&(this._scale=new pt(this,1,1)),this._scale}set scale(e){this._scale===er&&(this._scale=new pt(this,0,0)),typeof e=="string"&&(e=parseFloat(e)),typeof e=="number"?this._scale.set(e):this._scale.copyFrom(e)}get origin(){return this._origin===Ls&&(this._origin=new pt(this,0,0)),this._origin}set origin(e){this._origin===Ls&&(this._origin=new pt(this,0,0),this._pivot!==Bs&<("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof e=="number"?this._origin.set(e):this._origin.copyFrom(e)}get width(){return Math.abs(this.scale.x*this.getLocalBounds().width)}set width(e){const t=this.getLocalBounds().width;this._setWidth(e,t)}get height(){return Math.abs(this.scale.y*this.getLocalBounds().height)}set height(e){const t=this.getLocalBounds().height;this._setHeight(e,t)}getSize(e){e||(e={});const t=this.getLocalBounds();return e.width=Math.abs(this.scale.x*t.width),e.height=Math.abs(this.scale.y*t.height),e}setSize(e,t){const i=this.getLocalBounds();typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,i.width),t!==void 0&&this._setHeight(t,i.height)}_updateSkew(){const e=this._rotation,t=this._skew;this._cx=Math.cos(e+t._y),this._sx=Math.sin(e+t._y),this._cy=-Math.sin(e-t._x),this._sy=Math.cos(e-t._x)}updateTransform(e){return this.position.set(typeof e.x=="number"?e.x:this.position.x,typeof e.y=="number"?e.y:this.position.y),this.scale.set(typeof e.scaleX=="number"?e.scaleX||1:this.scale.x,typeof e.scaleY=="number"?e.scaleY||1:this.scale.y),this.rotation=typeof e.rotation=="number"?e.rotation:this.rotation,this.skew.set(typeof e.skewX=="number"?e.skewX:this.skew.x,typeof e.skewY=="number"?e.skewY:this.skew.y),this.pivot.set(typeof e.pivotX=="number"?e.pivotX:this.pivot.x,typeof e.pivotY=="number"?e.pivotY:this.pivot.y),this.origin.set(typeof e.originX=="number"?e.originX:this.origin.x,typeof e.originY=="number"?e.originY:this.origin.y),this}setFromMatrix(e){e.decompose(this)}updateLocalTransform(){const e=this._didContainerChangeTick;if(this._didLocalTransformChangeId===e)return;this._didLocalTransformChangeId=e;const t=this.localTransform,i=this._scale,s=this._pivot,r=this._origin,o=this._position,a=i._x,l=i._y,h=s._x,c=s._y,d=-r._x,u=-r._y;t.a=this._cx*a,t.b=this._sx*a,t.c=this._cy*l,t.d=this._sy*l,t.tx=o._x-(h*t.a+c*t.c)+(d*t.a+u*t.c)-d,t.ty=o._y-(h*t.b+c*t.d)+(d*t.b+u*t.d)-u}set alpha(e){e!==this.localAlpha&&(this.localAlpha=e,this._updateFlags|=Da,this._onUpdate())}get alpha(){return this.localAlpha}set tint(e){const i=ht.shared.setValue(e??16777215).toBgrNumber();i!==this.localColor&&(this.localColor=i,this._updateFlags|=Da,this._onUpdate())}get tint(){return es(this.localColor)}set blendMode(e){this.localBlendMode!==e&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=Of,this.localBlendMode=e,this._onUpdate())}get blendMode(){return this.localBlendMode}get visible(){return!!(this.localDisplayStatus&2)}set visible(e){const t=e?2:0;(this.localDisplayStatus&2)!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=ir,this.localDisplayStatus^=2,this._onUpdate())}get culled(){return!(this.localDisplayStatus&4)}set culled(e){const t=e?0:4;(this.localDisplayStatus&4)!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=ir,this.localDisplayStatus^=4,this._onUpdate())}get renderable(){return!!(this.localDisplayStatus&1)}set renderable(e){const t=e?1:0;(this.localDisplayStatus&1)!==t&&(this._updateFlags|=ir,this.localDisplayStatus^=1,this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._onUpdate())}get isRenderable(){return this.localDisplayStatus===7&&this.groupAlpha>0}destroy(e=!1){var s;if(this.destroyed)return;this.destroyed=!0;let t;if(this.children.length&&(t=this.removeChildren(0,this.children.length)),this.removeFromParent(),this.parent=null,this._maskEffect=null,this._filterEffect=null,this.effects=null,this._position=null,this._scale=null,this._pivot=null,this._origin=null,this._skew=null,this.emit("destroyed",this),this.removeAllListeners(),(typeof e=="boolean"?e:e==null?void 0:e.children)&&t)for(let r=0;r<t.length;++r)t[r].destroy(e);(s=this.renderGroup)==null||s.destroy(),this.renderGroup=null}}Q.mixin(O,bf,Pf,Df,Ef,Rf,Cf,Mf,kf,gf,xf,Af,vf);class Ti extends O{constructor(e){super(e),this.canBundle=!0,this.allowChildren=!1,this._roundPixels=0,this._lastUsed=-1,this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this._bounds=new Wt(0,1,0,0),this._boundsDirty=!0,this.autoGarbageCollect=e.autoGarbageCollect??!0}get bounds(){return this._boundsDirty?(this.updateBounds(),this._boundsDirty=!1,this._bounds):this._bounds}get roundPixels(){return!!this._roundPixels}set roundPixels(e){this._roundPixels=e?1:0}containsPoint(e){const t=this.bounds,{x:i,y:s}=e;return i>=t.minX&&i<=t.maxX&&s>=t.minY&&s<=t.maxY}onViewUpdate(){if(this._didViewChangeTick++,this._boundsDirty=!0,this.didViewUpdate)return;this.didViewUpdate=!0;const e=this.renderGroup||this.parentRenderGroup;e&&e.onChildViewUpdate(this)}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null),this.onViewUpdate()}destroy(e){this.unload(),super.destroy(e),this._bounds=null}collectRenderablesSimple(e,t,i){const{renderPipes:s}=t;s.blendMode.pushBlendMode(this,this.groupBlendMode,e);const o=s[this.renderPipeId];o!=null&&o.addRenderable&&o.addRenderable(this,e),this.didViewUpdate=!1;const a=this.children,l=a.length;for(let h=0;h<l;h++)a[h].collectRenderables(e,t,i);s.blendMode.popBlendMode(e)}}class re extends Ti{constructor(e=U.EMPTY){e instanceof U&&(e={texture:e});const{texture:t=U.EMPTY,anchor:i,roundPixels:s,width:r,height:o,...a}=e;super({label:"Sprite",...a}),this.renderPipeId="sprite",this.batched=!0,this._visualBounds={minX:0,maxX:1,minY:0,maxY:0},this._anchor=new pt({_onUpdate:()=>{this.onViewUpdate()}}),i?this.anchor=i:t.defaultAnchor&&(this.anchor=t.defaultAnchor),this.texture=t,this.allowChildren=!1,this.roundPixels=s??!1,r!==void 0&&(this.width=r),o!==void 0&&(this.height=o)}static from(e,t=!1){return e instanceof U?new re(e):new re(U.from(e,t))}set texture(e){e||(e=U.EMPTY);const t=this._texture;t!==e&&(t&&t.dynamic&&t.off("update",this.onViewUpdate,this),e.dynamic&&e.on("update",this.onViewUpdate,this),this._texture=e,this._width&&this._setWidth(this._width,this._texture.orig.width),this._height&&this._setHeight(this._height,this._texture.orig.height),this.onViewUpdate())}get texture(){return this._texture}get visualBounds(){return Cc(this._visualBounds,this._anchor,this._texture),this._visualBounds}get sourceBounds(){return X("8.6.1","Sprite.sourceBounds is deprecated, use visualBounds instead."),this.visualBounds}updateBounds(){const e=this._anchor,t=this._texture,i=this._bounds,{width:s,height:r}=t.orig;i.minX=-e._x*s,i.maxX=i.minX+s,i.minY=-e._y*r,i.maxY=i.minY+r}destroy(e=!1){if(super.destroy(e),typeof e=="boolean"?e:e==null?void 0:e.texture){const i=typeof e=="boolean"?e:e==null?void 0:e.textureSource;this._texture.destroy(i)}this._texture=null,this._visualBounds=null,this._bounds=null,this._anchor=null}get anchor(){return this._anchor}set anchor(e){typeof e=="number"?this._anchor.set(e):this._anchor.copyFrom(e)}get width(){return Math.abs(this.scale.x)*this._texture.orig.width}set width(e){this._setWidth(e,this._texture.orig.width),this._width=e}get height(){return Math.abs(this.scale.y)*this._texture.orig.height}set height(e){this._setHeight(e,this._texture.orig.height),this._height=e}getSize(e){return e||(e={}),e.width=Math.abs(this.scale.x)*this._texture.orig.width,e.height=Math.abs(this.scale.y)*this._texture.orig.height,e}setSize(e,t){typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,this._texture.orig.width),t!==void 0&&this._setHeight(t,this._texture.orig.height)}}const Wf=new Wt;function Ic(n,e,t){const i=Wf;n.measurable=!0,Ac(n,t,i),e.addBoundsMask(i),n.measurable=!1}function Dc(n,e,t){const i=fe.get();n.measurable=!0;const s=Rt.get().identity(),r=Fc(n,t,s);Rc(n,i,r),n.measurable=!1,e.addBoundsMask(i),Rt.return(s),fe.return(i)}function Fc(n,e,t){return n?(n!==e&&(Fc(n.parent,e,t),n.updateLocalTransform(),t.append(n.localTransform)),t):(lt("Mask bounds, renderable is not inside the root container"),t)}class Bc{constructor(e){this.priority=0,this.inverse=!1,this.pipe="alphaMask",e!=null&&e.mask&&this.init(e.mask)}init(e){this.mask=e,this.renderMaskToTexture=!(e instanceof re),this.mask.renderable=this.renderMaskToTexture,this.mask.includeInBuild=!this.renderMaskToTexture,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask=null)}addBounds(e,t){this.inverse||Ic(this.mask,e,t)}addLocalBounds(e,t){Dc(this.mask,e,t)}containsPoint(e,t){const i=this.mask;return t(i,e)}destroy(){this.reset()}static test(e){return e instanceof re}}Bc.extension=B.MaskEffect;class Lc{constructor(e){this.priority=0,this.pipe="colorMask",e!=null&&e.mask&&this.init(e.mask)}init(e){this.mask=e}destroy(){}static test(e){return typeof e=="number"}}Lc.extension=B.MaskEffect;class zc{constructor(e){this.priority=0,this.pipe="stencilMask",e!=null&&e.mask&&this.init(e.mask)}init(e){this.mask=e,this.mask.includeInBuild=!1,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask.includeInBuild=!0,this.mask=null)}addBounds(e,t){Ic(this.mask,e,t)}addLocalBounds(e,t){Dc(this.mask,e,t)}containsPoint(e,t){const i=this.mask;return t(i,e)}destroy(){this.reset()}static test(e){return e instanceof O}}zc.extension=B.MaskEffect;const Gf={createCanvas:(n,e)=>{const t=document.createElement("canvas");return t.width=n,t.height=e,t},createImage:()=>new Image,getCanvasRenderingContext2D:()=>CanvasRenderingContext2D,getWebGLRenderingContext:()=>WebGLRenderingContext,getNavigator:()=>navigator,getBaseUrl:()=>document.baseURI??window.location.href,getFontFaceSet:()=>document.fonts,fetch:(n,e)=>fetch(n,e),parseXML:n=>new DOMParser().parseFromString(n,"text/xml")};let Fa=Gf;const Z={get(){return Fa},set(n){Fa=n}};class Do extends Ut{constructor(e){e.resource||(e.resource=Z.get().createCanvas()),e.width||(e.width=e.resource.width,e.autoDensity||(e.width/=e.resolution)),e.height||(e.height=e.resource.height,e.autoDensity||(e.height/=e.resolution)),super(e),this.uploadMethodId="image",this.autoDensity=e.autoDensity,this.resizeCanvas(),this.transparent=!!e.transparent}resizeCanvas(){this.autoDensity&&"style"in this.resource&&(this.resource.style.width=`${this.width}px`,this.resource.style.height=`${this.height}px`),(this.resource.width!==this.pixelWidth||this.resource.height!==this.pixelHeight)&&(this.resource.width=this.pixelWidth,this.resource.height=this.pixelHeight)}resize(e=this.width,t=this.height,i=this._resolution){const s=super.resize(e,t,i);return s&&this.resizeCanvas(),s}static test(e){return globalThis.HTMLCanvasElement&&e instanceof HTMLCanvasElement||globalThis.OffscreenCanvas&&e instanceof OffscreenCanvas}get context2D(){return this._context2D||(this._context2D=this.resource.getContext("2d"))}}Do.extension=B.TextureSource;class wi extends Ut{constructor(e){super(e),this.uploadMethodId="image",this.autoGarbageCollect=!0}static test(e){return globalThis.HTMLImageElement&&e instanceof HTMLImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||globalThis.VideoFrame&&e instanceof VideoFrame}}wi.extension=B.TextureSource;var ke=(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))(ke||{});class sr{constructor(e,t=null,i=0,s=!1){this.next=null,this.previous=null,this._destroyed=!1,this._fn=e,this._context=t,this.priority=i,this._once=s}match(e,t=null){return this._fn===e&&this._context===t}emit(e){this._fn&&(this._context?this._fn.call(this._context,e):this._fn(e));const t=this.next;return this._once&&this.destroy(!0),this._destroyed&&(this.next=null),t}connect(e){this.previous=e,e.next&&(e.next.previous=this),this.next=e.next,e.next=this}destroy(e=!1){this._destroyed=!0,this._fn=null,this._context=null,this.previous&&(this.previous.next=this.next),this.next&&(this.next.previous=this.previous);const t=this.next;return this.next=e?null:t,this.previous=null,t}}const Oc=class Bt{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 sr(null,null,1/0),this.deltaMS=1/Bt.targetFPMS,this.elapsedMS=1/Bt.targetFPMS,this._tick=e=>{this._requestId=null,this.started&&(this.update(e),this.started&&this._requestId===null&&this._head.next&&(this._requestId=requestAnimationFrame(this._tick)))}}_requestIfNeeded(){this._requestId===null&&this._head.next&&(this.lastTime=performance.now(),this._lastFrame=this.lastTime,this._requestId=requestAnimationFrame(this._tick))}_cancelIfNeeded(){this._requestId!==null&&(cancelAnimationFrame(this._requestId),this._requestId=null)}_startIfPossible(){this.started?this._requestIfNeeded():this.autoStart&&this.start()}add(e,t,i=ke.NORMAL){return this._addListener(new sr(e,t,i))}addOnce(e,t,i=ke.NORMAL){return this._addListener(new sr(e,t,i,!0))}_addListener(e){let t=this._head.next,i=this._head;if(!t)e.connect(i);else{for(;t;){if(e.priority>t.priority){e.connect(i);break}i=t,t=t.next}e.previous||e.connect(i)}return this._startIfPossible(),this}remove(e,t){let i=this._head.next;for(;i;)i.match(e,t)?i=i.destroy():i=i.next;return this._head.next||this._cancelIfNeeded(),this}get count(){if(!this._head)return 0;let e=0,t=this._head;for(;t=t.next;)e++;return e}start(){this.started||(this.started=!0,this._requestIfNeeded())}stop(){this.started&&(this.started=!1,this._cancelIfNeeded())}destroy(){if(!this._protected){this.stop();let e=this._head.next;for(;e;)e=e.destroy(!0);this._head.destroy(),this._head=null}}update(e=performance.now()){let t;if(e>this.lastTime){if(t=this.elapsedMS=e-this.lastTime,t>this._maxElapsedMS&&(t=this._maxElapsedMS),t*=this.speed,this._minElapsedMS){const r=e-this._lastFrame|0;if(r<this._minElapsedMS)return;this._lastFrame=e-r%this._minElapsedMS}this.deltaMS=t,this.deltaTime=this.deltaMS*Bt.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=e}get FPS(){return 1e3/this.elapsedMS}get minFPS(){return 1e3/this._maxElapsedMS}set minFPS(e){const t=Math.min(this.maxFPS,e),i=Math.min(Math.max(0,t)/1e3,Bt.targetFPMS);this._maxElapsedMS=1/i}get maxFPS(){return this._minElapsedMS?Math.round(1e3/this._minElapsedMS):0}set maxFPS(e){if(e===0)this._minElapsedMS=0;else{const t=Math.max(this.minFPS,e);this._minElapsedMS=1/(t/1e3)}}static get shared(){if(!Bt._shared){const e=Bt._shared=new Bt;e.autoStart=!0,e._protected=!0}return Bt._shared}static get system(){if(!Bt._system){const e=Bt._system=new Bt;e.autoStart=!0,e._protected=!0}return Bt._system}};Oc.targetFPMS=.06;let mt=Oc,nr;async function Wc(){return nr??(nr=(async()=>{var o;const e=Z.get().createCanvas(1,1).getContext("webgl");if(!e)return"premultiply-alpha-on-upload";const t=await new Promise(a=>{const l=document.createElement("video");l.onloadeddata=()=>a(l),l.onerror=()=>a(null),l.autoplay=!1,l.crossOrigin="anonymous",l.preload="auto",l.src="data:video/webm;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAHTEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHGTbuMU6uEElTDZ1OsggEXTbuMU6uEHFO7a1OsggG97AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmoCrXsYMPQkBNgIRMYXZmV0GETGF2ZkSJiEBEAAAAAAAAFlSua8yuAQAAAAAAAEPXgQFzxYgAAAAAAAAAAZyBACK1nIN1bmSIgQCGhVZfVlA5g4EBI+ODhAJiWgDglLCBArqBApqBAlPAgQFVsIRVuYEBElTDZ9Vzc9JjwItjxYgAAAAAAAAAAWfInEWjh0VOQ09ERVJEh49MYXZjIGxpYnZweC12cDlnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjA0MDAwMDAwMAAAH0O2dcfngQCgwqGggQAAAIJJg0IAABAAFgA4JBwYSgAAICAAEb///4r+AAB1oZ2mm+6BAaWWgkmDQgAAEAAWADgkHBhKAAAgIABIQBxTu2uRu4+zgQC3iveBAfGCAXHwgQM=",l.load()});if(!t)return"premultiply-alpha-on-upload";const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i);const s=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,i,0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.NONE),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t);const r=new Uint8Array(4);return e.readPixels(0,0,1,1,e.RGBA,e.UNSIGNED_BYTE,r),e.deleteFramebuffer(s),e.deleteTexture(i),(o=e.getExtension("WEBGL_lose_context"))==null||o.loseContext(),r[0]<=r[3]?"premultiplied-alpha":"premultiply-alpha-on-upload"})()),nr}const En=class Gc extends Ut{constructor(e){super(e),this.isReady=!1,this.uploadMethodId="video",e={...Gc.defaultOptions,...e},this._autoUpdate=!0,this._isConnectedToTicker=!1,this._updateFPS=e.updateFPS||0,this._msToNextUpdate=0,this.autoPlay=e.autoPlay!==!1,this.alphaMode=e.alphaMode??"premultiply-alpha-on-upload",this._videoFrameRequestCallback=this._videoFrameRequestCallback.bind(this),this._videoFrameRequestCallbackHandle=null,this._load=null,this._resolve=null,this._reject=null,this._onCanPlay=this._onCanPlay.bind(this),this._onCanPlayThrough=this._onCanPlayThrough.bind(this),this._onError=this._onError.bind(this),this._onPlayStart=this._onPlayStart.bind(this),this._onPlayStop=this._onPlayStop.bind(this),this._onSeeked=this._onSeeked.bind(this),e.autoLoad!==!1&&this.load()}updateFrame(){if(!this.destroyed){if(this._updateFPS){const e=mt.shared.elapsedMS*this.resource.playbackRate;this._msToNextUpdate=Math.floor(this._msToNextUpdate-e)}(!this._updateFPS||this._msToNextUpdate<=0)&&(this._msToNextUpdate=this._updateFPS?Math.floor(1e3/this._updateFPS):0),this.isValid&&this.update()}}_videoFrameRequestCallback(){this.updateFrame(),this.destroyed?this._videoFrameRequestCallbackHandle=null:this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback)}get isValid(){return!!this.resource.videoWidth&&!!this.resource.videoHeight}async load(){if(this._load)return this._load;const e=this.resource,t=this.options;return(e.readyState===e.HAVE_ENOUGH_DATA||e.readyState===e.HAVE_FUTURE_DATA)&&e.width&&e.height&&(e.complete=!0),e.addEventListener("play",this._onPlayStart),e.addEventListener("pause",this._onPlayStop),e.addEventListener("seeked",this._onSeeked),this._isSourceReady()?this._mediaReady():(t.preload||e.addEventListener("canplay",this._onCanPlay),e.addEventListener("canplaythrough",this._onCanPlayThrough),e.addEventListener("error",this._onError,!0)),this.alphaMode=await Wc(),this._load=new Promise((i,s)=>{this.isValid?i(this):(this._resolve=i,this._reject=s,t.preloadTimeoutMs!==void 0&&(this._preloadTimeout=setTimeout(()=>{this._onError(new ErrorEvent(`Preload exceeded timeout of ${t.preloadTimeoutMs}ms`))})),e.load())}),this._load}_onError(e){this.resource.removeEventListener("error",this._onError,!0),this.emit("error",e),this._reject&&(this._reject(e),this._reject=null,this._resolve=null)}_isSourcePlaying(){const e=this.resource;return!e.paused&&!e.ended}_isSourceReady(){return this.resource.readyState>2}_onPlayStart(){this.isValid||this._mediaReady(),this._configureAutoUpdate()}_onPlayStop(){this._configureAutoUpdate()}_onSeeked(){this._autoUpdate&&!this._isSourcePlaying()&&(this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0)}_onCanPlay(){this.resource.removeEventListener("canplay",this._onCanPlay),this._mediaReady()}_onCanPlayThrough(){this.resource.removeEventListener("canplaythrough",this._onCanPlay),this._preloadTimeout&&(clearTimeout(this._preloadTimeout),this._preloadTimeout=void 0),this._mediaReady()}_mediaReady(){const e=this.resource;this.isValid&&(this.isReady=!0,this.resize(e.videoWidth,e.videoHeight)),this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0,this._resolve&&(this._resolve(this),this._resolve=null,this._reject=null),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.resource.play()}destroy(){this._configureAutoUpdate();const e=this.resource;e&&(e.removeEventListener("play",this._onPlayStart),e.removeEventListener("pause",this._onPlayStop),e.removeEventListener("seeked",this._onSeeked),e.removeEventListener("canplay",this._onCanPlay),e.removeEventListener("canplaythrough",this._onCanPlayThrough),e.removeEventListener("error",this._onError,!0),e.pause(),e.src="",e.load()),super.destroy()}get autoUpdate(){return this._autoUpdate}set autoUpdate(e){e!==this._autoUpdate&&(this._autoUpdate=e,this._configureAutoUpdate())}get updateFPS(){return this._updateFPS}set updateFPS(e){e!==this._updateFPS&&(this._updateFPS=e,this._configureAutoUpdate())}_configureAutoUpdate(){this._autoUpdate&&this._isSourcePlaying()?!this._updateFPS&&this.resource.requestVideoFrameCallback?(this._isConnectedToTicker&&(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(e){return globalThis.HTMLVideoElement&&e instanceof HTMLVideoElement}};En.extension=B.TextureSource;En.defaultOptions={...Ut.defaultOptions,autoLoad:!0,autoPlay:!0,updateFPS:0,crossorigin:!0,loop:!1,muted:!0,playsinline:!0,preload:!1};En.MIME_TYPES={ogv:"video/ogg",mov:"video/quicktime",m4v:"video/mp4"};let is=En;const Vt=(n,e,t=!1)=>(Array.isArray(n)||(n=[n]),e?n.map(i=>typeof i=="string"||t?e(i):i):n);class Uf{constructor(){this._parsers=[],this._cache=new Map,this._cacheMap=new Map}reset(){this._cacheMap.clear(),this._cache.clear()}has(e){return this._cache.has(e)}get(e){const t=this._cache.get(e);return t||lt(`[Assets] Asset id ${e} was not found in the Cache`),t}set(e,t){const i=Vt(e);let s;for(let l=0;l<this.parsers.length;l++){const h=this.parsers[l];if(h.test(t)){s=h.getCacheableAssets(i,t);break}}const r=new Map(Object.entries(s||{}));s||i.forEach(l=>{r.set(l,t)});const o=[...r.keys()],a={cacheKeys:o,keys:i};i.forEach(l=>{this._cacheMap.set(l,a)}),o.forEach(l=>{const h=s?s[l]:t;this._cache.has(l)&&this._cache.get(l)!==h&<("[Cache] already has key:",l),this._cache.set(l,r.get(l))})}remove(e){if(!this._cacheMap.has(e)){lt(`[Assets] Asset id ${e} was not found in the Cache`);return}const t=this._cacheMap.get(e);t.cacheKeys.forEach(s=>{this._cache.delete(s)}),t.keys.forEach(s=>{this._cacheMap.delete(s)})}get parsers(){return this._parsers}}const vt=new Uf,Kr=[];Q.handleByList(B.TextureSource,Kr);function Uc(n={}){const e=n&&n.resource,t=e?n.resource:n,i=e?n:{resource:n};for(let s=0;s<Kr.length;s++){const r=Kr[s];if(r.test(t))return new r(i)}throw new Error(`Could not find a source type for resource: ${i.resource}`)}function Hf(n={},e=!1){const t=n&&n.resource,i=t?n.resource:n,s=t?n:{resource:n};if(!e&&vt.has(i))return vt.get(i);const r=new U({source:Uc(s)});return r.on("destroy",()=>{vt.has(i)&&vt.remove(i)}),e||vt.set(i,r),r}function Nf(n,e=!1){return typeof n=="string"?vt.get(n):n instanceof Ut?new U({source:n}):Hf(n,e)}U.from=Nf;Ut.from=Uc;Q.add(Bc,Lc,zc,is,wi,Do,Ro);var Be=(n=>(n[n.Low=0]="Low",n[n.Normal=1]="Normal",n[n.High=2]="High",n))(Be||{});function Ht(n){if(typeof n!="string")throw new TypeError(`Path must be a string. Received ${JSON.stringify(n)}`)}function Li(n){return n.split("?")[0].split("#")[0]}function Vf(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $f(n,e,t){return n.replace(new RegExp(Vf(e),"g"),t)}function Xf(n,e){let t="",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(t.length<2||i!==2||t.charCodeAt(t.length-1)!==46||t.charCodeAt(t.length-2)!==46){if(t.length>2){const l=t.lastIndexOf("/");if(l!==t.length-1){l===-1?(t="",i=0):(t=t.slice(0,l),i=t.length-1-t.lastIndexOf("/")),s=a,r=0;continue}}else if(t.length===2||t.length===1){t="",i=0,s=a,r=0;continue}}}else t.length>0?t+=`/${n.slice(s+1,a)}`:t=n.slice(s+1,a),i=a-s-1;s=a,r=0}else o===46&&r!==-1?++r:r=-1}return t}const It={toPosix(n){return $f(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){Ht(n),n=this.toPosix(n);const e=/^file:\/\/\//.exec(n);if(e)return e[0];const t=/^[^/:]+:\/{0,2}/.exec(n);return t?t[0]:""},toAbsolute(n,e,t){if(Ht(n),this.isDataUrl(n)||this.isBlobUrl(n))return n;const i=Li(this.toPosix(e??Z.get().getBaseUrl())),s=Li(this.toPosix(t??this.rootname(i)));return n=this.toPosix(n),n.startsWith("/")?It.join(s,n.slice(1)):this.isAbsolute(n)?n:this.join(i,n)},normalize(n){if(Ht(n),n.length===0)return".";if(this.isDataUrl(n)||this.isBlobUrl(n))return n;n=this.toPosix(n);let e="";const t=n.startsWith("/");this.hasProtocol(n)&&(e=this.rootname(n),n=n.slice(e.length));const i=n.endsWith("/");return n=Xf(n),n.length>0&&i&&(n+="/"),t?`/${n}`:e+n},isAbsolute(n){return Ht(n),n=this.toPosix(n),this.hasProtocol(n)?!0:n.startsWith("/")},join(...n){if(n.length===0)return".";let e;for(let t=0;t<n.length;++t){const i=n[t];if(Ht(i),i.length>0)if(e===void 0)e=i;else{const s=n[t-1]??"";this.joinExtensions.includes(this.extname(s).toLowerCase())?e+=`/../${i}`:e+=`/${i}`}}return e===void 0?".":this.normalize(e)},dirname(n){if(Ht(n),n.length===0)return".";n=this.toPosix(n);let e=n.charCodeAt(0);const t=e===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(e=n.charCodeAt(a),e===47){if(!s){i=a;break}}else s=!1;return i===-1?t?"/":this.isUrl(o)?r+n:r:t&&i===1?"//":r+n.slice(0,i)},rootname(n){Ht(n),n=this.toPosix(n);let e="";if(n.startsWith("/")?e="/":e=this.getProtocol(n),this.isUrl(n)){const t=n.indexOf("/",e.length);t!==-1?e=n.slice(0,t):e=n,e.endsWith("/")||(e+="/")}return e},basename(n,e){Ht(n),e&&Ht(e),n=Li(this.toPosix(n));let t=0,i=-1,s=!0,r;if(e!==void 0&&e.length>0&&e.length<=n.length){if(e.length===n.length&&e===n)return"";let o=e.length-1,a=-1;for(r=n.length-1;r>=0;--r){const l=n.charCodeAt(r);if(l===47){if(!s){t=r+1;break}}else a===-1&&(s=!1,a=r+1),o>=0&&(l===e.charCodeAt(o)?--o===-1&&(i=r):(o=-1,i=a))}return t===i?i=a:i===-1&&(i=n.length),n.slice(t,i)}for(r=n.length-1;r>=0;--r)if(n.charCodeAt(r)===47){if(!s){t=r+1;break}}else i===-1&&(s=!1,i=r+1);return i===-1?"":n.slice(t,i)},extname(n){Ht(n),n=Li(this.toPosix(n));let e=-1,t=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){t=o+1;break}continue}i===-1&&(s=!1,i=o+1),a===46?e===-1?e=o:r!==1&&(r=1):e!==-1&&(r=-1)}return e===-1||i===-1||r===0||r===1&&e===i-1&&e===t+1?"":n.slice(e,i)},parse(n){Ht(n);const e={root:"",dir:"",base:"",ext:"",name:""};if(n.length===0)return e;n=Li(this.toPosix(n));let t=n.charCodeAt(0);const i=this.isAbsolute(n);let s;e.root=this.rootname(n),i||this.hasProtocol(n)?s=1:s=0;let r=-1,o=0,a=-1,l=!0,h=n.length-1,c=0;for(;h>=s;--h){if(t=n.charCodeAt(h),t===47){if(!l){o=h+1;break}continue}a===-1&&(l=!1,a=h+1),t===46?r===-1?r=h: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?e.base=e.name=n.slice(1,a):e.base=e.name=n.slice(o,a)):(o===0&&i?(e.name=n.slice(1,r),e.base=n.slice(1,a)):(e.name=n.slice(o,r),e.base=n.slice(o,a)),e.ext=n.slice(r,a)),e.dir=this.dirname(n),e},sep:"/",delimiter:":",joinExtensions:[".html"]};function Hc(n,e,t,i,s){const r=e[t];for(let o=0;o<r.length;o++){const a=r[o];t<e.length-1?Hc(n.replace(i[t],a),e,t+1,i,s):s.push(n.replace(i[t],a))}}function Yf(n){const e=/\{(.*?)\}/g,t=n.match(e),i=[];if(t){const s=[];t.forEach(r=>{const o=r.substring(1,r.length-1).split(",");s.push(o)}),Hc(n,s,0,t,i)}else i.push(n);return i}const fn=n=>!Array.isArray(n);class Ri{constructor(){this._defaultBundleIdentifierOptions={connector:"-",createBundleAssetId:(e,t)=>`${e}${this._bundleIdConnector}${t}`,extractAssetIdFromBundle:(e,t)=>t.replace(`${e}${this._bundleIdConnector}`,"")},this._bundleIdConnector=this._defaultBundleIdentifierOptions.connector,this._createBundleAssetId=this._defaultBundleIdentifierOptions.createBundleAssetId,this._extractAssetIdFromBundle=this._defaultBundleIdentifierOptions.extractAssetIdFromBundle,this._assetMap={},this._preferredOrder=[],this._parsers=[],this._resolverHash={},this._bundles={}}setBundleIdentifier(e){if(this._bundleIdConnector=e.connector??this._bundleIdConnector,this._createBundleAssetId=e.createBundleAssetId??this._createBundleAssetId,this._extractAssetIdFromBundle=e.extractAssetIdFromBundle??this._extractAssetIdFromBundle,this._extractAssetIdFromBundle("foo",this._createBundleAssetId("foo","bar"))!=="bar")throw new Error("[Resolver] GenerateBundleAssetId are not working correctly")}prefer(...e){e.forEach(t=>{this._preferredOrder.push(t),t.priority||(t.priority=Object.keys(t.params))}),this._resolverHash={}}set basePath(e){this._basePath=e}get basePath(){return this._basePath}set rootPath(e){this._rootPath=e}get rootPath(){return this._rootPath}get parsers(){return this._parsers}reset(){this.setBundleIdentifier(this._defaultBundleIdentifierOptions),this._assetMap={},this._preferredOrder=[],this._resolverHash={},this._rootPath=null,this._basePath=null,this._manifest=null,this._bundles={},this._defaultSearchParams=null}setDefaultSearchParams(e){if(typeof e=="string")this._defaultSearchParams=e;else{const t=e;this._defaultSearchParams=Object.keys(t).map(i=>`${encodeURIComponent(i)}=${encodeURIComponent(t[i])}`).join("&")}}getAlias(e){const{alias:t,src:i}=e;return Vt(t||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(e){this._manifest&<("[Resolver] Manifest already exists, this will be overwritten"),this._manifest=e,e.bundles.forEach(t=>{this.addBundle(t.name,t.assets)})}addBundle(e,t){const i=[];let s=t;Array.isArray(t)||(s=Object.entries(t).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 l;if(typeof a=="string"){const h=this._createBundleAssetId(e,a);i.push(h),l=[a,h]}else{const h=a.map(c=>this._createBundleAssetId(e,c));i.push(...h),l=[...a,...h]}this.add({...r,alias:l,src:o})}),this._bundles[e]=i}add(e){const t=[];Array.isArray(e)?t.push(...e):t.push(e);let i;i=r=>{this.hasKey(r)&<(`[Resolver] already has key: ${r} overwriting`)},Vt(t).forEach(r=>{const{src:o}=r;let{data:a,format:l,loadParser:h,parser:c}=r;const d=Vt(o).map(m=>typeof m=="string"?Yf(m):Array.isArray(m)?m:[m]),u=this.getAlias(r);Array.isArray(u)?u.forEach(i):i(u);const p=[],f=m=>{const g=this._parsers.find(x=>x.test(m));return{src:m,...g==null?void 0:g.parse(m)}};d.forEach(m=>{m.forEach(g=>{let x={};if(typeof g!="object"?x=f(g):(a=g.data??a,l=g.format??l,(g.loadParser||g.parser)&&(h=g.loadParser??h,c=g.parser??c),x={...f(g.src),...g}),!u)throw new Error(`[Resolver] alias is undefined for this asset: ${x.src}`);x=this._buildResolvedAsset(x,{aliases:u,data:a,format:l,loadParser:h,parser:c,progressSize:r.progressSize}),p.push(x)})}),u.forEach(m=>{this._assetMap[m]=p})})}resolveBundle(e){const t=fn(e);e=Vt(e);const i={};return e.forEach(s=>{const r=this._bundles[s];if(r){const o=this.resolve(r),a={};for(const l in o){const h=o[l];a[this._extractAssetIdFromBundle(s,l)]=h}i[s]=a}}),t?i[e[0]]:i}resolveUrl(e){const t=this.resolve(e);if(typeof e!="string"){const i={};for(const s in t)i[s]=t[s].src;return i}return t.src}resolve(e){const t=fn(e);e=Vt(e);const i={};return e.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(l=>{const h=r.filter(c=>c[a]?c[a]===l:!1);h.length&&(r=h)})}),this._resolverHash[s]=r[0]}else this._resolverHash[s]=this._buildResolvedAsset({alias:[s],src:s},{});i[s]=this._resolverHash[s]}),t?i[e[0]]:i}hasKey(e){return!!this._assetMap[e]}hasBundle(e){return!!this._bundles[e]}_getPreferredOrder(e){for(let t=0;t<e.length;t++){const i=e[t],s=this._preferredOrder.find(r=>r.params.format.includes(i.format));if(s)return s}return this._preferredOrder[0]}_appendDefaultSearchParams(e){if(!this._defaultSearchParams)return e;const t=/\?/.test(e)?"&":"?";return`${e}${t}${this._defaultSearchParams}`}_buildResolvedAsset(e,t){const{aliases:i,data:s,loadParser:r,parser:o,format:a,progressSize:l}=t;return(this._basePath||this._rootPath)&&(e.src=It.toAbsolute(e.src,this._basePath,this._rootPath)),e.alias=i??e.alias??[e.src],e.src=this._appendDefaultSearchParams(e.src),e.data={...s||{},...e.data},e.loadParser=r??e.loadParser,e.parser=o??e.parser,e.format=a??e.format??jf(e.src),l!==void 0&&(e.progressSize=l),e}}Ri.RETINA_PREFIX=/@([0-9\.]+)x/;function jf(n){return n.split(".").pop().split("?").shift().split("#").shift()}const Qr=(n,e)=>{const t=e.split("?")[1];return t&&(n+=`?${t}`),n},Nc=class ji{constructor(e,t){this.linkedSheets=[];let i=e;(e==null?void 0:e.source)instanceof Ut&&(i={texture:e,data:t});const{texture:s,data:r,cachePrefix:o=""}=i;this.cachePrefix=o,this._texture=s instanceof U?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(e=>{this._callback=e,this._batchIndex=0,this._frameKeys.length<=ji.BATCH_SIZE?(this._processFrames(0),this._processAnimations(),this._parseComplete()):this._nextBatch()})}parseSync(){return this._processFrames(0,!0),this._processAnimations(),this.textures}_processFrames(e,t=!1){let i=e;const s=t?1/0:ji.BATCH_SIZE;for(;i-e<s&&i<this._frameKeys.length;){const r=this._frameKeys[i],o=this._frames[r],a=o.frame;if(a){let l=null,h=null;const c=o.trimmed!==!1&&o.sourceSize?o.sourceSize:o.frame,d=new st(0,0,Math.floor(c.w)/this.resolution,Math.floor(c.h)/this.resolution);o.rotated?l=new st(Math.floor(a.x)/this.resolution,Math.floor(a.y)/this.resolution,Math.floor(a.h)/this.resolution,Math.floor(a.w)/this.resolution):l=new st(Math.floor(a.x)/this.resolution,Math.floor(a.y)/this.resolution,Math.floor(a.w)/this.resolution,Math.floor(a.h)/this.resolution),o.trimmed!==!1&&o.spriteSourceSize&&(h=new st(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 U({source:this.textureSource,frame:l,orig:d,trim:h,rotate:o.rotated?2:0,defaultAnchor:o.anchor,defaultBorders:o.borders,label:r.toString()})}i++}}_processAnimations(){const e=this.data.animations||{};for(const t in e){this.animations[t]=[];for(let i=0;i<e[t].length;i++){const s=e[t][i];this.animations[t].push(this.textures[s])}}}_parseComplete(){const e=this._callback;this._callback=null,this._batchIndex=0,e.call(this,this.textures)}_nextBatch(){this._processFrames(this._batchIndex*ji.BATCH_SIZE),this._batchIndex++,setTimeout(()=>{this._batchIndex*ji.BATCH_SIZE<this._frameKeys.length?this._nextBatch():(this._processAnimations(),this._parseComplete())},0)}destroy(e=!1){var t;for(const i in this.textures)this.textures[i].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,e&&((t=this._texture)==null||t.destroy(),this.textureSource.destroy()),this._texture=null,this.textureSource=null,this.linkedSheets=[]}};Nc.BATCH_SIZE=1e3;let Jr=Nc;const Zf=["jpg","png","jpeg","avif","webp","basis","etc2","bc7","bc6h","bc5","bc4","bc3","bc2","bc1","eac","astc"];function Vc(n,e,t){const i={};if(n.forEach(s=>{i[s]=e}),Object.keys(e.textures).forEach(s=>{i[`${e.cachePrefix}${s}`]=e.textures[s]}),!t){const s=It.dirname(n[0]);e.linkedSheets.forEach((r,o)=>{const a=Vc([`${s}/${e.data.meta.related_multi_packs[o]}`],r,!0);Object.assign(i,a)})}return i}const qf={extension:B.Asset,cache:{test:n=>n instanceof Jr,getCacheableAssets:(n,e)=>Vc(n,e,!1)},resolver:{extension:{type:B.ResolveParser,name:"resolveSpritesheet"},test:n=>{const t=n.split("?")[0].split("."),i=t.pop(),s=t.pop();return i==="json"&&Zf.includes(s)},parse:n=>{var t;const e=n.split(".");return{resolution:parseFloat(((t=Ri.RETINA_PREFIX.exec(n))==null?void 0:t[1])??"1"),format:e[e.length-2],src:n}}},loader:{name:"spritesheetLoader",id:"spritesheet",extension:{type:B.LoadParser,priority:Be.Normal,name:"spritesheetLoader"},async testParse(n,e){return It.extname(e.src).toLowerCase()===".json"&&!!n.frames},async parse(n,e,t){var d,u;const{texture:i,imageFilename:s,textureOptions:r,cachePrefix:o}=(e==null?void 0:e.data)??{};let a=It.dirname(e.src);a&&a.lastIndexOf("/")!==a.length-1&&(a+="/");let l;if(i instanceof U)l=i;else{const p=Qr(a+(s??n.meta.image),e.src);l=(await t.load([{src:p,data:r}]))[p]}const h=new Jr({texture:l.source,data:n,cachePrefix:o});await h.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 m of c){if(typeof m!="string")continue;let g=a+m;(u=e.data)!=null&&u.ignoreMultiPack||(g=Qr(g,e.src),p.push(t.load({src:g,data:{textureOptions:r,ignoreMultiPack:!0}})))}const f=await Promise.all(p);h.linkedSheets=f,f.forEach(m=>{m.linkedSheets=[h].concat(h.linkedSheets.filter(g=>g!==m))})}return h},async unload(n,e,t){await t.unload(n.textureSource._sourceOrigin),n.destroy(!1)}}};Q.add(qf);class Kf{constructor(e){this._lastTransform="",this._observer=null,this._tickerAttached=!1,this.updateTranslation=()=>{if(!this._canvas)return;const t=this._canvas.getBoundingClientRect(),i=this._canvas.width,s=this._canvas.height,r=t.width/i*this._renderer.resolution,o=t.height/s*this._renderer.resolution,a=t.left,l=t.top,h=`translate(${a}px, ${l}px) scale(${r}, ${o})`;h!==this._lastTransform&&(this._domElement.style.transform=h,this._lastTransform=h)},this._domElement=e.domElement,this._renderer=e.renderer,!(globalThis.OffscreenCanvas&&this._renderer.canvas instanceof OffscreenCanvas)&&(this._canvas=this._renderer.canvas,this._attachObserver())}get canvas(){return this._canvas}ensureAttached(){!this._domElement.parentNode&&this._canvas.parentNode&&(this._canvas.parentNode.appendChild(this._domElement),this.updateTranslation())}_attachObserver(){"ResizeObserver"in globalThis?(this._observer&&(this._observer.disconnect(),this._observer=null),this._observer=new ResizeObserver(e=>{for(const t of e){if(t.target!==this._canvas)continue;const i=this.canvas.width,s=this.canvas.height,r=t.contentRect.width/i*this._renderer.resolution,o=t.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,ke.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 Fo{constructor(e){this.bubbles=!0,this.cancelBubble=!0,this.cancelable=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=Fo.prototype.NONE,this.propagationStopped=!1,this.propagationImmediatelyStopped=!1,this.layer=new it,this.page=new it,this.NONE=0,this.CAPTURING_PHASE=1,this.AT_TARGET=2,this.BUBBLING_PHASE=3,this.manager=e}get layerX(){return this.layer.x}get layerY(){return this.layer.y}get pageX(){return this.page.x}get pageY(){return this.page.y}get data(){return this}composedPath(){return this.manager&&(!this.path||this.path[this.path.length-1]!==this.target)&&(this.path=this.target?this.manager.propagationPath(this.target):[]),this.path}initEvent(e,t,i){throw new Error("initEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}initUIEvent(e,t,i,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 rr=/iPhone/i,Ba=/iPod/i,La=/iPad/i,za=/\biOS-universal(?:.+)Mac\b/i,or=/\bAndroid(?:.+)Mobile\b/i,Oa=/Android/i,ni=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,zs=/Silk/i,he=/Windows Phone/i,Wa=/\bWindows(?:.+)ARM\b/i,Ga=/BlackBerry/i,Ua=/BB10/i,Ha=/Opera Mini/i,Na=/\b(CriOS|Chrome)(?:.+)Mobile/i,Va=/Mobile(?:.+)Firefox\b/i,$a=function(n){return typeof n<"u"&&n.platform==="MacIntel"&&typeof n.maxTouchPoints=="number"&&n.maxTouchPoints>1&&typeof MSStream>"u"};function Qf(n){return function(e){return e.test(n)}}function Xa(n){var e={userAgent:"",platform:"",maxTouchPoints:0};!n&&typeof navigator<"u"?e={userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints||0}:typeof n=="string"?e.userAgent=n:n&&n.userAgent&&(e={userAgent:n.userAgent,platform:n.platform,maxTouchPoints:n.maxTouchPoints||0});var t=e.userAgent,i=t.split("[FBAN");typeof i[1]<"u"&&(t=i[0]),i=t.split("Twitter"),typeof i[1]<"u"&&(t=i[0]);var s=Qf(t),r={apple:{phone:s(rr)&&!s(he),ipod:s(Ba),tablet:!s(rr)&&(s(La)||$a(e))&&!s(he),universal:s(za),device:(s(rr)||s(Ba)||s(La)||s(za)||$a(e))&&!s(he)},amazon:{phone:s(ni),tablet:!s(ni)&&s(zs),device:s(ni)||s(zs)},android:{phone:!s(he)&&s(ni)||!s(he)&&s(or),tablet:!s(he)&&!s(ni)&&!s(or)&&(s(zs)||s(Oa)),device:!s(he)&&(s(ni)||s(zs)||s(or)||s(Oa))||s(/\bokhttp\b/i)},windows:{phone:s(he),tablet:s(Wa),device:s(he)||s(Wa)},other:{blackberry:s(Ga),blackberry10:s(Ua),opera:s(Ha),firefox:s(Va),chrome:s(Na),device:s(Ga)||s(Ua)||s(Ha)||s(Va)||s(Na)},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 Jf=Xa.default??Xa,tg=Jf(globalThis.navigator),ar=Object.create(null),Ya=Object.create(null);function Bo(n,e){let t=Ya[n];return t===void 0&&(ar[e]===void 0&&(ar[e]=1),Ya[n]=t=ar[e]++),t}let ri;function $c(){return(!ri||ri!=null&&ri.isContextLost())&&(ri=Z.get().createCanvas().getContext("webgl",{})),ri}let Os;function eg(){if(!Os){Os="mediump";const n=$c();n&&n.getShaderPrecisionFormat&&(Os=n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.HIGH_FLOAT).precision?"highp":"mediump")}return Os}function ig(n,e,t){return e?n:t?(n=n.replace("out vec4 finalColor;",""),`
|
|
@@ -20,7 +20,7 @@ Deprecated since v${n}`,r=typeof console.groupCollapsed=="function"&&!di.noColor
|
|
|
20
20
|
`}function sg(n,e,t){const i=t?e.maxSupportedFragmentPrecision:e.maxSupportedVertexPrecision;if(n.substring(0,9)!=="precision"){let s=t?e.requestedFragmentPrecision:e.requestedVertexPrecision;return s==="highp"&&i!=="highp"&&(s="mediump"),`precision ${s} float;
|
|
21
21
|
${n}`}else if(i!=="highp"&&n.substring(0,15)==="precision highp")return n.replace("precision highp","precision mediump");return n}function ng(n,e){return e?`#version 300 es
|
|
22
22
|
${n}`:n}const rg={},og={};function ag(n,{name:e="pixi-program"},t=!0){e=e.replace(/\s+/g,"-"),e+=t?"-fragment":"-vertex";const i=t?rg:og;return i[e]?(i[e]++,e+=`-${i[e]}`):i[e]=1,n.indexOf("#define SHADER_NAME")!==-1?n:`${`#define SHADER_NAME ${e}`}
|
|
23
|
-
${n}`}function lg(n,e){return e?n.replace("#version 300 es",""):n}const lr={stripVersion:lg,ensurePrecision:sg,addProgramDefines:ig,setProgramName:ag,insertVersion:ng},zi=Object.create(null),Xc=class to{constructor(e){e={...to.defaultOptions,...e};const t=e.fragment.indexOf("#version 300 es")!==-1,i={stripVersion:t,ensurePrecision:{requestedFragmentPrecision:e.preferredFragmentPrecision,requestedVertexPrecision:e.preferredVertexPrecision,maxSupportedVertexPrecision:"highp",maxSupportedFragmentPrecision:eg()},setProgramName:{name:e.name},addProgramDefines:t,insertVersion:t};let s=e.fragment,r=e.vertex;Object.keys(lr).forEach(o=>{const a=i[o];s=lr[o](s,a,!0),r=lr[o](r,a,!1)}),this.fragment=s,this.vertex=r,this.transformFeedbackVaryings=e.transformFeedbackVaryings,this._key=Bo(`${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,zi[this._cacheKey]=null}static from(e){const t=`${e.vertex}:${e.fragment}`;return zi[t]||(zi[t]=new to(e),zi[t]._cacheKey=t),zi[t]}};Xc.defaultOptions={preferredVertexPrecision:"highp",preferredFragmentPrecision:"mediump"};let Ci=Xc;const ja={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 hg(n){return ja[n]??ja.float32}const cg={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"},Za=/@location\((\d+)\)\s+([a-zA-Z0-9_]+)\s*:\s*([a-zA-Z0-9_<>]+)(?:,|\s|\)|$)/g;function qa(n,e){let t;for(;(t=Za.exec(n))!==null;){const i=cg[t[3]]??"float32";e[t[2]]={location:parseInt(t[1],10),format:i,stride:hg(i).stride,offset:0,instance:!1,start:0}}Za.lastIndex=0}function dg(n){return n.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"")}function ug({source:n,entryPoint:e}){const t={},i=dg(n),s=i.indexOf(`fn ${e}(`);if(s===-1)return t;const r=i.indexOf("->",s);if(r===-1)return t;const o=i.substring(s,r);if(qa(o,t),Object.keys(t).length===0){const a=o.match(/\(\s*\w+\s*:\s*(\w+)/);if(a){const l=a[1],h=new RegExp(`struct\\s+${l}\\s*\\{([^}]+)\\}`,"s"),c=i.match(h);c&&qa(c[1],t)}}return t}function hr(n){var d,u;const e=/(^|[^/])@(group|binding)\(\d+\)[^;]+;/g,t=/@group\((\d+)\)/,i=/@binding\((\d+)\)/,s=/var(<[^>]+>)? (\w+)/,r=/:\s*([\w<>]+)/,o=/struct\s+(\w+)\s*{([^}]+)}/g,a=/(\w+)\s*:\s*([\w\<\>]+)/g,l=/struct\s+(\w+)/,h=(d=n.match(e))==null?void 0:d.map(p=>({group:parseInt(p.match(t)[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(!h)return{groups:[],structs:[]};const c=((u=n.match(o))==null?void 0:u.map(p=>{const f=p.match(l)[1],m=p.match(a).reduce((g,x)=>{const[S,b]=x.split(":");return g[S.trim()]=b.trim(),g},{});return m?{name:f,members:m}:null}).filter(({name:p})=>h.some(f=>f.type===p||f.type.includes(`<${p}>`))))??[];return{groups:h,structs:c}}var Ne=(n=>(n[n.VERTEX=1]="VERTEX",n[n.FRAGMENT=2]="FRAGMENT",n[n.COMPUTE=4]="COMPUTE",n))(Ne||{});function pg({groups:n}){const e=[];for(let t=0;t<n.length;t++){const i=n[t];e[i.group]||(e[i.group]=[]),i.isUniform?e[i.group].push({binding:i.binding,visibility:Ne.VERTEX|Ne.FRAGMENT,buffer:{type:"uniform"}}):i.type==="sampler"?e[i.group].push({binding:i.binding,visibility:Ne.FRAGMENT,sampler:{type:"filtering"}}):i.type==="texture_2d"||i.type.startsWith("texture_2d<")?e[i.group].push({binding:i.binding,visibility:Ne.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d",multisampled:!1}}):i.type==="texture_2d_array"||i.type.startsWith("texture_2d_array<")?e[i.group].push({binding:i.binding,visibility:Ne.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d-array",multisampled:!1}}):(i.type==="texture_cube"||i.type.startsWith("texture_cube<"))&&e[i.group].push({binding:i.binding,visibility:Ne.FRAGMENT,texture:{sampleType:"float",viewDimension:"cube",multisampled:!1}})}for(let t=0;t<e.length;t++)e[t]||(e[t]=[]);return e}function fg({groups:n}){const e=[];for(let t=0;t<n.length;t++){const i=n[t];e[i.group]||(e[i.group]={}),e[i.group][i.name]=i.binding}return e}function gg(n,e){const t=new Set,i=new Set,s=[...n.structs,...e.structs].filter(o=>t.has(o.name)?!1:(t.add(o.name),!0)),r=[...n.groups,...e.groups].filter(o=>{const a=`${o.name}-${o.binding}`;return i.has(a)?!1:(i.add(a),!0)});return{structs:s,groups:r}}const Oi=Object.create(null);class Ie{constructor(e){var a,l;this._layoutKey=0,this._attributeLocationsKey=0;const{fragment:t,vertex:i,layout:s,gpuLayout:r,name:o}=e;if(this.name=o,this.fragment=t,this.vertex=i,t.source===i.source){const h=hr(t.source);this.structsAndGroups=h}else{const h=hr(i.source),c=hr(t.source);this.structsAndGroups=gg(h,c)}this.layout=s??fg(this.structsAndGroups),this.gpuLayout=r??pg(this.structsAndGroups),this.autoAssignGlobalUniforms=((a=this.layout[0])==null?void 0:a.globalUniforms)!==void 0,this.autoAssignLocalUniforms=((l=this.layout[1])==null?void 0:l.localUniforms)!==void 0,this._generateProgramKey()}_generateProgramKey(){const{vertex:e,fragment:t}=this,i=e.source+t.source+e.entryPoint+t.entryPoint;this._layoutKey=Bo(i,"program")}get attributeData(){return this._attributeData??(this._attributeData=ug(this.vertex)),this._attributeData}destroy(){this.gpuLayout=null,this.layout=null,this.structsAndGroups=null,this.fragment=null,this.vertex=null,Oi[this._cacheKey]=null}static from(e){const t=`${e.vertex.source}:${e.fragment.source}:${e.fragment.entryPoint}:${e.vertex.entryPoint}`;return Oi[t]||(Oi[t]=new Ie(e),Oi[t]._cacheKey=t),Oi[t]}}const Yc=["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>"],mg=Yc.reduce((n,e)=>(n[e]=!0,n),{});function yg(n,e){switch(n){case"f32":return 0;case"vec2<f32>":return new Float32Array(2*e);case"vec3<f32>":return new Float32Array(3*e);case"vec4<f32>":return new Float32Array(4*e);case"mat2x2<f32>":return new Float32Array([1,0,0,1]);case"mat3x3<f32>":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4x4<f32>":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}const jc=class Zc{constructor(e,t){this._touched=0,this.uid=ft("uniform"),this._resourceType="uniformGroup",this._resourceId=ft("resource"),this.isUniformGroup=!0,this._dirtyId=0,this.destroyed=!1,t={...Zc.defaultOptions,...t},this.uniformStructures=e;const i={};for(const s in e){const r=e[s];if(r.name=s,r.size=r.size??1,!mg[r.type]){const o=r.type.match(/^array<(\w+(?:<\w+>)?),\s*(\d+)>$/);if(o){const[,a,l]=o;throw new Error(`Uniform type ${r.type} is not supported. Use type: '${a}', size: ${l} instead.`)}throw new Error(`Uniform type ${r.type} is not supported. Supported uniform types are: ${Yc.join(", ")}`)}r.value??(r.value=yg(r.type,r.size)),i[s]=r.value}this.uniforms=i,this._dirtyId=1,this.ubo=t.ubo,this.isStatic=t.isStatic,this._signature=Bo(Object.keys(i).map(s=>`${s}-${e[s].type}`).join("-"),"uniform-group")}update(){this._dirtyId++}};jc.defaultOptions={ubo:!1,isStatic:!1};let Mi=jc;class ss{constructor(e){this.resources=Object.create(null),this._dirty=!0;let t=0;for(const i in e){const s=e[i];this.setResource(s,t++)}this._updateKey()}_updateKey(){if(!this._dirty)return;this._dirty=!1;const e=[];let t=0;for(const i in this.resources)e[t++]=this.resources[i]._resourceId;this._key=e.join("|")}setResource(e,t){var s,r;const i=this.resources[t];e!==i&&(i&&((s=i.off)==null||s.call(i,"change",this.onResourceChange,this)),(r=e.on)==null||r.call(e,"change",this.onResourceChange,this),this.resources[t]=e,this._dirty=!0)}getResource(e){return this.resources[e]}_touch(e,t){const i=this.resources;for(const s in i)i[s]._gcLastUsed=e,i[s]._touched=t}destroy(){var t;const e=this.resources;for(const i in e){const s=e[i];(t=s==null?void 0:s.off)==null||t.call(s,"change",this.onResourceChange,this)}this.resources=null}onResourceChange(e){if(this._dirty=!0,e.destroyed){const t=this.resources;for(const i in t)t[i]===e&&(t[i]=null)}else this._updateKey()}}var pe=(n=>(n[n.WEBGL=1]="WEBGL",n[n.WEBGPU=2]="WEBGPU",n[n.CANVAS=4]="CANVAS",n[n.BOTH=3]="BOTH",n))(pe||{});class Je extends ae{constructor(e){super(),this.uid=ft("shader"),this._uniformBindMap=Object.create(null),this._ownedBindGroups=[],this._destroyed=!1;let{gpuProgram:t,glProgram:i,groups:s,resources:r,compatibleRenderers:o,groupMap:a}=e;this.gpuProgram=t,this.glProgram=i,o===void 0&&(o=0,t&&(o|=pe.WEBGPU),i&&(o|=pe.WEBGL)),this.compatibleRenderers=o;const l={};if(!r&&!s&&(r={}),r&&s)throw new Error("[Shader] Cannot have both resources and groups");if(!t&&s&&!a)throw new Error("[Shader] No group map or WebGPU shader provided - consider using resources instead.");if(!t&&s&&a)for(const h in a)for(const c in a[h]){const d=a[h][c];l[d]={group:h,binding:c,name:d}}else if(t&&s&&!a){const h=t.structsAndGroups.groups;a={},h.forEach(c=>{a[c.group]=a[c.group]||{},a[c.group][c.binding]=c.name,l[c.name]=c})}else if(r){s={},a={},t&&t.structsAndGroups.groups.forEach(d=>{a[d.group]=a[d.group]||{},a[d.group][d.binding]=d.name,l[d.name]=d});let h=0;for(const c in r)l[c]||(s[99]||(s[99]=new ss,this._ownedBindGroups.push(s[99])),l[c]={group:99,binding:h,name:c},a[99]=a[99]||{},a[99][h]=c,h++);for(const c in r){const d=c;let u=r[c];!u.source&&!u._resourceType&&(u=new Mi(u));const p=l[d];p&&(s[p.group]||(s[p.group]=new ss,this._ownedBindGroups.push(s[p.group])),s[p.group].setResource(u,p.binding))}}this.groups=s,this._uniformBindMap=a,this.resources=this._buildResourceAccessor(s,l)}addResource(e,t,i){var s,r;(s=this._uniformBindMap)[t]||(s[t]={}),(r=this._uniformBindMap[t])[i]||(r[i]=e),this.groups[t]||(this.groups[t]=new ss,this._ownedBindGroups.push(this.groups[t]))}_buildResourceAccessor(e,t){const i={};for(const s in t){const r=t[s];Object.defineProperty(i,r.name,{get(){return e[r.group].getResource(r.binding)},set(o){e[r.group].setResource(o,r.binding)}})}return i}destroy(e=!1){var t,i;this._destroyed||(this._destroyed=!0,this.emit("destroy",this),e&&((t=this.gpuProgram)==null||t.destroy(),(i=this.glProgram)==null||i.destroy()),this.gpuProgram=null,this.glProgram=null,this.removeAllListeners(),this._uniformBindMap=null,this._ownedBindGroups.forEach(s=>{s.destroy()}),this._ownedBindGroups=null,this.resources=null,this.groups=null)}static from(e){const{gpu:t,gl:i,...s}=e;let r,o;return t&&(r=Ie.from(t)),i&&(o=Ci.from(i)),new Je({gpuProgram:r,glProgram:o,...s})}}const xg={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},cr=0,dr=1,ur=2,pr=3,fr=4,gr=5,eo=class qc{constructor(){this.data=0,this.blendMode="normal",this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(this.data&1<<cr)}set blend(e){!!(this.data&1<<cr)!==e&&(this.data^=1<<cr)}get offsets(){return!!(this.data&1<<dr)}set offsets(e){!!(this.data&1<<dr)!==e&&(this.data^=1<<dr)}set cullMode(e){if(e==="none"){this.culling=!1;return}this.culling=!0,this.clockwiseFrontFace=e==="front"}get cullMode(){return this.culling?this.clockwiseFrontFace?"front":"back":"none"}get culling(){return!!(this.data&1<<ur)}set culling(e){!!(this.data&1<<ur)!==e&&(this.data^=1<<ur)}get depthTest(){return!!(this.data&1<<pr)}set depthTest(e){!!(this.data&1<<pr)!==e&&(this.data^=1<<pr)}get depthMask(){return!!(this.data&1<<gr)}set depthMask(e){!!(this.data&1<<gr)!==e&&(this.data^=1<<gr)}get clockwiseFrontFace(){return!!(this.data&1<<fr)}set clockwiseFrontFace(e){!!(this.data&1<<fr)!==e&&(this.data^=1<<fr)}get blendMode(){return this._blendMode}set blendMode(e){this.blend=e!=="none",this._blendMode=e,this._blendModeId=xg[e]||0}get polygonOffset(){return this._polygonOffset}set polygonOffset(e){this.offsets=!!e,this._polygonOffset=e}toString(){return`[pixi.js/core:State blendMode=${this.blendMode} clockwiseFrontFace=${this.clockwiseFrontFace} culling=${this.culling} depthMask=${this.depthMask} polygonOffset=${this.polygonOffset}]`}static for2d(){const e=new qc;return e.depthTest=!1,e.blend=!0,e}};eo.default2d=eo.for2d();let Ps=eo;const Kc=class io extends Je{constructor(e){e={...io.defaultOptions,...e},super(e),this.enabled=!0,this._state=Ps.for2d(),this.blendMode=e.blendMode,this.padding=e.padding,typeof e.antialias=="boolean"?this.antialias=e.antialias?"on":"off":this.antialias=e.antialias,this.resolution=e.resolution,this.blendRequired=e.blendRequired,this.clipToViewport=e.clipToViewport,this.addResource("uTexture",0,1),e.blendRequired&&this.addResource("uBackTexture",0,3)}apply(e,t,i,s){e.applyFilter(this,t,i,s)}get blendMode(){return this._state.blendMode}set blendMode(e){this._state.blendMode=e}static from(e){const{gpu:t,gl:i,...s}=e;let r,o;return t&&(r=Ie.from(t)),i&&(o=Ci.from(i)),new io({gpuProgram:r,glProgram:o,...s})}};Kc.defaultOptions={blendMode:"normal",resolution:1,padding:0,antialias:"off",blendRequired:!1,clipToViewport:!0};let Sg=Kc;const so=[];Q.handleByNamedList(B.Environment,so);async function bg(n){if(!n)for(let e=0;e<so.length;e++){const t=so[e];if(t.value.test()){await t.value.load();return}}}let Wi;function vg(){if(typeof Wi=="boolean")return Wi;try{Wi=new Function("param1","param2","param3","return param1[param2] === param3;")({a:"b"},"a","b")===!0}catch{Wi=!1}return Wi}function Ka(n,e,t=2){const i=e&&e.length,s=i?e[0]*t:n.length;let r=Qc(n,0,s,t,!0);const o=[];if(!r||r.next===r.prev)return o;let a,l,h;if(i&&(r=Pg(n,e,r,t)),n.length>80*t){a=n[0],l=n[1];let c=a,d=l;for(let u=t;u<s;u+=t){const p=n[u],f=n[u+1];p<a&&(a=p),f<l&&(l=f),p>c&&(c=p),f>d&&(d=f)}h=Math.max(c-a,d-l),h=h!==0?32767/h:0}return ps(r,o,t,a,l,h,0),o}function Qc(n,e,t,i,s){let r;if(s===zg(n,e,t,i)>0)for(let o=e;o<t;o+=i)r=Qa(o/i|0,n[o],n[o+1],r);else for(let o=t-i;o>=e;o-=i)r=Qa(o/i|0,n[o],n[o+1],r);return r&&_i(r,r.next)&&(gs(r),r=r.next),r}function ti(n,e){if(!n)return n;e||(e=n);let t=n,i;do if(i=!1,!t.steiner&&(_i(t,t.next)||dt(t.prev,t,t.next)===0)){if(gs(t),t=e=t.prev,t===t.next)break;i=!0}else t=t.next;while(i||t!==e);return e}function ps(n,e,t,i,s,r,o){if(!n)return;!o&&r&&kg(n,i,s,r);let a=n;for(;n.prev!==n.next;){const l=n.prev,h=n.next;if(r?Cg(n,i,s,r):wg(n)){e.push(l.i,n.i,h.i),gs(n),n=h.next,a=h.next;continue}if(n=h,n===a){o?o===1?(n=Mg(ti(n),e),ps(n,e,t,i,s,r,2)):o===2&&_g(n,e,t,i,s,r):ps(ti(n),e,t,i,s,r,1);break}}}function wg(n){const e=n.prev,t=n,i=n.next;if(dt(e,t,i)>=0)return!1;const s=e.x,r=t.x,o=i.x,a=e.y,l=t.y,h=i.y,c=Math.min(s,r,o),d=Math.min(a,l,h),u=Math.max(s,r,o),p=Math.max(a,l,h);let f=i.next;for(;f!==e;){if(f.x>=c&&f.x<=u&&f.y>=d&&f.y<=p&&Zi(s,a,r,l,o,h,f.x,f.y)&&dt(f.prev,f,f.next)>=0)return!1;f=f.next}return!0}function Cg(n,e,t,i){const s=n.prev,r=n,o=n.next;if(dt(s,r,o)>=0)return!1;const a=s.x,l=r.x,h=o.x,c=s.y,d=r.y,u=o.y,p=Math.min(a,l,h),f=Math.min(c,d,u),m=Math.max(a,l,h),g=Math.max(c,d,u),x=no(p,f,e,t,i),S=no(m,g,e,t,i);let b=n.prevZ,w=n.nextZ;for(;b&&b.z>=x&&w&&w.z<=S;){if(b.x>=p&&b.x<=m&&b.y>=f&&b.y<=g&&b!==s&&b!==o&&Zi(a,c,l,d,h,u,b.x,b.y)&&dt(b.prev,b,b.next)>=0||(b=b.prevZ,w.x>=p&&w.x<=m&&w.y>=f&&w.y<=g&&w!==s&&w!==o&&Zi(a,c,l,d,h,u,w.x,w.y)&&dt(w.prev,w,w.next)>=0))return!1;w=w.nextZ}for(;b&&b.z>=x;){if(b.x>=p&&b.x<=m&&b.y>=f&&b.y<=g&&b!==s&&b!==o&&Zi(a,c,l,d,h,u,b.x,b.y)&&dt(b.prev,b,b.next)>=0)return!1;b=b.prevZ}for(;w&&w.z<=S;){if(w.x>=p&&w.x<=m&&w.y>=f&&w.y<=g&&w!==s&&w!==o&&Zi(a,c,l,d,h,u,w.x,w.y)&&dt(w.prev,w,w.next)>=0)return!1;w=w.nextZ}return!0}function Mg(n,e){let t=n;do{const i=t.prev,s=t.next.next;!_i(i,s)&&td(i,t,t.next,s)&&fs(i,s)&&fs(s,i)&&(e.push(i.i,t.i,s.i),gs(t),gs(t.next),t=n=s),t=t.next}while(t!==n);return ti(t)}function _g(n,e,t,i,s,r){let o=n;do{let a=o.next.next;for(;a!==o.prev;){if(o.i!==a.i&&Fg(o,a)){let l=ed(o,a);o=ti(o,o.next),l=ti(l,l.next),ps(o,e,t,i,s,r,0),ps(l,e,t,i,s,r,0);return}a=a.next}o=o.next}while(o!==n)}function Pg(n,e,t,i){const s=[];for(let r=0,o=e.length;r<o;r++){const a=e[r]*i,l=r<o-1?e[r+1]*i:n.length,h=Qc(n,a,l,i,!1);h===h.next&&(h.steiner=!0),s.push(Dg(h))}s.sort(Ag);for(let r=0;r<s.length;r++)t=Tg(s[r],t);return t}function Ag(n,e){let t=n.x-e.x;if(t===0&&(t=n.y-e.y,t===0)){const i=(n.next.y-n.y)/(n.next.x-n.x),s=(e.next.y-e.y)/(e.next.x-e.x);t=i-s}return t}function Tg(n,e){const t=Rg(n,e);if(!t)return e;const i=ed(t,n);return ti(i,i.next),ti(t,t.next)}function Rg(n,e){let t=e;const i=n.x,s=n.y;let r=-1/0,o;if(_i(n,t))return t;do{if(_i(n,t.next))return t.next;if(s<=t.y&&s>=t.next.y&&t.next.y!==t.y){const d=t.x+(s-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(d<=i&&d>r&&(r=d,o=t.x<t.next.x?t:t.next,d===i))return o}t=t.next}while(t!==e);if(!o)return null;const a=o,l=o.x,h=o.y;let c=1/0;t=o;do{if(i>=t.x&&t.x>=l&&i!==t.x&&Jc(s<h?i:r,s,l,h,s<h?r:i,s,t.x,t.y)){const d=Math.abs(s-t.y)/(i-t.x);fs(t,n)&&(d<c||d===c&&(t.x>o.x||t.x===o.x&&Eg(o,t)))&&(o=t,c=d)}t=t.next}while(t!==a);return o}function Eg(n,e){return dt(n.prev,n,e.prev)<0&&dt(e.next,n,n.next)<0}function kg(n,e,t,i){let s=n;do s.z===0&&(s.z=no(s.x,s.y,e,t,i)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next;while(s!==n);s.prevZ.nextZ=null,s.prevZ=null,Ig(s)}function Ig(n){let e,t=1;do{let i=n,s;n=null;let r=null;for(e=0;i;){e++;let o=i,a=0;for(let h=0;h<t&&(a++,o=o.nextZ,!!o);h++);let l=t;for(;a>0||l>0&&o;)a!==0&&(l===0||!o||i.z<=o.z)?(s=i,i=i.nextZ,a--):(s=o,o=o.nextZ,l--),r?r.nextZ=s:n=s,s.prevZ=r,r=s;i=o}r.nextZ=null,t*=2}while(e>1);return n}function no(n,e,t,i,s){return n=(n-t)*s|0,e=(e-i)*s|0,n=(n|n<<8)&16711935,n=(n|n<<4)&252645135,n=(n|n<<2)&858993459,n=(n|n<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,n|e<<1}function Dg(n){let e=n,t=n;do(e.x<t.x||e.x===t.x&&e.y<t.y)&&(t=e),e=e.next;while(e!==n);return t}function Jc(n,e,t,i,s,r,o,a){return(s-o)*(e-a)>=(n-o)*(r-a)&&(n-o)*(i-a)>=(t-o)*(e-a)&&(t-o)*(r-a)>=(s-o)*(i-a)}function Zi(n,e,t,i,s,r,o,a){return!(n===o&&e===a)&&Jc(n,e,t,i,s,r,o,a)}function Fg(n,e){return n.next.i!==e.i&&n.prev.i!==e.i&&!Bg(n,e)&&(fs(n,e)&&fs(e,n)&&Lg(n,e)&&(dt(n.prev,n,e.prev)||dt(n,e.prev,e))||_i(n,e)&&dt(n.prev,n,n.next)>0&&dt(e.prev,e,e.next)>0)}function dt(n,e,t){return(e.y-n.y)*(t.x-e.x)-(e.x-n.x)*(t.y-e.y)}function _i(n,e){return n.x===e.x&&n.y===e.y}function td(n,e,t,i){const s=Gs(dt(n,e,t)),r=Gs(dt(n,e,i)),o=Gs(dt(t,i,n)),a=Gs(dt(t,i,e));return!!(s!==r&&o!==a||s===0&&Ws(n,t,e)||r===0&&Ws(n,i,e)||o===0&&Ws(t,n,i)||a===0&&Ws(t,e,i))}function Ws(n,e,t){return e.x<=Math.max(n.x,t.x)&&e.x>=Math.min(n.x,t.x)&&e.y<=Math.max(n.y,t.y)&&e.y>=Math.min(n.y,t.y)}function Gs(n){return n>0?1:n<0?-1:0}function Bg(n,e){let t=n;do{if(t.i!==n.i&&t.next.i!==n.i&&t.i!==e.i&&t.next.i!==e.i&&td(t,t.next,n,e))return!0;t=t.next}while(t!==n);return!1}function fs(n,e){return dt(n.prev,n,n.next)<0?dt(n,e,n.next)>=0&&dt(n,n.prev,e)>=0:dt(n,e,n.prev)<0||dt(n,n.next,e)<0}function Lg(n,e){let t=n,i=!1;const s=(n.x+e.x)/2,r=(n.y+e.y)/2;do t.y>r!=t.next.y>r&&t.next.y!==t.y&&s<(t.next.x-t.x)*(r-t.y)/(t.next.y-t.y)+t.x&&(i=!i),t=t.next;while(t!==n);return i}function ed(n,e){const t=ro(n.i,n.x,n.y),i=ro(e.i,e.x,e.y),s=n.next,r=e.prev;return n.next=e,e.prev=n,t.next=s,s.prev=t,i.next=t,t.prev=i,r.next=i,i.prev=r,i}function Qa(n,e,t,i){const s=ro(n,e,t);return i?(s.next=i.next,s.prev=i,i.next.prev=s,i.next=s):(s.prev=s,s.next=s),s}function gs(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 ro(n,e,t){return{i:n,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function zg(n,e,t,i){let s=0;for(let r=e,o=t-i;r<t;r+=i)s+=(n[o]-n[r])*(n[r+1]+n[o+1]),o=r;return s}const Og=Ka.default||Ka;var id=(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))(id||{});class Wg{constructor(e){this.items=[],this._name=e}emit(e,t,i,s,r,o,a,l){const{name:h,items:c}=this;for(let d=0,u=c.length;d<u;d++)c[d][h](e,t,i,s,r,o,a,l);return this}add(e){return e[this._name]&&(this.remove(e),this.items.push(e)),this}remove(e){const t=this.items.indexOf(e);return t!==-1&&this.items.splice(t,1),this}contains(e){return this.items.indexOf(e)!==-1}removeAll(){return this.items.length=0,this}destroy(){this.removeAll(),this.items=null,this._name=null}get empty(){return this.items.length===0}get name(){return this._name}}const Gg=["init","destroy","contextChange","resolutionChange","resetState","renderEnd","renderStart","render","update","postrender","prerender"],sd=class nd extends ae{constructor(e){super(),this.tick=0,this.uid=ft("renderer"),this.runners=Object.create(null),this.renderPipes=Object.create(null),this._initOptions={},this._systemsHash=Object.create(null),this.type=e.type,this.name=e.name,this.config=e;const t=[...Gg,...this.config.runners??[]];this._addRunners(...t),this._unsafeEvalCheck()}async init(e={}){const t=e.skipExtensionImports===!0?!0:e.manageImports===!1;await bg(t),this._addSystems(this.config.systems),this._addPipes(this.config.renderPipes,this.config.renderPipeAdaptors);for(const i in this._systemsHash)e={...this._systemsHash[i].constructor.defaultOptions,...e};e={...nd.defaultOptions,...e},this._roundPixels=e.roundPixels?1:0;for(let i=0;i<this.runners.init.items.length;i++)await this.runners.init.items[i].init(e);this._initOptions=e}render(e,t){this.tick++;let i=e;if(i instanceof O&&(i={container:i},t&&(X(tt,"passing a second argument is deprecated, please use render options instead"),i.target=t.renderTexture)),i.target||(i.target=this.view.renderTarget),i.target===this.view.renderTarget&&(this._lastObjectRendered=i.container,i.clearColor??(i.clearColor=this.background.colorRgba),i.clear??(i.clear=this.background.clearBeforeRender)),i.clearColor){const s=Array.isArray(i.clearColor)&&i.clearColor.length===4;i.clearColor=s?i.clearColor:ht.shared.setValue(i.clearColor).toArray()}i.transform||(i.container.updateLocalTransform(),i.transform=i.container.localTransform),i.container.visible&&(i.container.enableRenderGroup(),this.runners.prerender.emit(i),this.runners.renderStart.emit(i),this.runners.render.emit(i),this.runners.renderEnd.emit(i),this.runners.postrender.emit(i))}resize(e,t,i){const s=this.view.resolution;this.view.resize(e,t,i),this.emit("resize",this.view.screen.width,this.view.screen.height,this.view.resolution),i!==void 0&&i!==s&&this.runners.resolutionChange.emit(i)}clear(e={}){const t=this;e.target||(e.target=t.renderTarget.renderTarget),e.clearColor||(e.clearColor=this.background.colorRgba),e.clear??(e.clear=id.ALL);const{clear:i,clearColor:s,target:r,mipLevel:o,layer:a}=e;ht.shared.setValue(s??this.background.colorRgba),t.renderTarget.clear(r,i,ht.shared.toArray(),o??0,a??0)}get resolution(){return this.view.resolution}set resolution(e){this.view.resolution=e,this.runners.resolutionChange.emit(e)}get width(){return this.view.texture.frame.width}get height(){return this.view.texture.frame.height}get canvas(){return this.view.canvas}get lastObjectRendered(){return this._lastObjectRendered}get renderingToScreen(){return this.renderTarget.renderingToScreen}get screen(){return this.view.screen}_addRunners(...e){e.forEach(t=>{this.runners[t]=new Wg(t)})}_addSystems(e){let t;for(t in e){const i=e[t];this._addSystem(i.value,i.name)}}_addSystem(e,t){const i=new e(this);if(this[t])throw new Error(`Whoops! The name "${t}" is already in use`);this[t]=i,this._systemsHash[t]=i;for(const s in this.runners)this.runners[s].add(i);return this}_addPipes(e,t){const i=t.reduce((s,r)=>(s[r.name]=r.value,s),{});e.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(e=!1){this.runners.destroy.items.reverse(),this.runners.destroy.emit(e),(e===!0||typeof e=="object"&&e.releaseGlobalResources)&&_s.release(),Object.values(this.runners).forEach(t=>{t.destroy()}),this._systemsHash=null,this.renderPipes=null}generateTexture(e){return this.textureGenerator.generateTexture(e)}get roundPixels(){return!!this._roundPixels}_unsafeEvalCheck(){if(!vg())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()}};sd.defaultOptions={resolution:1,failIfMajorPerformanceCaveat:!1,roundPixels:!1};let rd=sd,Us;function Ug(n){return Us!==void 0||(Us=(()=>{var t;const e={stencil:!0,failIfMajorPerformanceCaveat:n??rd.defaultOptions.failIfMajorPerformanceCaveat};try{if(!Z.get().getWebGLRenderingContext())return!1;let s=Z.get().createCanvas().getContext("webgl",e);const r=!!((t=s==null?void 0:s.getContextAttributes())!=null&&t.stencil);if(s){const o=s.getExtension("WEBGL_lose_context");o&&o.loseContext()}return s=null,r}catch{return!1}})()),Us}let Hs;async function Hg(n={}){return Hs!==void 0||(Hs=await(async()=>{const e=Z.get().getNavigator().gpu;if(!e)return!1;try{return await(await e.requestAdapter(n)).requestDevice(),!0}catch{return!1}})()),Hs}const Ja=["webgl","webgpu","canvas"];async function Ng(n){let e=[];n.preference?(e.push(n.preference),Ja.forEach(r=>{r!==n.preference&&e.push(r)})):e=Ja.slice();let t,i={};for(let r=0;r<e.length;r++){const o=e[r];if(o==="webgpu"&&await Hg()){const{WebGPURenderer:a}=await je(async()=>{const{WebGPURenderer:l}=await import("./WebGPURenderer.CrTlLNt7.js");return{WebGPURenderer:l}},__vite__mapDeps([5,6,7,2,3,4]));t=a,i={...n,...n.webgpu};break}else if(o==="webgl"&&Ug(n.failIfMajorPerformanceCaveat??rd.defaultOptions.failIfMajorPerformanceCaveat)){const{WebGLRenderer:a}=await je(async()=>{const{WebGLRenderer:l}=await import("./WebGLRenderer.DDBDE-SE.js");return{WebGLRenderer:l}},__vite__mapDeps([8,6,7,2,3,4]));t=a,i={...n,...n.webgl};break}else if(o==="canvas"){const{CanvasRenderer:a}=await je(async()=>{const{CanvasRenderer:l}=await import("./CanvasRenderer.vEsk0ehs.js");return{CanvasRenderer:l}},__vite__mapDeps([9,7,2,3,4]));t=a,i={...n,...n.canvasOptions};break}}if(delete i.webgpu,delete i.webgl,delete i.canvasOptions,!t)throw new Error("No available renderer for the current environment");const s=new t;return await s.init(i),s}const od="8.16.0";class ad{static init(){var e;(e=globalThis.__PIXI_APP_INIT__)==null||e.call(globalThis,this,od)}static destroy(){}}ad.extension=B.Application;class Vg{constructor(e){this._renderer=e}init(){var e;(e=globalThis.__PIXI_RENDERER_INIT__)==null||e.call(globalThis,this._renderer,od)}destroy(){this._renderer=null}}Vg.extension={type:[B.WebGLSystem,B.WebGPUSystem],name:"initHook",priority:-10};class ld{static init(e){Object.defineProperty(this,"resizeTo",{configurable:!0,set(t){globalThis.removeEventListener("resize",this.queueResize),this._resizeTo=t,t&&(globalThis.addEventListener("resize",this.queueResize),this.resize())},get(){return this._resizeTo}}),this.queueResize=()=>{this._resizeTo&&(this._cancelResize(),this._resizeId=requestAnimationFrame(()=>this.resize()))},this._cancelResize=()=>{this._resizeId&&(cancelAnimationFrame(this._resizeId),this._resizeId=null)},this.resize=()=>{if(!this._resizeTo)return;this._cancelResize();let t,i;if(this._resizeTo===globalThis.window)t=globalThis.innerWidth,i=globalThis.innerHeight;else{const{clientWidth:s,clientHeight:r}=this._resizeTo;t=s,i=r}this.renderer.resize(t,i),this.render()},this._resizeId=null,this._resizeTo=null,this.resizeTo=e.resizeTo||null}static destroy(){globalThis.removeEventListener("resize",this.queueResize),this._cancelResize(),this._cancelResize=null,this.queueResize=null,this.resizeTo=null,this.resize=null}}ld.extension=B.Application;class hd{static init(e){e=Object.assign({autoStart:!0,sharedTicker:!1},e),Object.defineProperty(this,"ticker",{configurable:!0,set(t){this._ticker&&this._ticker.remove(this.render,this),this._ticker=t,t&&t.add(this.render,this,ke.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=e.sharedTicker?mt.shared:new mt,e.autoStart&&this.start()}static destroy(){if(this._ticker){const e=this._ticker;this.ticker=null,e.destroy()}}}hd.extension=B.Application;Q.add(ld);Q.add(hd);const cd=class oo{constructor(...e){this.stage=new O,e[0]!==void 0&&X(tt,"Application constructor options are deprecated, please use Application.init() instead.")}async init(e){e={...e},this.stage||(this.stage=new O),this.renderer=await Ng(e),oo._plugins.forEach(t=>{t.init.call(this,e)})}render(){this.renderer.render({container:this.stage})}get canvas(){return this.renderer.canvas}get view(){return X(tt,"Application.view is deprecated, please use Application.canvas instead."),this.renderer.canvas}get screen(){return this.renderer.screen}destroy(e=!1,t=!1){const i=oo._plugins.slice(0);i.reverse(),i.forEach(s=>{s.destroy.call(this)}),this.stage.destroy(t),this.stage=null,this.renderer.destroy(e),this.renderer=null}};cd._plugins=[];let dd=cd;Q.handleByList(B.Application,dd._plugins);Q.add(ad);const mr={test(n){return typeof n=="string"&&n.startsWith("info face=")},parse(n){const e=n.match(/^[a-z]+\s+.+$/gm),t={info:[],common:[],page:[],char:[],chars:[],kerning:[],kernings:[],distanceField:[]};for(const d in e){const u=e[d].match(/^[a-z]+/gm)[0],p=e[d].match(/[a-zA-Z]+=([^\s"']+|"([^"]*)")/gm),f={};for(const m in p){const g=p[m].split("="),x=g[0],S=g[1].replace(/"/gm,""),b=parseFloat(S),w=isNaN(b)?S:b;f[x]=w}t[u].push(f)}const i={chars:{},pages:[],lineHeight:0,fontSize:0,fontFamily:"",distanceField:null,baseLineOffset:0},[s]=t.info,[r]=t.common,[o]=t.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=t.page;for(let d=0;d<a.length;d++)i.pages.push({id:parseInt(a[d].id,10)||0,file:a[d].file});const l={};i.baseLineOffset=i.lineHeight-parseInt(r.base,10);const h=t.char;for(let d=0;d<h.length;d++){const u=h[d],p=parseInt(u.id,10);let f=u.letter??u.char??String.fromCharCode(p);f==="space"&&(f=" "),l[p]=f,i.chars[f]={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=t.kerning||[];for(let d=0;d<c.length;d++){const u=parseInt(c[d].first,10),p=parseInt(c[d].second,10),f=parseInt(c[d].amount,10);i.chars[l[p]].kerning[l[u]]=f}return i}},tl={test(n){const e=n;return typeof e!="string"&&"getElementsByTagName"in e&&e.getElementsByTagName("page").length&&e.getElementsByTagName("info")[0].getAttribute("face")!==null},parse(n){const e={chars:{},pages:[],lineHeight:0,fontSize:0,fontFamily:"",distanceField:null,baseLineOffset:0},t=n.getElementsByTagName("info")[0],i=n.getElementsByTagName("common")[0],s=n.getElementsByTagName("distanceField")[0];s&&(e.distanceField={type:s.getAttribute("fieldType"),range:parseInt(s.getAttribute("distanceRange"),10)});const r=n.getElementsByTagName("page"),o=n.getElementsByTagName("char"),a=n.getElementsByTagName("kerning");e.fontSize=parseInt(t.getAttribute("size"),10),e.fontFamily=t.getAttribute("face"),e.lineHeight=parseInt(i.getAttribute("lineHeight"),10);for(let h=0;h<r.length;h++)e.pages.push({id:parseInt(r[h].getAttribute("id"),10)||0,file:r[h].getAttribute("file")});const l={};e.baseLineOffset=e.lineHeight-parseInt(i.getAttribute("base"),10);for(let h=0;h<o.length;h++){const c=o[h],d=parseInt(c.getAttribute("id"),10);let u=c.getAttribute("letter")??c.getAttribute("char")??String.fromCharCode(d);u==="space"&&(u=" "),l[d]=u,e.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 h=0;h<a.length;h++){const c=parseInt(a[h].getAttribute("first"),10),d=parseInt(a[h].getAttribute("second"),10),u=parseInt(a[h].getAttribute("amount"),10);e.chars[l[d]].kerning[l[c]]=u}return e}},el={test(n){return typeof n=="string"&&n.match(/<font(\s|>)/)?tl.test(Z.get().parseXML(n)):!1},parse(n){return tl.parse(Z.get().parseXML(n))}},$g=[".xml",".fnt"],Xg={extension:{type:B.CacheParser,name:"cacheBitmapFont"},test:n=>!!(n!=null&&n.pages)&&!!(n!=null&&n.chars)&&typeof(n==null?void 0:n.fontFamily)=="string",getCacheableAssets(n,e){const t={};return n.forEach(i=>{t[i]=e,t[`${i}-bitmap`]=e}),t[`${e.fontFamily}-bitmap`]=e,t}},Yg={extension:{type:B.LoadParser,priority:Be.Normal},name:"loadBitmapFont",id:"bitmap-font",test(n){return $g.includes(It.extname(n).toLowerCase())},async testParse(n){return mr.test(n)||el.test(n)},async parse(n,e,t){const i=mr.test(n)?mr.parse(n):el.parse(n),{src:s}=e,{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 f=It.join(It.dirname(s),p);f=Qr(f,s),o.push({src:f,data:a})}const[l,{BitmapFont:h}]=await Promise.all([t.load(o),je(()=>import("./BitmapFont.ga4S-mSe.js"),__vite__mapDeps([10,2,3,4]))]),c=o.map(u=>l[u.src]);return new h({data:i,textures:c},s)},async load(n,e){return await(await Z.get().fetch(n)).text()},async unload(n,e,t){await Promise.all(n.pages.map(i=>t.unload(i.texture.source._sourceOrigin))),n.destroy()}};class jg{constructor(e,t=!1){this._loader=e,this._assetList=[],this._isLoading=!1,this._maxConcurrent=1,this.verbose=t}add(e){e.forEach(t=>{this._assetList.push(t)}),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 e=[],t=Math.min(this._assetList.length,this._maxConcurrent);for(let i=0;i<t;i++)e.push(this._assetList.pop());await this._loader.load(e),this._isLoading=!1,this._next()}}get active(){return this._isActive}set active(e){this._isActive!==e&&(this._isActive=e,e&&!this._isLoading&&this._next())}}const Zg={extension:{type:B.CacheParser,name:"cacheTextureArray"},test:n=>Array.isArray(n)&&n.every(e=>e instanceof U),getCacheableAssets:(n,e)=>{const t={};return n.forEach(i=>{e.forEach((s,r)=>{t[i+(r===0?"":r+1)]=s})}),t}};async function ud(n){if("Image"in globalThis)return new Promise(e=>{const t=new Image;t.onload=()=>{e(!0)},t.onerror=()=>{e(!1)},t.src=n});if("createImageBitmap"in globalThis&&"fetch"in globalThis){try{const e=await(await fetch(n)).blob();await createImageBitmap(e)}catch{return!1}return!0}return!1}const qg={extension:{type:B.DetectionParser,priority:1},test:async()=>ud("data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAAB0AAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAIAAAACAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQ0MAAAAABNjb2xybmNseAACAAIAAYAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAACVtZGF0EgAKCBgANogQEAwgMg8f8D///8WfhwB8+ErK42A="),add:async n=>[...n,"avif"],remove:async n=>n.filter(e=>e!=="avif")},il=["png","jpg","jpeg"],Kg={extension:{type:B.DetectionParser,priority:-1},test:()=>Promise.resolve(!0),add:async n=>[...n,...il],remove:async n=>n.filter(e=>!il.includes(e))},Qg="WorkerGlobalScope"in globalThis&&globalThis instanceof globalThis.WorkerGlobalScope;function kn(n){return Qg?!1:document.createElement("video").canPlayType(n)!==""}const Jg={extension:{type:B.DetectionParser,priority:0},test:async()=>kn("video/mp4"),add:async n=>[...n,"mp4","m4v"],remove:async n=>n.filter(e=>e!=="mp4"&&e!=="m4v")},tm={extension:{type:B.DetectionParser,priority:0},test:async()=>kn("video/ogg"),add:async n=>[...n,"ogv"],remove:async n=>n.filter(e=>e!=="ogv")},em={extension:{type:B.DetectionParser,priority:0},test:async()=>kn("video/webm"),add:async n=>[...n,"webm"],remove:async n=>n.filter(e=>e!=="webm")},im={extension:{type:B.DetectionParser,priority:0},test:async()=>ud("data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA="),add:async n=>[...n,"webp"],remove:async n=>n.filter(e=>e!=="webp")},pd=class rn{constructor(){this.loadOptions={...rn.defaultOptions},this._parsers=[],this._parsersValidated=!1,this.parsers=new Proxy(this._parsers,{set:(e,t,i)=>(this._parsersValidated=!1,e[t]=i,!0)}),this.promiseCache={}}reset(){this._parsersValidated=!1,this.promiseCache={}}_getLoadPromiseAndParser(e,t){const i={promise:null,parser:null};return i.promise=(async()=>{var o,a;let s=null,r=null;if((t.parser||t.loadParser)&&(r=this._parserHash[t.parser||t.loadParser],t.loadParser&<(`[Assets] "loadParser" is deprecated, use "parser" instead for ${e}`),r||lt(`[Assets] specified load parser "${t.parser||t.loadParser}" not found while loading ${e}`)),!r){for(let l=0;l<this.parsers.length;l++){const h=this.parsers[l];if(h.load&&((o=h.test)!=null&&o.call(h,e,t,this))){r=h;break}}if(!r)return lt(`[Assets] ${e} 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(e,t,this),i.parser=r;for(let l=0;l<this.parsers.length;l++){const h=this.parsers[l];h.parse&&h.parse&&await((a=h.testParse)==null?void 0:a.call(h,s,t,this))&&(s=await h.parse(s,t,this)||s,i.parser=h)}return s})(),i}async load(e,t){this._parsersValidated||this._validateParsers();const i=typeof t=="function"?{...rn.defaultOptions,...this.loadOptions,onProgress:t}:{...rn.defaultOptions,...this.loadOptions,...t||{}},{onProgress:s,onError:r,strategy:o,retryCount:a,retryDelay:l}=i;let h=0;const c={},d=fn(e),u=Vt(e,m=>({alias:[m],src:m,data:{}})),p=u.reduce((m,g)=>m+(g.progressSize||1),0),f=u.map(async m=>{const g=It.toAbsolute(m.src);c[m.src]||(await this._loadAssetWithRetry(g,m,{onProgress:s,onError:r,strategy:o,retryCount:a,retryDelay:l},c),h+=m.progressSize||1,s&&s(h/p))});return await Promise.all(f),d?c[u[0].src]:c}async unload(e){const i=Vt(e,s=>({alias:[s],src:s})).map(async s=>{var a,l;const r=It.toAbsolute(s.src),o=this.promiseCache[r];if(o){const h=await o.promise;delete this.promiseCache[r],await((l=(a=o.parser)==null?void 0:a.unload)==null?void 0:l.call(a,h,s,this))}});await Promise.all(i)}_validateParsers(){this._parsersValidated=!0,this._parserHash=this._parsers.filter(e=>e.name||e.id).reduce((e,t)=>(!t.name&&!t.id?lt("[Assets] parser should have an id"):(e[t.name]||e[t.id])&<(`[Assets] parser id conflict "${t.id}"`),e[t.name]=t,t.id&&(e[t.id]=t),e),{})}async _loadAssetWithRetry(e,t,i,s){let r=0;const{onError:o,strategy:a,retryCount:l,retryDelay:h}=i,c=d=>new Promise(u=>setTimeout(u,d));for(;;)try{this.promiseCache[e]||(this.promiseCache[e]=this._getLoadPromiseAndParser(e,t)),s[t.src]=await this.promiseCache[e].promise;return}catch(d){delete this.promiseCache[e],delete s[t.src],r++;const u=a!=="retry"||r>l;if(a==="retry"&&!u){o&&o(d,t),await c(h);continue}if(a==="skip"){o&&o(d,t);return}o&&o(d,t);const p=new Error(`[Loader.load] Failed to load ${e}.
|
|
23
|
+
${n}`}function lg(n,e){return e?n.replace("#version 300 es",""):n}const lr={stripVersion:lg,ensurePrecision:sg,addProgramDefines:ig,setProgramName:ag,insertVersion:ng},zi=Object.create(null),Xc=class to{constructor(e){e={...to.defaultOptions,...e};const t=e.fragment.indexOf("#version 300 es")!==-1,i={stripVersion:t,ensurePrecision:{requestedFragmentPrecision:e.preferredFragmentPrecision,requestedVertexPrecision:e.preferredVertexPrecision,maxSupportedVertexPrecision:"highp",maxSupportedFragmentPrecision:eg()},setProgramName:{name:e.name},addProgramDefines:t,insertVersion:t};let s=e.fragment,r=e.vertex;Object.keys(lr).forEach(o=>{const a=i[o];s=lr[o](s,a,!0),r=lr[o](r,a,!1)}),this.fragment=s,this.vertex=r,this.transformFeedbackVaryings=e.transformFeedbackVaryings,this._key=Bo(`${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,zi[this._cacheKey]=null}static from(e){const t=`${e.vertex}:${e.fragment}`;return zi[t]||(zi[t]=new to(e),zi[t]._cacheKey=t),zi[t]}};Xc.defaultOptions={preferredVertexPrecision:"highp",preferredFragmentPrecision:"mediump"};let Ci=Xc;const ja={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 hg(n){return ja[n]??ja.float32}const cg={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"},Za=/@location\((\d+)\)\s+([a-zA-Z0-9_]+)\s*:\s*([a-zA-Z0-9_<>]+)(?:,|\s|\)|$)/g;function qa(n,e){let t;for(;(t=Za.exec(n))!==null;){const i=cg[t[3]]??"float32";e[t[2]]={location:parseInt(t[1],10),format:i,stride:hg(i).stride,offset:0,instance:!1,start:0}}Za.lastIndex=0}function dg(n){return n.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"")}function ug({source:n,entryPoint:e}){const t={},i=dg(n),s=i.indexOf(`fn ${e}(`);if(s===-1)return t;const r=i.indexOf("->",s);if(r===-1)return t;const o=i.substring(s,r);if(qa(o,t),Object.keys(t).length===0){const a=o.match(/\(\s*\w+\s*:\s*(\w+)/);if(a){const l=a[1],h=new RegExp(`struct\\s+${l}\\s*\\{([^}]+)\\}`,"s"),c=i.match(h);c&&qa(c[1],t)}}return t}function hr(n){var d,u;const e=/(^|[^/])@(group|binding)\(\d+\)[^;]+;/g,t=/@group\((\d+)\)/,i=/@binding\((\d+)\)/,s=/var(<[^>]+>)? (\w+)/,r=/:\s*([\w<>]+)/,o=/struct\s+(\w+)\s*{([^}]+)}/g,a=/(\w+)\s*:\s*([\w\<\>]+)/g,l=/struct\s+(\w+)/,h=(d=n.match(e))==null?void 0:d.map(p=>({group:parseInt(p.match(t)[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(!h)return{groups:[],structs:[]};const c=((u=n.match(o))==null?void 0:u.map(p=>{const f=p.match(l)[1],m=p.match(a).reduce((g,x)=>{const[S,b]=x.split(":");return g[S.trim()]=b.trim(),g},{});return m?{name:f,members:m}:null}).filter(({name:p})=>h.some(f=>f.type===p||f.type.includes(`<${p}>`))))??[];return{groups:h,structs:c}}var Ne=(n=>(n[n.VERTEX=1]="VERTEX",n[n.FRAGMENT=2]="FRAGMENT",n[n.COMPUTE=4]="COMPUTE",n))(Ne||{});function pg({groups:n}){const e=[];for(let t=0;t<n.length;t++){const i=n[t];e[i.group]||(e[i.group]=[]),i.isUniform?e[i.group].push({binding:i.binding,visibility:Ne.VERTEX|Ne.FRAGMENT,buffer:{type:"uniform"}}):i.type==="sampler"?e[i.group].push({binding:i.binding,visibility:Ne.FRAGMENT,sampler:{type:"filtering"}}):i.type==="texture_2d"||i.type.startsWith("texture_2d<")?e[i.group].push({binding:i.binding,visibility:Ne.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d",multisampled:!1}}):i.type==="texture_2d_array"||i.type.startsWith("texture_2d_array<")?e[i.group].push({binding:i.binding,visibility:Ne.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d-array",multisampled:!1}}):(i.type==="texture_cube"||i.type.startsWith("texture_cube<"))&&e[i.group].push({binding:i.binding,visibility:Ne.FRAGMENT,texture:{sampleType:"float",viewDimension:"cube",multisampled:!1}})}for(let t=0;t<e.length;t++)e[t]||(e[t]=[]);return e}function fg({groups:n}){const e=[];for(let t=0;t<n.length;t++){const i=n[t];e[i.group]||(e[i.group]={}),e[i.group][i.name]=i.binding}return e}function gg(n,e){const t=new Set,i=new Set,s=[...n.structs,...e.structs].filter(o=>t.has(o.name)?!1:(t.add(o.name),!0)),r=[...n.groups,...e.groups].filter(o=>{const a=`${o.name}-${o.binding}`;return i.has(a)?!1:(i.add(a),!0)});return{structs:s,groups:r}}const Oi=Object.create(null);class Ie{constructor(e){var a,l;this._layoutKey=0,this._attributeLocationsKey=0;const{fragment:t,vertex:i,layout:s,gpuLayout:r,name:o}=e;if(this.name=o,this.fragment=t,this.vertex=i,t.source===i.source){const h=hr(t.source);this.structsAndGroups=h}else{const h=hr(i.source),c=hr(t.source);this.structsAndGroups=gg(h,c)}this.layout=s??fg(this.structsAndGroups),this.gpuLayout=r??pg(this.structsAndGroups),this.autoAssignGlobalUniforms=((a=this.layout[0])==null?void 0:a.globalUniforms)!==void 0,this.autoAssignLocalUniforms=((l=this.layout[1])==null?void 0:l.localUniforms)!==void 0,this._generateProgramKey()}_generateProgramKey(){const{vertex:e,fragment:t}=this,i=e.source+t.source+e.entryPoint+t.entryPoint;this._layoutKey=Bo(i,"program")}get attributeData(){return this._attributeData??(this._attributeData=ug(this.vertex)),this._attributeData}destroy(){this.gpuLayout=null,this.layout=null,this.structsAndGroups=null,this.fragment=null,this.vertex=null,Oi[this._cacheKey]=null}static from(e){const t=`${e.vertex.source}:${e.fragment.source}:${e.fragment.entryPoint}:${e.vertex.entryPoint}`;return Oi[t]||(Oi[t]=new Ie(e),Oi[t]._cacheKey=t),Oi[t]}}const Yc=["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>"],mg=Yc.reduce((n,e)=>(n[e]=!0,n),{});function yg(n,e){switch(n){case"f32":return 0;case"vec2<f32>":return new Float32Array(2*e);case"vec3<f32>":return new Float32Array(3*e);case"vec4<f32>":return new Float32Array(4*e);case"mat2x2<f32>":return new Float32Array([1,0,0,1]);case"mat3x3<f32>":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4x4<f32>":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}const jc=class Zc{constructor(e,t){this._touched=0,this.uid=ft("uniform"),this._resourceType="uniformGroup",this._resourceId=ft("resource"),this.isUniformGroup=!0,this._dirtyId=0,this.destroyed=!1,t={...Zc.defaultOptions,...t},this.uniformStructures=e;const i={};for(const s in e){const r=e[s];if(r.name=s,r.size=r.size??1,!mg[r.type]){const o=r.type.match(/^array<(\w+(?:<\w+>)?),\s*(\d+)>$/);if(o){const[,a,l]=o;throw new Error(`Uniform type ${r.type} is not supported. Use type: '${a}', size: ${l} instead.`)}throw new Error(`Uniform type ${r.type} is not supported. Supported uniform types are: ${Yc.join(", ")}`)}r.value??(r.value=yg(r.type,r.size)),i[s]=r.value}this.uniforms=i,this._dirtyId=1,this.ubo=t.ubo,this.isStatic=t.isStatic,this._signature=Bo(Object.keys(i).map(s=>`${s}-${e[s].type}`).join("-"),"uniform-group")}update(){this._dirtyId++}};jc.defaultOptions={ubo:!1,isStatic:!1};let Mi=jc;class ss{constructor(e){this.resources=Object.create(null),this._dirty=!0;let t=0;for(const i in e){const s=e[i];this.setResource(s,t++)}this._updateKey()}_updateKey(){if(!this._dirty)return;this._dirty=!1;const e=[];let t=0;for(const i in this.resources)e[t++]=this.resources[i]._resourceId;this._key=e.join("|")}setResource(e,t){var s,r;const i=this.resources[t];e!==i&&(i&&((s=i.off)==null||s.call(i,"change",this.onResourceChange,this)),(r=e.on)==null||r.call(e,"change",this.onResourceChange,this),this.resources[t]=e,this._dirty=!0)}getResource(e){return this.resources[e]}_touch(e,t){const i=this.resources;for(const s in i)i[s]._gcLastUsed=e,i[s]._touched=t}destroy(){var t;const e=this.resources;for(const i in e){const s=e[i];(t=s==null?void 0:s.off)==null||t.call(s,"change",this.onResourceChange,this)}this.resources=null}onResourceChange(e){if(this._dirty=!0,e.destroyed){const t=this.resources;for(const i in t)t[i]===e&&(t[i]=null)}else this._updateKey()}}var pe=(n=>(n[n.WEBGL=1]="WEBGL",n[n.WEBGPU=2]="WEBGPU",n[n.CANVAS=4]="CANVAS",n[n.BOTH=3]="BOTH",n))(pe||{});class Je extends ae{constructor(e){super(),this.uid=ft("shader"),this._uniformBindMap=Object.create(null),this._ownedBindGroups=[],this._destroyed=!1;let{gpuProgram:t,glProgram:i,groups:s,resources:r,compatibleRenderers:o,groupMap:a}=e;this.gpuProgram=t,this.glProgram=i,o===void 0&&(o=0,t&&(o|=pe.WEBGPU),i&&(o|=pe.WEBGL)),this.compatibleRenderers=o;const l={};if(!r&&!s&&(r={}),r&&s)throw new Error("[Shader] Cannot have both resources and groups");if(!t&&s&&!a)throw new Error("[Shader] No group map or WebGPU shader provided - consider using resources instead.");if(!t&&s&&a)for(const h in a)for(const c in a[h]){const d=a[h][c];l[d]={group:h,binding:c,name:d}}else if(t&&s&&!a){const h=t.structsAndGroups.groups;a={},h.forEach(c=>{a[c.group]=a[c.group]||{},a[c.group][c.binding]=c.name,l[c.name]=c})}else if(r){s={},a={},t&&t.structsAndGroups.groups.forEach(d=>{a[d.group]=a[d.group]||{},a[d.group][d.binding]=d.name,l[d.name]=d});let h=0;for(const c in r)l[c]||(s[99]||(s[99]=new ss,this._ownedBindGroups.push(s[99])),l[c]={group:99,binding:h,name:c},a[99]=a[99]||{},a[99][h]=c,h++);for(const c in r){const d=c;let u=r[c];!u.source&&!u._resourceType&&(u=new Mi(u));const p=l[d];p&&(s[p.group]||(s[p.group]=new ss,this._ownedBindGroups.push(s[p.group])),s[p.group].setResource(u,p.binding))}}this.groups=s,this._uniformBindMap=a,this.resources=this._buildResourceAccessor(s,l)}addResource(e,t,i){var s,r;(s=this._uniformBindMap)[t]||(s[t]={}),(r=this._uniformBindMap[t])[i]||(r[i]=e),this.groups[t]||(this.groups[t]=new ss,this._ownedBindGroups.push(this.groups[t]))}_buildResourceAccessor(e,t){const i={};for(const s in t){const r=t[s];Object.defineProperty(i,r.name,{get(){return e[r.group].getResource(r.binding)},set(o){e[r.group].setResource(o,r.binding)}})}return i}destroy(e=!1){var t,i;this._destroyed||(this._destroyed=!0,this.emit("destroy",this),e&&((t=this.gpuProgram)==null||t.destroy(),(i=this.glProgram)==null||i.destroy()),this.gpuProgram=null,this.glProgram=null,this.removeAllListeners(),this._uniformBindMap=null,this._ownedBindGroups.forEach(s=>{s.destroy()}),this._ownedBindGroups=null,this.resources=null,this.groups=null)}static from(e){const{gpu:t,gl:i,...s}=e;let r,o;return t&&(r=Ie.from(t)),i&&(o=Ci.from(i)),new Je({gpuProgram:r,glProgram:o,...s})}}const xg={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},cr=0,dr=1,ur=2,pr=3,fr=4,gr=5,eo=class qc{constructor(){this.data=0,this.blendMode="normal",this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(this.data&1<<cr)}set blend(e){!!(this.data&1<<cr)!==e&&(this.data^=1<<cr)}get offsets(){return!!(this.data&1<<dr)}set offsets(e){!!(this.data&1<<dr)!==e&&(this.data^=1<<dr)}set cullMode(e){if(e==="none"){this.culling=!1;return}this.culling=!0,this.clockwiseFrontFace=e==="front"}get cullMode(){return this.culling?this.clockwiseFrontFace?"front":"back":"none"}get culling(){return!!(this.data&1<<ur)}set culling(e){!!(this.data&1<<ur)!==e&&(this.data^=1<<ur)}get depthTest(){return!!(this.data&1<<pr)}set depthTest(e){!!(this.data&1<<pr)!==e&&(this.data^=1<<pr)}get depthMask(){return!!(this.data&1<<gr)}set depthMask(e){!!(this.data&1<<gr)!==e&&(this.data^=1<<gr)}get clockwiseFrontFace(){return!!(this.data&1<<fr)}set clockwiseFrontFace(e){!!(this.data&1<<fr)!==e&&(this.data^=1<<fr)}get blendMode(){return this._blendMode}set blendMode(e){this.blend=e!=="none",this._blendMode=e,this._blendModeId=xg[e]||0}get polygonOffset(){return this._polygonOffset}set polygonOffset(e){this.offsets=!!e,this._polygonOffset=e}toString(){return`[pixi.js/core:State blendMode=${this.blendMode} clockwiseFrontFace=${this.clockwiseFrontFace} culling=${this.culling} depthMask=${this.depthMask} polygonOffset=${this.polygonOffset}]`}static for2d(){const e=new qc;return e.depthTest=!1,e.blend=!0,e}};eo.default2d=eo.for2d();let Ps=eo;const Kc=class io extends Je{constructor(e){e={...io.defaultOptions,...e},super(e),this.enabled=!0,this._state=Ps.for2d(),this.blendMode=e.blendMode,this.padding=e.padding,typeof e.antialias=="boolean"?this.antialias=e.antialias?"on":"off":this.antialias=e.antialias,this.resolution=e.resolution,this.blendRequired=e.blendRequired,this.clipToViewport=e.clipToViewport,this.addResource("uTexture",0,1),e.blendRequired&&this.addResource("uBackTexture",0,3)}apply(e,t,i,s){e.applyFilter(this,t,i,s)}get blendMode(){return this._state.blendMode}set blendMode(e){this._state.blendMode=e}static from(e){const{gpu:t,gl:i,...s}=e;let r,o;return t&&(r=Ie.from(t)),i&&(o=Ci.from(i)),new io({gpuProgram:r,glProgram:o,...s})}};Kc.defaultOptions={blendMode:"normal",resolution:1,padding:0,antialias:"off",blendRequired:!1,clipToViewport:!0};let Sg=Kc;const so=[];Q.handleByNamedList(B.Environment,so);async function bg(n){if(!n)for(let e=0;e<so.length;e++){const t=so[e];if(t.value.test()){await t.value.load();return}}}let Wi;function vg(){if(typeof Wi=="boolean")return Wi;try{Wi=new Function("param1","param2","param3","return param1[param2] === param3;")({a:"b"},"a","b")===!0}catch{Wi=!1}return Wi}function Ka(n,e,t=2){const i=e&&e.length,s=i?e[0]*t:n.length;let r=Qc(n,0,s,t,!0);const o=[];if(!r||r.next===r.prev)return o;let a,l,h;if(i&&(r=Pg(n,e,r,t)),n.length>80*t){a=n[0],l=n[1];let c=a,d=l;for(let u=t;u<s;u+=t){const p=n[u],f=n[u+1];p<a&&(a=p),f<l&&(l=f),p>c&&(c=p),f>d&&(d=f)}h=Math.max(c-a,d-l),h=h!==0?32767/h:0}return ps(r,o,t,a,l,h,0),o}function Qc(n,e,t,i,s){let r;if(s===zg(n,e,t,i)>0)for(let o=e;o<t;o+=i)r=Qa(o/i|0,n[o],n[o+1],r);else for(let o=t-i;o>=e;o-=i)r=Qa(o/i|0,n[o],n[o+1],r);return r&&_i(r,r.next)&&(gs(r),r=r.next),r}function ti(n,e){if(!n)return n;e||(e=n);let t=n,i;do if(i=!1,!t.steiner&&(_i(t,t.next)||dt(t.prev,t,t.next)===0)){if(gs(t),t=e=t.prev,t===t.next)break;i=!0}else t=t.next;while(i||t!==e);return e}function ps(n,e,t,i,s,r,o){if(!n)return;!o&&r&&kg(n,i,s,r);let a=n;for(;n.prev!==n.next;){const l=n.prev,h=n.next;if(r?Cg(n,i,s,r):wg(n)){e.push(l.i,n.i,h.i),gs(n),n=h.next,a=h.next;continue}if(n=h,n===a){o?o===1?(n=Mg(ti(n),e),ps(n,e,t,i,s,r,2)):o===2&&_g(n,e,t,i,s,r):ps(ti(n),e,t,i,s,r,1);break}}}function wg(n){const e=n.prev,t=n,i=n.next;if(dt(e,t,i)>=0)return!1;const s=e.x,r=t.x,o=i.x,a=e.y,l=t.y,h=i.y,c=Math.min(s,r,o),d=Math.min(a,l,h),u=Math.max(s,r,o),p=Math.max(a,l,h);let f=i.next;for(;f!==e;){if(f.x>=c&&f.x<=u&&f.y>=d&&f.y<=p&&Zi(s,a,r,l,o,h,f.x,f.y)&&dt(f.prev,f,f.next)>=0)return!1;f=f.next}return!0}function Cg(n,e,t,i){const s=n.prev,r=n,o=n.next;if(dt(s,r,o)>=0)return!1;const a=s.x,l=r.x,h=o.x,c=s.y,d=r.y,u=o.y,p=Math.min(a,l,h),f=Math.min(c,d,u),m=Math.max(a,l,h),g=Math.max(c,d,u),x=no(p,f,e,t,i),S=no(m,g,e,t,i);let b=n.prevZ,w=n.nextZ;for(;b&&b.z>=x&&w&&w.z<=S;){if(b.x>=p&&b.x<=m&&b.y>=f&&b.y<=g&&b!==s&&b!==o&&Zi(a,c,l,d,h,u,b.x,b.y)&&dt(b.prev,b,b.next)>=0||(b=b.prevZ,w.x>=p&&w.x<=m&&w.y>=f&&w.y<=g&&w!==s&&w!==o&&Zi(a,c,l,d,h,u,w.x,w.y)&&dt(w.prev,w,w.next)>=0))return!1;w=w.nextZ}for(;b&&b.z>=x;){if(b.x>=p&&b.x<=m&&b.y>=f&&b.y<=g&&b!==s&&b!==o&&Zi(a,c,l,d,h,u,b.x,b.y)&&dt(b.prev,b,b.next)>=0)return!1;b=b.prevZ}for(;w&&w.z<=S;){if(w.x>=p&&w.x<=m&&w.y>=f&&w.y<=g&&w!==s&&w!==o&&Zi(a,c,l,d,h,u,w.x,w.y)&&dt(w.prev,w,w.next)>=0)return!1;w=w.nextZ}return!0}function Mg(n,e){let t=n;do{const i=t.prev,s=t.next.next;!_i(i,s)&&td(i,t,t.next,s)&&fs(i,s)&&fs(s,i)&&(e.push(i.i,t.i,s.i),gs(t),gs(t.next),t=n=s),t=t.next}while(t!==n);return ti(t)}function _g(n,e,t,i,s,r){let o=n;do{let a=o.next.next;for(;a!==o.prev;){if(o.i!==a.i&&Fg(o,a)){let l=ed(o,a);o=ti(o,o.next),l=ti(l,l.next),ps(o,e,t,i,s,r,0),ps(l,e,t,i,s,r,0);return}a=a.next}o=o.next}while(o!==n)}function Pg(n,e,t,i){const s=[];for(let r=0,o=e.length;r<o;r++){const a=e[r]*i,l=r<o-1?e[r+1]*i:n.length,h=Qc(n,a,l,i,!1);h===h.next&&(h.steiner=!0),s.push(Dg(h))}s.sort(Ag);for(let r=0;r<s.length;r++)t=Tg(s[r],t);return t}function Ag(n,e){let t=n.x-e.x;if(t===0&&(t=n.y-e.y,t===0)){const i=(n.next.y-n.y)/(n.next.x-n.x),s=(e.next.y-e.y)/(e.next.x-e.x);t=i-s}return t}function Tg(n,e){const t=Rg(n,e);if(!t)return e;const i=ed(t,n);return ti(i,i.next),ti(t,t.next)}function Rg(n,e){let t=e;const i=n.x,s=n.y;let r=-1/0,o;if(_i(n,t))return t;do{if(_i(n,t.next))return t.next;if(s<=t.y&&s>=t.next.y&&t.next.y!==t.y){const d=t.x+(s-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(d<=i&&d>r&&(r=d,o=t.x<t.next.x?t:t.next,d===i))return o}t=t.next}while(t!==e);if(!o)return null;const a=o,l=o.x,h=o.y;let c=1/0;t=o;do{if(i>=t.x&&t.x>=l&&i!==t.x&&Jc(s<h?i:r,s,l,h,s<h?r:i,s,t.x,t.y)){const d=Math.abs(s-t.y)/(i-t.x);fs(t,n)&&(d<c||d===c&&(t.x>o.x||t.x===o.x&&Eg(o,t)))&&(o=t,c=d)}t=t.next}while(t!==a);return o}function Eg(n,e){return dt(n.prev,n,e.prev)<0&&dt(e.next,n,n.next)<0}function kg(n,e,t,i){let s=n;do s.z===0&&(s.z=no(s.x,s.y,e,t,i)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next;while(s!==n);s.prevZ.nextZ=null,s.prevZ=null,Ig(s)}function Ig(n){let e,t=1;do{let i=n,s;n=null;let r=null;for(e=0;i;){e++;let o=i,a=0;for(let h=0;h<t&&(a++,o=o.nextZ,!!o);h++);let l=t;for(;a>0||l>0&&o;)a!==0&&(l===0||!o||i.z<=o.z)?(s=i,i=i.nextZ,a--):(s=o,o=o.nextZ,l--),r?r.nextZ=s:n=s,s.prevZ=r,r=s;i=o}r.nextZ=null,t*=2}while(e>1);return n}function no(n,e,t,i,s){return n=(n-t)*s|0,e=(e-i)*s|0,n=(n|n<<8)&16711935,n=(n|n<<4)&252645135,n=(n|n<<2)&858993459,n=(n|n<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,n|e<<1}function Dg(n){let e=n,t=n;do(e.x<t.x||e.x===t.x&&e.y<t.y)&&(t=e),e=e.next;while(e!==n);return t}function Jc(n,e,t,i,s,r,o,a){return(s-o)*(e-a)>=(n-o)*(r-a)&&(n-o)*(i-a)>=(t-o)*(e-a)&&(t-o)*(r-a)>=(s-o)*(i-a)}function Zi(n,e,t,i,s,r,o,a){return!(n===o&&e===a)&&Jc(n,e,t,i,s,r,o,a)}function Fg(n,e){return n.next.i!==e.i&&n.prev.i!==e.i&&!Bg(n,e)&&(fs(n,e)&&fs(e,n)&&Lg(n,e)&&(dt(n.prev,n,e.prev)||dt(n,e.prev,e))||_i(n,e)&&dt(n.prev,n,n.next)>0&&dt(e.prev,e,e.next)>0)}function dt(n,e,t){return(e.y-n.y)*(t.x-e.x)-(e.x-n.x)*(t.y-e.y)}function _i(n,e){return n.x===e.x&&n.y===e.y}function td(n,e,t,i){const s=Gs(dt(n,e,t)),r=Gs(dt(n,e,i)),o=Gs(dt(t,i,n)),a=Gs(dt(t,i,e));return!!(s!==r&&o!==a||s===0&&Ws(n,t,e)||r===0&&Ws(n,i,e)||o===0&&Ws(t,n,i)||a===0&&Ws(t,e,i))}function Ws(n,e,t){return e.x<=Math.max(n.x,t.x)&&e.x>=Math.min(n.x,t.x)&&e.y<=Math.max(n.y,t.y)&&e.y>=Math.min(n.y,t.y)}function Gs(n){return n>0?1:n<0?-1:0}function Bg(n,e){let t=n;do{if(t.i!==n.i&&t.next.i!==n.i&&t.i!==e.i&&t.next.i!==e.i&&td(t,t.next,n,e))return!0;t=t.next}while(t!==n);return!1}function fs(n,e){return dt(n.prev,n,n.next)<0?dt(n,e,n.next)>=0&&dt(n,n.prev,e)>=0:dt(n,e,n.prev)<0||dt(n,n.next,e)<0}function Lg(n,e){let t=n,i=!1;const s=(n.x+e.x)/2,r=(n.y+e.y)/2;do t.y>r!=t.next.y>r&&t.next.y!==t.y&&s<(t.next.x-t.x)*(r-t.y)/(t.next.y-t.y)+t.x&&(i=!i),t=t.next;while(t!==n);return i}function ed(n,e){const t=ro(n.i,n.x,n.y),i=ro(e.i,e.x,e.y),s=n.next,r=e.prev;return n.next=e,e.prev=n,t.next=s,s.prev=t,i.next=t,t.prev=i,r.next=i,i.prev=r,i}function Qa(n,e,t,i){const s=ro(n,e,t);return i?(s.next=i.next,s.prev=i,i.next.prev=s,i.next=s):(s.prev=s,s.next=s),s}function gs(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 ro(n,e,t){return{i:n,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function zg(n,e,t,i){let s=0;for(let r=e,o=t-i;r<t;r+=i)s+=(n[o]-n[r])*(n[r+1]+n[o+1]),o=r;return s}const Og=Ka.default||Ka;var id=(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))(id||{});class Wg{constructor(e){this.items=[],this._name=e}emit(e,t,i,s,r,o,a,l){const{name:h,items:c}=this;for(let d=0,u=c.length;d<u;d++)c[d][h](e,t,i,s,r,o,a,l);return this}add(e){return e[this._name]&&(this.remove(e),this.items.push(e)),this}remove(e){const t=this.items.indexOf(e);return t!==-1&&this.items.splice(t,1),this}contains(e){return this.items.indexOf(e)!==-1}removeAll(){return this.items.length=0,this}destroy(){this.removeAll(),this.items=null,this._name=null}get empty(){return this.items.length===0}get name(){return this._name}}const Gg=["init","destroy","contextChange","resolutionChange","resetState","renderEnd","renderStart","render","update","postrender","prerender"],sd=class nd extends ae{constructor(e){super(),this.tick=0,this.uid=ft("renderer"),this.runners=Object.create(null),this.renderPipes=Object.create(null),this._initOptions={},this._systemsHash=Object.create(null),this.type=e.type,this.name=e.name,this.config=e;const t=[...Gg,...this.config.runners??[]];this._addRunners(...t),this._unsafeEvalCheck()}async init(e={}){const t=e.skipExtensionImports===!0?!0:e.manageImports===!1;await bg(t),this._addSystems(this.config.systems),this._addPipes(this.config.renderPipes,this.config.renderPipeAdaptors);for(const i in this._systemsHash)e={...this._systemsHash[i].constructor.defaultOptions,...e};e={...nd.defaultOptions,...e},this._roundPixels=e.roundPixels?1:0;for(let i=0;i<this.runners.init.items.length;i++)await this.runners.init.items[i].init(e);this._initOptions=e}render(e,t){this.tick++;let i=e;if(i instanceof O&&(i={container:i},t&&(X(tt,"passing a second argument is deprecated, please use render options instead"),i.target=t.renderTexture)),i.target||(i.target=this.view.renderTarget),i.target===this.view.renderTarget&&(this._lastObjectRendered=i.container,i.clearColor??(i.clearColor=this.background.colorRgba),i.clear??(i.clear=this.background.clearBeforeRender)),i.clearColor){const s=Array.isArray(i.clearColor)&&i.clearColor.length===4;i.clearColor=s?i.clearColor:ht.shared.setValue(i.clearColor).toArray()}i.transform||(i.container.updateLocalTransform(),i.transform=i.container.localTransform),i.container.visible&&(i.container.enableRenderGroup(),this.runners.prerender.emit(i),this.runners.renderStart.emit(i),this.runners.render.emit(i),this.runners.renderEnd.emit(i),this.runners.postrender.emit(i))}resize(e,t,i){const s=this.view.resolution;this.view.resize(e,t,i),this.emit("resize",this.view.screen.width,this.view.screen.height,this.view.resolution),i!==void 0&&i!==s&&this.runners.resolutionChange.emit(i)}clear(e={}){const t=this;e.target||(e.target=t.renderTarget.renderTarget),e.clearColor||(e.clearColor=this.background.colorRgba),e.clear??(e.clear=id.ALL);const{clear:i,clearColor:s,target:r,mipLevel:o,layer:a}=e;ht.shared.setValue(s??this.background.colorRgba),t.renderTarget.clear(r,i,ht.shared.toArray(),o??0,a??0)}get resolution(){return this.view.resolution}set resolution(e){this.view.resolution=e,this.runners.resolutionChange.emit(e)}get width(){return this.view.texture.frame.width}get height(){return this.view.texture.frame.height}get canvas(){return this.view.canvas}get lastObjectRendered(){return this._lastObjectRendered}get renderingToScreen(){return this.renderTarget.renderingToScreen}get screen(){return this.view.screen}_addRunners(...e){e.forEach(t=>{this.runners[t]=new Wg(t)})}_addSystems(e){let t;for(t in e){const i=e[t];this._addSystem(i.value,i.name)}}_addSystem(e,t){const i=new e(this);if(this[t])throw new Error(`Whoops! The name "${t}" is already in use`);this[t]=i,this._systemsHash[t]=i;for(const s in this.runners)this.runners[s].add(i);return this}_addPipes(e,t){const i=t.reduce((s,r)=>(s[r.name]=r.value,s),{});e.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(e=!1){this.runners.destroy.items.reverse(),this.runners.destroy.emit(e),(e===!0||typeof e=="object"&&e.releaseGlobalResources)&&_s.release(),Object.values(this.runners).forEach(t=>{t.destroy()}),this._systemsHash=null,this.renderPipes=null}generateTexture(e){return this.textureGenerator.generateTexture(e)}get roundPixels(){return!!this._roundPixels}_unsafeEvalCheck(){if(!vg())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()}};sd.defaultOptions={resolution:1,failIfMajorPerformanceCaveat:!1,roundPixels:!1};let rd=sd,Us;function Ug(n){return Us!==void 0||(Us=(()=>{var t;const e={stencil:!0,failIfMajorPerformanceCaveat:n??rd.defaultOptions.failIfMajorPerformanceCaveat};try{if(!Z.get().getWebGLRenderingContext())return!1;let s=Z.get().createCanvas().getContext("webgl",e);const r=!!((t=s==null?void 0:s.getContextAttributes())!=null&&t.stencil);if(s){const o=s.getExtension("WEBGL_lose_context");o&&o.loseContext()}return s=null,r}catch{return!1}})()),Us}let Hs;async function Hg(n={}){return Hs!==void 0||(Hs=await(async()=>{const e=Z.get().getNavigator().gpu;if(!e)return!1;try{return await(await e.requestAdapter(n)).requestDevice(),!0}catch{return!1}})()),Hs}const Ja=["webgl","webgpu","canvas"];async function Ng(n){let e=[];n.preference?(e.push(n.preference),Ja.forEach(r=>{r!==n.preference&&e.push(r)})):e=Ja.slice();let t,i={};for(let r=0;r<e.length;r++){const o=e[r];if(o==="webgpu"&&await Hg()){const{WebGPURenderer:a}=await je(async()=>{const{WebGPURenderer:l}=await import("./WebGPURenderer.CNOqh8b3.js");return{WebGPURenderer:l}},__vite__mapDeps([5,6,7,2,3,4]));t=a,i={...n,...n.webgpu};break}else if(o==="webgl"&&Ug(n.failIfMajorPerformanceCaveat??rd.defaultOptions.failIfMajorPerformanceCaveat)){const{WebGLRenderer:a}=await je(async()=>{const{WebGLRenderer:l}=await import("./WebGLRenderer.DRQ9GEc2.js");return{WebGLRenderer:l}},__vite__mapDeps([8,6,7,2,3,4]));t=a,i={...n,...n.webgl};break}else if(o==="canvas"){const{CanvasRenderer:a}=await je(async()=>{const{CanvasRenderer:l}=await import("./CanvasRenderer.CY93dSp-.js");return{CanvasRenderer:l}},__vite__mapDeps([9,7,2,3,4]));t=a,i={...n,...n.canvasOptions};break}}if(delete i.webgpu,delete i.webgl,delete i.canvasOptions,!t)throw new Error("No available renderer for the current environment");const s=new t;return await s.init(i),s}const od="8.16.0";class ad{static init(){var e;(e=globalThis.__PIXI_APP_INIT__)==null||e.call(globalThis,this,od)}static destroy(){}}ad.extension=B.Application;class Vg{constructor(e){this._renderer=e}init(){var e;(e=globalThis.__PIXI_RENDERER_INIT__)==null||e.call(globalThis,this._renderer,od)}destroy(){this._renderer=null}}Vg.extension={type:[B.WebGLSystem,B.WebGPUSystem],name:"initHook",priority:-10};class ld{static init(e){Object.defineProperty(this,"resizeTo",{configurable:!0,set(t){globalThis.removeEventListener("resize",this.queueResize),this._resizeTo=t,t&&(globalThis.addEventListener("resize",this.queueResize),this.resize())},get(){return this._resizeTo}}),this.queueResize=()=>{this._resizeTo&&(this._cancelResize(),this._resizeId=requestAnimationFrame(()=>this.resize()))},this._cancelResize=()=>{this._resizeId&&(cancelAnimationFrame(this._resizeId),this._resizeId=null)},this.resize=()=>{if(!this._resizeTo)return;this._cancelResize();let t,i;if(this._resizeTo===globalThis.window)t=globalThis.innerWidth,i=globalThis.innerHeight;else{const{clientWidth:s,clientHeight:r}=this._resizeTo;t=s,i=r}this.renderer.resize(t,i),this.render()},this._resizeId=null,this._resizeTo=null,this.resizeTo=e.resizeTo||null}static destroy(){globalThis.removeEventListener("resize",this.queueResize),this._cancelResize(),this._cancelResize=null,this.queueResize=null,this.resizeTo=null,this.resize=null}}ld.extension=B.Application;class hd{static init(e){e=Object.assign({autoStart:!0,sharedTicker:!1},e),Object.defineProperty(this,"ticker",{configurable:!0,set(t){this._ticker&&this._ticker.remove(this.render,this),this._ticker=t,t&&t.add(this.render,this,ke.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=e.sharedTicker?mt.shared:new mt,e.autoStart&&this.start()}static destroy(){if(this._ticker){const e=this._ticker;this.ticker=null,e.destroy()}}}hd.extension=B.Application;Q.add(ld);Q.add(hd);const cd=class oo{constructor(...e){this.stage=new O,e[0]!==void 0&&X(tt,"Application constructor options are deprecated, please use Application.init() instead.")}async init(e){e={...e},this.stage||(this.stage=new O),this.renderer=await Ng(e),oo._plugins.forEach(t=>{t.init.call(this,e)})}render(){this.renderer.render({container:this.stage})}get canvas(){return this.renderer.canvas}get view(){return X(tt,"Application.view is deprecated, please use Application.canvas instead."),this.renderer.canvas}get screen(){return this.renderer.screen}destroy(e=!1,t=!1){const i=oo._plugins.slice(0);i.reverse(),i.forEach(s=>{s.destroy.call(this)}),this.stage.destroy(t),this.stage=null,this.renderer.destroy(e),this.renderer=null}};cd._plugins=[];let dd=cd;Q.handleByList(B.Application,dd._plugins);Q.add(ad);const mr={test(n){return typeof n=="string"&&n.startsWith("info face=")},parse(n){const e=n.match(/^[a-z]+\s+.+$/gm),t={info:[],common:[],page:[],char:[],chars:[],kerning:[],kernings:[],distanceField:[]};for(const d in e){const u=e[d].match(/^[a-z]+/gm)[0],p=e[d].match(/[a-zA-Z]+=([^\s"']+|"([^"]*)")/gm),f={};for(const m in p){const g=p[m].split("="),x=g[0],S=g[1].replace(/"/gm,""),b=parseFloat(S),w=isNaN(b)?S:b;f[x]=w}t[u].push(f)}const i={chars:{},pages:[],lineHeight:0,fontSize:0,fontFamily:"",distanceField:null,baseLineOffset:0},[s]=t.info,[r]=t.common,[o]=t.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=t.page;for(let d=0;d<a.length;d++)i.pages.push({id:parseInt(a[d].id,10)||0,file:a[d].file});const l={};i.baseLineOffset=i.lineHeight-parseInt(r.base,10);const h=t.char;for(let d=0;d<h.length;d++){const u=h[d],p=parseInt(u.id,10);let f=u.letter??u.char??String.fromCharCode(p);f==="space"&&(f=" "),l[p]=f,i.chars[f]={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=t.kerning||[];for(let d=0;d<c.length;d++){const u=parseInt(c[d].first,10),p=parseInt(c[d].second,10),f=parseInt(c[d].amount,10);i.chars[l[p]].kerning[l[u]]=f}return i}},tl={test(n){const e=n;return typeof e!="string"&&"getElementsByTagName"in e&&e.getElementsByTagName("page").length&&e.getElementsByTagName("info")[0].getAttribute("face")!==null},parse(n){const e={chars:{},pages:[],lineHeight:0,fontSize:0,fontFamily:"",distanceField:null,baseLineOffset:0},t=n.getElementsByTagName("info")[0],i=n.getElementsByTagName("common")[0],s=n.getElementsByTagName("distanceField")[0];s&&(e.distanceField={type:s.getAttribute("fieldType"),range:parseInt(s.getAttribute("distanceRange"),10)});const r=n.getElementsByTagName("page"),o=n.getElementsByTagName("char"),a=n.getElementsByTagName("kerning");e.fontSize=parseInt(t.getAttribute("size"),10),e.fontFamily=t.getAttribute("face"),e.lineHeight=parseInt(i.getAttribute("lineHeight"),10);for(let h=0;h<r.length;h++)e.pages.push({id:parseInt(r[h].getAttribute("id"),10)||0,file:r[h].getAttribute("file")});const l={};e.baseLineOffset=e.lineHeight-parseInt(i.getAttribute("base"),10);for(let h=0;h<o.length;h++){const c=o[h],d=parseInt(c.getAttribute("id"),10);let u=c.getAttribute("letter")??c.getAttribute("char")??String.fromCharCode(d);u==="space"&&(u=" "),l[d]=u,e.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 h=0;h<a.length;h++){const c=parseInt(a[h].getAttribute("first"),10),d=parseInt(a[h].getAttribute("second"),10),u=parseInt(a[h].getAttribute("amount"),10);e.chars[l[d]].kerning[l[c]]=u}return e}},el={test(n){return typeof n=="string"&&n.match(/<font(\s|>)/)?tl.test(Z.get().parseXML(n)):!1},parse(n){return tl.parse(Z.get().parseXML(n))}},$g=[".xml",".fnt"],Xg={extension:{type:B.CacheParser,name:"cacheBitmapFont"},test:n=>!!(n!=null&&n.pages)&&!!(n!=null&&n.chars)&&typeof(n==null?void 0:n.fontFamily)=="string",getCacheableAssets(n,e){const t={};return n.forEach(i=>{t[i]=e,t[`${i}-bitmap`]=e}),t[`${e.fontFamily}-bitmap`]=e,t}},Yg={extension:{type:B.LoadParser,priority:Be.Normal},name:"loadBitmapFont",id:"bitmap-font",test(n){return $g.includes(It.extname(n).toLowerCase())},async testParse(n){return mr.test(n)||el.test(n)},async parse(n,e,t){const i=mr.test(n)?mr.parse(n):el.parse(n),{src:s}=e,{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 f=It.join(It.dirname(s),p);f=Qr(f,s),o.push({src:f,data:a})}const[l,{BitmapFont:h}]=await Promise.all([t.load(o),je(()=>import("./BitmapFont.JB98v0Ym.js"),__vite__mapDeps([10,2,3,4]))]),c=o.map(u=>l[u.src]);return new h({data:i,textures:c},s)},async load(n,e){return await(await Z.get().fetch(n)).text()},async unload(n,e,t){await Promise.all(n.pages.map(i=>t.unload(i.texture.source._sourceOrigin))),n.destroy()}};class jg{constructor(e,t=!1){this._loader=e,this._assetList=[],this._isLoading=!1,this._maxConcurrent=1,this.verbose=t}add(e){e.forEach(t=>{this._assetList.push(t)}),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 e=[],t=Math.min(this._assetList.length,this._maxConcurrent);for(let i=0;i<t;i++)e.push(this._assetList.pop());await this._loader.load(e),this._isLoading=!1,this._next()}}get active(){return this._isActive}set active(e){this._isActive!==e&&(this._isActive=e,e&&!this._isLoading&&this._next())}}const Zg={extension:{type:B.CacheParser,name:"cacheTextureArray"},test:n=>Array.isArray(n)&&n.every(e=>e instanceof U),getCacheableAssets:(n,e)=>{const t={};return n.forEach(i=>{e.forEach((s,r)=>{t[i+(r===0?"":r+1)]=s})}),t}};async function ud(n){if("Image"in globalThis)return new Promise(e=>{const t=new Image;t.onload=()=>{e(!0)},t.onerror=()=>{e(!1)},t.src=n});if("createImageBitmap"in globalThis&&"fetch"in globalThis){try{const e=await(await fetch(n)).blob();await createImageBitmap(e)}catch{return!1}return!0}return!1}const qg={extension:{type:B.DetectionParser,priority:1},test:async()=>ud("data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAAB0AAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAIAAAACAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQ0MAAAAABNjb2xybmNseAACAAIAAYAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAACVtZGF0EgAKCBgANogQEAwgMg8f8D///8WfhwB8+ErK42A="),add:async n=>[...n,"avif"],remove:async n=>n.filter(e=>e!=="avif")},il=["png","jpg","jpeg"],Kg={extension:{type:B.DetectionParser,priority:-1},test:()=>Promise.resolve(!0),add:async n=>[...n,...il],remove:async n=>n.filter(e=>!il.includes(e))},Qg="WorkerGlobalScope"in globalThis&&globalThis instanceof globalThis.WorkerGlobalScope;function kn(n){return Qg?!1:document.createElement("video").canPlayType(n)!==""}const Jg={extension:{type:B.DetectionParser,priority:0},test:async()=>kn("video/mp4"),add:async n=>[...n,"mp4","m4v"],remove:async n=>n.filter(e=>e!=="mp4"&&e!=="m4v")},tm={extension:{type:B.DetectionParser,priority:0},test:async()=>kn("video/ogg"),add:async n=>[...n,"ogv"],remove:async n=>n.filter(e=>e!=="ogv")},em={extension:{type:B.DetectionParser,priority:0},test:async()=>kn("video/webm"),add:async n=>[...n,"webm"],remove:async n=>n.filter(e=>e!=="webm")},im={extension:{type:B.DetectionParser,priority:0},test:async()=>ud("data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA="),add:async n=>[...n,"webp"],remove:async n=>n.filter(e=>e!=="webp")},pd=class rn{constructor(){this.loadOptions={...rn.defaultOptions},this._parsers=[],this._parsersValidated=!1,this.parsers=new Proxy(this._parsers,{set:(e,t,i)=>(this._parsersValidated=!1,e[t]=i,!0)}),this.promiseCache={}}reset(){this._parsersValidated=!1,this.promiseCache={}}_getLoadPromiseAndParser(e,t){const i={promise:null,parser:null};return i.promise=(async()=>{var o,a;let s=null,r=null;if((t.parser||t.loadParser)&&(r=this._parserHash[t.parser||t.loadParser],t.loadParser&<(`[Assets] "loadParser" is deprecated, use "parser" instead for ${e}`),r||lt(`[Assets] specified load parser "${t.parser||t.loadParser}" not found while loading ${e}`)),!r){for(let l=0;l<this.parsers.length;l++){const h=this.parsers[l];if(h.load&&((o=h.test)!=null&&o.call(h,e,t,this))){r=h;break}}if(!r)return lt(`[Assets] ${e} 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(e,t,this),i.parser=r;for(let l=0;l<this.parsers.length;l++){const h=this.parsers[l];h.parse&&h.parse&&await((a=h.testParse)==null?void 0:a.call(h,s,t,this))&&(s=await h.parse(s,t,this)||s,i.parser=h)}return s})(),i}async load(e,t){this._parsersValidated||this._validateParsers();const i=typeof t=="function"?{...rn.defaultOptions,...this.loadOptions,onProgress:t}:{...rn.defaultOptions,...this.loadOptions,...t||{}},{onProgress:s,onError:r,strategy:o,retryCount:a,retryDelay:l}=i;let h=0;const c={},d=fn(e),u=Vt(e,m=>({alias:[m],src:m,data:{}})),p=u.reduce((m,g)=>m+(g.progressSize||1),0),f=u.map(async m=>{const g=It.toAbsolute(m.src);c[m.src]||(await this._loadAssetWithRetry(g,m,{onProgress:s,onError:r,strategy:o,retryCount:a,retryDelay:l},c),h+=m.progressSize||1,s&&s(h/p))});return await Promise.all(f),d?c[u[0].src]:c}async unload(e){const i=Vt(e,s=>({alias:[s],src:s})).map(async s=>{var a,l;const r=It.toAbsolute(s.src),o=this.promiseCache[r];if(o){const h=await o.promise;delete this.promiseCache[r],await((l=(a=o.parser)==null?void 0:a.unload)==null?void 0:l.call(a,h,s,this))}});await Promise.all(i)}_validateParsers(){this._parsersValidated=!0,this._parserHash=this._parsers.filter(e=>e.name||e.id).reduce((e,t)=>(!t.name&&!t.id?lt("[Assets] parser should have an id"):(e[t.name]||e[t.id])&<(`[Assets] parser id conflict "${t.id}"`),e[t.name]=t,t.id&&(e[t.id]=t),e),{})}async _loadAssetWithRetry(e,t,i,s){let r=0;const{onError:o,strategy:a,retryCount:l,retryDelay:h}=i,c=d=>new Promise(u=>setTimeout(u,d));for(;;)try{this.promiseCache[e]||(this.promiseCache[e]=this._getLoadPromiseAndParser(e,t)),s[t.src]=await this.promiseCache[e].promise;return}catch(d){delete this.promiseCache[e],delete s[t.src],r++;const u=a!=="retry"||r>l;if(a==="retry"&&!u){o&&o(d,t),await c(h);continue}if(a==="skip"){o&&o(d,t);return}o&&o(d,t);const p=new Error(`[Loader.load] Failed to load ${e}.
|
|
24
24
|
${d}`);throw d instanceof Error&&d.stack&&(p.stack=d.stack),p}}};pd.defaultOptions={onProgress:void 0,onError:void 0,strategy:"throw",retryCount:3,retryDelay:250};let sm=pd;function Le(n,e){if(Array.isArray(e)){for(const t of e)if(n.startsWith(`data:${t}`))return!0;return!1}return n.startsWith(`data:${e}`)}function Ei(n,e){const t=n.split("?")[0],i=It.extname(t).toLowerCase();return Array.isArray(e)?e.includes(i):i===e}const nm=".json",rm="application/json",om={extension:{type:B.LoadParser,priority:Be.Low},name:"loadJson",id:"json",test(n){return Le(n,rm)||Ei(n,nm)},async load(n){return await(await Z.get().fetch(n)).json()}},am=".txt",lm="text/plain",hm={name:"loadTxt",id:"text",extension:{type:B.LoadParser,priority:Be.Low,name:"loadTxt"},test(n){return Le(n,lm)||Ei(n,am)},async load(n){return await(await Z.get().fetch(n)).text()}},cm=["normal","bold","100","200","300","400","500","600","700","800","900"],dm=[".ttf",".otf",".woff",".woff2"],um=["font/ttf","font/otf","font/woff","font/woff2"],pm=/^(--|-?[A-Z_])[0-9A-Z_-]*$/i;function fm(n){const e=It.extname(n),s=It.basename(n,e).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(pm)){r=!1;break}let o=s.join(" ");return r||(o=`"${o.replace(/[\\"]/g,"\\$&")}"`),o}const gm=/^[0-9A-Za-z%:/?#\[\]@!\$&'()\*\+,;=\-._~]*$/;function mm(n){return gm.test(n)?n:encodeURI(n)}const ym={extension:{type:B.LoadParser,priority:Be.Low},name:"loadWebFont",id:"web-font",test(n){return Le(n,um)||Ei(n,dm)},async load(n,e){var i,s,r;const t=Z.get().getFontFaceSet();if(t){const o=[],a=((i=e.data)==null?void 0:i.family)??fm(n),l=((r=(s=e.data)==null?void 0:s.weights)==null?void 0:r.filter(c=>cm.includes(c)))??["normal"],h=e.data??{};for(let c=0;c<l.length;c++){const d=l[c],u=new FontFace(a,`url(${mm(n)})`,{...h,weight:d});await u.load(),t.add(u),o.push(u)}return vt.has(`${a}-and-url`)?vt.get(`${a}-and-url`).entries.push({url:n,faces:o}):vt.set(`${a}-and-url`,{entries:[{url:n,faces:o}]}),o.length===1?o[0]:o}return lt("[loadWebFont] FontFace API is not supported. Skipping loading font"),null},unload(n){const e=Array.isArray(n)?n:[n],t=e[0].family,i=vt.get(`${t}-and-url`),s=i.entries.find(r=>r.faces.some(o=>e.indexOf(o)!==-1));s.faces=s.faces.filter(r=>e.indexOf(r)===-1),s.faces.length===0&&(i.entries=i.entries.filter(r=>r!==s)),e.forEach(r=>{Z.get().getFontFaceSet().delete(r)}),i.entries.length===0&&vt.remove(`${t}-and-url`)}};var xm=bm,yr={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},Sm=/([astvzqmhlc])([^astvzqmhlc]*)/ig;function bm(n){var e=[];return n.replace(Sm,function(t,i,s){var r=i.toLowerCase();for(s=wm(s),r=="m"&&s.length>2&&(e.push([i].concat(s.splice(0,2))),r="l",i=i=="m"?"l":"L");;){if(s.length==yr[r])return s.unshift(i),e.push(s);if(s.length<yr[r])throw new Error("malformed path data");e.push([i].concat(s.splice(0,yr[r])))}}),e}var vm=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig;function wm(n){var e=n.match(vm);return e?e.map(Number):[]}const Cm=lc(xm);function Mm(n,e){const t=Cm(n),i=[];let s=null,r=0,o=0;for(let a=0;a<t.length;a++){const l=t[a],h=l[0],c=l;switch(h){case"M":r=c[1],o=c[2],e.moveTo(r,o);break;case"m":r+=c[1],o+=c[2],e.moveTo(r,o);break;case"H":r=c[1],e.lineTo(r,o);break;case"h":r+=c[1],e.lineTo(r,o);break;case"V":o=c[1],e.lineTo(r,o);break;case"v":o+=c[1],e.lineTo(r,o);break;case"L":r=c[1],o=c[2],e.lineTo(r,o);break;case"l":r+=c[1],o+=c[2],e.lineTo(r,o);break;case"C":r=c[5],o=c[6],e.bezierCurveTo(c[1],c[2],c[3],c[4],r,o);break;case"c":e.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],e.bezierCurveToShort(c[1],c[2],r,o);break;case"s":e.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],e.quadraticCurveTo(c[1],c[2],r,o);break;case"q":e.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],e.quadraticCurveToShort(r,o);break;case"t":r+=c[1],o+=c[2],e.quadraticCurveToShort(r,o);break;case"A":r=c[6],o=c[7],e.arcToSvg(c[1],c[2],c[3],c[4],c[5],r,o);break;case"a":r+=c[6],o+=c[7],e.arcToSvg(c[1],c[2],c[3],c[4],c[5],r,o);break;case"Z":case"z":e.closePath(),i.length>0&&(s=i.pop(),s?(r=s.startX,o=s.startY):(r=0,o=0)),s=null;break;default:lt(`Unknown SVG path command: ${h}`)}h!=="Z"&&h!=="z"&&s===null&&(s={startX:r,startY:o},i.push(s))}return e}class As{constructor(e=0,t=0,i=0){this.type="circle",this.x=e,this.y=t,this.radius=i}clone(){return new As(this.x,this.y,this.radius)}contains(e,t){if(this.radius<=0)return!1;const i=this.radius*this.radius;let s=this.x-e,r=this.y-t;return s*=s,r*=r,s+r<=i}strokeContains(e,t,i,s=.5){if(this.radius===0)return!1;const r=this.x-e,o=this.y-t,a=this.radius,l=(1-s)*i,h=Math.sqrt(r*r+o*o);return h<=a+l&&h>a-(i-l)}getBounds(e){return e||(e=new st),e.x=this.x-this.radius,e.y=this.y-this.radius,e.width=this.radius*2,e.height=this.radius*2,e}copyFrom(e){return this.x=e.x,this.y=e.y,this.radius=e.radius,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:Circle x=${this.x} y=${this.y} radius=${this.radius}]`}}class Lo{constructor(e=0,t=0,i=0,s=0){this.type="ellipse",this.x=e,this.y=t,this.halfWidth=i,this.halfHeight=s}clone(){return new Lo(this.x,this.y,this.halfWidth,this.halfHeight)}contains(e,t){if(this.halfWidth<=0||this.halfHeight<=0)return!1;let i=(e-this.x)/this.halfWidth,s=(t-this.y)/this.halfHeight;return i*=i,s*=s,i+s<=1}strokeContains(e,t,i,s=.5){const{halfWidth:r,halfHeight:o}=this;if(r<=0||o<=0)return!1;const a=i*(1-s),l=i-a,h=r-l,c=o-l,d=r+a,u=o+a,p=e-this.x,f=t-this.y,m=p*p/(h*h)+f*f/(c*c),g=p*p/(d*d)+f*f/(u*u);return m>1&&g<=1}getBounds(e){return e||(e=new st),e.x=this.x-this.halfWidth,e.y=this.y-this.halfHeight,e.width=this.halfWidth*2,e.height=this.halfHeight*2,e}copyFrom(e){return this.x=e.x,this.y=e.y,this.halfWidth=e.halfWidth,this.halfHeight=e.halfHeight,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:Ellipse x=${this.x} y=${this.y} halfWidth=${this.halfWidth} halfHeight=${this.halfHeight}]`}}function _m(n,e,t,i,s,r){const o=n-t,a=e-i,l=s-t,h=r-i,c=o*l+a*h,d=l*l+h*h;let u=-1;d!==0&&(u=c/d);let p,f;u<0?(p=t,f=i):u>1?(p=s,f=r):(p=t+u*l,f=i+u*h);const m=n-p,g=e-f;return m*m+g*g}let Pm,Am;class Ze{constructor(...e){this.type="polygon";let t=Array.isArray(e[0])?e[0]:e;if(typeof t[0]!="number"){const i=[];for(let s=0,r=t.length;s<r;s++)i.push(t[s].x,t[s].y);t=i}this.points=t,this.closePath=!0}isClockwise(){let e=0;const t=this.points,i=t.length;for(let s=0;s<i;s+=2){const r=t[s],o=t[s+1],a=t[(s+2)%i],l=t[(s+3)%i];e+=(a-r)*(l+o)}return e<0}containsPolygon(e){const t=this.getBounds(Pm),i=e.getBounds(Am);if(!t.containsRect(i))return!1;const s=e.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 e=this.points.slice(),t=new Ze(e);return t.closePath=this.closePath,t}contains(e,t){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],l=this.points[r*2+1],h=this.points[o*2],c=this.points[o*2+1];l>t!=c>t&&e<(h-a)*((t-l)/(c-l))+a&&(i=!i)}return i}strokeContains(e,t,i,s=.5){const r=i*i,o=r*(1-s),a=r-o,{points:l}=this,h=l.length-(this.closePath?0:2);for(let c=0;c<h;c+=2){const d=l[c],u=l[c+1],p=l[(c+2)%l.length],f=l[(c+3)%l.length],m=_m(e,t,d,u,p,f),g=Math.sign((p-d)*(t-u)-(f-u)*(e-d));if(m<=(g<0?a:o))return!0}return!1}getBounds(e){e||(e=new st);const t=this.points;let i=1/0,s=-1/0,r=1/0,o=-1/0;for(let a=0,l=t.length;a<l;a+=2){const h=t[a],c=t[a+1];i=h<i?h:i,s=h>s?h:s,r=c<r?c:r,o=c>o?c:o}return e.x=i,e.width=s-i,e.y=r,e.height=o-r,e}copyFrom(e){return this.points=e.points.slice(),this.closePath=e.closePath,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:PolygoncloseStroke=${this.closePath}points=${this.points.reduce((e,t)=>`${e}, ${t}`,"")}]`}get lastX(){return this.points[this.points.length-2]}get lastY(){return this.points[this.points.length-1]}get x(){return X("8.11.0","Polygon.lastX is deprecated, please use Polygon.lastX instead."),this.points[this.points.length-2]}get y(){return X("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 Ns=(n,e,t,i,s,r,o)=>{const a=n-t,l=e-i,h=Math.sqrt(a*a+l*l);return h>=s-r&&h<=s+o};class zo{constructor(e=0,t=0,i=0,s=0,r=20){this.type="roundedRectangle",this.x=e,this.y=t,this.width=i,this.height=s,this.radius=r}getBounds(e){return e||(e=new st),e.x=this.x,e.y=this.y,e.width=this.width,e.height=this.height,e}clone(){return new zo(this.x,this.y,this.width,this.height,this.radius)}copyFrom(e){return this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height,this}copyTo(e){return e.copyFrom(this),e}contains(e,t){if(this.width<=0||this.height<=0)return!1;if(e>=this.x&&e<=this.x+this.width&&t>=this.y&&t<=this.y+this.height){const i=Math.max(0,Math.min(this.radius,Math.min(this.width,this.height)/2));if(t>=this.y+i&&t<=this.y+this.height-i||e>=this.x+i&&e<=this.x+this.width-i)return!0;let s=e-(this.x+i),r=t-(this.y+i);const o=i*i;if(s*s+r*r<=o||(s=e-(this.x+this.width-i),s*s+r*r<=o)||(r=t-(this.y+this.height-i),s*s+r*r<=o)||(s=e-(this.x+i),s*s+r*r<=o))return!0}return!1}strokeContains(e,t,i,s=.5){const{x:r,y:o,width:a,height:l,radius:h}=this,c=i*(1-s),d=i-c,u=r+h,p=o+h,f=a-h*2,m=l-h*2,g=r+a,x=o+l;return(e>=r-c&&e<=r+d||e>=g-d&&e<=g+c)&&t>=p&&t<=p+m||(t>=o-c&&t<=o+d||t>=x-d&&t<=x+c)&&e>=u&&e<=u+f?!0:e<u&&t<p&&Ns(e,t,u,p,h,d,c)||e>g-h&&t<p&&Ns(e,t,g-h,p,h,d,c)||e>g-h&&t>x-h&&Ns(e,t,g-h,x-h,h,d,c)||e<u&&t>x-h&&Ns(e,t,u,x-h,h,d,c)}toString(){return`[pixi.js/math:RoundedRectangle x=${this.x} y=${this.y}width=${this.width} height=${this.height} radius=${this.radius}]`}}const fd={};function Tm(n,e,t){let i=2166136261;for(let s=0;s<e;s++)i^=n[s].uid,i=Math.imul(i,16777619),i>>>=0;return fd[i]||Rm(n,e,i,t)}function Rm(n,e,t,i){const s={};let r=0;for(let a=0;a<i;a++){const l=a<e?n[a]:U.EMPTY.source;s[r++]=l.source,s[r++]=l.style}const o=new ss(s);return fd[t]=o,o}class sl{constructor(e){typeof e=="number"?this.rawBinaryData=new ArrayBuffer(e):e instanceof Uint8Array?this.rawBinaryData=e.buffer:this.rawBinaryData=e,this.uint32View=new Uint32Array(this.rawBinaryData),this.float32View=new Float32Array(this.rawBinaryData),this.size=this.rawBinaryData.byteLength}get int8View(){return this._int8View||(this._int8View=new Int8Array(this.rawBinaryData)),this._int8View}get uint8View(){return this._uint8View||(this._uint8View=new Uint8Array(this.rawBinaryData)),this._uint8View}get int16View(){return this._int16View||(this._int16View=new Int16Array(this.rawBinaryData)),this._int16View}get int32View(){return this._int32View||(this._int32View=new Int32Array(this.rawBinaryData)),this._int32View}get float64View(){return this._float64Array||(this._float64Array=new Float64Array(this.rawBinaryData)),this._float64Array}get bigUint64View(){return this._bigUint64Array||(this._bigUint64Array=new BigUint64Array(this.rawBinaryData)),this._bigUint64Array}view(e){return this[`${e}View`]}destroy(){this.rawBinaryData=null,this.uint32View=null,this.float32View=null,this.uint16View=null,this._int8View=null,this._uint8View=null,this._int16View=null,this._int32View=null,this._float64Array=null,this._bigUint64Array=null}static sizeOf(e){switch(e){case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;default:throw new Error(`${e} isn't a valid view type`)}}}function nl(n,e,t,i){if(t??(t=0),i??(i=Math.min(n.byteLength-t,e.byteLength)),!(t&7)&&!(i&7)){const s=i/8;new Float64Array(e,0,s).set(new Float64Array(n,t,s))}else if(!(t&3)&&!(i&3)){const s=i/4;new Float32Array(e,0,s).set(new Float32Array(n,t,s))}else new Uint8Array(e).set(new Uint8Array(n,t,i))}const Em={normal:"normal-npm",add:"add-npm",screen:"screen-npm"};var km=(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))(km||{});function gn(n,e){return e.alphaMode==="no-premultiply-alpha"&&Em[n]||n}const Im=["precision mediump float;","void main(void){","float test = 0.1;","%forloop%","gl_FragColor = vec4(0.0);","}"].join(`
|
|
25
25
|
`);function Dm(n){let e="";for(let t=0;t<n;++t)t>0&&(e+=`
|
|
26
26
|
else `),t<n-1&&(e+=`if(test == ${t}.0){}`);return e}function Fm(n,e){if(n===0)throw new Error("Invalid value of `0` passed to `checkMaxIfStatementsInShader`");const t=e.createShader(e.FRAGMENT_SHADER);try{for(;;){const i=Im.replace(/%forloop%/gi,Dm(n));if(e.shaderSource(t,i),e.compileShader(t),!e.getShaderParameter(t,e.COMPILE_STATUS))n=n/2|0;else break}}finally{e.deleteShader(t)}return n}let oi=null;function Bm(){var e;if(oi)return oi;const n=$c();return oi=n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS),oi=Fm(oi,n),(e=n.getExtension("WEBGL_lose_context"))==null||e.loseContext(),oi}class Lm{constructor(){this.ids=Object.create(null),this.textures=[],this.count=0}clear(){for(let e=0;e<this.count;e++){const t=this.textures[e];this.textures[e]=null,this.ids[t.uid]=null}this.count=0}}class zm{constructor(){this.renderPipeId="batch",this.action="startBatch",this.start=0,this.size=0,this.textures=new Lm,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 ns=[];let mn=0;_s.register({clear:()=>{if(ns.length>0)for(const n of ns)n&&n.destroy();ns.length=0,mn=0}});function rl(){return mn>0?ns[--mn]:new zm}function ol(n){n.elements=null,ns[mn++]=n}let Gi=0;const gd=class md{constructor(e){this.uid=ft("batcher"),this.dirty=!0,this.batchIndex=0,this.batches=[],this._elements=[],e={...md.defaultOptions,...e},e.maxTextures||(X("v8.8.0","maxTextures is a required option for Batcher now, please pass it in the options"),e.maxTextures=Bm());const{maxTextures:t,attributesInitialSize:i,indicesInitialSize:s}=e;this.attributeBuffer=new sl(i*4),this.indexBuffer=new Uint16Array(s),this.maxTextures=t}begin(){this.elementSize=0,this.elementStart=0,this.indexSize=0,this.attributeSize=0;for(let e=0;e<this.batchIndex;e++)ol(this.batches[e]);this.batchIndex=0,this._batchIndexStart=0,this._batchIndexSize=0,this.dirty=!0}add(e){this._elements[this.elementSize++]=e,e._indexStart=this.indexSize,e._attributeStart=this.attributeSize,e._batcher=this,this.indexSize+=e.indexSize,this.attributeSize+=e.attributeSize*this.vertexSize}checkAndUpdateTexture(e,t){const i=e._batch.textures.ids[t._source.uid];return!i&&i!==0?!1:(e._textureId=i,e.texture=t,!0)}updateElement(e){this.dirty=!0;const t=this.attributeBuffer;e.packAsQuad?this.packQuadAttributes(e,t.float32View,t.uint32View,e._attributeStart,e._textureId):this.packAttributes(e,t.float32View,t.uint32View,e._attributeStart,e._textureId)}break(e){const t=this._elements;if(!t[this.elementStart])return;let i=rl(),s=i.textures;s.clear();const r=t[this.elementStart];let o=gn(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 l=this.attributeBuffer.float32View,h=this.attributeBuffer.uint32View,c=this.indexBuffer;let d=this._batchIndexSize,u=this._batchIndexStart,p="startBatch",f=[];const m=this.maxTextures;for(let g=this.elementStart;g<this.elementSize;++g){const x=t[g];t[g]=null;const b=x.texture._source,w=gn(x.blendMode,b),_=o!==w||a!==x.topology;if(b._batchTick===Gi&&!_){x._textureId=b._textureBindLocation,d+=x.indexSize,x.packAsQuad?(this.packQuadAttributes(x,l,h,x._attributeStart,x._textureId),this.packQuadIndex(c,x._indexStart,x._attributeStart/this.vertexSize)):(this.packAttributes(x,l,h,x._attributeStart,x._textureId),this.packIndex(x,c,x._indexStart,x._attributeStart/this.vertexSize)),x._batch=i,f.push(x);continue}b._batchTick=Gi,(s.count>=m||_)&&(this._finishBatch(i,u,d-u,s,o,a,e,p,f),p="renderBatch",u=d,o=w,a=x.topology,i=rl(),s=i.textures,s.clear(),f=[],++Gi),x._textureId=b._textureBindLocation=s.count,s.ids[b.uid]=s.count,s.textures[s.count++]=b,x._batch=i,f.push(x),d+=x.indexSize,x.packAsQuad?(this.packQuadAttributes(x,l,h,x._attributeStart,x._textureId),this.packQuadIndex(c,x._indexStart,x._attributeStart/this.vertexSize)):(this.packAttributes(x,l,h,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,e,p,f),u=d,++Gi),this.elementStart=this.elementSize,this._batchIndexStart=u,this._batchIndexSize=d}_finishBatch(e,t,i,s,r,o,a,l,h){e.gpuBindGroup=null,e.bindGroup=null,e.action=l,e.batcher=this,e.textures=s,e.blendMode=r,e.topology=o,e.start=t,e.size=i,e.elements=h,++Gi,this.batches[this.batchIndex++]=e,a.add(e)}finish(e){this.break(e)}ensureAttributeBuffer(e){e*4<=this.attributeBuffer.size||this._resizeAttributeBuffer(e*4)}ensureIndexBuffer(e){e<=this.indexBuffer.length||this._resizeIndexBuffer(e)}_resizeAttributeBuffer(e){const t=Math.max(e,this.attributeBuffer.size*2),i=new sl(t);nl(this.attributeBuffer.rawBinaryData,i.rawBinaryData),this.attributeBuffer=i}_resizeIndexBuffer(e){const t=this.indexBuffer;let i=Math.max(e,t.length*1.5);i+=i%2;const s=i>65535?new Uint32Array(i):new Uint16Array(i);if(s.BYTES_PER_ELEMENT!==t.BYTES_PER_ELEMENT)for(let r=0;r<t.length;r++)s[r]=t[r];else nl(t.buffer,s.buffer);this.indexBuffer=s}packQuadIndex(e,t,i){e[t]=i+0,e[t+1]=i+1,e[t+2]=i+2,e[t+3]=i+0,e[t+4]=i+2,e[t+5]=i+3}packIndex(e,t,i,s){const r=e.indices,o=e.indexSize,a=e.indexOffset,l=e.attributeOffset;for(let h=0;h<o;h++)t[i++]=s+r[h+a]-l}destroy(e={}){var t;if(this.batches!==null){for(let i=0;i<this.batchIndex;i++)ol(this.batches[i]);this.batches=null,this.geometry.destroy(!0),this.geometry=null,e.shader&&((t=this.shader)==null||t.destroy(),this.shader=null);for(let i=0;i<this._elements.length;i++)this._elements[i]&&(this._elements[i]._batch=null);this._elements=null,this.indexBuffer=null,this.attributeBuffer.destroy(),this.attributeBuffer=null}}};gd.defaultOptions={maxTextures:null,attributesInitialSize:4,indicesInitialSize:6};let Om=gd;var St=(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))(St||{});class Re extends ae{constructor(e){let{data:t,size:i}=e;const{usage:s,label:r,shrinkToFit:o}=e;super(),this._gpuData=Object.create(null),this._gcLastUsed=-1,this.autoGarbageCollect=!0,this.uid=ft("buffer"),this._resourceType="buffer",this._resourceId=ft("resource"),this._touched=0,this._updateID=1,this._dataInt32=null,this.shrinkToFit=!0,this.destroyed=!1,t instanceof Array&&(t=new Float32Array(t)),this._data=t,i??(i=t==null?void 0:t.byteLength);const a=!!t;this.descriptor={size:i,usage:s,mappedAtCreation:a,label:r},this.shrinkToFit=o??!0}get data(){return this._data}set data(e){this.setDataWithSize(e,e.length,!0)}get dataInt32(){return this._dataInt32||(this._dataInt32=new Int32Array(this.data.buffer)),this._dataInt32}get static(){return!!(this.descriptor.usage&St.STATIC)}set static(e){e?this.descriptor.usage|=St.STATIC:this.descriptor.usage&=~St.STATIC}setDataWithSize(e,t,i){if(this._updateID++,this._updateSize=t*e.BYTES_PER_ELEMENT,this._data===e){i&&this.emit("update",this);return}const s=this._data;if(this._data=e,this._dataInt32=null,!s||s.length!==e.length){!this.shrinkToFit&&s&&e.byteLength<s.byteLength?i&&this.emit("update",this):(this.descriptor.size=e.byteLength,this._resourceId=ft("resource"),this.emit("change",this));return}i&&this.emit("update",this)}update(e){this._updateSize=e??this._updateSize,this._updateID++,this.emit("update",this)}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null)}destroy(){this.destroyed=!0,this.unload(),this.emit("destroy",this),this.emit("change",this),this._data=null,this.descriptor=null,this.removeAllListeners()}}function yd(n,e){if(!(n instanceof Re)){let t=e?St.INDEX:St.VERTEX;n instanceof Array&&(e?(n=new Uint32Array(n),t=St.INDEX|St.COPY_DST):(n=new Float32Array(n),t=St.VERTEX|St.COPY_DST)),n=new Re({data:n,label:e?"index-mesh-buffer":"vertex-mesh-buffer",usage:t})}return n}function Wm(n,e,t){const i=n.getAttribute(e);if(!i)return t.minX=0,t.minY=0,t.maxX=0,t.maxY=0,t;const s=i.buffer.data;let r=1/0,o=1/0,a=-1/0,l=-1/0;const h=s.BYTES_PER_ELEMENT,c=(i.offset||0)/h,d=(i.stride||2*4)/h;for(let u=c;u<s.length;u+=d){const p=s[u],f=s[u+1];p>a&&(a=p),f>l&&(l=f),p<r&&(r=p),f<o&&(o=f)}return t.minX=r,t.minY=o,t.maxX=a,t.maxY=l,t}function Gm(n){return(n instanceof Re||Array.isArray(n)||n.BYTES_PER_ELEMENT)&&(n={buffer:n}),n.buffer=yd(n.buffer,!1),n}class ms extends ae{constructor(e={}){super(),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=ft("geometry"),this._layoutKey=0,this.instanceCount=1,this._bounds=new Wt,this._boundsDirty=!0;const{attributes:t,indexBuffer:i,topology:s}=e;if(this.buffers=[],this.attributes={},t)for(const r in t)this.addAttribute(r,t[r]);this.instanceCount=e.instanceCount??1,i&&this.addIndex(i),this.topology=s||"triangle-list"}onBufferUpdate(){this._boundsDirty=!0,this.emit("update",this)}getAttribute(e){return this.attributes[e]}getIndex(){return this.indexBuffer}getBuffer(e){return this.getAttribute(e).buffer}getSize(){for(const e in this.attributes){const t=this.attributes[e];return t.buffer.data.length/(t.stride/4||t.size)}return 0}addAttribute(e,t){const i=Gm(t);this.buffers.indexOf(i.buffer)===-1&&(this.buffers.push(i.buffer),i.buffer.on("update",this.onBufferUpdate,this),i.buffer.on("change",this.onBufferUpdate,this)),this.attributes[e]=i}addIndex(e){this.indexBuffer=yd(e,!0),this.buffers.push(this.indexBuffer)}get bounds(){return this._boundsDirty?(this._boundsDirty=!1,Wm(this,"aPosition",this._bounds)):this._bounds}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null)}destroy(e=!1){var t;this.emit("destroy",this),this.removeAllListeners(),e&&this.buffers.forEach(i=>i.destroy()),this.unload(),(t=this.indexBuffer)==null||t.destroy(),this.attributes=null,this.buffers=null,this.indexBuffer=null,this._bounds=null}}const Um=new Float32Array(1),Hm=new Uint32Array(1);class Nm extends ms{constructor(){const t=new Re({data:Um,label:"attribute-batch-buffer",usage:St.VERTEX|St.COPY_DST,shrinkToFit:!1}),i=new Re({data:Hm,label:"index-batch-buffer",usage:St.INDEX|St.COPY_DST,shrinkToFit:!1}),s=6*4;super({attributes:{aPosition:{buffer:t,format:"float32x2",stride:s,offset:0},aUV:{buffer:t,format:"float32x2",stride:s,offset:2*4},aColor:{buffer:t,format:"unorm8x4",stride:s,offset:4*4},aTextureIdAndRound:{buffer:t,format:"uint16x2",stride:s,offset:5*4}},indexBuffer:i})}}function al(n,e,t){if(n)for(const i in n){const s=i.toLocaleLowerCase(),r=e[s];if(r){let o=n[i];i==="header"&&(o=o.replace(/@in\s+[^;]+;\s*/g,"").replace(/@out\s+[^;]+;\s*/g,"")),t&&r.push(`//----${t}----//`),r.push(o)}else lt(`${i} placement hook does not exist in shader`)}}const Vm=/\{\{(.*?)\}\}/g;function ll(n){var i;const e={};return(((i=n.match(Vm))==null?void 0:i.map(s=>s.replace(/[{()}]/g,"")))??[]).forEach(s=>{e[s]=[]}),e}function hl(n,e){let t;const i=/@in\s+([^;]+);/g;for(;(t=i.exec(n))!==null;)e.push(t[1])}function cl(n,e,t=!1){const i=[];hl(e,i),n.forEach(a=>{a.header&&hl(a.header,i)});const s=i;t&&s.sort();const r=s.map((a,l)=>` @location(${l}) ${a},`).join(`
|
|
@@ -741,4 +741,4 @@ fn mainFragment(
|
|
|
741
741
|
|
|
742
742
|
return vec4<f32>(color, 1.0);
|
|
743
743
|
}
|
|
744
|
-
`,entryPoint:"main"}})}),h=new Wl({geometry:a,shader:l});return h.alpha=.8,h}updatePositionByOrigin(t,i){this.position.set(t,i)}clear(){this.removeChildren()}destroy(){this.removeChildren(),this.cacheAsTexture(!1)}}class w0{constructor(e){y(this,"heatmap");y(this,"pointsTopLeftOrigin",[]);y(this,"signalGrid",[]);y(this,"cellSize",2);y(this,"maxDistance",14);y(this,"smoothIterations",10);y(this,"heatmapAlpha",.8);y(this,"isHeatmapDrawn",!1);y(this,"loadTimer",null);y(this,"pendingPoints",null);this.appService=e,this.heatmap=new v0(e);const t=e.heatMapConfig;this.cellSize=t.cellSize,this.maxDistance=t.maxDistance,this.smoothIterations=t.smoothIterations,this.heatmapAlpha=t.heatmapAlpha}draw(e){if(e.length===0){this.clear();return}const t=this.appService;if(!t.isMapDrawn){this.pendingPoints=e;return}this.pendingPoints=null;const{minX:i,minY:s}=t.mapManager.mapBounds,r=e.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(e){var p;const t=this.appService,i=((p=t.mapState)==null?void 0:p.origin)||{x:0,y:0};let{minX:s,minY:r,maxX:o,maxY:a}=t.mapManager.mapBounds;r=r-i.y,s=s-i.x,a=a-i.y,o=o-i.x;const l=Math.ceil((a-r)/this.cellSize),h=Math.ceil((o-s)/this.cellSize),c=Array(l).fill(null).map(()=>Array(h).fill(null));for(let f=0;f<l;f++){const m=r+f*this.cellSize+this.cellSize/2,g=Math.min(this.cellSize,a-(m-this.cellSize/2));for(let x=0;x<h;x++){const S=s+x*this.cellSize+this.cellSize/2,b=Math.min(this.cellSize,o-(S-this.cellSize/2));let w=0,_=!1;for(let v=0;v<e.length;v++){const C=e[v];if(Math.abs(S-C.x)<=b/2&&Math.abs(m-C.y)<=g/2){const P=1-C.signal/7;w=Math.round(Math.max(w,P)*10)/10,_=!0}}c[f][x]={x:S,y:m,signal:w,hasPoint:_}}}const d=(f,m)=>{if(e.length===0)return 0;let g=0,x=0;for(const S of e){const b=Math.sqrt((f-S.x)**2+(m-S.y)**2);if(b<=this.maxDistance){const w=1/(1+b),_=1-S.signal/7;x+=w*_,g+=w}}return g===0?0:Math.round(x/g*1e3)/1e3},u=(f,m=1)=>{for(let g=0;g<m;g++){const x=f.map(S=>[...S]);for(let S=1;S<l-1;S++)for(let b=1;b<h-1;b++)if(!f[S][b].hasPoint){let w=0,_=0;const v=4;for(let C=-v;C<=v;C++)for(let P=-v;P<=v;P++){if(C===0&&P===0)continue;const A=S+C,R=b+P;if(A>=0&&A<l&&R>=0&&R<h){const E=1/(1+Math.sqrt(C*C+P*P)*.3);w+=f[A][R].signal*E,_+=E}}if(_>0){const C=w/_,P=.6,A=.4;x[S][b].signal=f[S][b].signal*P+C*A,x[S][b].signal>.1&&(x[S][b].signal=Math.max(x[S][b].signal,.2))}}for(let S=0;S<l;S++)for(let b=0;b<h;b++)f[S][b].signal=x[S][b].signal}};for(let f=0;f<l;f++)for(let m=0;m<h;m++){const g=c[f][m];g.hasPoint||(g.signal=d(g.x,g.y))}return u(c,this.smoothIterations),c}updatePositionByOrigin(e,t){this.heatmap.updatePositionByOrigin(e,t)}destroy(){this.heatmap.destroy()}}const Se=n=>({showRotateButton:n.showRotateButton??!0,showScaleButton:n.showScaleButton??!0,showDeleteButton:n.showDeleteButton??!0,showMoveButton:n.showMoveButton??!0}),C0=n=>({showScaleButton:n.showScaleButton??!0,showDeleteButton:n.showDeleteButton??!0,showMoveButton:n.showMoveButton??!0});function Ii(n,e){return e?"disabled":n?"editing":"idle"}const M0=.4;function Di(n,e){return(n==null?void 0:n.opacity)??(e==null?void 0:e.opacity)??M0}class oa extends W{constructor(t,i){super();y(this,"fillOptions");y(this,"isDragging",!1);y(this,"dragStartPosition",null);y(this,"gestureSession",null);y(this,"handlePointerDown",t=>{t.stopPropagation(),this.startDragging(t)});y(this,"handleDragPointerMove",t=>{var i,s;!this.isDragging||!this.dragStartPosition||(s=(i=this.fillOptions).onDragMove)==null||s.call(i,t)});y(this,"handleDragPointerUp",()=>{var t,i;this.gestureSession=null,this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null,(i=(t=this.fillOptions).onDragEnd)==null||i.call(t))});this.appService=t,this.fillOptions=i,this.setupInteraction(),this.draw()}setupInteraction(){this.fillOptions.enableInteraction&&(this.eventMode="static",this.on("pointerdown",this.handlePointerDown))}startDragging(t){var s,r;this.isDragging=!0;const i=this.parent.toLocal(t.global);this.dragStartPosition={x:i.x,y:i.y},(r=(s=this.fillOptions).onDragStart)==null||r.call(s,t),this.gestureSession=this.appService.gestureController.hijack(t),this.gestureSession.onMove(this.handleDragPointerMove),this.gestureSession.onEnd(this.handleDragPointerUp)}draw(){const{points:t,fillColor:i}=this.fillOptions;if(t.length<3)return;this.clear();const s=t.flatMap(r=>[r.x,r.y]);this.setFillStyle({color:i}).poly(s).fill()}getDragStartPosition(){return this.dragStartPosition}updateOptions(t){this.fillOptions={...this.fillOptions,...t},t.enableInteraction!==void 0&&(this.off("pointerdown",this.handlePointerDown),this.setupInteraction()),this.draw()}updatePoints(t){this.fillOptions.points=t,this.draw()}updateFillColor(t){this.fillOptions.fillColor=t,this.draw()}interruptDragging(){this.isDragging&&(this.gestureSession?this.gestureSession.cancel():this.handleDragPointerUp())}stopDragging(){var t;this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null,(t=this.gestureSession)==null||t.cancel(),this.gestureSession=null)}isCurrentlyDragging(){return this.isDragging}setInteractionEnabled(t){this.fillOptions.enableInteraction=t,t?(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()}}const Qh=24,Jh=.5,_0=.8;class P0 extends Yt{constructor(t,i){super(t);y(this,"iconConfig");y(this,"boxShortSide",0);y(this,"textureReady",!1);y(this,"visualState","idle");y(this,"unsubscribeMapRotation",null);this.iconConfig=i,this.eventMode="none",this.alpha=i.opacity??1,this.anchor.set(i.anchor??Jh),this.visible=!1,this.applyAntiRotation(t.runtime.mapRotation),this.unsubscribeMapRotation=z(t.runtime,"mapRotation",s=>{this.applyAntiRotation(s)}),this.loadIconTexture()}updateGeometry(t,i){this.destroyed||(this.boxShortSide=i,this.position.set(t.x,t.y),this.applyClampedSize())}setVisualState(t){this.visualState=t,this.applyVisibility()}async loadIconTexture(){const{src:t,size:i=Qh,sizeFixed:s=!0,anchor:r=Jh}=this.iconConfig;await this.loadTextureAndSetSize(t,{width:i,height:i,sizeFixed:s}),!this.destroyed&&(this.anchor.set(r),this.textureReady=!0,this.applyClampedSize(),this.applyVisibility())}updateScale(t){this.applyClampedSize(),super.updateScale(t)}applyAntiRotation(t){this.destroyed||(this.rotation=-t*Math.PI/180)}applyVisibility(){if(this.destroyed)return;const{showInEditing:t=!0,showInNormal:i=!0,showInDisabled:s}=this.iconConfig,r=this.visualState==="editing"?t:this.visualState==="disabled"?s??i:i;this.visible=this.textureReady&&r}applyClampedSize(){if(this.destroyed||!this.textureReady)return;const t=this.clampToBox(this.iconConfig.size??Qh);this.setFixedSize(t,t)}clampToBox(t){if(this.boxShortSide<=0)return t;const r=(this.iconConfig.sizeFixed??!0?this.boxShortSide*this.appService.currentScale:this.boxShortSide)*_0;return r>0?Math.min(t,r):t}destroy(t){var i;(i=this.unsubscribeMapRotation)==null||i.call(this),this.unsubscribeMapRotation=null,super.destroy(t)}}class Es{constructor(e){y(this,"id",null);y(this,"layer",null);y(this,"editingState",{});y(this,"idleState",{});y(this,"host",null);y(this,"onHostDestroyed",null);y(this,"detached",!1);this.deps=e}attach(e,t){this.layer&&this.detach(),this.detached=!1,this.host=e,this.id=t.id,this.editingState=t.editingState,this.idleState=t.idleState??{},this.layer=this.deps.editControls.registerEditControl(t.id,t.layerOptions);const i=()=>this.detach();return this.onHostDestroyed=i,e.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(e){if(this.id==null){M.warn("[EditableShape] setEditing called before attach; ignoring");return}this.deps.editControls.updateEditState(this.id,e?this.editingState:this.idleState)}applyEditState(e){if(this.id==null){M.warn("[EditableShape] applyEditState called before attach; ignoring");return}this.deps.editControls.updateEditState(this.id,e)}updatePoints(e,t=!0){var i;(i=this.layer)==null||i.updatePoints(e,t)}getLayer(){return this.layer}getMoveButton(){var e;return((e=this.layer)==null?void 0:e.getMoveButton())??null}}class Tn extends xs{constructor(t,{text:i,style:s}){super({text:i,style:s});y(this,"throttledUpdateScale");this.appService=t,this.throttledUpdateScale=Pt(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(t){t<=0||this.scale.set(1/t)}setBaseFontSize(t){this.style.fontSize=t}updateText(t){this.text=t}destroy(t){this.appService.emitter.off("antiScale",this.throttledUpdateScale),this.throttledUpdateScale.cancel(),super.destroy(t)}}class ap extends O{constructor(t){super();y(this,"throttledUpdateScale");this.appService=t,this.throttledUpdateScale=Pt(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(t){t!==0&&this.scale.set(1/t)}destroy(t){this.appService.emitter.off("antiScale",this.throttledUpdateScale),this.throttledUpdateScale.cancel(),super.destroy(t)}}class Wn extends ap{constructor(t,i){super(t);y(this,"background");y(this,"icon");y(this,"options");this.appService=t,this.options=i,this.background=new W,this.addChild(this.background),this.icon=new Yt(t),this.addChild(this.icon),this.eventMode="static",this.render(),this.setupHitArea(),this.setupEvents()}setupHitArea(){const t=this.appService,i=this.options.config||t.controlsConfig,s=8,r=i.iconWrapperWidth+s*2,o=i.iconWrapperHeight+s*2;this.hitArea=new st(-r/2,-o/2,r,o)}async render(){this.renderBackground(),this.renderIcon()}renderBackground(){const t=this.appService,i=this.options.config||t.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 t=this.appService,i=this.options.config||t.controlsConfig;await this.icon.loadTextureAndSetSize(this.options.iconAlias,{width:i.iconWidth,height:i.iconHeight,sizeFixed:!1}),this.icon.visible=!0}catch(t){M.error(`Failed to load icon: ${this.options.iconAlias}`,t)}}destroy(){super.destroy()}}class lp extends Wn{constructor(t,i){super(t,i);y(this,"isMoving",!1);y(this,"dragStartPosition",null);y(this,"gestureSession",null);y(this,"handleMovePointerMove",t=>{var i,s;!this.isMoving||!this.dragStartPosition||(s=(i=this.options).onMoveMove)==null||s.call(i,t)});y(this,"handleMovePointerUp",()=>{var t,i;this.gestureSession=null,this.isMoving&&(this.isMoving=!1,this.dragStartPosition=null,(i=(t=this.options).onMoveEnd)==null||i.call(t))});this.appService=t}setupEvents(){this.on("pointerdown",this.handlePointerDown.bind(this))}handlePointerDown(t){t.stopPropagation(),this.startMoving(t)}startMoving(t){var i,s;this.isMoving=!0,this.dragStartPosition=this.parent.toLocal(t.global),(s=(i=this.options).onMoveStart)==null||s.call(i),this.gestureSession=this.appService.gestureController.hijack(t),this.gestureSession.onMove(this.handleMovePointerMove),this.gestureSession.onEnd(this.handleMovePointerUp)}isCurrentlyMoving(){return this.isMoving}getDragStartPosition(){return this.dragStartPosition?{...this.dragStartPosition}:null}stopMoving(){var t,i;this.isMoving&&(this.gestureSession?this.gestureSession.cancel():(this.isMoving=!1,this.dragStartPosition=null,(i=(t=this.options).onMoveEnd)==null||i.call(t)))}destroy(){this.stopMoving(),this.gestureSession=null,this.off("pointerdown",this.handlePointerDown),super.destroy()}}class hp extends Wn{constructor(t,i){super(t,i);y(this,"clickHandler",null);this.appService=t}setupEvents(){this.clickHandler=new yt(this,{onClick:this.options.onClick,stopPropagation:!0})}destroy(){var t;(t=this.clickHandler)==null||t.destroy(),super.destroy()}}const A0=10;class T0 extends Wn{constructor(t,i){super(t,i);y(this,"isRotating",!1);y(this,"hasRotated",!1);y(this,"rotationCenter",{x:0,y:0});y(this,"downPosition",{x:0,y:0});y(this,"lastAngle",0);y(this,"clickHandler",null);y(this,"gestureSession",null);y(this,"handleRotationPointerMove",t=>{var o,a,l,h;if(!this.isRotating||!this.options.onRotationMove)return;if(!this.hasRotated){const c=t.global.x-this.downPosition.x,d=t.global.y-this.downPosition.y;if(Math.sqrt(c*c+d*d)<=A0)return;this.hasRotated=!0,(a=(o=this.options).onRotationStart)==null||a.call(o,this.rotationCenter)}const i=this.parent.toLocal(t.global),s=Math.atan2(i.y-this.rotationCenter.y,i.x-this.rotationCenter.x),r=s-this.lastAngle;(h=(l=this.options).onRotationMove)==null||h.call(l,r),this.lastAngle=s});y(this,"handleRotationPointerUp",()=>{var t,i;this.gestureSession=null,this.isRotating&&(this.isRotating=!1,this.hasRotated&&((i=(t=this.options).onRotationEnd)==null||i.call(t)),this.hasRotated=!1)});this.appService=t}setupEvents(){this.options.onClick&&(this.clickHandler=new yt(this,{onClick:()=>{var t,i;this.hasRotated||(i=(t=this.options).onClick)==null||i.call(t)},stopPropagation:!1})),this.on("pointerdown",this.handlePointerDown.bind(this))}handlePointerDown(t){t.stopPropagation(),this.startRotation(t)}startRotation(t){this.isRotating=!0,this.hasRotated=!1,this.downPosition={x:t.global.x,y:t.global.y};const i=this.options.getTargetPoints();this.rotationCenter=oe(i);const s=this.parent.toLocal(t.global);this.lastAngle=Math.atan2(s.y-this.rotationCenter.y,s.x-this.rotationCenter.x),this.gestureSession=this.appService.gestureController.hijack(t),this.gestureSession.onMove(this.handleRotationPointerMove),this.gestureSession.onEnd(this.handleRotationPointerUp)}isCurrentlyRotating(){return this.isRotating}stopRotation(){var t,i;this.isRotating&&(this.gestureSession?this.gestureSession.cancel():(this.isRotating=!1,this.hasRotated&&((i=(t=this.options).onRotationEnd)==null||i.call(t)),this.hasRotated=!1))}destroy(){var t;this.stopRotation(),this.gestureSession=null,(t=this.clickHandler)==null||t.destroy(),this.off("pointerdown",this.handlePointerDown),super.destroy()}}class pn extends Wn{constructor(t,i){super(t,i);y(this,"isScaling",!1);y(this,"initialButtonPosition",null);y(this,"dragStartPosition",null);y(this,"gestureSession",null);y(this,"handleScalePointerMove",t=>{var o,a;if(!this.isScaling||!this.initialButtonPosition||!this.dragStartPosition)return;const i=this.parent.toLocal(t.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})});y(this,"handleScalePointerUp",()=>{var t,i;this.gestureSession=null,this.isScaling&&(this.isScaling=!1,this.initialButtonPosition=null,this.dragStartPosition=null,(i=(t=this.options).onScaleEnd)==null||i.call(t))});this.appService=t}setupEvents(){this.on("pointerdown",this.handlePointerDown.bind(this))}handlePointerDown(t){t.stopPropagation(),this.startScaling(t)}startScaling(t){var i,s,r,o;if(this.isScaling=!0,this.dragStartPosition=this.parent.toLocal(t.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(),l=this.options.getButtonIndex();l>=0&&l<a.length&&(this.initialButtonPosition={...a[l]}),(o=(r=this.options).onScaleStart)==null||o.call(r,l)}this.gestureSession=this.appService.gestureController.hijack(t),this.gestureSession.onMove(this.handleScalePointerMove),this.gestureSession.onEnd(this.handleScalePointerUp)}isCurrentlyScaling(){return this.isScaling}stopScaling(){var t,i;this.isScaling&&(this.gestureSession?this.gestureSession.cancel():(this.isScaling=!1,this.initialButtonPosition=null,this.dragStartPosition=null,(i=(t=this.options).onScaleEnd)==null||i.call(t)))}destroy(){this.stopScaling(),this.gestureSession=null,this.off("pointerdown",this.handlePointerDown),super.destroy()}}const xt={REMOVE:0,ROTATE:1,SCALE:2,MOVE:3};class R0 extends O{constructor(t,i){super();y(this,"config");y(this,"events");y(this,"zonePoints",[]);y(this,"outlinePoints");y(this,"minSize",.1);y(this,"maxSize");y(this,"sizeConstraintPerEdge");y(this,"initialZonePoints",[]);y(this,"scaleCache",null);y(this,"rotationCache",null);y(this,"outlineBorder");y(this,"moveLine");y(this,"sizeText");y(this,"controlButtons");y(this,"deleteButton",null);y(this,"rotateButton",null);y(this,"scaleButton",null);y(this,"moveButton",null);y(this,"horizontalScaleButton",null);y(this,"verticalScaleButton",null);y(this,"horizontalScaleInitialPosition",null);y(this,"verticalScaleInitialPosition",null);y(this,"clickHandler",null);y(this,"throttledUpdateOutline");this.appService=t,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=Pt(this.updateOutlineForScale.bind(this),30,{leading:!0,trailing:!0}),this.initializeComponents(),this.registerScaleListener()}getDiagnosticPart(t){return{delete:this.deleteButton,rotate:this.rotateButton,scale:this.scaleButton,move:this.moveButton,"scale-x":this.horizontalScaleButton,"scale-y":this.verticalScaleButton}[t]??null}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 O,this.addChild(this.controlButtons),this.createControlButtons(),this.setupClickHandler()}createOutlineBorder(){const{outlineStrokeColor:t,outlineStrokeWidth:i,outlineDashed:s,outlineDashArray:r,outlineFillColor:o}=this.config;return new De(this.appService,{points:this.outlinePoints,closePath:!0,style:{color:t,width:i,isDashed:s,dashArray:r,fillColor:o}})}createMoveLine(){const{outlineStrokeColor:t,outlineStrokeWidth:i,outlineDashed:s,outlineDashArray:r}=this.config,o=this.calculateMoveLinePoints();return new De(this.appService,{points:o,closePath:!1,style:{color:t,width:i,isDashed:s,dashArray:r}})}createSizeText(){const t=this.calculateSizeText(),i=new Tn(this.appService,{text:t,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 t=new hp(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 t.position.set(this.outlinePoints[xt.REMOVE].x,this.outlinePoints[xt.REMOVE].y),t}createRotateButton(){const t=this.config.rotateMode==="step",i=new T0(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:t?void 0:s=>{var o,a;const r=this.handleInternalRotationMove(s);(a=(o=this.events).onRotateMove)==null||a.call(o,r??void 0)},onClick:t?()=>{var o,a,l,h;const s=this.config.stepRotateAngle??Math.PI/2,r=this.onClickRotateButton(s);(a=(o=this.events).onRotateMove)==null||a.call(o,r??void 0),(h=(l=this.events).onClickRotate)==null||h.call(l,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[xt.ROTATE].x,this.outlinePoints[xt.ROTATE].y),i}onClickRotateButton(t){this.rotationCache||this.initializeRotationCache(this.calculateRotationCenter());const i=this.handleInternalRotationMove(t);return this.resetRotationState(),i}createScaleButton(){const t=new pn(this.appService,{iconAlias:"scaleIcon",backgroundColor:this.config.iconWrapperFillColor,initialButtonPosition:this.outlinePoints[xt.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 t.position.set(this.outlinePoints[xt.SCALE].x,this.outlinePoints[xt.SCALE].y),t}createHorizontalScaleButton(){const[,t,i]=this.outlinePoints,s=this.getEdgeCenter(t,i),r=new pn(this.appService,{iconAlias:"horizontalScaleIcon",backgroundColor:this.config.iconWrapperFillColor,config:{iconWrapperWidth:18,iconWrapperHeight:18,iconWrapperBorderRadius:18,iconWidth:10,iconHeight:8},initialButtonPosition:s,onScaleStart:()=>{var l,h;const[,o,a]=this.zonePoints;this.horizontalScaleInitialPosition=this.getEdgeCenter(o,a),this.initializeScaleCache(),(h=(l=this.events).onScaleStart)==null||h.call(l)},onScaleMove:({deltaX:o,deltaY:a})=>{var h,c;const l=this.handleInternalHorizontalScaleMove(o,a);(c=(h=this.events).onScaleMoveHorizontal)==null||c.call(h,l??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[,,t,i]=this.outlinePoints,s=this.getEdgeCenter(t,i),r=new pn(this.appService,{iconAlias:"verticalScaleIcon",backgroundColor:this.config.iconWrapperFillColor,config:{iconWrapperWidth:18,iconWrapperHeight:18,iconWrapperBorderRadius:18,iconWidth:8,iconHeight:10},initialButtonPosition:s,onScaleStart:()=>{var l,h;const[,,o,a]=this.zonePoints;this.verticalScaleInitialPosition=this.getEdgeCenter(o,a),this.initializeScaleCache(),(h=(l=this.events).onScaleStart)==null||h.call(l)},onScaleMove:({deltaX:o,deltaY:a})=>{var h,c;const l=this.handleInternalVerticalScaleMove(o,a);(c=(h=this.events).onScaleMoveVertical)==null||c.call(h,l??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 t=this.calculateMoveButtonPosition(),i=new lp(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(t.x,t.y),i}createAndAddButton(t,i){return t.visible=i,this.controlButtons.addChild(t),t}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 t=this.zonePoints;if(t.length<4)return t;const s=this.appService.getApp().toFixedSize(this.config.outlineOffset);return gb(t,s)}calculateMoveButtonPosition(){const t=this.calculateOutlinePoints();if(t.length<4)return{x:0,y:0};const s=this.appService.getApp().toFixedSize(this.config.moveButtonOffset),r=t[xt.MOVE],o=t[xt.SCALE],a=t[xt.REMOVE];return gu(r,o,a,s)}calculateMoveLinePoints(){const t=this.calculateOutlinePoints();if(t.length<4)return[];const i=t[xt.MOVE],s=this.calculateMoveButtonPosition();return[i,s]}calculateSizeText(){const t=this.zonePoints;if(t.length<4)return"0m*0m";const[i,s,,r]=t,o=q(i,s),a=q(i,r),{coords:l}=this.appService,h=l.toMeters(Gt(o)),c=l.toMeters(Gt(a)),d=l.toDisplayUnit(h),u=l.toDisplayUnit(c),p=this.appService.runtimeSnapshot.unitLabel;return`${d.toFixed(1)}${p}*${u.toFixed(1)}${p}`}getEdgeCenter(t,i){return{x:(t.x+i.x)/2,y:(t.y+i.y)/2}}calculatePerpendicularOffset(t,i,s,r=!1){const o=se(Mt(i,t)),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:l,textOffset:h}=this.config,d=this.appService.getApp().toFixedSize(h);let u,p;switch(l){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 t=this.zonePoints;if(t.length<4)return 0;const[i,s,r,o]=t,{textPosition:a}=this.config;let l,h;switch(a){case"top":l=i,h=s;break;case"right":l=s,h=r;break;case"bottom":l=r,h=o;break;case"left":l=o,h=i;break;default:l=i,h=s;break}const c=this.appService.appContainer.getMapRotationRadians();return hn(l,h,c)}calculateHorizontalScaleButtonRotation(){const t=this.zonePoints;if(t.length<4)return 0;const[,i,s]=t,r=this.appService.appContainer.getMapRotationRadians();return hn(i,s,r)+Math.PI/2}calculateVerticalScaleButtonRotation(){const t=this.zonePoints;if(t.length<4)return 0;const[,,i,s]=t,r=this.appService.appContainer.getMapRotationRadians();return hn(s,i,r)}updatePoints(t,i=!0){this.zonePoints=t,this.updateOutlineBorder(),this.moveLine&&this.updateMoveLine(),this.updateControlButtonsPosition(),this.updateSizeText(i)}updateOutlineBorder(){const t=this.calculateOutlinePoints();this.outlinePoints=t,this.outlineBorder.updatePoints(t)}updateMoveLine(){if(!this.moveLine)return;const t=this.calculateMoveLinePoints();this.moveLine.updatePoints(t)}updateSizeText(t=!0){if(this.sizeText){if(t){const i=this.calculateSizeText();this.sizeText.updateText(i)}this.updateSizeTextPosition()}}updateSizeTextPosition(){if(!this.sizeText)return;const t=this.calculateSizeTextPosition();this.sizeText.position.set(t.x,t.y);const i=this.calculateSizeTextRotation();this.sizeText.rotation=i}updateControlButtonsPosition(){if(!this.deleteButton||!this.scaleButton||!this.moveButton)return;const t=this.calculateOutlinePoints();if(t.length<4)return;const i=this.calculateMoveButtonPosition(),s=[{button:this.deleteButton,point:t[xt.REMOVE]},{button:this.scaleButton,point:t[xt.SCALE]},{button:this.moveButton,point:i}];if(this.rotateButton&&s.push({button:this.rotateButton,point:t[xt.ROTATE]}),this.horizontalScaleButton){const r=t[xt.ROTATE],o=t[xt.SCALE],a=pu(r,o,0);s.push({button:this.horizontalScaleButton,point:a})}if(this.verticalScaleButton){const r=t[xt.SCALE],o=t[xt.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 yt(this,{onClick:()=>{var t,i;(i=(t=this.events).onClick)==null||i.call(t)},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 t={...this.initialZonePoints[xt.SCALE]};if(!t)return;const i=xt.REMOVE,{x:s,y:r}=this.initialZonePoints[i],[,o,,a]=this.initialZonePoints,l={x:s,y:r},h=Mt(l,o),c=Mt(l,a),d=bs(h),u=bs(c);d===0||u===0||(this.scaleCache={fixedPoint:l,edge1:h,edge2:c,edge1Len:d,edge2Len:u,initialButtonPosition:t})}sizeConstraintPixels(){const{coords:t}=this.appService,i=(r,o)=>({minSizePixels:t.toPixels(et(r)),maxSizePixels:o!=null?t.toPixels(et(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(t,i){if(this.initialZonePoints.length!==4||!this.scaleCache)return null;const{edge1:s,edge2:r}=this.sizeConstraintPixels(),{fixedPoint:o,edge1:a,edge2:l,edge1Len:h,edge2Len:c,initialButtonPosition:d}=this.scaleCache,u={x:d.x+t,y:d.y+i},p=Mt(o,u);let f=qs(p,a,h,s.minSizePixels,s.maxSizePixels),m=qs(p,l,c,r.minSizePixels,r.maxSizePixels);if(this.config.scaleMode==="ratioLocked"){const g=Math.min(f,m);f=g,m=g}return this.calculatePointsFromScale(o,a,l,f,m)}resetScaleState(){this.scaleCache=null}handleInternalHorizontalScaleMove(t,i){if(this.initialZonePoints.length!==4||!this.scaleCache||!this.horizontalScaleInitialPosition)return null;const{fixedPoint:s,edge1:r,edge2:o,edge1Len:a}=this.scaleCache,{edge1:l}=this.sizeConstraintPixels(),h={x:this.horizontalScaleInitialPosition.x+t,y:this.horizontalScaleInitialPosition.y+i},c=Mt(s,h),d=qs(c,r,a,l.minSizePixels,l.maxSizePixels);return this.calculatePointsFromScale(s,r,o,d,1)}handleInternalVerticalScaleMove(t,i){if(this.initialZonePoints.length!==4||!this.scaleCache||!this.verticalScaleInitialPosition)return null;const{fixedPoint:s,edge1:r,edge2:o,edge2Len:a}=this.scaleCache,{edge2:l}=this.sizeConstraintPixels(),h={x:this.verticalScaleInitialPosition.x+t,y:this.verticalScaleInitialPosition.y+i},c=Mt(s,h),d=1,u=qs(c,o,a,l.minSizePixels,l.maxSizePixels);return this.calculatePointsFromScale(s,r,o,d,u)}calculatePointsFromScale(t,i,s,r,o){const{x:a,y:l}=t;return[t,{x:a+i.x*r,y:l+i.y*r},{x:a+i.x*r+s.x*o,y:l+i.y*r+s.y*o},{x:a+s.x*o,y:l+s.y*o}]}initializeRotationCache(t){this.zonePoints.length<3||(this.rotationCache={rotationCenter:t,initialPoints:this.zonePoints.map(i=>({...i})),totalAngle:0})}handleInternalRotationMove(t){if(!this.rotationCache||this.rotationCache.initialPoints.length<3)return null;const{rotationCenter:i,initialPoints:s}=this.rotationCache;return this.rotationCache.totalAngle+=t,pb(s,i,this.rotationCache.totalAngle)}resetRotationState(){this.rotationCache=null}calculateRotationCenter(){return this.zonePoints.length===0?{x:0,y:0}:oe(this.zonePoints)}updateEditState({showRotateButton:t=!1,showScaleButton:i=!1,showRadialScaleButton:s=!1,showDeleteButton:r=!1,showMoveButton:o=!1,showBorder:a=!1,showSizeText:l=!1,borderStyle:h}){this.rotateButton&&(this.rotateButton.visible=t),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=t||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=l),a&&(this.updateOutlineBorder(),c&&(this.moveLine&&o&&this.updateMoveLine(),this.updateControlButtonsPosition()),l&&this.updateSizeTextPosition()),h&&this.outlineBorder.updateStyle({isDashed:h.isDashed,dashArray:h.dashArray})}getOperationState(){var r,o,a,l,h;const t=((r=this.scaleButton)==null?void 0:r.isCurrentlyScaling())||((o=this.horizontalScaleButton)==null?void 0:o.isCurrentlyScaling())||((a=this.verticalScaleButton)==null?void 0:a.isCurrentlyScaling())||!1,i=((l=this.rotateButton)==null?void 0:l.isCurrentlyRotating())||!1,s=((h=this.moveButton)==null?void 0:h.isCurrentlyMoving())||!1;return{isDragging:!1,isScaling:t,isRotating:i,isMoving:s,hasAnyOperation:t||i||s}}stopAllOperations(){var t,i,s,r,o;(t=this.scaleButton)==null||t.stopScaling(),(i=this.horizontalScaleButton)==null||i.stopScaling(),(s=this.verticalScaleButton)==null||s.stopScaling(),(r=this.rotateButton)==null||r.stopRotation(),(o=this.moveButton)==null||o.stopMoving()}getControlButtonsContainer(){return this.controlButtons}getMoveButton(){return this.moveButton}calculateEdgeMidpoint(t,i){const s=this.calculateOutlinePoints();if(s.length<4)return{x:0,y:0};const r=s[t],o=s[i];return{x:(r.x+o.x)/2,y:(r.y+o.y)/2}}destroy(){var t,i,s,r,o,a,l,h,c,d,u;this.appService.emitter.off("antiScale",this.throttledUpdateOutline),this.throttledUpdateOutline.cancel(),this.appService.emitter.off("mapRotationUpdate",this.throttledUpdateOutline),(t=this.clickHandler)==null||t.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(),(l=this.verticalScaleButton)==null||l.destroy(),this.deleteButton=null,this.rotateButton=null,this.scaleButton=null,this.moveButton=null,this.horizontalScaleButton=null,this.verticalScaleButton=null,(h=this.outlineBorder)==null||h.destroy(),(c=this.moveLine)==null||c.destroy(),(d=this.sizeText)==null||d.destroy(),(u=this.controlButtons)==null||u.destroy(),super.destroy()}}function E0(n,e,t){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,...Se({showRotateButton:(t==null?void 0:t.showRotateButton)??n.showRotateButton,showScaleButton:(t==null?void 0:t.showScaleButton)??n.showScaleButton,showDeleteButton:(t==null?void 0:t.showDeleteButton)??n.showDeleteButton,showMoveButton:(t==null?void 0:t.showMoveButton)??n.showMoveButton}),showRadialScaleButton:t==null?void 0:t.showRadialScaleButton,rotateMode:t==null?void 0:t.rotateMode,scaleMode:"free",textColor:String(n.textColor),textPosition:n.textPosition,textOffset:n.textOffset,moveButtonOffset:e.moveButtonOffset,textFontSize:e.textFontSize,textFontFamily:e.textFontFamily,textFontWeight:e.textFontWeight}}function Gn(n,e){return{coords:n.coords,editControls:n.editControlManager,getZoneConfig:t=>k0(n,t),controlsConfig:n.getConfig().controls,makeControlFill:t=>new oa(n,t),makeBorder:t=>new De(n,t),makeCenterIcon:t=>new P0(n,t),render:{request:t=>n.getApp().requestRender(t,!0),stop:t=>n.getApp().stopRender(t)},events:e}}function k0(n,e){var i;const t=n.getConfig();if(Pe(e)){const s=t.controls[e];if(s)return s}else{const s=(i=t.customZoneTypes)==null?void 0:i[e];if(s)return s}return fc.cleanZone}class Un extends O{constructor(t){super();y(this,"zoneData");y(this,"zoneType");y(this,"zoneConfig");y(this,"controlsConfig");y(this,"zoneEvents");y(this,"deps");y(this,"controlFill");y(this,"zoneBorder");y(this,"editableShape");y(this,"centerIcon",null);y(this,"clickHandler",null);y(this,"initialZonePoints",[]);y(this,"dragStartPosition",null);y(this,"editing",!1);y(this,"disabled",!1);y(this,"resolvedMaxSizeCache",null);y(this,"handleDragStart",()=>{this.resolveVisualState()==="editing"&&(this.initialZonePoints=this.zoneData.points.map(t=>({...t})),this.dragStartPosition=this.controlFill.getDragStartPosition(),this.deps.render.request("zone-drag"))});y(this,"handleDragMove",t=>{if(this.resolveVisualState()!=="editing"||this.initialZonePoints.length===0||!this.dragStartPosition)return;const i=this.parent.toLocal(t.global),s=i.x-this.dragStartPosition.x,r=i.y-this.dragStartPosition.y;this.applyTranslation(s,r)});y(this,"handleDragEnd",()=>{var t,i;this.initialZonePoints=[],this.dragStartPosition=null,this.deps.render.stop("zone-drag"),(i=(t=this.zoneEvents).onUpdate)==null||i.call(t,this.getZoneData())});y(this,"handleRotationStart",()=>{this.deps.render.request("zone-rotate")});y(this,"handleRotationMove",t=>{t&&(this.zoneData.points=t,this.drawZone(!1))});y(this,"handleScaleStart",()=>{this.deps.render.request("zone-scale")});y(this,"handleScaleMove",t=>{t&&(this.zoneData.points=t,this.drawZone())});y(this,"handleMoveStart",()=>{this.initialZonePoints=this.zoneData.points.map(t=>({...t})),this.deps.render.request("zone-move")});y(this,"handleMove",t=>{var a;if(this.resolveVisualState()!=="editing"||this.initialZonePoints.length===0)return;const i=this.parent.toLocal(t.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)});y(this,"handleMoveEnd",()=>{var t,i;this.initialZonePoints=[],this.deps.render.stop("zone-move"),(i=(t=this.zoneEvents).onUpdate)==null||i.call(t,this.getZoneData())});y(this,"handleTransformEnd",()=>{var t,i;this.initialZonePoints=[],this.deps.render.stop("zone-rotate"),this.deps.render.stop("zone-scale"),(i=(t=this.zoneEvents).onUpdate)==null||i.call(t,this.getZoneData())});y(this,"handleDelete",()=>{var t,i;(i=(t=this.zoneEvents).onRemove)==null||i.call(t,this.zoneData.id)});y(this,"handleClick",()=>{var t,i;this.resolveVisualState()!=="editing"&&((i=(t=this.zoneEvents)==null?void 0:t.onClick)==null||i.call(t,this.getZoneData()))});const{deps:i,zoneData:s,zoneType:r}=t;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.applyVisualState()}getResolvedMaxSize(){const t=this.zoneConfig.maxSize;if(this.resolvedMaxSizeCache&&this.resolvedMaxSizeCache.key===t)return this.resolvedMaxSizeCache.value;const i=ne(this.zoneConfig.minSize,t,this.zoneType);return this.resolvedMaxSizeCache={key:t,value:i},i}validateZoneShape(t){if(t.length<4)return t;const i=this.getResolvedMaxSize();return this.deps.coords.validateShape(Fn(t),{minSize:et(this.zoneConfig.minSize),maxSize:i!=null?et(i):void 0})}initializeComponents(){this.controlFill=this.createControlFill(),this.addChild(this.controlFill),this.zoneBorder=this.createBorder(),this.addChild(this.zoneBorder);const t=this.zoneConfig.centerIcon;t&&(this.centerIcon=this.deps.makeCenterIcon(t),this.addChild(this.centerIcon),this.updateCenterIcon(this.zoneData.points))}createControlFill(){return this.deps.makeControlFill({points:this.zoneData.points,fillColor:this.zoneConfig.fillColor,enableInteraction:this.resolveVisualState()==="editing",onDragStart:this.handleDragStart,onDragMove:this.handleDragMove,onDragEnd:this.handleDragEnd})}createBorder(){return this.deps.makeBorder({points:this.zoneData.points,closePath:!0,style:this.resolveBorderStyle(this.resolveVisualState())})}createEditControlLayer(){const t=E0(this.zoneConfig,this.controlsConfig,{showRotateButton:this.zoneConfig.showRotateButton,showRadialScaleButton:!1,rotateMode:"free"});this.editableShape=new Es({editControls:this.deps.editControls});const i=this.getResolvedMaxSize(),s={config:t,zonePoints:this.zoneData.points,minSize:this.zoneConfig.minSize,maxSize:i??void 0,contentLayer:Te,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:{...Se(this.zoneConfig),showRadialScaleButton:!1,showBorder:!0,showSizeText:!0},idleState:{showRotateButton:!1,showScaleButton:!1,showRadialScaleButton:!1,showDeleteButton:!1,showMoveButton:!1,showBorder:!1,showSizeText:!1}})}applyTranslation(t,i){this.zoneData.points=this.initialZonePoints.map(s=>({x:s.x+t,y:s.y+i})),this.drawZone()}setupClickHandler(){this.interactiveChildren=!0,this.clickHandler=new yt(this,{onClick:this.handleClick,stopPropagation:!1})}drawZone(t=!0){const{points:i}=this.zoneData;i.length<4||(this.controlFill.updatePoints(i),this.zoneBorder.updatePoints(i),this.updateCenterIcon(i),this.editableShape.updatePoints(i,t))}updateCenterIcon(t){this.centerIcon&&this.centerIcon.updateGeometry(oe(t),I0(t))}resolveVisualState(){return Ii(this.editing,this.disabled)}applyVisualState(){var i,s;const t=this.resolveVisualState();t==="disabled"&&this.controlFill.interruptDragging(),this.controlFill.setInteractionEnabled(t==="editing"),this.controlFill.updateFillColor(t==="disabled"?((i=this.zoneConfig.disabled)==null?void 0:i.fillColor)??this.zoneConfig.fillColor:this.zoneConfig.fillColor),this.updateBorderStyle(this.resolveBorderStyle(t)),this.editableShape.setEditing(t==="editing"),(s=this.centerIcon)==null||s.setVisualState(t),this.alpha=t==="disabled"?Di(this.zoneConfig.disabled,this.controlsConfig.disabledStyle):1}resolveBorderStyle(t){if(t==="disabled"){const s=this.zoneConfig.disabled;return{color:(s==null?void 0:s.strokeColor)??this.zoneConfig.strokeColor,width:(s==null?void 0:s.strokeWidth)??this.zoneConfig.strokeWidth,isDashed:(s==null?void 0:s.isDashed)??this.zoneConfig.normal.isDashed,dashArray:(s==null?void 0:s.dashArray)??this.zoneConfig.normal.dashArray}}const i=t==="editing"?this.zoneConfig.editing:this.zoneConfig.normal;return{color:this.zoneConfig.strokeColor,width:this.zoneConfig.strokeWidth,isDashed:i.isDashed,dashArray:i.dashArray}}updateBorderStyle(t){this.zoneBorder.updateStyle(t)}setEditing(t){this.editing!==t&&(this.editing=t,this.applyVisualState())}isEditing(){return this.editing}setDisabled(t){this.disabled!==t&&(this.disabled=t,this.applyVisualState())}isDisabled(){return this.disabled}isLiftedForEditing(){return this.resolveVisualState()==="editing"}updateZoneData(t){const i=this.validateZoneShape(t.points);this.zoneData={...t,points:i},this.drawZone()}getZoneData(){return{...this.zoneData}}refreshDisplay(){this.drawZone()}destroy(){var t,i,s,r;this.editableShape.detach(),(t=this.clickHandler)==null||t.destroy(),this.clickHandler=null,(i=this.centerIcon)==null||i.destroy(),this.centerIcon=null,(s=this.zoneBorder)==null||s.destroy(),(r=this.controlFill)==null||r.destroy(),super.destroy()}}function I0(n){if(n.length<4)return 0;const e=(t,i)=>Math.hypot(i.x-t.x,i.y-t.y);return Math.min(e(n[0],n[1]),e(n[1],n[2]))}class aa extends Un{constructor(e,t){super({deps:Gn(e,{onRemove:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onRemoveForbiddenSweepZone)==null||r.call(s,i)},onUpdate:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onUpdateForbiddenSweepZone)==null||r.call(s,i)},onClick:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onClickForbiddenSweepZone)==null||r.call(s,i)}}),zoneData:t.zoneData,zoneType:"forbiddenSweepZone"})}static create(e,t){return new aa(e,{zoneData:t})}}class la extends Un{constructor(e,t){super({deps:Gn(e,{onRemove:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onRemoveForbiddenMopZone)==null||r.call(s,i)},onUpdate:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onUpdateForbiddenMopZone)==null||r.call(s,i)},onClick:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onClickForbiddenMopZone)==null||r.call(s,i)}}),zoneData:t.zoneData,zoneType:"forbiddenMopZone"})}static create(e,t){return new la(e,{zoneData:t})}}class ha extends Un{constructor(e,t){super({deps:Gn(e,{onRemove:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onRemoveCleanZone)==null||r.call(s,i)},onUpdate:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onUpdateCleanZone)==null||r.call(s,i)},onClick:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onClickCleanZone)==null||r.call(s,i)}}),zoneData:t.zoneData,zoneType:"cleanZone"})}static create(e,t){return new ha(e,{zoneData:t})}}class ci extends W{constructor(t,i){super();y(this,"lineOptions");y(this,"strokeContext",null);y(this,"drawDashLine",()=>{const{start:t,end:i,style:s}=this.lineOptions;this.clear(),this.strokeContext&&this.strokeContext.destroy();const r=this.appService;this.strokeContext=new J;const o=r.getApp().toFixedSize(s.width);this.strokeContext.setStrokeStyle({color:s.color,width:o}),this.drawDashedLineToContext(this.strokeContext,t.x,t.y,i.x,i.y,s.dashArray[0],s.dashArray[1]),this.strokeContext.stroke(),this.context=this.strokeContext});this.appService=t,this.lineOptions={...i},this.eventMode="static",this.drawDashLine(),this.setupAntiScaleListener()}setupAntiScaleListener(){this.appService.emitter.on("antiScale",this.drawDashLine)}drawDashedLineToContext(t,i,s,r,o,a,l){const h=r-i,c=o-s,d=Math.sqrt(h*h+c*c);if(d===0)return;const u=this.appService,p=u.getApp().toFixedSize(a),f=u.getApp().toFixedSize(l),m=p+f,g=d/m,x=Math.round(g);if(x===0){t.moveTo(i,s),t.lineTo(r,o);return}const S=d/x,b=S*(p/m),w=h/d,_=c/d;for(let v=0;v<x;v++){const C=v*S,P=C+b;if(C>=d)break;const A=Math.min(P,d),R=i+C*w,T=s+C*_,E=i+A*w,I=s+A*_;t.moveTo(R,T),t.lineTo(E,I)}}updatePoints(t,i){this.lineOptions.start=t,this.lineOptions.end=i,this.drawDashLine()}updateStyle(t){this.lineOptions.style={...this.lineOptions.style,...t},this.drawDashLine()}getOptions(){return{...this.lineOptions}}destroy(){this.appService.emitter.off("antiScale",this.drawDashLine),this.strokeContext&&this.strokeContext.destroy(),super.destroy()}}const te=class te extends O{constructor(t){super();y(this,"wallData");y(this,"wallConfig");y(this,"controlsConfig");y(this,"wallEvents");y(this,"appService");y(this,"wallLine");y(this,"outlineBorder");y(this,"moveLine");y(this,"lengthText");y(this,"controlButtons");y(this,"removeButton",null);y(this,"scaleButton",null);y(this,"moveButton",null);y(this,"initialWallPoints",[]);y(this,"initialButtonPosition",null);y(this,"isDragging",!1);y(this,"dragStartPosition",null);y(this,"gestureSession",null);y(this,"resolvedMaxWidthCache",null);y(this,"throttledUpdateOutline");y(this,"throttledHandleScaleChange");y(this,"wallLineClickHandler",null);y(this,"handleRemove",()=>{var t,i;(i=(t=this.wallEvents).onRemove)==null||i.call(t,this.wallData.id)});y(this,"initializeOperation",()=>{this.initialWallPoints=this.wallData.points.map(t=>({...t}))});y(this,"finalizeOperation",()=>{var t,i;this.initialWallPoints=[],(i=(t=this.wallEvents).onUpdate)==null||i.call(t,this.getWallData())});y(this,"handleScaleStart",()=>{this.initializeOperation();const t=this.calculateOutlinePoints();t.length>te.BUTTON_INDICES.SCALE&&(this.initialButtonPosition={...t[te.BUTTON_INDICES.SCALE]}),this.appService.getApp().requestRender("virtualwall-scale",!0)});y(this,"handleScaleMove",({deltaX:t,deltaY:i})=>{if(this.initialWallPoints.length===0||!this.initialButtonPosition)return;const s={x:this.initialButtonPosition.x+t,y:this.initialButtonPosition.y+i};this.applyScaleAndRotation(s)});y(this,"handleScaleEnd",()=>{this.finalizeOperation(),this.initialButtonPosition=null,this.appService.getApp().stopRender("virtualwall-scale")});y(this,"handleMoveStart",()=>{this.initializeOperation(),this.appService.getApp().requestRender("virtualwall-move",!0)});y(this,"handleMove",t=>{var a;if(this.initialWallPoints.length===0)return;const i=this.parent.toLocal(t.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)});y(this,"handleMoveEnd",()=>{this.finalizeOperation(),this.appService.getApp().stopRender("virtualwall-move")});y(this,"handleScaleChange",()=>{this.redrawSolidLine(),this.setupWallLineHitArea()});y(this,"handleWallLinePointerDown",t=>{this.resolveVisualState()==="editing"&&(t.stopPropagation(),this.startDragging(t))});y(this,"handleDragPointerMove",t=>{!this.isDragging||!this.dragStartPosition||this.handleMove(t)});y(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={}}=t;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=Pt(this.handleScaleChange.bind(this),30,{leading:!0,trailing:!0}),this.throttledUpdateOutline=Pt(this.updateOutlineForScale.bind(this),30,{leading:!0,trailing:!0}),this.initializeComponents(),this.updateEditState(),this.registerScaleListener()}getDiagnosticPart(t){return{delete:this.removeButton,scale:this.scaleButton,move:this.moveButton}[t]??null}registerScaleListener(){this.appService.emitter.on("antiScale",this.throttledUpdateOutline),this.appService.emitter.on("antiScale",this.throttledHandleScaleChange),this.appService.emitter.on("mapRotationUpdate",this.throttledUpdateOutline)}getResolvedMaxWidth(){const t=this.wallConfig.maxWidth;if(this.resolvedMaxWidthCache&&this.resolvedMaxWidthCache.key===t)return this.resolvedMaxWidthCache.value;const i=ne(this.wallConfig.minWidth,t,"virtualWall");return this.resolvedMaxWidthCache={key:t,value:i},i}validateAndCorrectWallLength(t){if(t.length<2)return t;const[i,s]=t,{coords:r}=this.appService,o=r.toPixels(et(this.wallConfig.minWidth)),a=this.getResolvedMaxWidth(),l=a!=null?r.toPixels(et(a)):void 0,h=q(i,s),c=h<o,d=l!=null&&h>l;if(!c&&!d)return t;if(h===0)return[i,{x:i.x+o,y:i.y}];const u=se(Mt(i,s));let p=h;return l!=null&&(p=Math.min(p,l)),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)}isDisabledEnabled(){return this.appService.runtimeSnapshot.disabledVirtualWallIds.includes(this.wallData.id)}resolveVisualState(){return Ii(this.isEditingEnabled(),this.isDisabledEnabled())}isLiftedForEditing(){return this.resolveVisualState()==="editing"}updateOutlineForScale(){this.resolveVisualState()==="editing"&&(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 O,this.controlButtons.visible=this.resolveVisualState()==="editing",this.addChild(this.controlButtons),this.createControlButtons()}createWallLine(t=!0){const{points:i}=this.wallData;if(i.length<2)return;const s=this.resolveWallLineStyle();s.isDashed?this.wallLine=new ci(this.appService,{start:i[0],end:i[1],style:{color:s.color,width:s.width,dashArray:s.dashArray}}):this.wallLine=this.createSolidLine(i[0],i[1],s.width,s.color),t&&this.setupWallLineInteraction()}createLengthText(){const t=this.calculateWallLengthInMeters(),i=this.formatLengthText(t),s=new Tn(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:t}=this.wallData;if(t.length<2)return 0;const i=q(t[0],t[1]);return this.appService.coords.toMeters(Gt(i))}formatLengthText(t){const i=this.appService.coords.toDisplayUnit(et(t)),s=this.appService.runtimeSnapshot.unitLabel;return`${i.toFixed(1)}${s}`}calculateTextPosition(){const{points:t}=this.wallData;if(t.length<2)return{x:0,y:0};const[i,s]=t,r=this.appService.getApp().toFixedSize(this.wallConfig.textOffset);return pu(i,s,r)}calculateTextRotation(){const{points:t}=this.wallData;if(t.length<2)return 0;const[i,s]=t,r=this.appService.appContainer.getMapRotationRadians();return hn(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 t=this.calculateOutlinePoints();return new De(this.appService,{points:t,closePath:!0,style:this.getOutlineStyle()})}createMoveLine(){const t=this.calculateOutlinePoints(),i=this.calculateMoveLinePoints(t);return new De(this.appService,{points:i,closePath:!1,style:this.getOutlineStyle()})}calculateOutlinePoints(t){const i=t||this.wallData.points;if(i.length<2)return i;const s=this.appService.getApp().toFixedSize(this.wallConfig.outlineOffset),r=fb(i[0],i[1],s);return[r[3],r[2],r[1],r[0]]}calculateMoveLinePoints(t){if(t.length<4)return[];const{MOVE:i}=te.BUTTON_INDICES,s=t[i],r=this.calculateMoveButtonPosition();return[s,r]}calculateMoveButtonPosition(){const{moveButtonOffset:t}=this.controlsConfig,i=this.calculateOutlinePoints();if(i.length<4)return{x:0,y:0};const{MOVE:s}=te.BUTTON_INDICES,r=i[s],o=i[(s+3)%4],a=i[(s+1)%4],l=this.appService.getApp().toFixedSize(t);return gu(r,a,o,l)}createControlButtons(){const t=this.calculateOutlinePoints();if(t.length<4)return;const{REMOVE:i,SCALE:s}=te.BUTTON_INDICES;this.removeButton=new hp(this.appService,{iconAlias:"deleteIcon",backgroundColor:this.wallConfig.iconWrapperFillColor,onClick:this.handleRemove}),this.removeButton.position.set(t[i].x,t[i].y),this.scaleButton=new pn(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(t[s].x,t[s].y);const r=this.calculateMoveButtonPosition();this.moveButton=new lp(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(t){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[te.BUTTON_INDICES.SCALE],l=s,h=Mt(r,l),c=q(r,l),d=Math.atan2(h.y,h.x),u=Mt(r,a),p=u.x*Math.cos(d)+u.y*Math.sin(d),f=-u.x*Math.sin(d)+u.y*Math.cos(d),m=p-c,g=Mt(r,t),x=q(r,t),{coords:S}=this.appService,b=S.toPixels(et(this.wallConfig.minWidth)),w=this.getResolvedMaxWidth(),_=w!=null?S.toPixels(et(w)):void 0;let v,C;if(x<1e-4)v=d,C=0;else{const E=Math.atan2(g.y,g.x),I=Math.sqrt(Math.max(0,x*x-f*f)),F=Math.atan2(f,Math.max(0,I));v=E-F,C=I-m}let P=C;P<b?P=b:_!=null&&P>_&&(P=_);const A=r.x+P*Math.cos(v),R=r.y+P*Math.sin(v),T={x:Math.abs(A)<1e-10?0:A,y:Math.abs(R)<1e-10?0:R};this.wallData.points=[r,T],this.drawVirtualWall(),this.updateControlButtonsPosition()}applyTranslation(t,i){this.wallData.points=this.initialWallPoints.map(s=>({x:s.x+t,y:s.y+i})),this.drawVirtualWall(),this.updateControlButtonsPosition()}drawVirtualWall(){this.updateWallLine(),this.updateLengthText(),this.updateOutlineComponents()}updateWallLine(){const{points:t}=this.wallData;t.length<2||(this.wallLine instanceof ci?this.wallLine.updatePoints(t[0],t[1]):this.redrawSolidLine(),this.setupWallLineHitArea())}updateLengthText(){if(!this.lengthText)return;const t=this.calculateWallLengthInMeters(),i=this.formatLengthText(t);this.lengthText.updateText(i),this.updateLengthTextPosition()}updateLengthTextPosition(){if(!this.lengthText)return;const t=this.calculateTextPosition();this.lengthText.position.set(t.x,t.y);const i=this.calculateTextRotation();this.lengthText.rotation=i}updateOutlineComponents(){const t=this.calculateOutlinePoints();this.outlineBorder.updatePoints(t);const i=this.calculateMoveLinePoints(t);this.moveLine.updatePoints(i)}updateControlButtonsPosition(){if(!this.removeButton||!this.scaleButton||!this.moveButton)return;const t=this.calculateOutlinePoints();if(t.length<4)return;const{REMOVE:i,SCALE:s}=te.BUTTON_INDICES,r=this.calculateMoveButtonPosition();this.removeButton.position.set(t[i].x,t[i].y),this.scaleButton.position.set(t[s].x,t[s].y),this.moveButton.position.set(r.x,r.y)}updateEditState(){const t=this.resolveVisualState(),i=t==="editing",s=C0(this.wallConfig);t==="disabled"&&this.interruptActiveOperations(),this.controlButtons.visible=i,this.removeButton&&(this.removeButton.visible=s.showDeleteButton),this.scaleButton&&(this.scaleButton.visible=s.showScaleButton),this.moveButton&&(this.moveButton.visible=s.showMoveButton),this.outlineBorder.visible=i,this.moveLine.visible=i&&s.showMoveButton,this.lengthText&&(this.lengthText.visible=i),i&&(this.updateOutlineComponents(),this.updateControlButtonsPosition(),this.updateLengthTextPosition()),this.updateWallLineStyle(),this.setupWallLineInteraction(),this.alpha=t==="disabled"?Di(this.wallConfig.disabled,this.controlsConfig.disabledStyle):1}interruptActiveOperations(){var t,i,s;(t=this.gestureSession)==null||t.cancel(),(i=this.scaleButton)==null||i.stopScaling(),(s=this.moveButton)==null||s.stopMoving()}createSolidLine(t,i,s,r){const o=new W;o.eventMode="static";const a=this.appService.getApp().toFixedSize(s);return o.moveTo(t.x,t.y),o.lineTo(i.x,i.y),o.stroke({color:r,width:a}),o}updateWallLineStyle(){const t=this.resolveWallLineStyle();this.wallLine instanceof ci!==t.isDashed?(this.removeChild(this.wallLine),this.wallLine.destroy(),this.createWallLine(!1),this.addChild(this.wallLine)):this.wallLine instanceof ci?this.wallLine.updateStyle({color:t.color,width:t.width,dashArray:t.dashArray}):this.redrawSolidLine()}resolveWallLineStyle(){const{editing:t,normal:i,lineWidth:s,lineColor:r,disabled:o}=this.wallConfig,a=this.resolveVisualState();if(a==="disabled")return{color:((o==null?void 0:o.lineColor)??r).toString(),width:(o==null?void 0:o.lineWidth)??s,isDashed:(o==null?void 0:o.isDashed)??i.isDashed,dashArray:(o==null?void 0:o.dashArray)??i.dashArray};const l=a==="editing"?t:i;return{color:r.toString(),width:s,isDashed:l.isDashed,dashArray:l.dashArray}}redrawSolidLine(){const t=this.appService;if(!this.wallLine||this.wallLine instanceof ci)return;const{points:i}=this.wallData;if(i.length<2)return;const s=this.resolveWallLineStyle(),r=t.getApp().toFixedSize(s.width);this.wallLine.clear(),this.wallLine.setStrokeStyle({color:s.color,width:r}).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 t=this.resolveVisualState()==="editing";(i=this.wallLineClickHandler)==null||i.destroy(),this.wallLineClickHandler=null,this.wallLine.off("pointerdown",this.handleWallLinePointerDown),t?this.wallLine.on("pointerdown",this.handleWallLinePointerDown):this.wallLineClickHandler=new yt(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(t){const i=this.appService;this.isDragging=!0;const s=this.parent.toLocal(t.global);this.dragStartPosition={x:s.x,y:s.y},this.initializeOperation(),i.getApp().requestRender("virtualwall-drag",!0),this.gestureSession=this.appService.gestureController.hijack(t),this.gestureSession.onMove(this.handleDragPointerMove),this.gestureSession.onEnd(this.handleDragPointerUp)}getDragStartPosition(){return this.dragStartPosition}setupWallLineHitArea(){if(!this.wallLine)return;const{points:t}=this.wallData;if(t.length<2)return;const{hitAreaThickness:i}=this.wallConfig,s=this.appService.getApp().toFixedSize(i),r=fu(t[0],t[1],s);if(r.length===0)return;const o=new Ze(r);this.wallLine.hitArea=o}getWallData(){return{...this.wallData}}updateWallData(t){this.wallData={...t,points:this.validateAndCorrectWallLength(t.points)},this.drawVirtualWall(),this.updateControlButtonsPosition()}updateEditingState(){this.updateEditState()}refreshDisplay(){this.drawVirtualWall()}destroy(){var t,i,s,r,o,a,l,h,c,d;this.appService.emitter.off("antiScale",this.throttledUpdateOutline),this.appService.emitter.off("antiScale",this.throttledHandleScaleChange),this.throttledUpdateOutline.cancel(),this.throttledHandleScaleChange.cancel(),this.appService.emitter.off("mapRotationUpdate",this.throttledUpdateOutline),this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null),(t=this.gestureSession)==null||t.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(),(l=this.controlButtons)==null||l.destroy(),(h=this.removeButton)==null||h.destroy(),(c=this.scaleButton)==null||c.destroy(),(d=this.moveButton)==null||d.destroy(),this.removeButton=null,this.scaleButton=null,this.moveButton=null,super.destroy()}};y(te,"BUTTON_INDICES",{REMOVE:0,SCALE:2,MOVE:3});let Mo=te;class D0 extends O{constructor(t){super();y(this,"thresholdData");y(this,"thresholdConfig");y(this,"thresholdEvents");y(this,"appService");y(this,"band");y(this,"bandFill");y(this,"bandStripes");y(this,"bandBorder");y(this,"stripesMask");y(this,"editableShape");y(this,"bandClickHandler",null);y(this,"lastVisualState",null);y(this,"initialPoints",null);y(this,"isDragging",!1);y(this,"hasDragMoved",!1);y(this,"dragStartPosition",null);y(this,"gestureSession",null);y(this,"resolvedMaxLengthCache",null);y(this,"resolvedMaxHeightCache",null);y(this,"throttledRedraw");y(this,"resolveSizeConstraintPerEdge",()=>({edge1:{min:this.thresholdConfig.minLength,max:this.getResolvedMaxLength()},edge2:{min:this.thresholdConfig.minHeight,max:this.getResolvedMaxHeight()}}));y(this,"handleRemove",()=>{var t,i;(i=(t=this.thresholdEvents).onRemove)==null||i.call(t,this.thresholdData.id)});y(this,"handleRotateStart",()=>{this.appService.getApp().requestRender("threshold-rotate",!0)});y(this,"handleRotateMove",t=>{t&&(this.setFromQuad(t),this.refreshAfterGeometryChange())});y(this,"handleRotateEnd",()=>{var t,i;this.appService.getApp().stopRender("threshold-rotate"),(i=(t=this.thresholdEvents).onUpdate)==null||i.call(t,this.getThresholdData())});y(this,"handleScaleStart",()=>{this.appService.getApp().requestRender("threshold-scale",!0)});y(this,"handleScaleMove",t=>{t&&(this.setFromQuad(t),this.refreshAfterGeometryChange())});y(this,"handleScaleEnd",()=>{var t,i;this.appService.getApp().stopRender("threshold-scale"),(i=(t=this.thresholdEvents).onUpdate)==null||i.call(t,this.getThresholdData())});y(this,"handleMoveStart",()=>{this.initialPoints=this.clonePoints(),this.appService.getApp().requestRender("threshold-move",!0)});y(this,"handleMoveMove",t=>{var r;if(!this.initialPoints||!this.parent)return;const i=this.parent.toLocal(t.global),s=(r=this.editableShape.getMoveButton())==null?void 0:r.getDragStartPosition();s&&this.applyTranslation(i.x-s.x,i.y-s.y)});y(this,"handleMoveEnd",()=>{var t,i;this.initialPoints=null,this.appService.getApp().stopRender("threshold-move"),(i=(t=this.thresholdEvents).onUpdate)==null||i.call(t,this.getThresholdData())});y(this,"handleBandPointerDown",t=>{this.resolveVisualState()==="editing"&&(t.stopPropagation(),this.startDragging(t))});y(this,"handleDragPointerMove",t=>{if(!this.isDragging||!this.dragStartPosition||!this.initialPoints)return;this.hasDragMoved=!0;const i=this.parent.toLocal(t.global);this.applyTranslation(i.x-this.dragStartPosition.x,i.y-this.dragStartPosition.y)});y(this,"handleDragPointerUp",()=>{var t,i;this.gestureSession=null,this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null,this.initialPoints=null,this.appService.getApp().stopRender("threshold-drag"),this.hasDragMoved&&(this.hasDragMoved=!1,(i=(t=this.thresholdEvents).onUpdate)==null||i.call(t,this.getThresholdData())))});const{appService:i,thresholdData:s,events:r={}}=t;this.appService=i,this.thresholdEvents=r,this.thresholdConfig=i.controlsConfig.threshold,this.thresholdData=this.validateAndCorrect(s),this.band=new O,this.bandFill=new W,this.bandStripes=new W,this.bandBorder=new W,this.stripesMask=new W,this.bandFill.eventMode="none",this.bandStripes.eventMode="none",this.bandBorder.eventMode="none",this.stripesMask.eventMode="none",this.bandStripes.mask=this.stripesMask,this.band.addChild(this.bandFill),this.band.addChild(this.bandStripes),this.band.addChild(this.bandBorder),this.band.addChild(this.stripesMask),this.addChild(this.band),this.drawBand(),this.eventMode="passive",this.setupBandInteraction(),this.editableShape=this.createEditControls(),this.updateEditState(),this.throttledRedraw=Pt(this.handleScaleChange.bind(this),30,{leading:!0,trailing:!0}),this.appService.emitter.on("antiScale",this.throttledRedraw)}getThresholdData(){return{...this.thresholdData,points:this.clonePoints()}}updateThresholdData(t){this.thresholdData=this.validateAndCorrect(t),this.refreshAfterGeometryChange()}updateEditingState(){this.updateEditState()}refreshDisplay(){this.editableShape.updatePoints(this.getQuadPoints())}isEditingEnabled(){return this.appService.runtimeSnapshot.editingThresholdIds.includes(this.thresholdData.id)}isDisabledEnabled(){return this.appService.runtimeSnapshot.disabledThresholdIds.includes(this.thresholdData.id)}resolveVisualState(){return Ii(this.isEditingEnabled(),this.isDisabledEnabled())}isLiftedForEditing(){return this.resolveVisualState()==="editing"}resolveEditingState(){return{...Se(this.thresholdConfig),showRadialScaleButton:!1,showBorder:!0,showSizeText:!0}}updateEditState(){var o;const t=this.resolveVisualState(),i=t==="editing";t==="disabled"&&((o=this.gestureSession)==null||o.cancel()),i?this.editableShape.applyEditState(this.resolveEditingState()):this.editableShape.setEditing(!1);const s=this.lastVisualState==="disabled",r=t==="disabled";this.lastVisualState=t,this.alpha=r?Di(this.thresholdConfig.disabled,this.appService.controlsConfig.disabledStyle):1,s!==r&&this.drawBand()}getQuadPoints(){return this.clonePoints()}setFromQuad(t){t.length<4||(this.thresholdData={...this.thresholdData,points:t.map(i=>({...i}))})}getBandFrame(){const[t,i,s,r]=this.thresholdData.points,o={x:(t.x+r.x)/2,y:(t.y+r.y)/2},a={x:(i.x+s.x)/2,y:(i.y+s.y)/2};return{origin:o,rotation:Math.atan2(a.y-o.y,a.x-o.x),length:q(o,a),thickness:q(t,r)}}createEditControls(){const t=this.thresholdConfig,i=this.appService.controlsConfig,s=new Es({editControls:this.appService.editControlManager}),r={config:{outlineStrokeColor:t.outlineStrokeColor,outlineStrokeWidth:t.outlineStrokeWidth,outlineDashed:t.outlineDashed,outlineDashArray:t.outlineDashArray,outlineFillColor:t.outlineFillColor,outlineOffset:t.outlineOffset,iconWrapperFillColor:t.iconWrapperFillColor,...Se(t),showRadialScaleButton:!1,rotateMode:"free",scaleMode:"free",textColor:t.textColor,textPosition:"top",textOffset:t.textOffset,moveButtonOffset:i.moveButtonOffset,textFontSize:i.textFontSize,textFontFamily:i.textFontFamily,textFontWeight:i.textFontWeight},zonePoints:this.getQuadPoints(),sizeConstraintPerEdge:this.resolveSizeConstraintPerEdge,contentLayer:Pi,events:{onRemove:this.handleRemove,onRotateStart:this.handleRotateStart,onRotateMove:this.handleRotateMove,onRotateEnd:this.handleRotateEnd,onScaleStart:this.handleScaleStart,onScaleMove:this.handleScaleMove,onScaleEnd:this.handleScaleEnd,onMoveStart:this.handleMoveStart,onMoveMove:this.handleMoveMove,onMoveEnd:this.handleMoveEnd}};return s.attach(this,{id:this.thresholdData.id,topology:"quad",layerOptions:r,editingState:this.resolveEditingState(),idleState:{showRotateButton:!1,showScaleButton:!1,showRadialScaleButton:!1,showDeleteButton:!1,showMoveButton:!1,showBorder:!1,showSizeText:!1}}),s}setupBandInteraction(){this.updateBandHitArea(),this.bandClickHandler=new yt(this.band,{onClick:()=>{var t,i;this.appService.gestureController.suppressMapClick(),(i=(t=this.thresholdEvents).onClick)==null||i.call(t,this.getThresholdData())},stopPropagation:!1}),this.band.on("pointerdown",this.handleBandPointerDown)}updateBandHitArea(){const t=this.getBandFrame(),i=this.appService.getApp().toFixedSize(this.thresholdConfig.hitAreaPadding),s=t.thickness+i*2;this.band.hitArea=new st(0,-s/2,t.length,s)}startDragging(t){this.isDragging=!0,this.hasDragMoved=!1;const i=this.parent.toLocal(t.global);this.dragStartPosition={x:i.x,y:i.y},this.initialPoints=this.clonePoints(),this.appService.getApp().requestRender("threshold-drag",!0),this.gestureSession=this.appService.gestureController.hijack(t),this.gestureSession.onMove(this.handleDragPointerMove),this.gestureSession.onEnd(this.handleDragPointerUp)}applyTranslation(t,i){this.initialPoints&&(this.thresholdData={...this.thresholdData,points:this.initialPoints.map(s=>({x:s.x+t,y:s.y+i}))},this.refreshAfterGeometryChange())}refreshAfterGeometryChange(){this.drawBand(),this.updateBandHitArea(),this.editableShape.updatePoints(this.getQuadPoints())}clonePoints(){return this.thresholdData.points.map(t=>({...t}))}handleScaleChange(){this.drawBand(),this.updateBandHitArea()}getResolvedMaxLength(){const t=this.thresholdConfig.maxLength;if(this.resolvedMaxLengthCache&&this.resolvedMaxLengthCache.key===t)return this.resolvedMaxLengthCache.value;const i=ne(this.thresholdConfig.minLength,t,"threshold");return this.resolvedMaxLengthCache={key:t,value:i},i}getResolvedMaxHeight(){const t=this.thresholdConfig.maxHeight;if(this.resolvedMaxHeightCache&&this.resolvedMaxHeightCache.key===t)return this.resolvedMaxHeightCache.value;const i=ne(this.thresholdConfig.minHeight,t,"threshold.height");return this.resolvedMaxHeightCache={key:t,value:i},i}validateAndCorrect(t){return{...t,points:this.normalizeQuad(t.points),type:t.type??"passable"}}normalizeQuad(t){if(!Jo(t))return t.map(a=>({...a}));const i=db(lu(Fn(t))),s=ou(i),r=this.getResolvedMaxLength(),o=this.getResolvedMaxHeight();return this.appService.coords.validateShape(s,{edge1:{min:et(this.thresholdConfig.minLength),max:r!=null?et(r):void 0},edge2:{min:et(this.thresholdConfig.minHeight),max:o!=null?et(o):void 0}})}getTypeStyle(){var r,o;const t=this.thresholdData.type==="passable",i=t?this.thresholdConfig.passable:this.thresholdConfig.impassable;if(this.resolveVisualState()!=="disabled")return i;const s=t?(r=this.thresholdConfig.disabled)==null?void 0:r.passable:(o=this.thresholdConfig.disabled)==null?void 0:o.impassable;return s?{...i,...s}:i}drawBand(){const{stripeWidth:t,stripeGap:i,stripeDirection:s,borderWidth:r,cornerRadius:o}=this.thresholdConfig,a=this.getTypeStyle(),l=this.appService.getApp(),h=this.getBandFrame(),{length:c,thickness:d}=h,u=l.toFixedSize(r);if(this.bandFill.clear(),this.bandStripes.clear(),this.bandBorder.clear(),this.stripesMask.clear(),c===0||d===0)return;this.band.position.set(h.origin.x,h.origin.y),this.band.rotation=h.rotation;const p=d/2,f=Math.min(l.toFixedSize(o),p,c/2);this.bandFill.roundRect(0,-p,c,d,f).fill(a.fillColor),this.bandBorder.roundRect(0,-p,c,d,f).stroke({color:a.color,width:u}),this.stripesMask.roundRect(0,-p,c,d,f).fill(16777215);const m=t*d,g=m+i*d;if(g<=0)return;const x=s==="backward"?1:-1,b=p+m,w=2*b/Math.tan(this.getStripeAngleRadians());let _=!1;for(let v=-w;v<c;v+=g)this.bandStripes.moveTo(v,-b*x).lineTo(v+w,b*x),_=!0;_&&this.bandStripes.stroke({color:a.color,width:m})}getStripeAngleRadians(){const t=this.thresholdConfig.stripeAngle;return(Number.isFinite(t)?Math.min(90,Math.max(10,t)):45)*Math.PI/180}destroy(){var t,i;this.appService.emitter.off("antiScale",this.throttledRedraw),this.throttledRedraw.cancel(),this.editableShape.detach(),this.isDragging&&(this.isDragging=!1,this.hasDragMoved=!1,this.dragStartPosition=null,this.initialPoints=null),(t=this.gestureSession)==null||t.cancel(),this.gestureSession=null,this.band.off("pointerdown",this.handleBandPointerDown),(i=this.bandClickHandler)==null||i.destroy(),this.bandClickHandler=null,this.bandStripes.mask=null,this.bandFill.destroy(),this.bandStripes.destroy(),this.bandBorder.destroy(),this.stripesMask.destroy(),this.band.destroy(),super.destroy()}}const F0=6,B0=160,L0=32,tc=(n,e)=>Math.max(1,Math.min(Math.round(n)||1,e));class z0 extends O{constructor(t){super();y(this,"rampData");y(this,"rampConfig");y(this,"rampEvents");y(this,"appService");y(this,"body");y(this,"bodyFill");y(this,"bodyStripes");y(this,"bodyBorder");y(this,"stripesMask");y(this,"editableShape");y(this,"bodyClickHandler",null);y(this,"lastVisualState",null);y(this,"initialPoints",null);y(this,"isDragging",!1);y(this,"hasDragMoved",!1);y(this,"dragStartPosition",null);y(this,"gestureSession",null);y(this,"resolvedMaxWidthCache",null);y(this,"resolvedMaxHeightCache",null);y(this,"throttledRedraw");y(this,"resolveSizeConstraintPerEdge",()=>({edge1:{min:this.rampConfig.minWidth,max:this.getResolvedMaxWidth()},edge2:{min:this.rampConfig.minHeight,max:this.getResolvedMaxHeight()}}));y(this,"handleRemove",()=>{var t,i;(i=(t=this.rampEvents).onRemove)==null||i.call(t,this.rampData.id)});y(this,"handleRotateStart",()=>{this.appService.getApp().requestRender("ramp-rotate",!0)});y(this,"handleRotateMove",t=>{t&&(this.setFromQuad(t),this.refreshAfterGeometryChange())});y(this,"handleRotateEnd",()=>{var t,i;this.appService.getApp().stopRender("ramp-rotate"),(i=(t=this.rampEvents).onUpdate)==null||i.call(t,this.getRampData())});y(this,"handleScaleStart",()=>{this.appService.getApp().requestRender("ramp-scale",!0)});y(this,"handleScaleMove",t=>{t&&(this.setFromQuad(t),this.refreshAfterGeometryChange())});y(this,"handleScaleEnd",()=>{var t,i;this.appService.getApp().stopRender("ramp-scale"),(i=(t=this.rampEvents).onUpdate)==null||i.call(t,this.getRampData())});y(this,"handleMoveStart",()=>{this.initialPoints=this.clonePoints(),this.appService.getApp().requestRender("ramp-move",!0)});y(this,"handleMoveMove",t=>{var r;if(!this.initialPoints||!this.parent)return;const i=this.parent.toLocal(t.global),s=(r=this.editableShape.getMoveButton())==null?void 0:r.getDragStartPosition();s&&this.applyTranslation(i.x-s.x,i.y-s.y)});y(this,"handleMoveEnd",()=>{var t,i;this.initialPoints=null,this.appService.getApp().stopRender("ramp-move"),(i=(t=this.rampEvents).onUpdate)==null||i.call(t,this.getRampData())});y(this,"handleBodyPointerDown",t=>{this.resolveVisualState()==="editing"&&(t.stopPropagation(),this.startDragging(t))});y(this,"handleDragPointerMove",t=>{if(!this.isDragging||!this.dragStartPosition||!this.initialPoints)return;this.hasDragMoved=!0;const i=this.parent.toLocal(t.global);this.applyTranslation(i.x-this.dragStartPosition.x,i.y-this.dragStartPosition.y)});y(this,"handleDragPointerUp",()=>{var t,i;this.gestureSession=null,this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null,this.initialPoints=null,this.appService.getApp().stopRender("ramp-drag"),this.hasDragMoved&&(this.hasDragMoved=!1,(i=(t=this.rampEvents).onUpdate)==null||i.call(t,this.getRampData())))});const{appService:i,rampData:s,events:r={}}=t;this.appService=i,this.rampEvents=r,this.rampConfig=i.controlsConfig.ramp,this.rampData=this.validateAndCorrect(s),this.body=new O,this.bodyFill=new W,this.bodyStripes=new W,this.bodyBorder=new W,this.stripesMask=new W,this.bodyFill.eventMode="none",this.bodyStripes.eventMode="none",this.bodyBorder.eventMode="none",this.stripesMask.eventMode="none",this.bodyStripes.mask=this.stripesMask,this.body.addChild(this.bodyFill),this.body.addChild(this.bodyStripes),this.body.addChild(this.bodyBorder),this.body.addChild(this.stripesMask),this.addChild(this.body),this.drawBody(),this.eventMode="passive",this.setupBodyInteraction(),this.editableShape=this.createEditControls(),this.updateEditState(),this.throttledRedraw=Pt(this.handleScaleChange.bind(this),30,{leading:!0,trailing:!0}),this.appService.emitter.on("antiScale",this.throttledRedraw)}getRampData(){return{...this.rampData,points:this.clonePoints()}}updateRampData(t){this.rampData=this.validateAndCorrect(t),this.refreshAfterGeometryChange()}updateEditingState(){this.updateEditState()}refreshDisplay(){this.editableShape.updatePoints(this.getQuadPoints())}isEditingEnabled(){return this.appService.runtimeSnapshot.editingRampIds.includes(this.rampData.id)}isDisabledEnabled(){return this.appService.runtimeSnapshot.disabledRampIds.includes(this.rampData.id)}resolveVisualState(){return Ii(this.isEditingEnabled(),this.isDisabledEnabled())}isLiftedForEditing(){return this.resolveVisualState()==="editing"}resolveEditingState(){return{...Se(this.rampConfig),showRadialScaleButton:!1,showBorder:!0,showSizeText:!0}}updateEditState(){var o;const t=this.resolveVisualState(),i=t==="editing";t==="disabled"&&((o=this.gestureSession)==null||o.cancel()),i?this.editableShape.applyEditState(this.resolveEditingState()):this.editableShape.setEditing(!1);const s=this.lastVisualState==="disabled",r=t==="disabled";this.lastVisualState=t,this.alpha=r?Di(this.rampConfig.disabled,this.appService.controlsConfig.disabledStyle):1,s!==r&&this.drawBody()}getQuadPoints(){return this.clonePoints()}setFromQuad(t){t.length<4||(this.rampData={...this.rampData,points:t.map(i=>({...i}))})}getFrame(){const[t,i,,s]=this.rampData.points;return{origin:t,rotation:Math.atan2(i.y-t.y,i.x-t.x),width:q(t,i),height:q(t,s)}}createEditControls(){const t=this.rampConfig,i=this.appService.controlsConfig,s=new Es({editControls:this.appService.editControlManager}),r={config:{outlineStrokeColor:t.outlineStrokeColor,outlineStrokeWidth:t.outlineStrokeWidth,outlineDashed:t.outlineDashed,outlineDashArray:t.outlineDashArray,outlineFillColor:t.outlineFillColor,outlineOffset:t.outlineOffset,iconWrapperFillColor:t.iconWrapperFillColor,...Se(t),showRadialScaleButton:!1,rotateMode:"free",scaleMode:"free",textColor:t.textColor,textPosition:"top",textOffset:t.textOffset,moveButtonOffset:i.moveButtonOffset,textFontSize:i.textFontSize,textFontFamily:i.textFontFamily,textFontWeight:i.textFontWeight},zonePoints:this.getQuadPoints(),sizeConstraintPerEdge:this.resolveSizeConstraintPerEdge,contentLayer:Pi,events:{onRemove:this.handleRemove,onRotateStart:this.handleRotateStart,onRotateMove:this.handleRotateMove,onRotateEnd:this.handleRotateEnd,onScaleStart:this.handleScaleStart,onScaleMove:this.handleScaleMove,onScaleEnd:this.handleScaleEnd,onMoveStart:this.handleMoveStart,onMoveMove:this.handleMoveMove,onMoveEnd:this.handleMoveEnd}};return s.attach(this,{id:this.rampData.id,topology:"quad",layerOptions:r,editingState:this.resolveEditingState(),idleState:{showRotateButton:!1,showScaleButton:!1,showRadialScaleButton:!1,showDeleteButton:!1,showMoveButton:!1,showBorder:!1,showSizeText:!1}}),s}setupBodyInteraction(){this.updateBodyHitArea(),this.bodyClickHandler=new yt(this.body,{onClick:()=>{var t,i;this.appService.gestureController.suppressMapClick(),(i=(t=this.rampEvents).onClick)==null||i.call(t,this.getRampData())},stopPropagation:!1}),this.body.on("pointerdown",this.handleBodyPointerDown)}updateBodyHitArea(){const t=this.getFrame();this.body.hitArea=new st(0,0,t.width,t.height)}startDragging(t){this.isDragging=!0,this.hasDragMoved=!1;const i=this.parent.toLocal(t.global);this.dragStartPosition={x:i.x,y:i.y},this.initialPoints=this.clonePoints(),this.appService.getApp().requestRender("ramp-drag",!0),this.gestureSession=this.appService.gestureController.hijack(t),this.gestureSession.onMove(this.handleDragPointerMove),this.gestureSession.onEnd(this.handleDragPointerUp)}applyTranslation(t,i){this.initialPoints&&(this.rampData={...this.rampData,points:this.initialPoints.map(s=>({x:s.x+t,y:s.y+i}))},this.refreshAfterGeometryChange())}refreshAfterGeometryChange(){this.drawBody(),this.updateBodyHitArea(),this.editableShape.updatePoints(this.getQuadPoints())}clonePoints(){return this.rampData.points.map(t=>({...t}))}handleScaleChange(){this.drawBody()}getResolvedMaxWidth(){const t=this.rampConfig.maxWidth;if(this.resolvedMaxWidthCache&&this.resolvedMaxWidthCache.key===t)return this.resolvedMaxWidthCache.value;const i=ne(this.rampConfig.minWidth,t,"ramp");return this.resolvedMaxWidthCache={key:t,value:i},i}getResolvedMaxHeight(){const t=this.rampConfig.maxHeight;if(this.resolvedMaxHeightCache&&this.resolvedMaxHeightCache.key===t)return this.resolvedMaxHeightCache.value;const i=ne(this.rampConfig.minHeight,t,"ramp.height");return this.resolvedMaxHeightCache={key:t,value:i},i}validateAndCorrect(t){return{...t,points:this.normalizeQuad(t.points)}}normalizeQuad(t){if(!au(t))return t.map(o=>({...o}));const i=lu(Fn(t)),s=this.getResolvedMaxWidth(),r=this.getResolvedMaxHeight();return this.appService.coords.validateShape(i,{edge1:{min:et(this.rampConfig.minWidth),max:s!=null?et(s):void 0},edge2:{min:et(this.rampConfig.minHeight),max:r!=null?et(r):void 0}})}resolveBodyStyle(){const t=this.rampConfig;return this.resolveVisualState()!=="disabled"||!t.disabled?t:{fillColor:t.disabled.fillColor??t.fillColor,strokeColor:t.disabled.strokeColor??t.strokeColor,strokeWidth:t.disabled.strokeWidth??t.strokeWidth,arrowColor:t.disabled.arrowColor??t.arrowColor}}drawBody(){const t=this.rampConfig,i=this.resolveBodyStyle(),s=this.appService.getApp(),r=this.getFrame(),{width:o,height:a}=r,l=s.toFixedSize(i.strokeWidth);if(this.bodyFill.clear(),this.bodyStripes.clear(),this.bodyBorder.clear(),this.stripesMask.clear(),o===0||a===0)return;this.body.position.set(r.origin.x,r.origin.y),this.body.rotation=r.rotation,this.bodyFill.rect(0,0,o,a).fill(i.fillColor),this.bodyBorder.rect(0,0,o,a).stroke({color:i.strokeColor,width:l});const h=s.toFixedSize(t.arrowThickness),c=h+s.toFixedSize(t.arrowGap);if(!Number.isFinite(h)||h<=0||!Number.isFinite(c)||c<=0)return;const d=s.toFixedSize(t.arrowInset),u=Math.min(Math.max(Number.isFinite(d)?d:0,0),o/2,a/2),p=o-u*2,f=a-u*2;if(p<=0||f<=0)return;this.stripesMask.rect(u,u,p,f).fill(16777215);const{columns:m,columnGap:g,arrowWidth:x,rows:S,rise:b,spacing:w,thickness:_}=this.layoutArrows(p,f,h,c),v=this.getMiterOvershoot(_),C=v+b+_/2,P=S>1?u+v+b:u+(f-C)/2+v+b;for(let A=0;A<S;A++){const R=P+w*A;for(let T=0;T<m;T++){const E=u+(x+g)*T;this.bodyStripes.moveTo(E,R).lineTo(E+x/2,R-b).lineTo(E+x,R)}}this.bodyStripes.stroke({color:this.resolveBodyStyle().arrowColor,width:_})}layoutArrows(t,i,s,r){const o=Math.min(t,i),a=this.rampConfig.arrowDensity,l=Number.isFinite(a)?Math.max(1,Math.floor(a)):F0,h=Math.max(o/l,r),c=this.getArrowThicknessRatio(),d=Math.max(h*(1-c),0),u=Math.floor((t+d)/(r+d)),p=tc(Math.min(Math.round(t/o),u),L0),f=p>1?d:0,m=(t-f*(p-1))/p,g=m/2*Math.tan(this.getArrowAngleRadians()),x=Math.floor((i-g-s)/r)+1,S=tc(Math.min(Math.round(i/h),x),B0),b=(1/Math.cos(this.getArrowAngleRadians())+1)/2;if(S<=1){const v=(i-g)/b;return{columns:p,columnGap:f,arrowWidth:m,rows:1,rise:g,spacing:0,thickness:Math.max(Math.min(h*c,v),s)}}let w=(i-g)/(S-1+c*b),_=w*c;return _<s&&(_=s,w=(i-g-_*b)/(S-1)),{columns:p,columnGap:f,arrowWidth:m,rows:S,rise:g,spacing:w,thickness:_}}getMiterOvershoot(t){return t/2/Math.cos(this.getArrowAngleRadians())}getArrowThicknessRatio(){const t=this.rampConfig.arrowThicknessRatio;return!Number.isFinite(t)||t<=0?0:t}getArrowAngleRadians(){const t=this.rampConfig.arrowAngle;return(Number.isFinite(t)?Math.min(60,Math.max(1,t)):9)*Math.PI/180}destroy(){var t,i;this.appService.emitter.off("antiScale",this.throttledRedraw),this.throttledRedraw.cancel(),this.editableShape.detach(),this.isDragging&&(this.isDragging=!1,this.hasDragMoved=!1,this.dragStartPosition=null,this.initialPoints=null),(t=this.gestureSession)==null||t.cancel(),this.gestureSession=null,this.body.off("pointerdown",this.handleBodyPointerDown),(i=this.bodyClickHandler)==null||i.destroy(),this.bodyClickHandler=null,this.bodyStripes.mask=null,this.bodyFill.destroy(),this.bodyStripes.destroy(),this.bodyBorder.destroy(),this.stripesMask.destroy(),this.body.destroy(),super.destroy()}}const O0={fontSize:12,fontFamily:"system-ui, -apple-system, sans-serif",fontWeight:"400",color:"#5d68fe",position:"top",offset:-8,editing:{visible:!0},normal:{visible:!0}};class ca extends O{constructor(t){super();y(this,"spotData");y(this,"spotConfig");y(this,"controlsConfig");y(this,"spotEvents");y(this,"appService");y(this,"controlFill");y(this,"spotBorder");y(this,"centerIcon");y(this,"sizeText");y(this,"nameText");y(this,"clickHandler",null);y(this,"initialSpotPoint",null);y(this,"dragStartMousePosition",null);y(this,"throttledUpdateScale");y(this,"unsubscribeMapRotation",null);y(this,"iconAlias");y(this,"editingIdsKey");y(this,"handleDragStart",t=>{this.isEditingEnabled()&&(this.initialSpotPoint={...this.spotData.point},this.dragStartMousePosition=this.parent.toLocal(t.global),this.appService.getApp().requestRender("spot-drag",!0))});y(this,"handleDragMove",t=>{if(!this.isEditingEnabled()||!this.initialSpotPoint||!this.dragStartMousePosition||!this.controlFill)return;const i=this.parent.toLocal(t.global),s=i.x-this.dragStartMousePosition.x,r=i.y-this.dragStartMousePosition.y;this.applyTranslation(s,r)});y(this,"handleDragEnd",()=>{var t,i;this.initialSpotPoint=null,this.dragStartMousePosition=null,this.appService.getApp().stopRender("spot-drag"),(i=(t=this.spotEvents).onUpdate)==null||i.call(t,this.getSpotData())});const{appService:i,spotData:s,events:r={},config:o,iconAlias:a,editingIdsKey:l}=t;this.appService=i,this.spotData=s,this.spotEvents=r,this.controlsConfig=this.appService.controlsConfig,this.spotConfig=o??this.appService.controlsConfig.spot,this.iconAlias=a??"spotIcon",this.editingIdsKey=l??"editingSpotIds",this.position.set(s.point.x,s.point.y),this.throttledUpdateScale=Pt(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[this.editingIdsKey].includes(this.spotData.id)}isLiftedForEditing(){return this.isEditingEnabled()}shouldShowIcon(){return(this.isEditingEnabled()?this.spotConfig.editing:this.spotConfig.normal).showIcon}calculateRectanglePoints(){const{size:t}=this.spotConfig;if(t===0)return[{x:0,y:0},{x:0,y:0},{x:0,y:0},{x:0,y:0}];const s=this.appService.coords.toPixels(et(t))/2;return[{x:-s,y:-s},{x:s,y:-s},{x:s,y:s},{x:-s,y:s}]}initializeComponents(){const t=this.calculateRectanglePoints();this.spotConfig.size>0&&(this.controlFill=this.createControlFill(t),this.addChild(this.controlFill),this.spotBorder=this.createBorder(t),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(t){const i=this.isEditingEnabled();return new oa(this.appService,{points:t,fillColor:this.spotConfig.fillColor,enableInteraction:i,onDragStart:this.handleDragStart,onDragMove:this.handleDragMove,onDragEnd:this.handleDragEnd})}createBorder(t){const s=this.isEditingEnabled()?this.spotConfig.editing:this.spotConfig.normal;return new De(this.appService,{points:t,closePath:!0,style:{color:this.spotConfig.strokeColor,width:this.spotConfig.strokeWidth,isDashed:s.isDashed,dashArray:s.dashArray}})}createCenterIcon(){const t=new Yt(this.appService);return this.loadIconTexture(t),t.position.set(0,0),t.eventMode="static",this.setupIconDrag(t),t.visible=!1,t}async loadIconTexture(t){const{iconSize:i,iconSizeFixed:s,iconAnchor:r}=this.spotConfig;await t.loadTextureAndSetSize(this.iconAlias,{width:i,height:i,sizeFixed:s}),r&&t.anchor.set(r.x,r.y),this.applyAntiRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation||(this.unsubscribeMapRotation=z(this.appService.runtime,"mapRotation",o=>{this.applyAntiRotation(o)})),t.visible=this.shouldShowIcon()}applyAntiRotation(t){const i=-t*Math.PI/180;this.rotation=i}setupIconDrag(t){let i=null,s=!1;const r=a=>{if(!s||!this.initialSpotPoint||!i)return;const l=this.parent.toLocal(a.global),h=l.x-i.x,c=l.y-i.y;this.applyTranslation(h,c)},o=()=>{var a,l;s&&(s=!1,this.initialSpotPoint=null,i=null,this.appService.getApp().stopRender("spot-drag"),(l=(a=this.spotEvents).onUpdate)==null||l.call(a,this.getSpotData()))};t.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 l=this.appService.gestureController.hijack(a);l.onMove(r),l.onEnd(o)})}createSizeText(){const t=this.calculateSpotSizeText(),i=new Tn(this.appService,{text:t,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:t}=this.spotConfig,i=this.appService.coords.toDisplayUnit(et(t)),s=this.appService.runtimeSnapshot.unitLabel;return`${i.toFixed(1)}${s}*${i.toFixed(1)}${s}`}calculateSizeTextPosition(){const{textPosition:t,textOffset:i}=this.spotConfig;return this.calculateTextPosition(t,i)}calculateTextPosition(t,i){const s=this.calculateRectanglePoints();if(s.length<4)return{x:0,y:0};const[r,o,a,l]=s,h=this.appService.getApp().toFixedSize(i);let c,d;switch(t){case"top":{c={x:(r.x+o.x)/2,y:(r.y+o.y)/2},d={x:c.x,y:c.y+h};break}case"right":{c={x:(o.x+a.x)/2,y:(o.y+a.y)/2},d={x:c.x+h,y:c.y};break}case"bottom":{c={x:(l.x+a.x)/2,y:(l.y+a.y)/2},d={x:c.x,y:c.y+h};break}case"left":{c={x:(r.x+l.x)/2,y:(r.y+l.y)/2},d={x:c.x-h,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+h};break}}return d}getNameLabelConfig(){return this.spotConfig.nameLabel??O0}createNameText(){const t=this.getNameLabelConfig(),i=new Tn(this.appService,{text:this.calculateSpotNameText(),style:{fontSize:t.fontSize,fontFamily:t.fontFamily,fontWeight:t.fontWeight,fill:t.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 t;return((t=this.spotData.name)==null?void 0:t.trim())??""}calculateNameTextPosition(){const{position:t,offset:i}=this.getNameLabelConfig();return this.calculateTextPosition(t,i)}shouldShowNameText(){if(!this.calculateSpotNameText())return!1;const i=this.isEditingEnabled(),s=this.getNameLabelConfig();return(i?s.editing:s.normal).visible}applyTranslation(t,i){if(!this.initialSpotPoint)return;const s={x:this.initialSpotPoint.x+t,y:this.initialSpotPoint.y+i};this.spotData.roomId!==void 0&&!this.appService.mapManager.isPointInRoom(s,this.spotData.roomId)||(this.spotData.point=s,this.drawSpot())}setupClickHandler(){const t=this.spotConfig.size>0?this:this.centerIcon;this.clickHandler=new yt(t,{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 t=this.calculateRectanglePoints();this.position.set(this.spotData.point.x,this.spotData.point.y),this.spotConfig.size>0&&(this.controlFill&&this.controlFill.updatePoints(t),this.spotBorder&&this.spotBorder.updatePoints(t)),this.spotConfig.showText&&this.sizeText&&this.updateSizeText(),this.nameText&&this.updateNameText()}updateSizeText(){if(!this.sizeText)return;const t=this.calculateSpotSizeText();this.sizeText.updateText(t),this.updateSizeTextPosition()}updateSizeTextPosition(){if(!this.sizeText)return;const t=this.calculateSizeTextPosition();this.sizeText.position.set(t.x,t.y)}updateNameText(){this.nameText&&(this.nameText.updateText(this.calculateSpotNameText()),this.updateNameTextPosition())}updateNameTextPosition(){if(!this.nameText)return;const t=this.calculateNameTextPosition();this.nameText.position.set(t.x,t.y)}updateEditState(){const t=this.isEditingEnabled(),i=t?this.spotConfig.editing:this.spotConfig.normal;if(this.sizeText&&(this.sizeText.visible=t&&this.spotConfig.showText),this.nameText&&(this.nameText.visible=this.shouldShowNameText()),this.centerIcon){this.centerIcon.visible=this.shouldShowIcon();const s=this.spotConfig.iconAnchor;s&&this.centerIcon.anchor.set(s.x,s.y)}this.sizeText&&(this.sizeText.visible=this.spotConfig.showText),this.controlFill&&(this.controlFill.setInteractionEnabled(t),this.controlFill.visible=i.showFill??i.showFrame),this.spotBorder&&(this.spotBorder.updateStyle({isDashed:i.isDashed,dashArray:i.dashArray}),this.spotBorder.visible=i.showFrame)}updateSpotData(t){this.spotData={...t},!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 t,i,s,r,o,a;this.appService.emitter.off("antiScale",this.throttledUpdateScale),this.throttledUpdateScale.cancel(),this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),(t=this.clickHandler)==null||t.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(t,i,s){return new ca({appService:t,spotData:i,config:s==null?void 0:s.config,iconAlias:s==null?void 0:s.iconAlias,editingIdsKey:s==null?void 0:s.editingIdsKey,events:(s==null?void 0:s.events)??{onUpdate:r=>{var o,a;(a=(o=t.events)==null?void 0:o.onUpdateSpot)==null||a.call(o,r)},onClick:r=>{var o,a;(a=(o=t.events)==null?void 0:o.onClickSpot)==null||a.call(o,r)}}})}}const Gr=3,W0={fontSize:12,fontFamily:"system-ui, -apple-system, sans-serif",fontWeight:"400",color:"#333333",position:"bottom",offset:4,editing:{visible:!0,color:"#ff4d4f",fontWeight:"600"},normal:{visible:!0,color:"#333333",fontWeight:"400"}},nn={normal:{radius:6,color:"#00B578",strokeColor:"#ffffff",strokeWidth:2,halo:!1},editing:{radius:6,color:"#ff4d4f",strokeColor:"#ffffff",strokeWidth:2,halo:{radius:10,color:"#ff4d4f",alpha:.2}}};class G0 extends ap{constructor(t){const{appService:i,wayPointData:s,order:r,events:o={}}=t;super(i);y(this,"wayPointData");y(this,"order");y(this,"wayPointConfig");y(this,"controlsConfig");y(this,"wayPointEvents");y(this,"icon");y(this,"dotNode");y(this,"orderContainer");y(this,"orderBackground");y(this,"orderText");y(this,"nameText");y(this,"clickHandler",null);y(this,"dotClickHandler",null);y(this,"didDrag",!1);y(this,"initialWayPointPoint",null);y(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.setupAntiRotation(),this.initializeComponents(),this.updateEditState(),this.setupClickHandler()}setupAntiRotation(){this.applyAntiRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation||(this.unsubscribeMapRotation=z(this.appService.runtime,"mapRotation",t=>{this.applyAntiRotation(t)}))}isEditingEnabled(){return(this.appService.runtimeSnapshot.editingWayPointIds||[]).includes(this.wayPointData.id)}isDragEnabled(){return this.wayPointData.canDrag!==void 0?this.wayPointData.canDrag:this.wayPointConfig.canDrag??!0}initializeComponents(){this.getShape()==="dot"?this.ensureDotNode():(this.ensureIcon(),this.wayPointConfig.showOrder&&this.ensureOrderContainer()),this.calculateWayPointNameText()&&(this.nameText=this.createNameText(),this.addChild(this.nameText))}ensureDotNode(){return this.dotNode||(this.dotNode=this.createDotNode(),this.addChild(this.dotNode),this.setupClickHandler()),this.dotNode}ensureIcon(){return this.icon||(this.icon=this.createIcon(),this.addChild(this.icon),this.setupClickHandler()),this.icon}ensureOrderContainer(){return this.orderContainer||(this.createOrderContainer(),this.addChild(this.orderContainer)),this.orderContainer}createDotNode(){const t=new W;return t.position.set(0,0),t.eventMode="static",this.setupIconDrag(t),t}createIcon(){const t=new Yt(this.appService);return this.loadIconTexture(t),t.position.set(0,0),t.anchor.set(.5,1),t.eventMode="static",this.setupIconDrag(t),t}async loadIconTexture(t){const i=this.isEditingEnabled(),s=i?this.wayPointConfig.editing:this.wayPointConfig.normal,{iconSize:r}=s,o=i?"wayPointActive":"wayPoint";await t.loadTextureAndSetSize(o,{width:r,height:r,sizeFixed:!1}),!(this.destroyed||t.destroyed||this.getShape()!=="pin")&&(t.visible=!0,this.orderContainer&&this.updateOrderPosition(),this.nameText&&this.updateNamePosition())}applyAntiRotation(t){const i=-t*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 O,this.orderBackground=new W,this.orderText=new xs({text:this.order.toString(),style:new ee({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)}getNameLabelConfig(){return this.wayPointConfig.nameLabel??W0}calculateWayPointNameText(){var t;return((t=this.wayPointData.name)==null?void 0:t.trim())??""}shouldShowNameText(){if(!this.calculateWayPointNameText())return!1;const i=this.isEditingEnabled(),s=this.getNameLabelConfig(),r=i?s.editing:s.normal;return(r==null?void 0:r.visible)!==!1}resolveNameLabelStyle(){var h,c;const t=this.getNameLabelConfig(),i=this.isEditingEnabled(),s=i?t.editing:t.normal,r=(s==null?void 0:s.fontSize)??t.fontSize,o=(s==null?void 0:s.fontWeight)??t.fontWeight,a=(s==null?void 0:s.fontFamily)??t.fontFamily,l=i?((h=t.editing)==null?void 0:h.color)??t.color??"#ff4444":((c=t.normal)==null?void 0:c.color)??t.color??"#333333";return{fontSize:r,fontFamily:a,fontWeight:o,fill:l}}createNameText(){var l,h,c;const{fontSize:t,fontFamily:i,fontWeight:s,fill:r}=this.resolveNameLabelStyle(),o=new xs({text:this.calculateWayPointNameText(),style:new ee({fontSize:t,fontFamily:i,fontWeight:s,fill:r,align:"center"})}),a=(h=(l=this.appService).getApp)==null?void 0:h.call(l);return(c=a==null?void 0:a.renderer)!=null&&c.resolution&&(o.resolution=a.renderer.resolution),o.eventMode="none",this.updateNamePosition(o),o.visible=this.shouldShowNameText(),o}updateNamePosition(t=this.nameText){if(!t)return;const i=this.getNameLabelConfig(),s=i.position??"bottom",r=i.offset??4,o=this.isEditingEnabled();if(this.getShape()==="dot"){const c=this.wayPointConfig.dot,d=o?c==null?void 0:c.editing:c==null?void 0:c.normal,u=o?nn.editing:nn.normal,p=(d==null?void 0:d.radius)??u.radius,f=(d==null?void 0:d.halo)!==void 0?d.halo:u.halo,m=f&&f.alpha!==0?f.radius??p+4:p,g=Math.max(p,m);switch(s){case"top":{t.anchor.set(.5,1),t.position.set(0,-g-r);break}case"left":{t.anchor.set(1,.5),t.position.set(-g-r,0);break}case"right":{t.anchor.set(0,.5),t.position.set(g+r,0);break}case"bottom":default:{t.anchor.set(.5,0),t.position.set(0,g+r);break}}return}const l=o?this.wayPointConfig.editing:this.wayPointConfig.normal,{iconSize:h}=l;switch(s){case"top":{t.anchor.set(.5,1);let c=h;if(this.wayPointConfig.showOrder&&l.orderContainer){const d=l.orderContainer.offsetY+l.orderContainer.size/2;c=Math.max(h,d)}t.position.set(0,-c-r);break}case"left":{t.anchor.set(1,.5),t.position.set(-h/2-r,-h/2);break}case"right":{t.anchor.set(0,.5),t.position.set(h/2+r,-h/2);break}case"bottom":default:{t.anchor.set(.5,0),t.position.set(0,r);break}}}setupIconDrag(t){let i=null,s=null,r=null,o=!1,a=!1;const l=c=>{if(!(!o||!i||!s||!r)&&this.parent){const d=this.parent.toLocal(c.global),u=d.x-i.x,p=d.y-i.y,f=Math.hypot(c.global.x-s.x,c.global.y-s.y);if(!a&&f<=Gr)return;a=!0,this.didDrag=!0;const m={x:r.x+u,y:r.y+p};this.wayPointData.point=m,this.position.set(m.x,m.y),this.orderContainer&&this.updateOrderPosition()}},h=()=>{var c,d;o&&(o=!1,i=null,s=null,r=null,a&&(a=!1,(d=(c=this.wayPointEvents).onUpdate)==null||d.call(c,this.wayPointData)))};t.on("pointerdown",c=>{if(this.didDrag=!1,!(!this.isEditingEnabled()||!this.isDragEnabled())&&(c.stopPropagation(),r={...this.wayPointData.point},s={x:c.global.x,y:c.global.y},this.parent&&(i=this.parent.toLocal(c.global)),o=!0,a=!1,this.parent)){const d=this.appService.gestureController.hijack(c);d.onMove(l),d.onEnd(h)}})}setupClickHandler(){const t=()=>{var i,s;this.didDrag||(this.appService.gestureController.suppressMapClick(),(s=(i=this.wayPointEvents).onClick)==null||s.call(i,this.wayPointData))};this.icon&&!this.clickHandler&&(this.clickHandler=new yt(this.icon,{stopPropagation:!1,clickThreshold:Gr,onClick:t})),this.dotNode&&!this.dotClickHandler&&(this.dotClickHandler=new yt(this.dotNode,{stopPropagation:!1,clickThreshold:Gr,onClick:t}))}updateWayPoint(t){this.wayPointData=t,this.nameText?(this.nameText.text=this.calculateWayPointNameText(),this.nameText.visible=this.shouldShowNameText(),this.updateNamePosition()):this.calculateWayPointNameText()&&(this.nameText=this.createNameText(),this.addChild(this.nameText),this.setupClickHandler()),this.drawWayPoint()}updateOrder(t){this.order=t,this.orderText&&(this.orderText.text=t.toString())}getWayPointData(){return{...this.wayPointData}}drawWayPoint(){this.position.set(this.wayPointData.point.x,this.wayPointData.point.y),this.orderContainer&&this.updateOrderPosition(),this.nameText&&this.updateNamePosition()}getShape(){return this.wayPointConfig.shape??"pin"}updateDotNode(){if(!this.dotNode)return;const t=this.isEditingEnabled(),i=this.wayPointConfig.dot,s=t?i==null?void 0:i.editing:i==null?void 0:i.normal,r=t?nn.editing:nn.normal,o=(s==null?void 0:s.radius)??r.radius,a=(s==null?void 0:s.color)??r.color,l=(s==null?void 0:s.strokeColor)??r.strokeColor,h=(s==null?void 0:s.strokeWidth)??r.strokeWidth,c=(s==null?void 0:s.halo)!==void 0?s.halo:r.halo;if(this.dotNode.clear(),c&&c.alpha!==0){const p=c.radius??o+4,f=c.color??a,m=c.alpha??.2;this.dotNode.circle(0,0,p),this.dotNode.fill({color:f,alpha:m})}this.dotNode.circle(0,0,o),this.dotNode.fill({color:a}),h>0&&this.dotNode.stroke({color:l,width:h});const d=c&&c.alpha!==0?c.radius??o+4:o,u=Math.max(o+8,d,16);this.dotNode.hitArea=new As(0,0,u),this.dotNode.cursor="pointer",this.dotNode.visible=!0}updateEditState(){var s,r;(r=(s=this.appService)==null?void 0:s.controlsConfig)!=null&&r.wayPoint&&(this.wayPointConfig=this.appService.controlsConfig.wayPoint);const t=this.isEditingEnabled();if(this.getShape()==="dot")this.icon&&(this.icon.visible=!1),this.orderContainer&&(this.orderContainer.visible=!1),this.ensureDotNode(),this.updateDotNode();else{this.dotNode&&(this.dotNode.visible=!1);const o=this.ensureIcon();if(o.visible=!0,this.loadIconTexture(o),this.wayPointConfig.showOrder&&this.ensureOrderContainer(),this.orderContainer&&this.orderText&&this.orderBackground){const a=t?this.wayPointConfig.editing:this.wayPointConfig.normal;this.orderText.style=new ee({fontSize:a.orderText.fontSize,fontFamily:a.orderText.fontFamily,fontWeight:a.orderText.fontWeight,fill:a.orderText.color,align:"center",trim:!0});const{size:l,backgroundColor:h}=a.orderContainer;this.orderBackground.clear(),this.orderBackground.circle(0,0,l/2).fill(h),this.orderContainer.visible=this.wayPointConfig.showOrder,this.updateOrderPosition()}}if(this.nameText){const{fontSize:o,fontFamily:a,fontWeight:l,fill:h}=this.resolveNameLabelStyle();this.nameText.style=new ee({fontSize:o,fontFamily:a,fontWeight:l,fill:h,align:"center"}),this.nameText.visible=this.shouldShowNameText(),this.updateNamePosition()}}onEditStateChange(){this.updateEditState()}isLiftedForEditing(){return this.isEditingEnabled()}destroy(){this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null),this.dotClickHandler&&(this.dotClickHandler.destroy(),this.dotClickHandler=null),this.icon&&this.icon.removeAllListeners(),this.dotNode&&(this.dotNode.removeAllListeners(),this.dotNode.destroy()),this.nameText&&(this.nameText.destroy(),this.nameText=void 0),super.destroy()}}class ec extends W{constructor(t,i){super();y(this,"isDragging",!1);y(this,"dragStartPosition",null);y(this,"initialPosition");y(this,"gestureSession",null);y(this,"unsubscribeMapRotation",null);y(this,"handleDragPointerMove",t=>{var a,l;if(!this.isDragging||!this.dragStartPosition)return;const i=this.parent.toLocal(t.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),(l=(a=this.options).onDragMove)==null||l.call(a,o)});y(this,"handleDragPointerUp",()=>{var i,s;if(this.gestureSession=null,!this.isDragging)return;const t=this.appService;this.isDragging=!1,this.dragStartPosition=null,t.getApp().stopRender("endpoint-drag"),(s=(i=this.options).onDragEnd)==null||s.call(i)});this.appService=t,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.setupAntiRotation(),this.draw()}setupAntiRotation(){if(this.options.config.endPointShape!=="diamond")return;const{runtime:t}=this.appService;this.applyAntiRotation(t.mapRotation),this.unsubscribeMapRotation=z(t,"mapRotation",i=>{this.applyAntiRotation(i)})}applyAntiRotation(t){this.destroyed||(this.rotation=-t*Math.PI/180)}draw(){const t=this.appService,{config:i}=this.options,s=t.getApp().toFixedSize(i.endPointSize),r=t.getApp().toFixedSize(i.endPointStrokeWidth);this.clear();const o=s/2;i.endPointShape==="diamond"?this.poly([0,-o,o,0,0,o,-o,0]):this.circle(0,0,o),this.fill({color:i.endPointColor}),this.stroke({color:i.endPointStrokeColor,width:r}),this.setupHitArea()}setupHitArea(){const t=this.appService,{config:i}=this.options,s=Math.max(i.endPointSize/2+10,20),r=t.getApp().toFixedSize(s);this.hitArea=new As(0,0,r)}setupEvents(){this.on("pointerdown",this.handlePointerDown.bind(this))}handlePointerDown(t){t.stopPropagation(),this.startDragging(t)}startDragging(t){var s,r;const i=this.appService;this.isDragging=!0,this.dragStartPosition=this.parent.toLocal(t.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(t),this.gestureSession.onMove(this.handleDragPointerMove),this.gestureSession.onEnd(this.handleDragPointerUp)}updatePosition(t){this.position.set(t.x,t.y),this.initialPosition={...t}}getPosition(){return{x:this.x,y:this.y}}redraw(){this.draw()}destroy(){var t,i;this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null),(t=this.gestureSession)==null||t.cancel(),this.gestureSession=null,(i=this.unsubscribeMapRotation)==null||i.call(this),this.unsubscribeMapRotation=null,this.off("pointerdown",this.handlePointerDown),super.destroy()}}class U0 extends O{constructor(t){super();y(this,"endPoints");y(this,"dividerConfig");y(this,"dividerEvents");y(this,"roomId");y(this,"appService");y(this,"roomGeometry",null);y(this,"dashLine");y(this,"solidLine",null);y(this,"startEndPoint");y(this,"endEndPoint");y(this,"solidLinePoints",null);y(this,"initialDividerPoints",[]);y(this,"isDragging",!1);y(this,"dragStartPosition",null);y(this,"gestureSession",null);y(this,"throttledHandleScaleChange");y(this,"handleEndPointDragStart",()=>{this.initialDividerPoints=this.endPoints.map(t=>({...t})),this.clearSolidLine(),this.appService.getApp().requestRender("divider-endpoint-drag",!0)});y(this,"handleEndPointDragMove",(t,i)=>{this.initialDividerPoints.length!==0&&(this.endPoints[t]=i,this.updateDashLine(),this.updateSolidLine(),this.setupDashLineHitArea())});y(this,"handleEndPointDragEnd",()=>{this.initialDividerPoints=[],this.appService.getApp().stopRender("divider-endpoint-drag"),this.finalizeDragUpdate()});y(this,"handleDashLinePointerDown",t=>{t.stopPropagation(),this.startDragging(t)});y(this,"handleDragPointerMove",t=>{if(!this.isDragging||!this.dragStartPosition||this.initialDividerPoints.length===0)return;const i=this.parent.toLocal(t.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()});y(this,"handleDragPointerUp",()=>{this.gestureSession=null,this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null,this.initialDividerPoints=[],this.appService.getApp().stopRender("divider-drag"),this.finalizeDragUpdate())});y(this,"handleScaleChange",()=>{var t,i;(t=this.startEndPoint)==null||t.redraw(),(i=this.endEndPoint)==null||i.redraw(),this.updateSolidLine(),this.setupDashLineHitArea()});const{appService:i,endPoints:s,roomId:r,events:o={}}=t;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=Pt(this.handleScaleChange.bind(this),30,{leading:!0,trailing:!0}),this.initializeComponents(),this.calculateAndCreateSolidLine(),this.registerScaleListener()}validateDividerPoints(t){if(t.length>=2)return t.slice(0,2);const i=t[0]||{x:0,y:0},s={x:i.x+50,y:i.y};return[i,s]}createDefaultdividerPoints(){if(!this.roomGeometry)return M.warn("Room geometry not available, creating fallback divider"),[{x:0,y:0},{x:100,y:0}];const t=this.appService.getApp().mapState;if(!t)return M.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,l=r==="horizontal"?i.width+2*s:i.height+2*s;return Cb(o,a,l,r).map(c=>({x:c.x-t.origin.x,y:c.y-t.origin.y}))}initializeComponents(){this.createDashLine(),this.addChild(this.dashLine),this.createEndPoints(),this.addChild(this.startEndPoint),this.addChild(this.endEndPoint),this.setupDashLineInteraction()}createDashLine(){const t=this.endPoints;if(t.length<2)return;const{dashLineWidth:i,dashLineDashArray:s,lineColor:r}=this.dividerConfig;this.dashLine=new ci(this.appService,{start:t[0],end:t[1],style:{color:r.toString(),width:i,dashArray:s}})}createEndPoints(){const t=this.endPoints;this.startEndPoint=new ec(this.appService,{position:t[0],config:this.dividerConfig,onDragStart:this.handleEndPointDragStart,onDragMove:i=>this.handleEndPointDragMove(0,i),onDragEnd:this.handleEndPointDragEnd}),this.endEndPoint=new ec(this.appService,{position:t[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 t=this.endPoints;if(t.length<2)return;const{hitAreaThickness:i}=this.dividerConfig,s=this.appService.getApp().toFixedSize(i),r=fu(t[0],t[1],s);if(r.length===0)return;const o=new Ze(r);this.dashLine.hitArea=o}startDragging(t){this.isDragging=!0;const i=this.parent.toLocal(t.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(t),this.gestureSession.onMove(this.handleDragPointerMove),this.gestureSession.onEnd(this.handleDragPointerUp)}finalizeDragUpdate(){var s,r,o,a;this.calculateAndCreateSolidLine();const t=this.getDividerEndPoints();this.checkAndResetIfOutOfRoom()&&((r=(s=this.dividerEvents).onOutOfRoom)==null||r.call(s,t)),(a=(o=this.dividerEvents).onUpdate)==null||a.call(o,this.getDividerEndPoints())}updateAllComponents(){this.updateDashLine(),this.updateSolidLine(),this.updateEndPoints(),this.setupDashLineHitArea()}updateDashLine(){const t=this.endPoints;t.length<2||!this.dashLine||this.dashLine.updatePoints(t[0],t[1])}updateSolidLine(){if(!this.solidLine||!this.solidLinePoints)return;const{solidLineWidth:t,lineColor:i}=this.dividerConfig,s=this.appService.getApp().toFixedSize(t);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 t=this.endPoints;this.startEndPoint&&this.startEndPoint.updatePosition(t[0]),this.endEndPoint&&this.endEndPoint.updatePosition(t[1])}registerScaleListener(){const{emitter:t}=this.appService;t.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 t=this.appService.mapManager.roomFill;return!t||typeof this.roomId!="number"?null:t.getRoomGraphicsMap().get(this.roomId)||null}calculateLineRoomIntersection(){const t=this.endPoints;if(t.length<2||typeof this.roomId!="number")return null;const[i,s]=t,r=this.isPointInRoomFill(i),o=this.isPointInRoomFill(s);if(r||o)return null;const a=rb(i,s),l=[];for(const p of a)this.isPointInRoomFill(p)&&l.push(p);if(l.length===0)return null;const h=l[0],c=l[l.length-1];return q(h,c)<3?null:Mb(h,c,.5)}isPointInRoomFill(t){if(typeof this.roomId!="number")return!1;const i=this.appService.getApp().mapState;if(!i)return!1;const s={x:t.x+i.origin.x,y:t.y+i.origin.y};return i.mapType==="raster"?this.isPointInRasterRoomFill(s):this.isPointInStructuredRoomFill(s)}isPointInRasterRoomFill(t){t.x-=.5,t.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(t.x),l=Math.round(t.y);if(a<0||l<0||a>=o)return!1;const h=l*o+a;for(let c=0;c<r.pixelIndices.length;c++)if(r.pixelIndices[c]===h)return!0;return!1}isPointInStructuredRoomFill(t){const i={x:Math.round(t.x),y:Math.round(t.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:t}=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!wb(r,o,t.x,t.y,t.width,t.height)}isDividerUnableToSplitRoom(){return!this.roomGeometry||typeof this.roomId!="number"||!this.getRoomGraphics()||!this.appService.getApp().mapState||this.endPoints.length<2?!1:this.solidLinePoints===null}checkAndResetIfOutOfRoom(){const t=this.appService.dividerConfig.outOfRoomCriterion==="solidLine"?this.isDividerUnableToSplitRoom():this.isDividerCompletelyOutOfRoom();return t&&this.appService.dividerConfig.resetDividerWhenOutOfRoom&&this.resetToDefaultState(),t}resetToDefaultState(){this.endPoints=this.createDefaultdividerPoints(),this.calculateAndCreateSolidLine(),this.updateComponents()}updateComponents(){const t=this.endPoints;t.length>=2&&(this.dashLine.updatePoints(t[0],t[1]),this.startEndPoint.position.set(t[0].x,t[0].y),this.endEndPoint.position.set(t[1].x,t[1].y),this.setupDashLineInteraction())}createSolidLine(){if(!this.solidLinePoints)return;const{solidLineWidth:t,lineColor:i}=this.dividerConfig;this.solidLine=new W,this.solidLine.eventMode="none";const s=this.appService.getApp().toFixedSize(t);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(t){this.endPoints=this.validateDividerPoints(t),this.updateAllComponents(),this.calculateAndCreateSolidLine()}destroy(){var t,i,s,r;this.appService.emitter.off("antiScale",this.throttledHandleScaleChange),this.throttledHandleScaleChange.cancel(),this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null,this.initialDividerPoints=[]),(t=this.gestureSession)==null||t.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 _o=["forbiddenSweepZone","forbiddenMopZone","cleanZone","virtualWall","spot","wayPoint","divider"],H0=["ramp","threshold"],N0=999;function ic(n,e,t,i){const s=i?e:n,r=i?n:e;!s||s.children.includes(t)||(r==null||r.removeChild(t),s.addChild(t))}function V0(n){if(!n||n.length===0)return[..._o];const e=new Set,t=[];for(const i of n)e.has(i)||(e.add(i),t.push(i));for(const i of _o)e.has(i)||t.push(i);return t}class $0{constructor(e){y(this,"zoneMaps",new Map);y(this,"virtualWallMap",new Map);y(this,"thresholdMap",new Map);y(this,"rampMap",new Map);y(this,"spotMap",new Map);y(this,"roomAnchorMap",new Map);y(this,"roomAnchorsData",[]);y(this,"wayPointMap",new Map);y(this,"divider",null);y(this,"controlContainers",new Map);y(this,"floorMarkContainers",new Map);y(this,"editingContainers",new Map);y(this,"unsubscribeFns",[]);y(this,"builtinZoneFactories",{forbiddenSweepZone:e=>aa.create(this.appService,e),forbiddenMopZone:e=>la.create(this.appService,e),cleanZone:e=>ha.create(this.appService,e)});this.appService=e,this.initializeControlContainers();const t=z(e.runtime,"editingForbiddenSweepZoneIds",v=>{M.log(`[runtime] editingForbiddenSweepZoneIds: ${v}`);const C=this.zoneMaps.get("forbiddenSweepZone");C&&this.updateZonesEditState("forbiddenSweepZone",C)}),i=z(e.runtime,"editingForbiddenMopZoneIds",v=>{M.log(`[runtime] editingForbiddenMopZoneIds: ${v}`);const C=this.zoneMaps.get("forbiddenMopZone");C&&this.updateZonesEditState("forbiddenMopZone",C)}),s=z(e.runtime,"editingCleanZoneIds",v=>{M.log(`[runtime] editingCleanZoneIds: ${v}`);const C=this.zoneMaps.get("cleanZone");C&&this.updateZonesEditState("cleanZone",C)}),r=z(e.runtime,"editingCustomZoneIds",v=>{M.log(`[runtime] editingCustomZoneIds: ${JSON.stringify(v??{})}`);for(const[C,P]of this.zoneMaps)Pe(C)||P.size&&this.updateZonesEditState(C,P)}),o=z(e.runtime,"editingVirtualWallIds",v=>{M.log(`[runtime] editingVirtualWallIds: ${v}`),this.updateVirtualWallsEditState(this.virtualWallMap)}),a=z(e.runtime,"editingThresholdIds",v=>{M.log(`[runtime] editingThresholdIds: ${v}`),this.updateThresholdsEditState(this.thresholdMap)}),l=z(e.runtime,"editingRampIds",v=>{M.log(`[runtime] editingRampIds: ${v}`),this.updateRampsEditState(this.rampMap)}),h=z(e.runtime,"editingSpotIds",v=>{M.log(`[runtime] editingSpotIds: ${v}`),this.updateSpotsEditState(this.spotMap,"spot")}),c=z(e.runtime,"editingRoomAnchorIds",v=>{M.log(`[runtime] editingRoomAnchorIds: ${v}`),this.updateSpotsEditState(this.roomAnchorMap,"roomAnchor")}),d=z(e.runtime,"editingWayPointIds",v=>{M.log(`[runtime] editingWayPointIds: ${v}`),this.updateWayPointsEditState(this.wayPointMap)}),u=z(e.runtime,"disabledForbiddenSweepZoneIds",v=>{M.log(`[runtime] disabledForbiddenSweepZoneIds: ${v}`);const C=this.zoneMaps.get("forbiddenSweepZone");C&&this.updateZonesEditState("forbiddenSweepZone",C)}),p=z(e.runtime,"disabledForbiddenMopZoneIds",v=>{M.log(`[runtime] disabledForbiddenMopZoneIds: ${v}`);const C=this.zoneMaps.get("forbiddenMopZone");C&&this.updateZonesEditState("forbiddenMopZone",C)}),f=z(e.runtime,"disabledCleanZoneIds",v=>{M.log(`[runtime] disabledCleanZoneIds: ${v}`);const C=this.zoneMaps.get("cleanZone");C&&this.updateZonesEditState("cleanZone",C)}),m=z(e.runtime,"disabledCustomZoneIds",v=>{M.log(`[runtime] disabledCustomZoneIds: ${JSON.stringify(v??{})}`);for(const[C,P]of this.zoneMaps)Pe(C)||P.size&&this.updateZonesEditState(C,P)}),g=z(e.runtime,"disabledVirtualWallIds",v=>{M.log(`[runtime] disabledVirtualWallIds: ${v}`),this.updateVirtualWallsEditState(this.virtualWallMap)}),x=z(e.runtime,"disabledThresholdIds",v=>{M.log(`[runtime] disabledThresholdIds: ${v}`),this.updateThresholdsEditState(this.thresholdMap)}),S=z(e.runtime,"disabledRampIds",v=>{M.log(`[runtime] disabledRampIds: ${v}`),this.updateRampsEditState(this.rampMap)}),b=z(e.runtime,"dividingRoomId",v=>{M.log(`[runtime] dividingRoomId: ${v}`),this.handleDividingRoomIdChange(v)}),w=z(e.runtime,"unit",v=>{M.log(`[runtime] unit changed: ${v}`),this.handleUnitChange()}),_=z(e.runtime,"unitLabel",v=>{M.log(`[runtime] unitLabel changed: ${v}`),this.handleUnitChange()});this.unsubscribeFns.push(t,i,u,p,f,m,g,x,S,s,r,o,a,l,h,c,d,b,w,_)}getDiagnosticObjects(e=201){let t=this.virtualWallMap.size+this.thresholdMap.size+this.rampMap.size+this.spotMap.size+this.roomAnchorMap.size+this.wayPointMap.size;if(this.zoneMaps.forEach(s=>{t+=s.size}),t>e)throw new Error("BUDGET_EXCEEDED: entities");const i=[];return this.zoneMaps.forEach((s,r)=>s.forEach((o,a)=>i.push({type:r,id:a,container:o,read:()=>o.getZoneData()}))),this.virtualWallMap.forEach((s,r)=>i.push({type:"virtualWall",id:r,container:s,read:()=>s.getWallData(),part:o=>s.getDiagnosticPart(o)})),this.thresholdMap.forEach((s,r)=>i.push({type:"threshold",id:r,container:s,read:()=>s.getThresholdData()})),this.rampMap.forEach((s,r)=>i.push({type:"ramp",id:r,container:s,read:()=>s.getRampData()})),this.spotMap.forEach((s,r)=>i.push({type:"spot",id:r,container:s,read:()=>s.getSpotData()})),this.roomAnchorMap.forEach((s,r)=>i.push({type:"roomAnchor",id:r,container:s,read:()=>s.getSpotData()})),this.wayPointMap.forEach((s,r)=>i.push({type:"wayPoint",id:r,container:s,read:()=>s.getWayPointData()})),i}updateRenderOrder(){this.applyRenderOrder()}initializeControlContainers(){const e=this.appService.appContainer.getLayer(Te);if(!e){M.warn("[ControlsManager] LAYER_CONTROLS not found during init");return}for(const t of _o){const i=new O;i.label=`controls:${t}`,this.controlContainers.set(t,i),e.addChild(i)}this.applyRenderOrder()}applyRenderOrder(){const e=this.appService.appContainer.getLayer(Te);if(!e)return;V0(this.appService.getConfig().controls.renderOrder).forEach((i,s)=>{const r=this.controlContainers.get(i);r&&(r.zIndex=s)}),e.sortableChildren=!0,e.sortChildren()}addToControlLayer(e,t){let i=this.controlContainers.get(e);if(!i){const s=this.appService.appContainer.getLayer(Te);if(!s){M.warn("[ControlsManager] LAYER_CONTROLS not found");return}i=new O,i.label=`controls:${e}`,this.controlContainers.set(e,i),s.addChild(i),this.applyRenderOrder()}i.addChild(t)}addToFloorMarkLayer(e,t){let i=this.floorMarkContainers.get(e);if(!i){const s=this.appService.appContainer.getLayer(Pi);if(!s){M.warn("[ControlsManager] LAYER_FLOOR_MARK not found");return}i=new O,i.label=`floorMark:${e}`,i.zIndex=H0.indexOf(e),this.floorMarkContainers.set(e,i),s.addChild(i),s.sortableChildren=!0,s.sortChildren()}i.addChild(t)}syncControlEditingLayer(e,t){const i=t.isLiftedForEditing();ic(this.controlContainers.get(e),this.editingContainerFor("controls",Te,i),t,i)}syncFloorMarkEditingLayer(e,t){const i=t.isLiftedForEditing();ic(this.floorMarkContainers.get(e),this.editingContainerFor("floorMark",Pi,i),t,i)}editingContainerFor(e,t,i){const s=this.editingContainers.get(e);if(s||!i)return s;const r=this.appService.appContainer.getLayer(t);if(!r){M.warn(`[ControlsManager] ${t} not found`);return}const o=new O;return o.label=`${e}:editing`,o.zIndex=N0,r.addChild(o),r.sortableChildren=!0,r.sortChildren(),this.editingContainers.set(e,o),o}drawForbiddenSweepZones(e){this.drawZonesByType("forbiddenSweepZone",e)}getForbiddenSweepZones(){return this.getZonesDataByType("forbiddenSweepZone")}clearAllForbiddenSweepZones(){this.clearAllZonesByType("forbiddenSweepZone")}drawForbiddenMopZones(e){this.drawZonesByType("forbiddenMopZone",e)}getForbiddenMopZones(){return this.getZonesDataByType("forbiddenMopZone")}clearAllForbiddenMopZones(){this.clearAllZonesByType("forbiddenMopZone")}drawCleanZones(e){this.drawZonesByType("cleanZone",e)}getCleanZones(){return this.getZonesDataByType("cleanZone")}clearAllCleanZones(){this.clearAllZonesByType("cleanZone")}drawVirtualWalls(e){var r;const t=this.appService,i=this.virtualWallMap,s=new Set(e.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));e.forEach(o=>{const a=i.get(o.id);if(a)this.isWallDataEqual(a.getWallData(),o)||a.updateWallData(o);else{const l=new Mo({appService:t,wallData:o,events:{onRemove:h=>{var c,d;(d=(c=t.events)==null?void 0:c.onRemoveVirtualWall)==null||d.call(c,h)},onUpdate:h=>{var c,d;(d=(c=t.events)==null?void 0:c.onUpdateVirtualWall)==null||d.call(c,h)},onClick:h=>{var c,d;(d=(c=t.events)==null?void 0:c.onClickVirtualWall)==null||d.call(c,h)}}});i.set(o.id,l),this.addToControlLayer("virtualWall",l),this.syncControlEditingLayer("virtualWall",l)}})}getVirtualWalls(){return this.getWallsData(this.virtualWallMap)}clearAllVirtualWalls(){this.clearAllWalls(this.virtualWallMap)}drawThresholds(e){var o;const t=this.appService,i=this.thresholdMap,s=e.filter(a=>{var l;return Jo(a.points)?!0:(M.warn(`[Controls] threshold "${a.id}" ignored: points must be 4 corner coordinates (clockwise 左上→右上→右下→左下), got ${((l=a.points)==null?void 0:l.length)??0}`),!1)}),r=new Set(s.map(a=>a.id));for(const[a,l]of i)r.has(a)||((o=l.parent)==null||o.removeChild(l),l.destroy(),i.delete(a));s.forEach(a=>{const l=i.get(a.id);if(l)this.isThresholdDataEqual(l.getThresholdData(),a)||l.updateThresholdData(a);else{const h=new D0({appService:t,thresholdData:a,events:{onRemove:c=>{var d,u;(u=(d=t.events)==null?void 0:d.onRemoveThreshold)==null||u.call(d,c)},onUpdate:c=>{var d,u;(u=(d=t.events)==null?void 0:d.onUpdateThreshold)==null||u.call(d,c)},onClick:c=>{var d,u;(u=(d=t.events)==null?void 0:d.onClickThreshold)==null||u.call(d,c)}}});i.set(a.id,h),this.addToFloorMarkLayer("threshold",h),this.syncFloorMarkEditingLayer("threshold",h)}})}getThresholds(){return Array.from(this.thresholdMap.values()).map(e=>e.getThresholdData())}clearAllThresholds(){var e;for(const t of this.thresholdMap.values())(e=t.parent)==null||e.removeChild(t),t.destroy();this.thresholdMap.clear()}drawRamps(e){var o;const t=this.appService,i=this.rampMap,s=e.filter(a=>{var l;return au(a.points)?!0:(M.warn(`[Controls] ramp "${a.id}" ignored: points must be 4 corner coordinates (clockwise 左上→右上→右下→左下), got ${((l=a.points)==null?void 0:l.length)??0}`),!1)}),r=new Set(s.map(a=>a.id));for(const[a,l]of i)r.has(a)||((o=l.parent)==null||o.removeChild(l),l.destroy(),i.delete(a));s.forEach(a=>{const l=i.get(a.id);if(l)this.isRampDataEqual(l.getRampData(),a)||l.updateRampData(a);else{const h=new z0({appService:t,rampData:a,events:{onRemove:c=>{var d,u;(u=(d=t.events)==null?void 0:d.onRemoveRamp)==null||u.call(d,c)},onUpdate:c=>{var d,u;(u=(d=t.events)==null?void 0:d.onUpdateRamp)==null||u.call(d,c)},onClick:c=>{var d,u;(u=(d=t.events)==null?void 0:d.onClickRamp)==null||u.call(d,c)}}});i.set(a.id,h),this.addToFloorMarkLayer("ramp",h),this.syncFloorMarkEditingLayer("ramp",h)}})}getRamps(){return Array.from(this.rampMap.values()).map(e=>e.getRampData())}clearAllRamps(){var e;for(const t of this.rampMap.values())(e=t.parent)==null||e.removeChild(t),t.destroy();this.rampMap.clear()}drawSpots(e){this.drawSpotsInto(e,this.spotMap,{layer:"spot"})}getSpots(){return this.getSpotsData(this.spotMap)}clearAllSpots(){this.clearAllSpotsInternal(this.spotMap)}drawRoomAnchors(e){this.roomAnchorsData=e?[...e]:[],this.renderRoomAnchors()}getRoomAnchors(){return[...this.roomAnchorsData]}clearAllRoomAnchors(){this.roomAnchorsData=[],this.clearAllSpotsInternal(this.roomAnchorMap)}syncRoomAnchorData(e){this.roomAnchorsData.findIndex(i=>i.id===e.id)!==-1&&(this.roomAnchorsData=this.roomAnchorsData.map(i=>i.id===e.id?{...i,...e}:i))}refreshRoomAnchors(){this.clearAllSpotsInternal(this.roomAnchorMap),this.renderRoomAnchors()}renderRoomAnchors(){const e=this.appService.getConfig().controls.roomAnchor;if(!(e!=null&&e.show)){this.clearAllSpotsInternal(this.roomAnchorMap);return}this.drawSpotsInto(this.roomAnchorsData,this.roomAnchorMap,{layer:"roomAnchor",createOverrides:{config:e,iconAlias:"roomAnchorIcon",editingIdsKey:"editingRoomAnchorIds",events:{onUpdate:t=>{var s,r;const i={id:t.id,point:t.point,name:t.name,roomId:t.roomId};this.syncRoomAnchorData(i),(r=(s=this.appService.events)==null?void 0:s.onUpdateRoomAnchor)==null||r.call(s,i)},onClick:t=>{var i,s;(s=(i=this.appService.events)==null?void 0:i.onClickRoomAnchor)==null||s.call(i,{id:t.id,point:t.point,name:t.name,roomId:t.roomId})}}}})}getZoneMap(e){let t=this.zoneMaps.get(e);return t||(t=new Map,this.zoneMaps.set(e,t)),t}resolveZoneFactory(e){var s;const t=this.builtinZoneFactories[e];return t||((s=this.appService.getConfig().customZoneTypes)!=null&&s[e]?r=>new Un({deps:Gn(this.appService,{onRemove:o=>{var a,l;return(l=(a=this.appService.events)==null?void 0:a.onRemoveCustomZone)==null?void 0:l.call(a,e,o)},onUpdate:o=>{var a,l;return(l=(a=this.appService.events)==null?void 0:a.onUpdateCustomZone)==null?void 0:l.call(a,e,o)},onClick:o=>{var a,l;return(l=(a=this.appService.events)==null?void 0:a.onClickCustomZone)==null?void 0:l.call(a,e,o)}}),zoneData:r,zoneType:e}):null)}drawCustomZones(e,t){this.drawZonesByType(e,t)}getCustomZones(e){return this.getZonesDataByType(e)}clearCustomZones(e){this.clearAllZonesByType(e)}drawZonesByType(e,t){const i=this.resolveZoneFactory(e);if(!i){M.warn(`[ControlsManager] Unknown zone type: ${e}`);return}const s=this.getZoneMap(e);this.drawZonesImpl(t,s,i,e)}getZonesDataByType(e){const t=this.zoneMaps.get(e);return t?this.getZonesData(t):[]}clearAllZonesByType(e){const t=this.zoneMaps.get(e);t&&this.clearAllZones(t)}refreshZonesConfig(){for(const[e,t]of this.zoneMaps){if(t.size===0)continue;const i=this.resolveZoneFactory(e);if(!i)continue;const s=this.getZonesData(t);this.clearAllZones(t),this.drawZonesImpl(s,t,i,e)}}drawZonesImpl(e,t,i,s){if(!e||e.length===0){this.clearAllZones(t);return}const r=new Set(t.keys()),o=new Set(e.map(a=>a.id));for(const a of r)o.has(a)||this.removeZone(a,t);e.forEach(a=>{const l=t.get(a.id);l?this.isZoneDataEqual(l.getZoneData(),a)||l.updateZoneData(a):this.addNewZone(a,t,i,s)})}addNewZone(e,t,i,s){const r=i(e);t.set(e.id,r),this.addToControlLayer(s,r),r.setDisabled(this.getDisabledZoneIds(String(s)).includes(e.id)),r.setEditing(this.getEditingZoneIds(String(s)).includes(e.id)),this.syncControlEditingLayer(s,r)}removeZone(e,t){var s;const i=t.get(e);i&&((s=i.parent)==null||s.removeChild(i),i.destroy(),t.delete(e))}getZonesData(e){const t=[];return e.forEach(i=>{t.push(i.getZoneData())}),t}clearAllZones(e){e.forEach((t,i)=>{var r;const s=e.get(i);s&&((r=s.parent)==null||r.removeChild(s),s.destroy())}),e.clear()}getEditingZoneIds(e){var i;const t=this.appService.runtimeSnapshot;switch(e){case"forbiddenSweepZone":return t.editingForbiddenSweepZoneIds;case"forbiddenMopZone":return t.editingForbiddenMopZoneIds;case"cleanZone":return t.editingCleanZoneIds;default:return((i=t.editingCustomZoneIds)==null?void 0:i[e])??[]}}getDisabledZoneIds(e){var i;const t=this.appService.runtimeSnapshot;switch(e){case"forbiddenSweepZone":return t.disabledForbiddenSweepZoneIds;case"forbiddenMopZone":return t.disabledForbiddenMopZoneIds;case"cleanZone":return t.disabledCleanZoneIds;default:return((i=t.disabledCustomZoneIds)==null?void 0:i[e])??[]}}updateZonesEditState(e,t){const i=this.getEditingZoneIds(e),s=this.getDisabledZoneIds(e);t.forEach((r,o)=>{r.setDisabled(s.includes(o)),r.setEditing(i.includes(o)),this.syncControlEditingLayer(e,r)})}updateVirtualWallsEditState(e){e.forEach(t=>{t.updateEditingState(),this.syncControlEditingLayer("virtualWall",t)})}updateThresholdsEditState(e){e.forEach(t=>{t.updateEditingState(),this.syncFloorMarkEditingLayer("threshold",t)})}updateRampsEditState(e){e.forEach(t=>{t.updateEditingState(),this.syncFloorMarkEditingLayer("ramp",t)})}isZoneDataEqual(e,t){if(e.id!==t.id||e.points.length!==t.points.length)return!1;for(let i=0;i<e.points.length;i++){const s=e.points[i],r=t.points[i];if(Math.abs(s.x-r.x)>.1||Math.abs(s.y-r.y)>.1)return!1}return!0}getWallsData(e){return Array.from(e.values()).map(t=>t.getWallData())}clearAllWalls(e){for(const t of e.values())t.destroy();e.clear()}isWallDataEqual(e,t){if(e.id!==t.id||e.points.length!==t.points.length)return!1;for(let i=0;i<e.points.length;i++){const s=e.points[i],r=t.points[i];if(Math.abs(s.x-r.x)>.1||Math.abs(s.y-r.y)>.1)return!1}return!0}isThresholdDataEqual(e,t){if(e.id!==t.id||(e.type??"passable")!==(t.type??"passable")||e.points.length!==t.points.length)return!1;for(let i=0;i<e.points.length;i++){const s=e.points[i],r=t.points[i];if(Math.abs(s.x-r.x)>.1||Math.abs(s.y-r.y)>.1)return!1}return!0}isRampDataEqual(e,t){if(e.id!==t.id||e.points.length!==t.points.length)return!1;for(let i=0;i<e.points.length;i++){const s=e.points[i],r=t.points[i];if(Math.abs(s.x-r.x)>.1||Math.abs(s.y-r.y)>.1)return!1}return!0}drawSpotsInto(e,t,i){if(!e||e.length===0){this.clearAllSpotsInternal(t);return}const s=new Set(t.keys()),r=new Set(e.map(o=>o.id));for(const o of s)r.has(o)||this.removeSpot(o,t);e.forEach(o=>{const a=t.get(o.id);a?this.isSpotDataEqual(a.getSpotData(),o)||a.updateSpotData(o):this.addNewSpot(o,t,i)})}addNewSpot(e,t,i){const s=ca.create(this.appService,e,i.createOverrides);t.set(e.id,s),this.addToControlLayer(i.layer,s),this.syncControlEditingLayer(i.layer,s)}removeSpot(e,t){var s;const i=t.get(e);i&&((s=i.parent)==null||s.removeChild(i),i.destroy(),t.delete(e))}getSpotsData(e){const t=[];return e.forEach(i=>{t.push(i.getSpotData())}),t}clearAllSpotsInternal(e){e.forEach((t,i)=>{var r;const s=e.get(i);s&&((r=s.parent)==null||r.removeChild(s),s.destroy())}),e.clear()}updateSpotsEditState(e,t){e.forEach(i=>{i.updateEditState(),this.syncControlEditingLayer(t,i)})}refreshSpotsEditState(){this.updateSpotsEditState(this.spotMap,"spot")}isSpotDataEqual(e,t){if(e.id!==t.id)return!1;const i=e.point,s=t.point;return Math.abs(i.x-s.x)>.1||Math.abs(i.y-s.y)>.1||e.roomId!==t.roomId?!1:e.name===t.name}drawWayPoints(e){M.log("[ControlsManager] drawWayPoints",e);const t=Array.from(this.wayPointMap.keys()),i=e.map(r=>r.id);t.filter(r=>!i.includes(r)).forEach(r=>{this.removeWayPoint(r,this.wayPointMap)}),e.forEach((r,o)=>{const a=o+1,l=this.wayPointMap.get(r.id);l?(this.isWayPointDataEqual(l.getWayPointData(),r)||l.updateWayPoint(r),l.updateOrder(a)):this.addNewWayPoint(r,a,this.wayPointMap)})}clearAllWayPoints(){M.log("[ControlsManager] clearAllWayPoints"),this.clearAllWayPointsInternal(this.wayPointMap)}getWayPoints(){return this.getWayPointsData(this.wayPointMap)}refreshWayPointsConfig(){this.updateWayPointsEditState(this.wayPointMap)}addNewWayPoint(e,t,i){var o,a;const s=this.appService,r=new G0({appService:s,wayPointData:e,order:t,events:{onUpdate:(o=s.events)==null?void 0:o.onUpdateWayPoint,onClick:(a=s.events)==null?void 0:a.onClickWayPoint}});i.set(e.id,r),this.addToControlLayer("wayPoint",r),this.syncControlEditingLayer("wayPoint",r)}removeWayPoint(e,t){var s;const i=t.get(e);i&&((s=i.parent)==null||s.removeChild(i),i.destroy(),t.delete(e))}getWayPointsData(e){const t=[];return e.forEach(i=>{t.push(i.getWayPointData())}),t}clearAllWayPointsInternal(e){e.forEach((t,i)=>{var r;const s=e.get(i);s&&((r=s.parent)==null||r.removeChild(s),s.destroy())}),e.clear()}updateWayPointsEditState(e){e.forEach(t=>{t.onEditStateChange(),this.syncControlEditingLayer("wayPoint",t)})}isWayPointDataEqual(e,t){if(e.id!==t.id)return!1;const i=e.point,s=t.point;return Math.abs(i.x-s.x)>.1||Math.abs(i.y-s.y)>.1?!1:e.name===t.name&&e.canDrag===t.canDrag}handleDividingRoomIdChange(e){if(e==null||e===-1){this.clearDivider();return}if(!this.getRoomGeometry(e)){this.clearDivider();return}this.createDefaultDivider(e)}getRoomGeometry(e){return this.appService.mapManager.getRoomById(e)}createDefaultDivider(e){const t=this.appService;this.clearDivider(),this.divider=new U0({appService:this.appService,roomId:e,events:{onUpdate:i=>{var s,r;(r=(s=t.events)==null?void 0:s.onUpdateDivider)==null||r.call(s,i)},onOutOfRoom:i=>{var s,r;(r=(s=t.events)==null?void 0:s.onDividerOutOfRoom)==null||r.call(s,i)}}}),this.addToControlLayer("divider",this.divider)}clearDivider(){var e;this.divider&&((e=this.divider.parent)==null||e.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(){M.debug("[ControlsManager] Unit changed, refreshing all size texts");for(const e of this.zoneMaps.values())e.forEach(t=>{t.refreshDisplay()});this.virtualWallMap.forEach(e=>{e.refreshDisplay()}),this.thresholdMap.forEach(e=>{e.refreshDisplay()}),this.rampMap.forEach(e=>{e.refreshDisplay()}),this.spotMap.forEach(e=>{e.refreshDisplay()}),this.roomAnchorMap.forEach(e=>{e.refreshDisplay()})}destroy(){this.unsubscribeFns.forEach(e=>e()),this.unsubscribeFns=[];for(const e of this.zoneMaps.keys())this.clearAllZonesByType(e);this.clearAllVirtualWalls(),this.clearAllThresholds(),this.clearAllRamps(),this.clearAllSpots(),this.clearAllRoomAnchors(),this.clearDivider(),this.controlContainers.forEach(e=>{e.removeFromParent(),e.destroy({children:!0})}),this.controlContainers.clear(),this.floorMarkContainers.forEach(e=>{e.removeFromParent(),e.destroy({children:!0})}),this.floorMarkContainers.clear(),this.editingContainers.forEach(e=>{e.removeFromParent(),e.destroy({children:!0})}),this.editingContainers.clear()}}class X0 extends Yt{constructor(t,i){super(t);y(this,"objectData");y(this,"clickHandler",null);y(this,"unsubscribeMapRotation",null);this.appService=t,this.objectData=i}async initializeSprite(){const t=this.appService.detectedObjectConfig,i=this.objectData.width||t.width,s=this.objectData.height||t.height;this.refreshElasticConfig(),await this.loadTextureAndSetSize(this.objectData.src,{width:i,height:s}),this.anchor.set(t.anchor.x,t.anchor.y),this.position.set(this.objectData.x,this.objectData.y),this.visible=!0,this.applyAntiRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation=z(this.appService.runtime,"mapRotation",r=>{this.applyAntiRotation(r)}),t.interactive?this.setupClickHandler():this.eventMode="none"}refreshElasticConfig(){var t;if(!((t=this.appService.elasticScale)!=null&&t.isAvailable())){this.setElasticFactors(null);return}this.setElasticFactors(Uv(this.appService.detectedObjectConfig,this.appService.elasticScaleConfig.breakpoints))}applyAntiRotation(t){const i=-t*Math.PI/180;this.rotation=i}setupClickHandler(){this.clickHandler&&this.clickHandler.destroy(),this.clickHandler=new yt(this,{onClick:()=>this.handleClick(),stopPropagation:!1})}handleClick(){var t,i;(i=(t=this.appService.events)==null?void 0:t.onClickDetectedObject)==null||i.call(t,this.getObjectData())}getObjectData(){return{...this.objectData}}async updateObjectData(t){const i=this.objectData;this.objectData=t;const s=this.appService.detectedObjectConfig;if(this.refreshElasticConfig(),i.src!==t.src){const r=t.width||s.width,o=t.height||s.height;await this.loadTextureAndSetSize(t.src,{width:r,height:o})}if(i.width!==t.width||i.height!==t.height){const r=t.width||s.width,o=t.height||s.height;this.setFixedSize(r,o)}this.position.set(t.x,t.y),s.interactive?this.clickHandler||this.setupClickHandler():this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null)}isSameData(t){return this.objectData.id===t.id&&this.objectData.src===t.src&&this.objectData.x===t.x&&this.objectData.y===t.y&&this.objectData.width===t.width&&this.objectData.height===t.height}destroy(){this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null),super.destroy()}}class Y0{constructor(e){y(this,"detectedObjectMap",new Map);y(this,"unsubscribeShowDetectedObjects",null);this.appService=e,this.applyLayerVisibility(this.appService.runtime.showDetectedObjects),this.unsubscribeShowDetectedObjects=z(this.appService.runtime,"showDetectedObjects",t=>{this.applyLayerVisibility(t)})}getDiagnosticObjects(e=201){if(this.detectedObjectMap.size>e)throw new Error("BUDGET_EXCEEDED: entities");return Array.from(this.detectedObjectMap.entries(),([t,i])=>({type:"detectedObject",id:t,container:i,read:()=>i.getObjectData()}))}async drawDetectedObjects(e){if(!e||e.length===0){this.clearAllDetectedObjects();return}const t=new Set(e.map(s=>s.id)),i=Array.from(this.detectedObjectMap.keys());for(const s of i)t.has(s)||this.removeDetectedObject(s);for(const s of e){const r=this.detectedObjectMap.get(s.id);r?r.isSameData(s)||await r.updateObjectData(s):await this.addNewDetectedObject(s)}}refreshElasticConfig(){this.detectedObjectMap.forEach(e=>{e.refreshElasticConfig()})}applyLayerVisibility(e){const t=this.appService.appContainer.getLayer(pi);t&&(t.visible=e)}clearAllDetectedObjects(){const e=this.appService;this.detectedObjectMap.forEach(t=>{e.appContainer.removeFromLayer(pi,t),t.destroy()}),this.detectedObjectMap.clear()}async addNewDetectedObject(e){const t=this.appService,i=new X0(this.appService,e);await i.initializeSprite(),this.detectedObjectMap.set(e.id,i),t.appContainer.addToLayer(pi,i)}removeDetectedObject(e){const t=this.appService,i=this.detectedObjectMap.get(e);i&&(t.appContainer.removeFromLayer(pi,i),i.destroy(),this.detectedObjectMap.delete(e))}destroy(){this.unsubscribeShowDetectedObjects&&(this.unsubscribeShowDetectedObjects(),this.unsubscribeShowDetectedObjects=null),this.clearAllDetectedObjects()}}var Ke={},cp={},ye={};Object.defineProperty(ye,"__esModule",{value:!0});ye.loop=ye.conditional=ye.parse=void 0;var j0=function n(e,t){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(t))t.forEach(function(o){return n(e,o,i,s)});else if(typeof t=="function")t(e,i,s,n);else{var r=Object.keys(t)[0];Array.isArray(t[r])?(s[r]={},n(e,t[r],i,s[r])):s[r]=t[r](e,i,s,n)}return i};ye.parse=j0;var Z0=function(e,t){return function(i,s,r,o){t(i,s,r)&&o(i,e,s,r)}};ye.conditional=Z0;var q0=function(e,t){return function(i,s,r,o){for(var a=[],l=i.pos;t(i,s,r);){var h={};if(o(i,e,s,h),i.pos===l)break;l=i.pos,a.push(h)}return a}};ye.loop=q0;var gt={};Object.defineProperty(gt,"__esModule",{value:!0});gt.readBits=gt.readArray=gt.readUnsigned=gt.readString=gt.peekBytes=gt.readBytes=gt.peekByte=gt.readByte=gt.buildStream=void 0;var K0=function(e){return{data:e,pos:0}};gt.buildStream=K0;var dp=function(){return function(e){return e.data[e.pos++]}};gt.readByte=dp;var Q0=function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return function(t){return t.data[t.pos+e]}};gt.peekByte=Q0;var Hn=function(e){return function(t){return t.data.subarray(t.pos,t.pos+=e)}};gt.readBytes=Hn;var J0=function(e){return function(t){return t.data.subarray(t.pos,t.pos+e)}};gt.peekBytes=J0;var tC=function(e){return function(t){return Array.from(Hn(e)(t)).map(function(i){return String.fromCharCode(i)}).join("")}};gt.readString=tC;var eC=function(e){return function(t){var i=Hn(2)(t);return e?(i[1]<<8)+i[0]:(i[0]<<8)+i[1]}};gt.readUnsigned=eC;var iC=function(e,t){return function(i,s,r){for(var o=typeof t=="function"?t(i,s,r):t,a=Hn(e),l=new Array(o),h=0;h<o;h++)l[h]=a(i);return l}};gt.readArray=iC;var sC=function(e,t,i){for(var s=0,r=0;r<i;r++)s+=e[t+r]&&Math.pow(2,i-r-1);return s},nC=function(e){return function(t){for(var i=dp()(t),s=new Array(8),r=0;r<8;r++)s[7-r]=!!(i&1<<r);return Object.keys(e).reduce(function(o,a){var l=e[a];return l.length?o[a]=sC(s,l.index,l.length):o[a]=s[l.index],o},{})}};gt.readBits=nC;(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var e=ye,t=gt,i={blocks:function(u){for(var p=0,f=[],m=u.data.length,g=0,x=(0,t.readByte)()(u);x!==p&&x;x=(0,t.readByte)()(u)){if(u.pos+x>=m){var S=m-u.pos;f.push((0,t.readBytes)(S)(u)),g+=S;break}f.push((0,t.readBytes)(x)(u)),g+=x}for(var b=new Uint8Array(g),w=0,_=0;_<f.length;_++)b.set(f[_],w),w+=f[_].length;return b}},s=(0,e.conditional)({gce:[{codes:(0,t.readBytes)(2)},{byteSize:(0,t.readByte)()},{extras:(0,t.readBits)({future:{index:0,length:3},disposal:{index:3,length:3},userInput:{index:6},transparentColorGiven:{index:7}})},{delay:(0,t.readUnsigned)(!0)},{transparentColorIndex:(0,t.readByte)()},{terminator:(0,t.readByte)()}]},function(d){var u=(0,t.peekBytes)(2)(d);return u[0]===33&&u[1]===249}),r=(0,e.conditional)({image:[{code:(0,t.readByte)()},{descriptor:[{left:(0,t.readUnsigned)(!0)},{top:(0,t.readUnsigned)(!0)},{width:(0,t.readUnsigned)(!0)},{height:(0,t.readUnsigned)(!0)},{lct:(0,t.readBits)({exists:{index:0},interlaced:{index:1},sort:{index:2},future:{index:3,length:2},size:{index:5,length:3}})}]},(0,e.conditional)({lct:(0,t.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,t.readByte)()},i]}]},function(d){return(0,t.peekByte)()(d)===44}),o=(0,e.conditional)({text:[{codes:(0,t.readBytes)(2)},{blockSize:(0,t.readByte)()},{preData:function(u,p,f){return(0,t.readBytes)(f.text.blockSize)(u)}},i]},function(d){var u=(0,t.peekBytes)(2)(d);return u[0]===33&&u[1]===1}),a=(0,e.conditional)({application:[{codes:(0,t.readBytes)(2)},{blockSize:(0,t.readByte)()},{id:function(u,p,f){return(0,t.readString)(f.blockSize)(u)}},i]},function(d){var u=(0,t.peekBytes)(2)(d);return u[0]===33&&u[1]===255}),l=(0,e.conditional)({comment:[{codes:(0,t.readBytes)(2)},i]},function(d){var u=(0,t.peekBytes)(2)(d);return u[0]===33&&u[1]===254}),h=[{header:[{signature:(0,t.readString)(3)},{version:(0,t.readString)(3)}]},{lsd:[{width:(0,t.readUnsigned)(!0)},{height:(0,t.readUnsigned)(!0)},{gct:(0,t.readBits)({exists:{index:0},resolution:{index:1,length:3},sort:{index:4},size:{index:5,length:3}})},{backgroundColorIndex:(0,t.readByte)()},{pixelAspectRatio:(0,t.readByte)()}]},(0,e.conditional)({gct:(0,t.readArray)(3,function(d,u){return Math.pow(2,u.lsd.gct.size+1)})},function(d,u){return u.lsd.gct.exists}),{frames:(0,e.loop)([s,a,l,r,o],function(d){var u=(0,t.peekByte)()(d);return u===33||u===44})}],c=h;n.default=c})(cp);var Nn={};Object.defineProperty(Nn,"__esModule",{value:!0});Nn.deinterlace=void 0;var rC=function(e,t){for(var i=new Array(e.length),s=e.length/t,r=function(u,p){var f=e.slice(p*t,(p+1)*t);i.splice.apply(i,[u*t,t].concat(f))},o=[0,4,2,1],a=[8,8,4,2],l=0,h=0;h<4;h++)for(var c=o[h];c<s;c+=a[h])r(c,l),l++;return i};Nn.deinterlace=rC;var Vn={};Object.defineProperty(Vn,"__esModule",{value:!0});Vn.lzw=void 0;var oC=function(e,t,i){var s=4096,r=-1,o=i,a,l,h,c,d,u,p,v,f,m,_,g,C,P,R,A,x=new Array(i),S=new Array(s),b=new Array(s),w=new Array(s+1);for(g=e,l=1<<g,d=l+1,a=l+2,p=r,c=g+1,h=(1<<c)-1,f=0;f<l;f++)S[f]=0,b[f]=f;var _,v,C,P,A,R;for(_=v=C=P=A=R=0,m=0;m<o;){if(P===0){if(v<c){_+=t[R]<<v,v+=8,R++;continue}if(f=_&h,_>>=c,v-=c,f>a||f==d)break;if(f==l){c=g+1,h=(1<<c)-1,a=l+2,p=r;continue}if(p==r){w[P++]=b[f],p=f,C=f;continue}for(u=f,f==a&&(w[P++]=C,f=p);f>l;)w[P++]=b[f],f=S[f];C=b[f]&255,w[P++]=C,a<s&&(S[a]=p,b[a]=C,a++,!(a&h)&&a<s&&(c++,h+=a)),p=u}P--,x[A++]=w[P],m++}for(m=A;m<o;m++)x[m]=0;return x};Vn.lzw=oC;Object.defineProperty(Ke,"__esModule",{value:!0});var up=Ke.decompressFrames=Ke.decompressFrame=pp=Ke.parseGIF=void 0,aC=uC(cp),lC=ye,hC=gt,cC=Nn,dC=Vn;function uC(n){return n&&n.__esModule?n:{default:n}}var pC=function(e){var t=new Uint8Array(e);return(0,lC.parse)((0,hC.buildStream)(t),aC.default)},pp=Ke.parseGIF=pC,fC=function(e){for(var t=e.pixels.length,i=new Uint8ClampedArray(t*4),s=0;s<t;s++){var r=s*4,o=e.pixels[s],a=e.colorTable[o]||[0,0,0];i[r]=a[0],i[r+1]=a[1],i[r+2]=a[2],i[r+3]=o!==e.transparentIndex?255:0}return i},fp=function(e,t,i){if(!e.image){console.warn("gif frame does not have associated image.");return}var s=e.image,r=s.descriptor.width*s.descriptor.height,o=(0,dC.lzw)(s.data.minCodeSize,s.data.blocks,r);s.descriptor.lct.interlaced&&(o=(0,cC.deinterlace)(o,s.descriptor.width));var a={pixels:o,dims:{top:e.image.descriptor.top,left:e.image.descriptor.left,width:e.image.descriptor.width,height:e.image.descriptor.height}};return s.descriptor.lct&&s.descriptor.lct.exists?a.colorTable=s.lct:a.colorTable=t,e.gce&&(a.delay=(e.gce.delay||10)*10,a.disposalType=e.gce.extras.disposal,e.gce.extras.transparentColorGiven&&(a.transparentIndex=e.gce.transparentColorIndex)),i&&(a.patch=fC(a)),a};Ke.decompressFrame=fp;var gC=function(e,t){return e.frames.filter(function(i){return i.image}).map(function(i){return fp(i,e.gct,t)})};up=Ke.decompressFrames=gC;class $n{constructor(e){if(!e||!e.length)throw new Error("Invalid frames");const[{texture:{width:t,height:i}}]=e;this.width=t,this.height=i,this.frames=e,this.textures=this.frames.map(s=>s.texture),this.totalFrames=this.frames.length,this.duration=this.frames[this.totalFrames-1].end}destroy(){for(const e of this.textures)e.destroy(!0);for(const e of this.frames)e.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(e,t){if(!e||e.byteLength===0)throw new Error("Invalid buffer");const i=S=>{let b=null;for(const w of S.frames)b=w.gce??b,"image"in w&&!("gce"in w)&&(w.gce=b)},s=pp(e);i(s);const r=up(s,!0),o=[],a=s.lsd.width,l=s.lsd.height,h=Z.get().createCanvas(a,l),c=h.getContext("2d",{willReadFrequently:!0}),d=Z.get().createCanvas(),u=d.getContext("2d");let p=0,f=null;const{fps:m=30,...g}=t??{},x=1e3/m;for(let S=0;S<r.length;S++){const{disposalType:b=2,delay:w=x,patch:_,dims:{width:v,height:C,left:P,top:A}}=r[S];d.width=v,d.height=C,u.clearRect(0,0,v,C);const R=u.createImageData(v,C);R.data.set(_),u.putImageData(R,0,0),b===3&&(f=c.getImageData(0,0,a,l)),c.drawImage(d,P,A);const T=c.getImageData(0,0,a,l);b===2?c.clearRect(0,0,a,l):b===3&&c.putImageData(f,0,0);const E=Z.get().createCanvas(T.width,T.height);E.getContext("2d").putImageData(T,0,0),o.push({start:p,end:p+w,texture:new U({source:new Do({resource:E,...g})})}),p+=w}return h.width=h.height=0,d.width=d.height=0,new $n(o)}}const mC={extension:B.Asset,detection:{test:async()=>!0,add:async n=>[...n,"gif"],remove:async n=>n.filter(e=>e!=="gif")},loader:{name:"gifLoader",id:"gif",test:n=>It.extname(n)===".gif"||n.startsWith("data:image/gif"),load:async(n,e)=>{const i=await(await Z.get().fetch(n)).arrayBuffer();return $n.from(i,e==null?void 0:e.data)},unload:async n=>{n.destroy()}}},gp=class Po extends re{constructor(...e){const t=e[0]instanceof $n?{source:e[0]}:e[0],{source:i,fps:s,loop:r,animationSpeed:o,autoPlay:a,autoUpdate:l,onComplete:h,onFrameChange:c,onLoop:d,...u}=Object.assign({},Po.defaultOptions,t);super({texture:U.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:l,onComplete:h,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,ke.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(e){var o,a;if(!this._playing)return;const t=this.animationSpeed*e.deltaTime/mt.targetFPMS,i=this._currentTime+t,s=i%this.duration,r=this._source.frames.findIndex(l=>l.start<=s&&l.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(e){e!==this._autoUpdate&&(this._autoUpdate=e,!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(e){this._updateFrameIndex(e),this._currentTime=this._source.frames[e].start}get source(){return this._source}_updateFrameIndex(e){var t;if(e<0||e>=this.totalFrames)throw new Error(`Frame index out of range, expecting 0 to ${this.totalFrames}, got ${e}`);this._currentFrame!==e&&(this._currentFrame=e,this.dirty=!0,(t=this.onFrameChange)==null||t.call(this,e))}get totalFrames(){return this._source.totalFrames}destroy(e=!1){this.stop(),super.destroy(),e&&this._source.destroy();const t=null;this._source=t,this.onComplete=t,this.onFrameChange=t,this.onLoop=t}clone(){const e=new Po({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 e.dirty=!0,e}};gp.defaultOptions={fps:30,loop:!0,animationSpeed:1,autoPlay:!0,autoUpdate:!0,onComplete:null,onFrameChange:null,onLoop:null};let yC=gp;Q.add(mC);class da extends yC{constructor(t,i){super(i);y(this,"throttledUpdateScale");y(this,"fixedWidth",0);y(this,"fixedHeight",0);y(this,"isFixedSizeSet",!1);y(this,"sizeFixed",!0);y(this,"baselineScale",1);y(this,"basePositionX",0);y(this,"basePositionY",0);y(this,"pixelOffset",null);this.appService=t,this.anchor.set(.5),this.visible=!1,this.throttledUpdateScale=Pt(this.updateScale.bind(this),30,{leading:!0,trailing:!0}),this.registerScaleListener()}setFixedSize(t,i){this.fixedWidth=t,this.fixedHeight=i,this.isFixedSizeSet=!0,this.applySize()}setSizeFixed(t){this.sizeFixed=t,this.baselineScale=1,t&&this.isFixedSizeSet?this.applySize():!t&&this.isFixedSizeSet&&this.applySize()}setBasePosition(t,i){this.basePositionX=t,this.basePositionY=i,this.pixelOffset?this.applyPixelOffset():this.position.set(t,i)}setPixelOffset(t){this.pixelOffset=t,t?this.applyPixelOffset():this.position.set(this.basePositionX,this.basePositionY)}applyPixelOffset(){if(this.destroyed||!this.pixelOffset)return;if(!this.sizeFixed){this.position.set(this.basePositionX,this.basePositionY);return}const t=this.appService.currentScale,i=this.appService.appContainer.getMapRotationRadians(),s=Bn(this.pixelOffset,t,i);this.position.set(this.basePositionX+s.x,this.basePositionY+s.y)}set width(t){if(this.isFixedSizeSet){M.warn("EnhancedGifSprite: 使用 setFixedSize() 方法来设置宽度");return}this.setFixedSize(t,this.fixedHeight||t)}set height(t){if(this.isFixedSizeSet){M.warn("EnhancedGifSprite: 使用 setFixedSize() 方法来设置高度");return}this.setFixedSize(this.fixedWidth||t,t)}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 t=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=t/s,o=i/s;super.scale.set(r,o)}else super.scale.set(t/this.baselineScale,i/this.baselineScale)}updateScale(t){this.sizeFixed&&(this.isFixedSizeSet?this.applySize():t!==0&&super.scale.set(1/t),this.applyPixelOffset())}static async createFromSrc(t,i,s){try{const r=await Y.load(i),o=new da(t,{source:r});return s.sizeFixed!==void 0&&o.setSizeFixed(s.sizeFixed),o.setFixedSize(s.width,s.height),o}catch(r){throw M.error(`Failed to load GIF "${i}":`,r),r}}draw(t,i){const{x:s,y:r,rotation:o=0}=t;i&&!this.visible?this.visible=i():!i&&!this.visible&&(this.visible=!0),this.rotation=o,this.position.set(s,r)}destroy(t){this.appService.emitter.off("antiScale",this.throttledUpdateScale),this.throttledUpdateScale.cancel(),super.destroy(t)}}class li extends da{constructor(t,i,s){super(t,{source:i});y(this,"elementData");y(this,"clickHandler",null);y(this,"unsubscribeMapRotation",null);y(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 t=this.elementData.anchor||{x:.5,y:.5};this.anchor.set(t.x,t.y),this.setPixelOffset(this.elementData.pixelOffset??null),this.setBasePosition(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=z(this.appService.runtime,"mapRotation",i=>{this.applyRotation(i),this.applyPixelOffset()}),this.visible=!0,this.elementData.interactive?this.setupClickHandler():this.eventMode="none"}applyRotation(t){const i=-t*Math.PI/180;this.rotation=this.userRotation+i}setupClickHandler(){this.clickHandler&&this.clickHandler.destroy(),this.clickHandler=new yt(this,{onClick:()=>this.handleClick(),stopPropagation:!1})}handleClick(){var t,i;(i=(t=this.appService.events)==null?void 0:t.onClickCustomElement)==null||i.call(t,this.getElementData())}getElementData(){return{...this.elementData}}async updateElementData(t){const i=this.elementData;if(this.elementData=t,i.src!==t.src)throw new Error("GIF source change requires recreation of instance");i.sizeFixed!==t.sizeFixed&&t.sizeFixed!==void 0&&this.setSizeFixed(t.sizeFixed),(i.width!==t.width||i.height!==t.height)&&this.setFixedSize(t.width,t.height);const s=t.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.setPixelOffset(t.pixelOffset??null),this.setBasePosition(t.x,t.y),t.rotation!==void 0&&(this.userRotation=t.rotation,this.applyRotation(this.appService.runtime.mapRotation)),t.opacity!==void 0&&(this.alpha=t.opacity),t.interactive?this.clickHandler||this.setupClickHandler():(this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null),this.eventMode="none")}isSameData(t){const i=this.elementData.anchor||{x:.5,y:.5},s=t.anchor||{x:.5,y:.5},r=this.elementData.pixelOffset,o=t.pixelOffset;return this.elementData.id===t.id&&this.elementData.type===t.type&&this.elementData.src===t.src&&this.elementData.x===t.x&&this.elementData.y===t.y&&this.elementData.width===t.width&&this.elementData.height===t.height&&this.elementData.rotation===t.rotation&&this.elementData.opacity===t.opacity&&this.elementData.interactive===t.interactive&&this.elementData.sizeFixed===t.sizeFixed&&i.x===s.x&&i.y===s.y&&((r==null?void 0:r.x)??0)===((o==null?void 0:o.x)??0)&&((r==null?void 0:r.y)??0)===((o==null?void 0:o.y)??0)}destroy(){this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null),super.destroy()}}class Ur extends Yt{constructor(t,i){super(t);y(this,"elementData");y(this,"clickHandler",null);y(this,"unsubscribeMapRotation",null);y(this,"userRotation",0);this.appService=t,this.elementData=i}async initialize(){await this.loadTextureAndSetSize(this.elementData.src,{width:this.elementData.width,height:this.elementData.height,sizeFixed:this.elementData.sizeFixed});const t=this.elementData.anchor||{x:.5,y:.5};this.anchor.set(t.x,t.y),this.setPixelOffset(this.elementData.pixelOffset??null),this.setBasePosition(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=z(this.appService.runtime,"mapRotation",i=>{this.applyRotation(i),this.applyPixelOffset()}),this.visible=!0,this.elementData.interactive?this.setupClickHandler():this.eventMode="none"}applyRotation(t){const i=-t*Math.PI/180;this.rotation=this.userRotation+i}setupClickHandler(){this.clickHandler&&this.clickHandler.destroy(),this.clickHandler=new yt(this,{onClick:()=>this.handleClick(),stopPropagation:!1})}handleClick(){var t,i;(i=(t=this.appService.events)==null?void 0:t.onClickCustomElement)==null||i.call(t,this.getElementData())}getElementData(){return{...this.elementData}}async updateElementData(t){const i=this.elementData;this.elementData=t,i.src!==t.src?await this.loadTextureAndSetSize(t.src,{width:t.width,height:t.height,sizeFixed:t.sizeFixed}):(i.sizeFixed!==t.sizeFixed&&t.sizeFixed!==void 0&&this.setSizeFixed(t.sizeFixed),(i.width!==t.width||i.height!==t.height)&&this.setFixedSize(t.width,t.height));const s=t.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.setPixelOffset(t.pixelOffset??null),this.setBasePosition(t.x,t.y),t.rotation!==void 0&&(this.userRotation=t.rotation,this.applyRotation(this.appService.runtime.mapRotation)),t.opacity!==void 0&&(this.alpha=t.opacity),t.interactive?this.clickHandler||this.setupClickHandler():(this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null),this.eventMode="none")}isSameData(t){const i=this.elementData.anchor||{x:.5,y:.5},s=t.anchor||{x:.5,y:.5},r=this.elementData.pixelOffset,o=t.pixelOffset;return this.elementData.id===t.id&&this.elementData.type===t.type&&this.elementData.src===t.src&&this.elementData.x===t.x&&this.elementData.y===t.y&&this.elementData.width===t.width&&this.elementData.height===t.height&&this.elementData.rotation===t.rotation&&this.elementData.opacity===t.opacity&&this.elementData.interactive===t.interactive&&this.elementData.sizeFixed===t.sizeFixed&&i.x===s.x&&i.y===s.y&&((r==null?void 0:r.x)??0)===((o==null?void 0:o.x)??0)&&((r==null?void 0:r.y)??0)===((o==null?void 0:o.y)??0)}destroy(){this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null),super.destroy()}}class xC extends Ex{constructor(t,i){super(i);y(this,"throttledUpdateScale");y(this,"fixedWidth",0);y(this,"fixedHeight",0);y(this,"isFixedSizeSet",!1);y(this,"userCenterX",0);y(this,"userCenterY",0);y(this,"sizeFixed",!0);y(this,"pixelOffset",null);this.appService=t,this.anchor.set(0,0),this.throttledUpdateScale=Pt(this.updateScale.bind(this),30,{leading:!0,trailing:!0}),this.registerScaleListener()}setFixedSize(t,i){this.fixedWidth=t,this.fixedHeight=i,this.isFixedSizeSet=!0,this.applyFixedSize(),this.updatePositionFromCenter()}setCenterPosition(t,i){this.userCenterX=t,this.userCenterY=i,this.updatePositionFromCenter()}setPixelOffset(t){this.pixelOffset=t,this.isFixedSizeSet&&this.updatePositionFromCenter()}applyPixelOffset(){this.isFixedSizeSet&&this.updatePositionFromCenter()}setSizeFixed(t){this.sizeFixed=t,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);let o=this.userCenterX,a=this.userCenterY;if(this.sizeFixed&&this.pixelOffset){const l=this.appService.appContainer.getMapRotationRadians(),h=Bn(this.pixelOffset,i,l);o+=h.x,a+=h.y}this.position.set(o-s,a-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(t){this.isFixedSizeSet&&t!==0&&(this.applyFixedSize(),this.updatePositionFromCenter())}updateTransform(t){return super.updateTransform(t)}destroy(t){this.appService.emitter.off("antiScale",this.throttledUpdateScale),this.throttledUpdateScale.cancel(),super.destroy(t)}}class ds extends xC{constructor(t,i){const s=document.createElement("div");ds.setupDefaultStyles(s,i),s.innerHTML=i.htmlContent;super(t,{element:s});y(this,"elementData");y(this,"domClickHandler",null);y(this,"resizeObserver",null);y(this,"debugMarker",null);y(this,"unsubscribeMapRotation",null);y(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.setPixelOffset(this.elementData.pixelOffset??null),this.elementData.rotation!==void 0&&(this.userRotation=this.elementData.rotation),this.applyRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation=z(this.appService.runtime,"mapRotation",t=>{this.applyRotation(t),this.applyPixelOffset()}),this.elementData.interactive?this.setupClickHandler():this.eventMode="none"}applyRotation(t){const i=-t*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 t=()=>{this.element&&(this.element.isConnected?this.showElement():requestAnimationFrame(t))};requestAnimationFrame(t)}waitForElementDimensions(){this.element&&(typeof ResizeObserver<"u"?(this.resizeObserver=new ResizeObserver(t=>{var s;const i=t[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 t=()=>{if(!this.element)return;if(!this.element.isConnected){requestAnimationFrame(t);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(t)};requestAnimationFrame(t)}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.syncDomOverlay(),this.appService.getApp().renderOnceNextFrame()}setupClickHandler(){this.element&&(this.domClickHandler=t=>{t.preventDefault(),t.stopPropagation(),this.handleClick()},this.element.addEventListener("click",this.domClickHandler))}handleClick(){var t,i;(i=(t=this.appService.events)==null?void 0:t.onClickCustomElement)==null||i.call(t,this.getElementData())}getElementData(){return{...this.elementData}}async updateElementData(t){const i=this.elementData;this.elementData=t,i.htmlContent!==t.htmlContent&&this.element&&(this.element.innerHTML=t.htmlContent,(!t.width||!t.height)&&this.waitForElementDimensions()),(i.width!==t.width||i.height!==t.height)&&(t.width&&t.height?(this.setFixedSize(t.width,t.height),this.element&&(this.element.style.width=`${t.width}px`,this.element.style.height=`${t.height}px`)):this.setupAutoSize()),this.setPixelOffset(t.pixelOffset??null),t.width&&t.height?this.setCenterPosition(t.x,t.y):this.getIsFixedSizeSet()?this.setCenterPosition(t.x,t.y):this.position.set(t.x,t.y),i.sizeFixed!==t.sizeFixed&&t.sizeFixed!==void 0&&this.setSizeFixed(t.sizeFixed),this.userRotation=t.rotation??0,this.applyRotation(this.appService.runtime.mapRotation),this.alpha=t.opacity??1,t.interactive?this.domClickHandler||this.setupClickHandler():(this.eventMode="none",this.domClickHandler&&this.element&&(this.element.removeEventListener("click",this.domClickHandler),this.domClickHandler=null))}isSameData(t){const i=this.elementData.pixelOffset,s=t.pixelOffset;return this.elementData.id===t.id&&this.elementData.type===t.type&&this.elementData.htmlContent===t.htmlContent&&this.elementData.x===t.x&&this.elementData.y===t.y&&this.elementData.width===t.width&&this.elementData.height===t.height&&this.elementData.rotation===t.rotation&&this.elementData.opacity===t.opacity&&this.elementData.interactive===t.interactive&&this.elementData.sizeFixed===t.sizeFixed&&((i==null?void 0:i.x)??0)===((s==null?void 0:s.x)??0)&&((i==null?void 0:i.y)??0)===((s==null?void 0:s.y)??0)}static setupDefaultStyles(t,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(t.style,s),t.style.setProperty("-webkit-tap-highlight-color","transparent"),t.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 SC{constructor(e){y(this,"customElementsMap",new Map);y(this,"gifTicker",null);y(this,"gifElements",new Set);this.appService=e}getDiagnosticObjects(e=201){if(this.customElementsMap.size>e)throw new Error("BUDGET_EXCEEDED: entities");return Array.from(this.customElementsMap.entries(),([t,i])=>({type:"customElement",id:t,container:i,read:()=>i.getElementData()}))}async drawCustomElements(e){if(!e||e.length===0){this.clearAllCustomElements();return}const t=new Set(e.map(r=>r.id)),i=Array.from(this.customElementsMap.keys());for(const r of i)t.has(r)||this.removeCustomElement(r);const s=e.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 e=this.appService;this.customElementsMap.forEach(t=>{t instanceof li?e.appContainer.removeFromLayer(hs,t):e.appContainer.removeFromLayer(ls,t),t.destroy()}),this.customElementsMap.clear(),this.gifElements.clear(),this.stopGifTicker()}async addNewCustomElement(e){const t=this.appService;let i;switch(e.type){case"image":i=new Ur(this.appService,e);break;case"gif":{const s=await Y.load(e.src);i=new li(this.appService,s,e);break}case"html":i=new ds(this.appService,e);break;default:throw new Error(`Unsupported custom element type: ${e.type}`)}await i.initialize(),this.customElementsMap.set(e.id,i),i instanceof li?(t.appContainer.addToLayer(hs,i),this.gifElements.add(i)):t.appContainer.addToLayer(ls,i)}removeCustomElement(e){const t=this.appService,i=this.customElementsMap.get(e);i&&(i instanceof li?(this.gifElements.delete(i),t.appContainer.removeFromLayer(hs,i)):t.appContainer.removeFromLayer(ls,i),i.destroy(),this.customElementsMap.delete(e))}isSameData(e,t){return e.getElementData().type!==t.type?!1:t.type==="image"&&e instanceof Ur||t.type==="gif"&&e instanceof li||t.type==="html"&&e instanceof ds?e.isSameData(t):!1}async updateElementData(e,t){if(t.type==="image"&&e instanceof Ur)await e.updateElementData(t);else if(t.type==="gif"&&e instanceof li)await e.updateElementData(t);else if(t.type==="html"&&e instanceof ds)await e.updateElementData(t);else throw new Error("Element type mismatch during update")}updateGifTicker(){this.gifElements.size>0?this.startGifTicker():this.stopGifTicker()}startGifTicker(){var e;(e=this.gifTicker)!=null&&e.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 e;(e=this.gifTicker)!=null&&e.started&&(M.log("⏸️ [GifTicker] 停止 GIF 专用渲染"),this.gifTicker.stop())}renderGifContainer(){const e=this.appService;if(this.gifElements.size===0)return;const t=e.getApp();t.renderer.render(t.stage)}destroy(){this.stopGifTicker(),this.gifTicker&&(this.gifTicker.destroy(),this.gifTicker=null),this.clearAllCustomElements()}}class bC extends O{constructor(t,i){super();y(this,"roomId");y(this,"roomIndex");y(this,"appService");y(this,"nameText");y(this,"iconSprite",null);y(this,"iconWrapper",null);y(this,"iconBg",null);this.appService=t,this.roomId=i.id,this.roomIndex=i.index;const{nameLabel:s,type:r}=t.roomConfig,{showRoomType:o}=t.runtime,a=i.colorIndex??i.index,l=this.getRoomNameColor(a),h=new ee({fontSize:s.fontSize,fontFamily:s.fontFamily,fontWeight:s.fontWeight,fill:l,align:"center"}),c=i.name||"Unknown";this.nameText=new xs({text:c,style:h}),this.nameText.anchor.set(.5),o&&i.type!=null&&(r!=null&&r.assets)&&r.assets[i.type]&&this.createIcon(i.type,l),this.addChild(this.nameText),this.layout()}createIcon(t,i){const{type:s}=this.appService.roomConfig,r=s.iconSize||14;this.iconWrapper||(this.iconWrapper=new O,this.addChild(this.iconWrapper)),s.container.visible?(this.iconBg||(this.iconBg=new W,this.iconWrapper.addChild(this.iconBg)),this.drawIconBg(i)):this.iconBg&&(this.iconBg.destroy(),this.iconBg=null),this.iconSprite||(this.iconSprite=new Yt(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[t],{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(t){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(t)}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,l=-(o+i+r)/2;s==="left"?(this.iconWrapper.x=l+o/2,this.nameText.x=l+o+i+r/2):(this.nameText.x=l+r/2,this.iconWrapper.x=l+r+i+o/2),this.iconWrapper.y=0,this.nameText.y=0}updateName(t){this.nameText.text=t,this.layout()}refreshColor(t){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,t);this.nameText.style.fill=o,this.iconBg&&this.drawIconBg(o),this.iconSprite&&(this.iconSprite.tint=i.container.visible?"#ffffff":o)}getRoomNameColor(t,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[t%s.nameInactive.length]:s.name[t%s.name.length];const a=s.nameNormal||s.name;return a[t%a.length]}async updateRoomType(t){const{type:i}=this.appService.roomConfig;if(!this.appService.runtime.showRoomType||t==null||!(i!=null&&i.assets)||!i.assets[t])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(t,a),this.iconWrapper&&(this.iconWrapper.visible=!0)}this.layout()}updateRoomTypeVisibility(t){if(this.iconWrapper)this.iconWrapper.visible=t,this.layout();else if(t){const i=this.appService.getRoomData(this.roomId);i&&this.updateRoomType(i.type??null)}}destroy(t){this.iconBg&&(this.iconBg.destroy(),this.iconBg=null),this.iconSprite&&(this.iconSprite.destroy(),this.iconSprite=null),this.iconWrapper&&(this.iconWrapper.destroy(),this.iconWrapper=null),this.nameText.destroy({texture:!0,textureSource:!0}),super.destroy(t)}}class vC extends O{constructor(t,i){super();y(this,"background");y(this,"foldedIndicator");y(this,"propertyIcons",new Map);y(this,"orderContainer");y(this,"orderBackground");y(this,"orderText");y(this,"isFolded",!1);y(this,"roomId");y(this,"roomIndex");y(this,"isDestroyed",!1);this.appService=t;const s=this.appService.roomConfig;this.roomId=i.id,this.roomIndex=i.index,this.background=new W,this.foldedIndicator=new W,this.foldedIndicator.visible=!1;const{property:r}=s,o=i.colorIndex??i.index,a=this.getIconColor(o);this.initializePropertyIcons(r.displayOrders,a);const l=this.resolveOrderTextColor(o);this.orderContainer=new O,this.orderBackground=new W,this.orderText=new xs({text:"",style:new ee({fontSize:r.cleanOrder.fontSize,fontFamily:r.cleanOrder.fontFamily,fontWeight:r.cleanOrder.fontWeight,fill:l,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:h})=>{this.addChild(h)}),this.addChild(this.orderContainer),this.visible=this.appService.runtimeSnapshot.showRoomProperty}initializePropertyIcons(t,i){const s=["cleanMode","suction","cistern","cleanTimes"];t.forEach(r=>{const o=s.includes(r),a=new Yt(this.appService);a.tint=i,a.anchor.set(0,0),this.propertyIcons.set(r,{fieldName:r,sprite:a,isBuiltin:o})})}async updateProperty(t){this.isDestroyed||this.destroyed||(await this.updateIcons(t),!(this.isDestroyed||this.destroyed)&&this.updateBackground())}getFieldValue(t,i){if(["cleanMode","suction","cistern","cleanTimes"].includes(i))return t[i]??null;if(t.customData&&i in t.customData){const r=t.customData[i];return typeof r=="number"?r:null}return null}getAssetAlias(t,i){const s={cleanMode:r=>`cleanMode_${r}`,suction:r=>`fan_${r}`,cistern:r=>`water_${r}`,cleanTimes:r=>`cleanTimes${r}`};return t in s?s[t](i):`custom_${t}_${i}`}shouldShowField(t,i,s){const{showRoomProperty:r}=this.appService.runtimeSnapshot;return!(s===null||!r||i==="cleanTimes"&&s<=0)}getDisplayElements(t){const{displayOrders:i}=this.appService.roomConfig.property,{showRoomOrder:s}=this.appService.runtimeSnapshot,r=t.order||0,o=s&&r>0,a=[];return o&&a.push({element:this.orderContainer,show:!0,isOrder:!0,fieldName:"order"}),i.forEach(l=>{const h=this.propertyIcons.get(l);if(!h||!h.sprite)return;const c=this.getFieldValue(t,l);this.shouldShowField(t,l,c)&&c!==null&&a.push({element:h.sprite,show:!0,isOrder:!1,fieldName:l,value:c})}),{elementsToShow:a,orderValue:r}}async updateIcons(t){if(this.isDestroyed||this.destroyed||this.isFolded)return;const{iconWidth:i,iconHeight:s,container:r,cleanOrder:o,iconGap:a}=this.appService.roomConfig.property,{paddingHorizontal:l,paddingVertical:h}=r,{elementsToShow:c,orderValue:d}=this.getDisplayElements(t);this.orderContainer.visible=!1,this.propertyIcons.forEach(({sprite:f})=>{f.visible=!1});const u=[];if(c.forEach(f=>{if(f.isOrder){this.orderContainer.visible=!0,this.orderText.text=d.toString();const m=t.colorIndex??this.roomIndex;this.orderBackground.clear(),this.orderBackground.setFillStyle({color:this.resolveOrderBackgroundColor(m)}),this.orderBackground.circle(i/2,s/2,i/2).fill();const g=this.resolveOrderTextColor(m);this.orderText.style.fill=g,this.orderText.position.set(i/2,s/2)}else{const m=this.propertyIcons.get(f.fieldName);if(m&&m.sprite){m.sprite.visible=!0;const g=this.getAssetAlias(f.fieldName,f.value);u.push(m.sprite.loadTextureAndSetSize(g,{width:i,height:s,sizeFixed:!1}))}}}),await Promise.all(u),this.isDestroyed||this.destroyed)return;let p=l;c.forEach((f,m)=>{const{element:g,isOrder:x}=f;!g||!g.position||(g.position.set(p,h),p+=i,m<c.length-1&&(x?p+=o.gapRight:p+=a))})}updateBackground(){if(this.isDestroyed||this.destroyed)return;const t=this.appService.roomConfig,{container:i,foldable:s}=t.property,{borderRadius:r,tailHeight:o,tailWidth:a,backgroundColor:l}=i,h=this.calculateContentWidth(),c=this.calculateContentHeight(),d=Math.min(r,h/2,c/2),u=d*.8,p=Math.max(h-u*2,a*.5),f=Math.min(a,h/2,p);if(this.background.clear(),this.background.setFillStyle({color:l}),s){const m=(h-f)/2,g=c+o;this.background.moveTo(d,0),this.background.lineTo(h-d,0),this.background.arcTo(h,0,h,d,d),this.background.lineTo(h,c-d),this.background.arcTo(h,c,h-d,c,d),this.background.lineTo(m+f,c),this.background.lineTo(m+f/2,g),this.background.lineTo(m,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,h,c,d);this.background.fill()}calculateContentWidth(){const{iconWidth:t,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:l}=this.getDisplayElements(a);let h=o;return l.forEach((c,d)=>{const{isOrder:u}=c;h+=t,d<l.length-1&&(u?h+=s.gapRight:h+=r)}),h+=o,h}calculateContentHeight(){const t=this.appService.roomConfig,{iconHeight:i,container:s}=t.property;return s.paddingVertical+i+s.paddingVertical}getTotalHeight(){const{foldable:t,container:i}=this.appService.roomConfig.property,{tailHeight:s}=i;return this.isFolded?s:this.calculateContentHeight()+(t?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(t){const{foldable:i}=this.appService.roomConfig.property;if(!i){(this.isFolded||this.foldedIndicator.visible)&&await this.expand();return}this.isFolded=t,t?(this.background.visible=!1,this.orderContainer.visible=!1,this.propertyIcons.forEach(({sprite:s})=>{s.visible=!1}),this.foldedIndicator.visible=!0,this.updateFoldedIndicator()):await this.expand()}async expand(){this.isFolded=!1,this.background.visible=!0,this.foldedIndicator.visible=!1,this.foldedIndicator.position.set(0,0),this.updateBackground();const t=this.appService.getRoomData(this.roomId);t&&await this.updateIcons(t)}isFoldedState(){const{foldable:t}=this.appService.roomConfig.property;return t?this.isFolded:!1}updateFoldedIndicator(){if(!this.appService.runtimeSnapshot.showRoomPropertyFoldIndicator){this.foldedIndicator.clear(),this.foldedIndicator.visible=!1;return}const t=this.appService.roomConfig,{tailHeight:i,tailWidth:s,backgroundColor:r}=t.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(t){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[t%o.length]}return i.cleanOrder.color}resolveOrderBackgroundColor(t){const{property:i}=this.appService.roomConfig;return i.cleanOrder.backgroundColor==="auto"?this.getIconColor(t):i.cleanOrder.backgroundColor}getIconColor(t){const{colors:i}=this.appService.roomConfig,{propertyTheme:s,propertyThemeInactive:r,propertyThemeNormal:o}=i,{enableRoomSelection:a,selectRoomIds:l}=this.appService.runtime;if(a)return!l.includes(this.roomId)&&r?r[t%r.length]:s[t%s.length];const h=o||s;return h[t%h.length]}refreshColor(){const t=this.appService.getRoomData(this.roomId),i=(t==null?void 0:t.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:this.resolveOrderBackgroundColor(i)}),this.orderBackground.circle(o/2,a/2,o/2).fill();const l=this.resolveOrderTextColor(i);this.orderText.style.fill=l}}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.propertyIcons.forEach(({sprite:t})=>{t.destroy()}),this.propertyIcons.clear(),super.destroy({children:!0,context:!0}))}}class wC extends O{constructor(t,i){super();y(this,"background");y(this,"checkmarkIcon");y(this,"bubble");y(this,"roomIndex");y(this,"roomId");this.appService=t;const s=this.appService.roomConfig;this.roomId=i.id,this.roomIndex=i.index,this.background=new W,this.bubble=new W;const{colors:{selectionIndicatorIcon:r}}=s;this.checkmarkIcon=new Yt(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(t){const{roomSelectionMode:i,enableRoomSelection:s,selectRoomIds:r}=this.appService.runtimeSnapshot;if(!s||i!=="checkmark"){this.visible=!1;return}const o=r.includes(t.id);await this.showCheckmarkMode(o),this.updateBackground()}async showCheckmarkMode(t){const{selectionIndicator:i}=this.appService.roomConfig,{iconWidth:s,iconHeight:r}=i;if(t){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:t,colors:i}=this.appService.roomConfig,{containerWidth:s,containerHeight:r,strokeWidth:o,strokeColor:a,borderRadius:l,tailHeight:h,tailWidth:c}=t,d=this.appService.getRoomData(this.roomId),u=(d==null?void 0:d.colorIndex)??this.roomIndex,p=i.selectionIndicatorBackground[u%i.selectionIndicatorBackground.length],f=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,l).fill().setStrokeStyle({color:f,width:o,alignment:0}).stroke(),h>0&&c>0){const m=(s-c)/2;this.bubble.setFillStyle({color:f});const g=r+o;this.bubble.poly([m,g-1,m+c,g-1,m+c/2,g+h]).fill()}}getTotalHeight(){const{selectionIndicator:t}=this.appService.roomConfig,{containerHeight:i,tailHeight:s,strokeWidth:r}=t;return i+r+(s>0?s:0)}getTotalWidth(){const{selectionIndicator:t}=this.appService.roomConfig;return t.containerWidth}async refreshColor(){const t=this.appService.getRoomData(this.roomId);t&&await this.updateIndicator(t)}destroy(){var t;(t=this.checkmarkIcon)==null||t.destroy(),super.destroy({children:!0,context:!0})}}class CC extends O{constructor(t,i){super();y(this,"roomId");y(this,"roomName");y(this,"roomProperty",null);y(this,"roomSelectionIndicator",null);y(this,"clickHandler",null);y(this,"unsubscribeMapRotation",null);y(this,"updateScaleBound",null);y(this,"elasticUpdateBound",null);y(this,"elasticFactors",null);this.appService=t,this.enableRenderGroup(),this.roomId=i.id,this.updateScaleBound=s=>this.updateScale(s),this.appService.emitter.on("antiScale",this.updateScaleBound),this.elasticUpdateBound=()=>this.updateScale(this.appService.currentScale),this.appService.emitter.on("elasticScaleUpdate",this.elasticUpdateBound),this.refreshElasticConfig(),this.updateScale(this.appService.currentScale),i.centerPoint&&this.position.set(i.centerPoint.x,i.centerPoint.y),this.roomName=new bC(this.appService,i),this.roomName.visible=this.appService.runtimeSnapshot.showRoomName,this.applyAntiRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation=z(this.appService.runtime,"mapRotation",s=>{this.applyAntiRotation(s)}),this.clickHandler=new yt(this,{onClick:()=>{var s,r;(r=(s=this.appService.events)==null?void 0:s.onClickRoomProperties)==null||r.call(s,i)}})}async initialize(t){await this.createRoomProperty(t),await this.createRoomSelectionIndicator(t),this.updateLayout()}applyAntiRotation(t){const i=-t*Math.PI/180;this.rotation=i}refreshElasticConfig(){var t;if(!((t=this.appService.elasticScale)!=null&&t.isAvailable())){this.elasticFactors=null;return}this.elasticFactors=Gv(this.appService.roomConfig,this.appService.elasticScaleConfig.breakpoints)}updateScale(t){var s;if(!t)return;const i=((s=this.appService.elasticScale)==null?void 0:s.getFactor(this.elasticFactors))??1;this.scale.set(1/t*i)}shouldShowRoomProperty(){const{showRoomOrder:t,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 l=t&&(a.order||0)>0;let h=!1;if(i){const{displayOrders:c}=this.appService.roomConfig.property;h=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 l||h}shouldShowRoomSelectionIndicator(){const{enableRoomSelection:t,roomSelectionMode:i}=this.appService.runtimeSnapshot;return t&&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(t){this.roomProperty&&(this.removeChild(this.roomProperty),this.roomProperty.destroy()),this.roomProperty=new vC(this.appService,t),await this.roomProperty.updateProperty(t),this.addChild(this.roomProperty),this.addChild(this.roomName),await this.updateRoomPropertyVisibility(),this.updateLayout()}async createRoomSelectionIndicator(t){this.roomSelectionIndicator&&(this.removeChild(this.roomSelectionIndicator),this.roomSelectionIndicator.destroy()),this.roomSelectionIndicator=new wC(this.appService,t),await this.updateRoomSelectionIndicatorVisibility(),this.addChild(this.roomSelectionIndicator)}updateLayout(){var h,c,d,u,p,f;if(this.destroyed)return;const{property:{offsetY:t,offsetX:i},selectionIndicator:{offsetY:s,offsetX:r}}=this.appService.roomConfig,o=((h=this.roomProperty)==null?void 0:h.visible)||!1,a=((c=this.roomName)==null?void 0:c.visible)||!1,l=((d=this.roomSelectionIndicator)==null?void 0:d.visible)||!1;if(o&&this.roomProperty){const m=this.roomProperty.getTotalHeight(),g=this.roomProperty.getTotalWidth();if(this.roomProperty.isFoldedState()){const S=-g/2+i,b=-m/2-t;this.roomProperty.position.set(S,b)}else a&&((u=this.roomName)!=null&&u.position)?(this.roomProperty.position.set(-g/2+i,-t-m),this.roomName.position.set(0,0)):this.roomProperty.position.set(-g/2+i,-m/2-t)}if(l&&this.roomSelectionIndicator){const m=this.roomSelectionIndicator.getTotalHeight(),g=this.roomSelectionIndicator.getTotalWidth();a&&((p=this.roomName)!=null&&p.position)?(this.roomSelectionIndicator.position.set(-g/2+r,-s-m),this.roomName.position.set(0,0)):this.roomSelectionIndicator.position.set(-g/2+r,-m/2-s)}a&&!o&&!l&&((f=this.roomName)!=null&&f.position)&&this.roomName.position.set(0,0)}updateName(t){this.roomName.updateName(t)}async updateRoomType(t){await this.roomName.updateRoomType(t),this.updateLayout()}updateRoomNameVisibility(t){this.roomName.visible=t,this.updateLayout()}updateRoomTypeVisibility(t){this.roomName.updateRoomTypeVisibility(t),this.updateLayout()}updatePosition(t){this.position.set(t.x,t.y)}async refreshColor(){this.roomName&&this.roomName.refreshColor(),this.roomProperty&&this.roomProperty.refreshColor(),this.roomSelectionIndicator&&await this.roomSelectionIndicator.refreshColor()}destroy(){var t,i,s,r;(t=this.clickHandler)==null||t.destroy(),this.clickHandler=null,this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),this.updateScaleBound&&(this.appService.emitter.off("antiScale",this.updateScaleBound),this.updateScaleBound=null),this.elasticUpdateBound&&(this.appService.emitter.off("elasticScaleUpdate",this.elasticUpdateBound),this.elasticUpdateBound=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(),this.isRenderGroup&&(this.isRenderGroup=!1),super.destroy()}}class MC extends O{constructor(t){super({isRenderGroup:!0});y(this,"floorTypeMap",new Map);y(this,"floorTypeMasks",new Map);y(this,"floorTypeContexts",new Map);y(this,"floorTypeToRooms",new Map);this.appService=t,this.appService.appContainer.addToLayer(sa,this)}async createFloorTypes(t){if(!this.appService.runtimeSnapshot.showRoomFloorType)return;this.clearFloorTypes();const s=this.groupRoomsByFloorType(t),r=[];for(const[o,a]of s)r.push(this.createMergedFloorType(o,a));await Promise.all(r)}groupRoomsByFloorType(t){const i=new Map,s=this.appService;return t.forEach((r,o)=>{const a=s.getRoomData(o),l=(a==null?void 0:a.floorType)||0;l>=0&&(i.has(l)||i.set(l,[]),i.get(l).push({roomId:o,graphics:r}))}),i}async createMergedFloorType(t,i){const s=this.appService,{assets:r,opacity:o,scale:a}=s.roomConfig.floorType,l=t%r.length,h=`floorType${l}`;if(!r[l]){M.warn(`No texture asset configured for floorType: ${t}`);return}const c=await Y.load(h);if(!c){M.warn(`Floor material texture not found: ${h}`);return}const d=i.map(({graphics:g})=>g.getLocalBounds()),u=bb(d),p=new Sn({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:f,contexts:m}=this.createMergedMask(i.map(({graphics:g})=>g));p.mask=f,this.addChild(p),this.floorTypeMap.set(t,p),this.floorTypeMasks.set(t,f),this.floorTypeContexts.set(t,m),this.floorTypeToRooms.set(t,new Set(i.map(({roomId:g})=>g)))}createMergedMask(t){const i=new O,s=[];return t.forEach(r=>{const o=new W,a=r.context.clone();o.context=a,s.push(a),i.addChild(o)}),{maskContainer:i,contexts:s}}clearFloorTypes(){this.floorTypeMasks.forEach(t=>{try{t.destroy({children:!0})}catch(i){M.warn("Error destroying floor mask:",i)}}),this.floorTypeMasks.clear(),this.floorTypeContexts.forEach(t=>{try{t.forEach(i=>{try{i.destroy()}catch(s){M.warn("Error destroying cloned graphics context:",s)}})}catch(i){M.warn("Error destroying graphics contexts:",i)}}),this.floorTypeContexts.clear(),this.floorTypeMap.forEach(t=>{try{this.removeChild(t),t.destroy()}catch(i){M.warn("Error destroying floor material:",i)}}),this.floorTypeMap.clear(),this.floorTypeToRooms.clear()}destroy(){this.clearFloorTypes(),super.destroy()}}const Hr=(n,e)=>n&&e?{x:n.x-e.x,y:n.y-e.y}:null;class _C{constructor(e){y(this,"unsubscribeFns",[]);y(this,"roomInfoContainer",new O);y(this,"roomInfoMap",new Map);y(this,"roomDisplayMap",new Map);y(this,"roomFloorType");this.appService=e,this.roomFloorType=new MC(e),e.appContainer.addToLayer(Iu,this.roomInfoContainer);const t=z(e.runtime,"showRoomFloorType",u=>{M.log(`[runtime] showRoomFloorType: ${u}`),u?this.updateFloorTypes():this.roomFloorType.clearFloorTypes()}),i=z(e.runtime,"showRoomProperty",u=>{M.log(`[runtime] showRoomProperty: ${u}`),this.updateAllRoomPropertyVisibility()}),s=z(e.runtime,"showRoomPropertyFoldIndicator",u=>{M.log(`[runtime] showRoomPropertyFoldIndicator: ${u}`),this.updateAllRoomPropertyVisibility()}),r=z(e.runtime,"showRoomOrder",u=>{M.log(`[runtime] showRoomOrder: ${u}`),this.updateAllRoomPropertyVisibility()}),o=z(e.runtime,"roomPropertyFoldIds",u=>{M.log(`[runtime] roomPropertyFoldIds: ${u}`),this.updateAllRoomPropertyVisibility()}),a=z(e.runtime,"showRoomName",u=>{M.log(`[runtime] showRoomName: ${u}`),this.updateAllRoomNameVisibility(u)}),l=z(e.runtime,"showRoomType",u=>{M.log(`[runtime] showRoomType: ${u}`),this.updateAllRoomTypeVisibility(u)}),h=z(e.runtime,"enableRoomSelection",u=>{M.log(`[runtime] enableRoomSelection: ${u}`),this.updateAllRoomPropertyVisibility(),this.updateAllRoomSelectionIndicatorVisibility(),this.refreshAllRoomColors()}),c=z(e.runtime,"selectRoomIds",u=>{M.log(`[runtime] selectRoomIds: ${u}`),this.updateAllRoomPropertyVisibility(),this.updateAllRoomSelectionIndicatorVisibility(),this.refreshAllRoomColors()}),d=z(e.runtime,"roomSelectionMode",u=>{M.log(`[runtime] roomSelectionMode: ${u}`),this.updateAllRoomPropertyVisibility(),this.updateAllRoomSelectionIndicatorVisibility(),this.refreshAllRoomColors()});this.unsubscribeFns.push(t,i,s,r,o,a,l,h,c,d)}async drawRoomProperty(e){var s;const t=this.appService;this.roomDisplayMap.clear();const i=((s=t.getApp().mapState)==null?void 0:s.origin)??null;return e.forEach((r,o)=>{const a=t.mapManager.getRoomById(r.id),l=(a==null?void 0:a.centerPoint)||null,h={...r,centerPoint:l,relativeCenterPoint:Hr(l,i),index:o,colorIndex:a==null?void 0:a.colorIndex};this.roomDisplayMap.set(r.id,h)}),await this.updateRoomInfoDisplay(),await this.updateFloorTypes(),!0}async updateRoomInfoDisplay(){if(this.roomDisplayMap.size===0){this.appService.mapManager.getAllRooms().length===0&&this.clearRoomInfos();return}const e=Array.from(this.roomDisplayMap.values()).filter(t=>t.centerPoint!==null);this.clearRoomInfos(),await Promise.all(e.map(t=>this.createRoomInfo(t)))}async createRoomInfo(e){var s,r;const t=new CC(this.appService,e);this.roomInfoContainer.addChild(t),this.roomInfoMap.set(e.id,t);const i=(r=(s=this.appService.mapManager).getRoomLabelAnchor)==null?void 0:r.call(s,e.id);i&&e.centerPoint&&(i.x!==e.centerPoint.x||i.y!==e.centerPoint.y)&&t.updatePosition(i),await t.initialize(e)}updateRoomName(e,t){const i=this.roomInfoMap.get(e);i&&i.updateName(t)}async updateRoomType(e,t){const i=this.roomDisplayMap.get(e);i&&(i.type=t);const s=this.roomInfoMap.get(e);s&&await s.updateRoomType(t)}updateRoomPosition(e,t){var r;const i=this.roomDisplayMap.get(e);if(i){i.centerPoint=t;const o=((r=this.appService.getApp().mapState)==null?void 0:r.origin)??null;i.relativeCenterPoint=Hr(t,o)}const s=this.roomInfoMap.get(e);s&&s.updatePosition(t)}clearRoomInfos(){if(this.roomInfoMap.size===0)return;const e=Array.from(this.roomInfoMap.values());this.roomInfoContainer.removeChildren(),e.forEach(t=>{try{t.destroy()}catch(i){M.warn(`[RoomManager] Error destroying RoomInfo for room ${t.roomId}:`,i)}}),this.roomInfoMap.clear()}getRoomPropertyById(e){return this.roomDisplayMap.get(e)}async refresh(){var i;const e=this.appService;this.roomFloorType.clearFloorTypes();const t=((i=e.getApp().mapState)==null?void 0:i.origin)??null;this.roomDisplayMap.forEach((s,r)=>{const o=e.mapManager.getRoomById(r),a=(o==null?void 0:o.centerPoint)||null;if(s.centerPoint!==a){s.centerPoint=a,s.relativeCenterPoint=Hr(a,t);const h=this.roomInfoMap.get(r);h&&a&&h.updatePosition(a)}const l=o==null?void 0:o.colorIndex;if(s.colorIndex!==l&&l!==void 0){s.colorIndex=l;const h=this.roomInfoMap.get(r);h&&h.refreshColor()}}),await this.updateRoomInfoDisplay(),await this.updateFloorTypes()}async refreshRoomConfig(){this.roomInfoMap.size!==0&&(this.refreshAllRoomColors(),await this.updateAllRoomPropertyVisibility())}refreshElasticConfig(){this.roomInfoMap.forEach(e=>{e.refreshElasticConfig()})}async updateAllRoomPropertyVisibility(){this.roomInfoMap.size!==0&&await Promise.all(Array.from(this.roomInfoMap.values()).map(async e=>{try{await e.updateRoomPropertyVisibility()}catch(t){console.warn(`[RoomManager] Failed to update room property visibility for room ${e.roomId}`,t)}}))}updateAllRoomNameVisibility(e){this.roomInfoMap.size!==0&&this.roomInfoMap.forEach(t=>{t.updateRoomNameVisibility(e)})}updateAllRoomTypeVisibility(e){this.roomInfoMap.size!==0&&this.roomInfoMap.forEach(t=>{t.updateRoomTypeVisibility(e)})}updateAllRoomSelectionIndicatorVisibility(){this.roomInfoMap.size!==0&&this.roomInfoMap.forEach(e=>{e.updateRoomSelectionIndicatorVisibility()})}refreshAllRoomColors(){this.roomInfoMap.size!==0&&this.roomInfoMap.forEach(e=>{e.refreshColor()})}async updateFloorTypes(){const e=this.appService,t=e.mapManager.roomFill.getRoomGraphicsMap();t.size>0?(await this.roomFloorType.createFloorTypes(t),e.getApp().renderOnceNextFrame()):e.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(e=>e()),this.unsubscribeFns=[],this.clearRoomInfos(),this.roomInfoContainer.destroy(),this.roomFloorType.destroy()}}var oc,ac;(oc=navigator==null?void 0:navigator.userAgent)!=null&&oc.includes("tuya-ark-ide")||((ac=navigator==null?void 0:navigator.userAgent)==null||ac.includes("miniProgram"));const PC=()=>{var i,s;if(!tg.any)return!0;const n=navigator.userAgent.toLowerCase(),e=()=>{const r=navigator.deviceMemory;return r?r>=4:!0};let t=!1;if(/iphone|ipad|ipod/.test(n)){const r=(i=n.match(/os (\d+)_/))==null?void 0:i[1];t=(r?parseInt(r):0)>=12}else if(/android/.test(n)){const r=(s=n.match(/android (\d+)/))==null?void 0:s[1];t=(r?parseInt(r):0)>=10}return t&&e()};class AC extends O{constructor(t,i,s){super();y(this,"graphics");y(this,"sprite",null);y(this,"viewportBounds");y(this,"lastConfig",null);y(this,"onImageLoaded");this.label="background",this.viewportBounds=i,this.onImageLoaded=s,this.graphics=new W,this.graphics.label="backgroundGraphics",this.addChild(this.graphics),this.render(t)}async render(t){if(this.lastConfig=t,this.clear(),t.backgroundImage){await this.renderImage(t.backgroundImage,t.backgroundAlpha);return}if(t.backgroundGradient){this.renderGradient(t.backgroundGradient);return}if(t.backgroundColor!==void 0){this.renderSolidColor(t.backgroundColor,t.backgroundAlpha);return}M.warn("[Background] No background configuration provided")}clear(){this.graphics.clear(),this.sprite&&(this.removeChild(this.sprite),this.sprite.destroy(),this.sprite=null)}renderSolidColor(t,i){this.graphics.clear(),this.graphics.rect(0,0,this.viewportBounds.width,this.viewportBounds.height).fill({color:t,alpha:i}),M.debug("[Background] Rendered solid color background",{color:t,alpha:i})}renderGradient(t){const{width:i,height:s}=this.viewportBounds;if(this.graphics.clear(),t.type==="linear"){const r=t.x0??0,o=t.y0??0,a=t.x1??1,l=t.y1??1,h=new Xt({type:"linear",start:{x:r,y:o},end:{x:a,y:l},colorStops:t.colorStops});this.graphics.rect(0,0,i,s).fill(h),M.debug("[Background] Rendered linear gradient background",{x0:r,y0:o,x1:a,y1:l,colorStops:t.colorStops.length})}else if(t.type==="radial"){const r=t.cx??.5,o=t.cy??.5,a=t.r??.5,l=new Xt({type:"radial",center:{x:r,y:o},innerRadius:0,outerCenter:{x:r,y:o},outerRadius:a,colorStops:t.colorStops});this.graphics.rect(0,0,i,s).fill(l),M.debug("[Background] Rendered radial gradient background",{cx:r,cy:o,r:a,colorStops:t.colorStops.length})}}async renderImage(t,i){var s,r,o,a;try{const l=await Y.load(t.src);if(!l){M.error("[Background] Failed to load image:",t.src),(s=this.lastConfig)!=null&&s.backgroundColor&&this.renderSolidColor(this.lastConfig.backgroundColor,i);return}this.sprite=new re(l),this.sprite.label="backgroundSprite",this.sprite.alpha=i;const{width:h,height:c}=this.viewportBounds,d=t.fit||"cover",u=((r=t.position)==null?void 0:r.x)??.5,p=((o=t.position)==null?void 0:o.y)??.5,f=l.width,m=l.height,g=f/m,x=h/c;switch(d){case"fill":this.sprite.width=h,this.sprite.height=c,this.sprite.x=0,this.sprite.y=0;break;case"contain":g>x?(this.sprite.width=h,this.sprite.height=h/g):(this.sprite.height=c,this.sprite.width=c*g),this.sprite.x=(h-this.sprite.width)*u,this.sprite.y=(c-this.sprite.height)*p;break;case"cover":g>x?(this.sprite.height=c,this.sprite.width=c*g):(this.sprite.width=h,this.sprite.height=h/g),this.sprite.x=(h-this.sprite.width)*u,this.sprite.y=(c-this.sprite.height)*p;break;case"none":this.sprite.width=f,this.sprite.height=m,this.sprite.x=(h-f)*u,this.sprite.y=(c-m)*p;break}t.repeat&&M.warn("[Background] Repeat mode not yet implemented"),this.addChild(this.sprite),M.debug("[Background] Rendered image background",{src:t.src,fit:d,position:{x:u,y:p},spriteSize:{width:this.sprite.width,height:this.sprite.height}}),this.onImageLoaded&&this.onImageLoaded()}catch(l){M.error("[Background] Error loading background image:",l),(a=this.lastConfig)!=null&&a.backgroundColor&&this.renderSolidColor(this.lastConfig.backgroundColor,i)}}async update(t){await this.render(t)}async updateViewportBounds(t){this.viewportBounds=t,this.lastConfig&&await this.render(this.lastConfig)}destroy(){this.clear(),super.destroy()}}class TC extends O{constructor(t){super();y(this,"carpetData");y(this,"carpetConfig");y(this,"controlsConfig");y(this,"carpetEvents");y(this,"appService");y(this,"controlFill");y(this,"editableShape");y(this,"clickHandler",null);y(this,"maskContainer",null);y(this,"maskGraphics",null);y(this,"texture",null);y(this,"textureMap",new Map);y(this,"tilingSprite",null);y(this,"initialZonePoints",[]);y(this,"unsubscribeFns",[]);y(this,"resolvedMaxSizeCache",null);y(this,"handleDragStart",()=>{this.resolveVisualState()==="editing"&&(this.carpetData.points&&this.carpetData.points.length>0?this.initialZonePoints=this.carpetData.points.map(t=>({...t})):this.initialZonePoints=[],this.appService.getApp().requestRender("zone-drag",!0))});y(this,"handleDragMove",t=>{if(this.resolveVisualState()!=="editing"||this.initialZonePoints.length===0||this.carpetData.shape==="custom")return;const i=this.parent.toLocal(t.global),s=this.controlFill.getDragStartPosition();if(!s)return;const r=i.x-s.x,o=i.y-s.y;this.applyTranslation(r,o)});y(this,"handleDragEnd",()=>{var t,i;this.initialZonePoints=[],this.appService.getApp().stopRender("zone-drag"),(i=(t=this.carpetEvents).onUpdate)==null||i.call(t,this.getCarpetData())});y(this,"handleMoveStart",()=>{this.carpetData.points&&this.carpetData.points.length>0?this.initialZonePoints=this.carpetData.points.map(t=>({...t})):this.initialZonePoints=[],this.appService.getApp().requestRender("zone-move",!0)});y(this,"handleMove",t=>{var a,l;if(this.resolveVisualState()!=="editing"||this.initialZonePoints.length===0)return;const i=this.parent.toLocal(t.global),s=(l=(a=this.editableShape)==null?void 0:a.getMoveButton())==null?void 0:l.getDragStartPosition();if(!s)return;const r=i.x-s.x,o=i.y-s.y;this.applyTranslation(r,o)});y(this,"handleMoveEnd",()=>{var t,i;this.initialZonePoints=[],this.appService.getApp().stopRender("zone-move"),(i=(t=this.carpetEvents).onUpdate)==null||i.call(t,this.getCarpetData())});y(this,"handleRotationStart",()=>{this.appService.getApp().requestRender("zone-rotate",!0)});y(this,"handleRotationMove",t=>{t&&(this.carpetData.points=t,this.drawCarpet())});y(this,"handleRotationEnd",()=>{var t,i;this.appService.getApp().stopRender("zone-rotate"),(i=(t=this.carpetEvents).onUpdate)==null||i.call(t,this.getCarpetData())});y(this,"handleClickRotate",t=>{var i,s;t&&(this.carpetData.points=t,this.drawCarpet()),this.appService.getApp().renderOnce(),(s=(i=this.carpetEvents).onUpdate)==null||s.call(i,this.getCarpetData())});y(this,"handleScaleStart",()=>{this.appService.getApp().requestRender("zone-scale",!0)});y(this,"handleScaleMove",t=>{t&&(this.carpetData.points=t,this.drawCarpet())});y(this,"handleScaleMoveHorizontal",t=>{t&&(this.carpetData.points=t,this.drawCarpet())});y(this,"handleScaleMoveVertical",t=>{t&&(this.carpetData.points=t,this.drawCarpet())});y(this,"handleScaleEnd",()=>{var t,i;this.appService.getApp().stopRender("zone-scale"),(i=(t=this.carpetEvents).onUpdate)==null||i.call(t,this.getCarpetData())});y(this,"handleDelete",()=>{var t,i;(i=(t=this.carpetEvents).onRemove)==null||i.call(t,this.carpetData.id)});y(this,"handleClick",()=>{var t,i;this.resolveVisualState()!=="editing"&&((i=(t=this.carpetEvents)==null?void 0:t.onClick)==null||i.call(t,this.getCarpetData()))});y(this,"handlePointsUpdate",t=>{this.carpetData.points=t,this.drawCarpet()});const{appService:i,carpetData:s,events:r={},textureMap:o}=t;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 t=this.carpetConfig.maxSize;if(this.resolvedMaxSizeCache&&this.resolvedMaxSizeCache.key===t)return this.resolvedMaxSizeCache.value;const i=ne(this.carpetConfig.minSize,t,"carpet");return this.resolvedMaxSizeCache={key:t,value:i},i}validateCarpetShape(t){const i=this.getResolvedMaxSize();return this.appService.coords.validateShape(Fn(t),{minSize:et(this.carpetConfig.minSize),maxSize:i!=null?et(i):void 0})}processCarpetData(t){if(t.points&&t.points.length>=2)if(t.shape==="custom")this.carpetData={...t,points:t.points};else{const s=this.validateCarpetShape(t.points);this.carpetData={...t,points:s}}else this.carpetData={...t,points:[],shape:t.shape||"rectangle"}}getControlsConfig(){const{controls:t}=this.appService.getConfig();return t}isEditingEnabled(){return this.appService.runtimeSnapshot.editingCarpetIds.includes(this.carpetData.id)}isSelected(){return this.appService.runtimeSnapshot.selectedCarpetIds.includes(this.carpetData.id)}isDisabledEnabled(){return this.appService.runtimeSnapshot.disabledCarpetIds.includes(this.carpetData.id)}resolveVisualState(){return Ii(this.isEditingEnabled(),this.isDisabledEnabled())}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 t=new O;return this.maskGraphics=new W,this.updateMaskShape(),t.addChild(this.maskGraphics),t.mask=this.maskGraphics,t}createControlFill(){return new oa(this.appService,{points:this.carpetData.points||[],fillColor:this.carpetConfig.fillColor,enableInteraction:this.resolveVisualState()==="editing",onDragStart:this.handleDragStart,onDragMove:this.handleDragMove,onDragEnd:this.handleDragEnd})}createEditControlLayer(){const t=this.isEditingEnabled(),i=this.carpetData.shape==="custom",s=Se(this.carpetConfig),r=!!t&&!i&&s.showScaleButton&&this.carpetConfig.scaleMode==="ratioLocked",o={...Dr(this.carpetConfig,["outlineStrokeWidth","outlineDashed","outlineDashArray","outlineFillColor","outlineOffset","outlineStrokeColor"]),...Dr(this.carpetConfig,["textColor","textPosition","textOffset"]),...Dr(this.controlsConfig,["textFontSize","textFontFamily","textFontWeight"]),showRotateButton:!!t&&!i&&s.showRotateButton,showScaleButton:!!t&&!i&&s.showScaleButton,showDeleteButton:!!t&&s.showDeleteButton,showMoveButton:!!t&&!i&&s.showMoveButton,showRadialScaleButton:r,iconWrapperFillColor:this.carpetConfig.iconWrapperFillColor,deleteIconWrapperFillColor:this.carpetConfig.deleteIconWrapperFillColor,rotateMode:this.carpetConfig.rotateMode,scaleMode:this.carpetConfig.scaleMode,moveButtonOffset:this.controlsConfig.moveButtonOffset},a=i?this.calculateBoundingRectanglePoints():this.carpetData.points||[];this.editableShape=new Es({editControls:this.appService.editControlManager});const l=this.getResolvedMaxSize();this.editableShape.attach(this,{id:this.carpetData.id,topology:"quad",layerOptions:{config:o,zonePoints:a,minSize:this.carpetConfig.minSize,maxSize:l??void 0,contentLayer:yi,events:{onRemove:this.handleDelete,onRotateStart:this.handleRotationStart,onRotateMove:this.handleRotationMove,onClickRotate:this.handleClickRotate,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&&s.showRotateButton,showScaleButton:!i&&s.showScaleButton,showDeleteButton:s.showDeleteButton,showMoveButton:!i&&s.showMoveButton,showBorder:!0,showSizeText:!0,borderStyle:this.carpetConfig.editing,showRadialScaleButton:!i&&s.showScaleButton&&this.carpetConfig.scaleMode==="ratioLocked"},idleState:{showRotateButton:!1,showScaleButton:!1,showDeleteButton:!1,showMoveButton:!1,showBorder:!1,showSizeText:!1}})}setupClickHandler(){this.interactiveChildren=!0,this.clickHandler=new yt(this,{onClick:()=>{var t,i;this.resolveVisualState()!=="editing"&&((i=(t=this.carpetEvents)==null?void 0:t.onClick)==null||i.call(t,this.getCarpetData()))},stopPropagation:!1})}setupEnableRoomSelectionListener(){const t=z(this.appService.runtime,"enableRoomSelection",s=>{this.updateClickHandlerState(s)});this.unsubscribeFns.push(t);const i=this.appService.runtimeSnapshot.enableRoomSelection;this.updateClickHandlerState(i)}isRoomSelectionEnabled(){return this.appService.runtimeSnapshot.enableRoomSelection}updateClickHandlerState(t){if(t){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:t}=this.carpetData;let i=1/0,s=1/0,r=-1/0,o=-1/0;if(t&&t.length>0)for(const a of t)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:t}=this.carpetData;if(!t||t.length===0)return[];const{minX:i,minY:s,maxX:r,maxY:o}=bn(t);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:t,shape:i}=this.carpetData;if(!(!t||!Array.isArray(t)||t.length<2)){if(i==="round"){if(t.length<4)return;const r=oe(t),[o,a,,l]=t,h=q(o,a),c=q(o,l),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,h/2,c/2)}else{const r=t.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:t,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,t),this.appService.getApp().renderOnce())}catch(r){console.warn("Failed to load carpet texture:",r)}}createTilingSprite(t,i){if(!this.texture||!this.maskContainer)return;const s=this.calculateBounds();this.tilingSprite=new Sn({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(t),this.tilingSprite.alpha=i,this.maskContainer.addChild(this.tilingSprite)}updateTilingSprite(){if(!this.tilingSprite)return;const t=this.calculateBounds();this.tilingSprite.position.set(t.minX-50,t.minY-50),this.tilingSprite.width=t.maxX-t.minX+100,this.tilingSprite.height=t.maxY-t.minY+100}applyTranslation(t,i){this.carpetData.points=this.initialZonePoints.map(s=>({x:s.x+t,y:s.y+i})),this.drawCarpet()}drawCarpet(){const{points:t}=this.carpetData;if(!(!t||t.length<2)&&(this.updateMaskShape(),this.updateTilingSprite(),this.controlFill.updatePoints(t),this.editableShape)){const r=this.carpetData.shape==="custom"?this.calculateBoundingRectanglePoints():t;this.editableShape.updatePoints(r)}}updateEditState(){var a;const t=this.resolveVisualState(),i=t==="editing",s=t==="disabled",r=this.isSelected()&&!s,o=this.shouldShowEditControl()&&!s||!1;s&&this.controlFill.interruptDragging(),this.controlFill.setInteractionEnabled(i),this.controlFill.updateFillColor(s?((a=this.carpetConfig.disabled)==null?void 0:a.fillColor)??this.carpetConfig.fillColor:this.carpetConfig.fillColor),this.alpha=s?Di(this.carpetConfig.disabled,this.controlsConfig.disabledStyle):1,this.editableShape&&(r&&!i?this.editableShape.applyEditState({showRotateButton:!1,showScaleButton:!1,showDeleteButton:!1,showMoveButton:!1,showBorder:!0,showSizeText:!1,borderStyle:this.carpetConfig.normal}):this.editableShape.setEditing(i)),this.zIndex=o?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(t){const s=this.carpetData.type;if(t.points&&t.points.length>=2)if(t.shape==="custom")this.carpetData={...t,points:t.points};else{const r=this.validateCarpetShape(t.points);this.carpetData={...t,points:r}}else this.carpetData={...t,points:t.points||[]};s!==this.carpetData.type&&this.loadTexture(),this.drawCarpet(),this.updateEditState()}getCarpetData(){return{...this.carpetData}}refreshDisplay(){this.drawCarpet()}destroy(){var t,i,s,r,o;this.editableShape.detach(),this.unsubscribeFns.forEach(a=>a()),this.unsubscribeFns=[],(t=this.tilingSprite)==null||t.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 RC{constructor(e){y(this,"customCarpetMap",new Map);y(this,"unsubscribeFns",[]);y(this,"textureMap",new Map);y(this,"texturesLoaded",!1);y(this,"texturesLoadingPromise",null);this.appService=e,this.applyLayerVisibility(e.runtime.showCustomCarpets);const t=z(e.runtime,"editingCarpetIds",o=>{M.log(`[runtime] editingCarpetIds: ${o}`),this.updateCarpetsEditState()}),i=z(e.runtime,"selectedCarpetIds",o=>{M.log(`[runtime] selectedCarpetIds: ${o}`),this.updateCarpetsEditState()}),s=z(e.runtime,"disabledCarpetIds",o=>{M.log(`[runtime] disabledCarpetIds: ${o}`),this.updateCarpetsEditState()}),r=z(e.runtime,"showCustomCarpets",o=>{M.log(`[runtime] showCustomCarpets: ${o}`),this.applyLayerVisibility(o)});this.unsubscribeFns.push(t,i,s,r)}getDiagnosticObjects(e=201){if(this.customCarpetMap.size>e)throw new Error("BUDGET_EXCEEDED: entities");return Array.from(this.customCarpetMap.entries(),([t,i])=>({type:"customCarpet",id:t,container:i,read:()=>i.getCarpetData()}))}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 e=this.appService,{material:t,src:i}=e.carpetConfig;if(t)for(const s of t){const r=await Y.load(s.src);this.textureMap.set(s.type,r)}if(i){const s=await Y.load(i);this.textureMap.set(-1,s)}}async drawCustomCarpets(e){if(await this.loadTextures(),!e||e.length===0){this.clearAllCustomCarpets();return}const t=new Set(this.customCarpetMap.keys()),i=new Set(e.map(s=>s.id));for(const s of t)i.has(s)||this.removeCustomCarpet(s);e.forEach(s=>{const r=this.customCarpetMap.get(s.id.toString());r?this.isCarpetDataEqual(r.getCarpetData(),s)||r.updateCarpetData(s):this.addNewCustomCarpet(s)})}getCustomCarpets(){const e=[];return this.customCarpetMap.forEach(t=>{e.push(t.getCarpetData())}),e}getCustomCarpetById(e){return this.customCarpetMap.get(e)}clearAllCustomCarpets(){this.customCarpetMap.forEach((e,t)=>{var s;const i=this.customCarpetMap.get(t);i&&((s=i.parent)==null||s.removeChild(i),i.destroy())}),this.customCarpetMap.clear()}addNewCustomCarpet(e){const t=this.appService,i=new TC({appService:t,carpetData:e,textureMap:this.textureMap,events:{onRemove:s=>{var r,o;(o=(r=t.events)==null?void 0:r.onDeleteCustomCarpet)==null||o.call(r,{id:s})},onUpdate:s=>{var r,o;(o=(r=t.events)==null?void 0:r.onUpdateCustomCarpet)==null||o.call(r,s)},onClick:s=>{var r,o;(o=(r=t.events)==null?void 0:r.onClickCarpet)==null||o.call(r,{id:s.id})}}});this.customCarpetMap.set(e.id.toString(),i),t.appContainer.addToLayer(yi,i)}removeCustomCarpet(e){const t=this.appService,i=this.customCarpetMap.get(e);i&&(t.appContainer.removeFromLayer(yi,i),i.destroy(),this.customCarpetMap.delete(e))}updateCarpetsEditState(){this.customCarpetMap.forEach(e=>{e.updateEditState()})}applyLayerVisibility(e){const t=this.appService.appContainer.getLayer(yi);t&&(t.visible=e)}isCarpetDataEqual(e,t){if(e.id!==t.id||e.type!==t.type||e.shape!==t.shape)return!1;const i=e.points||[],s=t.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(e=>{e.refreshDisplay()})}refreshConfig(){this.customCarpetMap.forEach(e=>{e.refreshConfig()})}destroy(){this.unsubscribeFns.forEach(e=>e()),this.unsubscribeFns=[],this.clearAllCustomCarpets()}}function EC(n,e){return{coords:n.coords,editControls:n.editControlManager,furnitureConfig:n.furnitureConfig,controlsConfig:n.controlsConfig,gestures:n.gestureController,render:{request:t=>n.getApp().requestRender(t,!0),stop:t=>n.getApp().stopRender(t),once:t=>n.getApp().requestRender(t,!1)},events:e}}const sc="furniture-drag",nc="furniture-scale",rc="furniture-move",Nr="furniture-rotate";class kC extends O{constructor(t){super();y(this,"deps");y(this,"config");y(this,"controlsConfig");y(this,"furnitureEvents");y(this,"data");y(this,"textureAlias");y(this,"sprite");y(this,"editableShape");y(this,"editing",!1);y(this,"disabled",!1);y(this,"clickHandler",null);y(this,"dragStartPosition",null);y(this,"initialPoints",[]);y(this,"isDragging",!1);y(this,"gestureSession",null);y(this,"originalSizeMeters",null);y(this,"resolveSizeConstraintPerEdge",()=>{var o,a;const{minScaleRatio:t,maxScaleRatio:i}=this.config,s=i===1/0||i==null?void 0:i,r=l=>{if(!l||l<=0)return{min:.1,max:void 0};const h=l*(t||0);return{min:h>0?h:.1,max:s!=null?l*s:void 0}};return{edge1:r((o=this.originalSizeMeters)==null?void 0:o.width),edge2:r((a=this.originalSizeMeters)==null?void 0:a.height)}});y(this,"onDragStart",t=>{if(this.resolveVisualState()!=="editing"||!this.parent||t.target!==this&&t.target!==this.sprite)return;t.stopPropagation();const i=this.parent.toLocal(t.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(t),this.gestureSession.onMove(this.onDragMove),this.gestureSession.onEnd(this.onDragEnd)});y(this,"onDragMove",t=>{if(!this.dragStartPosition||!this.parent)return;const i=this.parent.toLocal(t.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(sc)),this.data.points=this.initialPoints.map(o=>({x:o.x+s,y:o.y+r})),this.redraw())});y(this,"onDragEnd",()=>{var t,i;this.gestureSession=null,this.dragStartPosition&&(this.isDragging&&((i=(t=this.furnitureEvents).onUpdate)==null||i.call(t,this.getData()),this.deps.render.stop(sc)),this.dragStartPosition=null,this.initialPoints=[],this.isDragging=!1)});y(this,"handleRotateStart",()=>{this.deps.render.request(Nr)});y(this,"handleRotateMove",t=>{t&&(this.data.points=t,this.redraw())});y(this,"handleTapRotate",t=>{var i,s;t&&(this.data.points=t,this.redraw()),this.captureOriginalSize(),this.deps.render.once(Nr),(s=(i=this.furnitureEvents).onUpdate)==null||s.call(i,this.getData())});y(this,"handleScaleStart",()=>{this.deps.render.request(nc)});y(this,"handleScaleMove",t=>{t&&(this.data.points=t,this.redraw())});y(this,"handleMoveStart",()=>{this.initialPoints=this.data.points.map(t=>({...t})),this.deps.render.request(rc)});y(this,"handleMove",t=>{var a;if(this.resolveVisualState()!=="editing"||this.initialPoints.length===0||!this.parent)return;const i=this.parent.toLocal(t.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(l=>({x:l.x+r,y:l.y+o})),this.redraw()});y(this,"handleMoveEnd",()=>{var t,i;this.initialPoints=[],this.deps.render.stop(rc),(i=(t=this.furnitureEvents).onUpdate)==null||i.call(t,this.getData())});y(this,"handleTransformEnd",()=>{var t,i;this.deps.render.stop(Nr),this.deps.render.stop(nc),(i=(t=this.furnitureEvents).onUpdate)==null||i.call(t,this.getData())});y(this,"handleDelete",()=>{var t,i;(i=(t=this.furnitureEvents).onRemove)==null||i.call(t,this.data.id)});y(this,"handleClick",()=>{var t,i;this.resolveVisualState()!=="editing"&&((i=(t=this.furnitureEvents).onClick)==null||i.call(t,this.getData()))});const{deps:i,data:s,textureAlias:r}=t;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.applyVisualState()}captureOriginalSize(){const t=this.data.points;if(t.length<4){this.originalSizeMeters=null;return}const i=q(t[0],t[1]),s=q(t[1],t[2]);this.originalSizeMeters={width:this.deps.coords.toMeters(Gt(i)),height:this.deps.coords.toMeters(Gt(s))}}createSprite(){const t=Y.get(this.textureAlias);this.sprite=new re(t),this.sprite.anchor.set(.5),this.sprite.alpha=this.config.opacity,this.sprite.eventMode="passive",this.addChild(this.sprite)}updateSpriteTransform(){const t=this.data.points;if(t.length<4)return;const i=oe(t),s=t[1].x-t[0].x,r=t[1].y-t[0].y,o=Math.atan2(r,s),a=q(t[0],t[1]),l=q(t[1],t[2]);this.sprite.position.set(i.x,i.y),this.sprite.rotation=o,this.sprite.width=a,this.sprite.height=l}createEditControlLayer(){const t={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),...Se(this.config),showRadialScaleButton:!1,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 Es({editControls:this.deps.editControls});const i={config:t,zonePoints:this.data.points,sizeConstraintPerEdge:this.resolveSizeConstraintPerEdge,contentLayer:ws,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:this.resolveEditingState(),idleState:{showRotateButton:!1,showScaleButton:!1,showRadialScaleButton:!1,showDeleteButton:!1,showMoveButton:!1,showBorder:!1,showSizeText:!1}})}setupInteraction(){this.clickHandler=new yt(this,{onClick:t=>{!this.isDragging&&((t==null?void 0:t.target)===this||(t==null?void 0:t.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))}resolveEditingState(){return{...Se(this.config),showRadialScaleButton:!1,showBorder:!0,showSizeText:this.config.showSizeText}}resolveVisualState(){return Ii(this.editing,this.disabled)}applyVisualState(){var i;const t=this.resolveVisualState();t==="disabled"&&((i=this.gestureSession)==null||i.cancel()),t==="editing"?this.editableShape.applyEditState(this.resolveEditingState()):this.editableShape.setEditing(!1),this.alpha=t==="disabled"?Di(this.config.disabled,this.controlsConfig.disabledStyle):1,this.zIndex=t==="editing"?1e3:0}updateEditState(t){this.editing!==t&&(this.editing=t,this.applyVisualState())}isEditing(){return this.editing}setDisabled(t){this.disabled!==t&&(this.disabled=t,this.applyVisualState())}isDisabled(){return this.disabled}getData(){return{id:this.data.id,furnitureType:this.data.furnitureType,points:this.data.points.map(t=>({...t}))}}updateData(t){this.data={...t,points:t.points.map(i=>({...i}))},this.captureOriginalSize(),this.data.points.length>=4&&(this.updateSpriteTransform(),this.editableShape.updatePoints(this.data.points))}destroy(){var t,i,s;(t=this.editableShape)==null||t.detach(),(i=this.gestureSession)==null||i.cancel(),this.gestureSession=null,(s=this.clickHandler)==null||s.destroy(),this.clickHandler=null,super.destroy({children:!0})}}class IC{constructor(e){y(this,"furnitureMap",new Map);y(this,"unsubscribeFns",[]);this.appService=e,this.applyLayerVisibility(e.runtime.showFurnitures);const t=z(e.runtime,"editingFurnitureIds",r=>{M.log(`[runtime] editingFurnitureIds: ${r}`),this.updateEditState()}),i=z(e.runtime,"disabledFurnitureIds",r=>{M.log(`[runtime] disabledFurnitureIds: ${r}`),this.updateEditState()}),s=z(e.runtime,"showFurnitures",r=>{M.log(`[runtime] showFurnitures: ${r}`),this.applyLayerVisibility(r)});this.unsubscribeFns.push(t,i,s)}getDiagnosticObjects(e=201){if(this.furnitureMap.size>e)throw new Error("BUDGET_EXCEEDED: entities");return Array.from(this.furnitureMap.entries(),([t,i])=>({type:"furniture",id:t,container:i,read:()=>i.getData()}))}async drawFurnitures(e){if(!e||e.length===0){this.clearAll();return}const t=new Set(this.furnitureMap.keys()),i=new Set(e.map(r=>r.id));for(const r of t)i.has(r)||this.removeFurniture(r);const s=[];for(const r of e){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(e){const t=this.appService;if(!t.furnitureConfig.assets.find(c=>c.type===e.furnitureType)){M.warn(`[FurnitureManager] No asset found for furnitureType: ${e.furnitureType}`);return}const r=`furniture_${e.furnitureType}`;await Y.load(r);const o=EC(t,{onRemove:c=>{var d,u;(u=(d=t.events)==null?void 0:d.onRemoveFurniture)==null||u.call(d,c)},onUpdate:c=>{var d,u;(u=(d=t.events)==null?void 0:d.onUpdateFurniture)==null||u.call(d,c)},onClick:c=>{var d,u;(u=(d=t.events)==null?void 0:d.onClickFurniture)==null||u.call(d,c)}}),a=new kC({deps:o,data:e,textureAlias:r});this.furnitureMap.set(e.id,a),t.appContainer.addToLayer(ws,a);const l=t.runtime.editingFurnitureIds,h=t.runtime.disabledFurnitureIds;a.setDisabled(h.includes(e.id)),a.updateEditState(l.includes(e.id))}removeFurniture(e){var i;const t=this.furnitureMap.get(e);t&&((i=t.parent)==null||i.removeChild(t),t.destroy(),this.furnitureMap.delete(e))}clearAll(){var e;for(const[,t]of this.furnitureMap)(e=t.parent)==null||e.removeChild(t),t.destroy();this.furnitureMap.clear()}applyLayerVisibility(e){const t=this.appService.appContainer.getLayer(ws);t&&(t.visible=e)}updateEditState(){const e=this.appService.runtime.editingFurnitureIds,t=this.appService.runtime.disabledFurnitureIds;this.furnitureMap.forEach((i,s)=>{i.setDisabled(t.includes(s)),i.updateEditState(e.includes(s))})}getFurnitures(){const e=[];return this.furnitureMap.forEach(t=>{e.push(t.getData())}),e}isDataEqual(e,t){if(e.id!==t.id||e.furnitureType!==t.furnitureType||e.points.length!==t.points.length)return!1;for(let i=0;i<e.points.length;i++)if(Math.abs(e.points[i].x-t.points[i].x)>.1||Math.abs(e.points[i].y-t.points[i].y)>.1)return!1;return!0}destroy(){this.unsubscribeFns.forEach(e=>e()),this.unsubscribeFns=[],this.clearAll()}}class DC{constructor(e){y(this,"editControlLayers",new Map);this.appService=e}registerEditControl(e,t){const i=this.appService;this.editControlLayers.has(e)&&this.unregisterEditControl(e);const s=new R0(i,t);if(!i.appContainer.addToLayer(xi,s))throw M.warn(`[EditControlManager] Failed to add edit control layer for id: ${e}`),s.destroy(),new Error(`Failed to register edit control for id: ${e}`);if(this.editControlLayers.set(e,s),t.contentLayer){const o=i.appContainer.getLayer(xi),a=i.appContainer.getLayer(t.contentLayer);o&&a&&(o.position.x!==a.position.x||o.position.y!==a.position.y)&&M.warn(`[EditControlManager] Edit layer position does not match content layer "${t.contentLayer}" position — edit controls will appear misaligned. Ensure "${t.contentLayer}" is in ORIGIN_TRACKED_LAYERS.`,{edit:o.position,content:a.position})}return s}unregisterEditControl(e){const t=this.editControlLayers.get(e);if(!t)return;this.appService.appContainer.removeFromLayer(xi,t),t.destroy(),this.editControlLayers.delete(e)}getEditControl(e){return this.editControlLayers.get(e)}updateEditState(e,t){const i=this.editControlLayers.get(e);i&&i.updateEditState(t)}clearAll(){Array.from(this.editControlLayers.keys()).forEach(t=>this.unregisterEditControl(t))}getAllEditControls(){return Array.from(this.editControlLayers.values())}hasEditControl(e){return this.editControlLayers.has(e)}}const FC=new Set(["onUpdateForbiddenSweepZone","onUpdateForbiddenMopZone","onUpdateCleanZone","onUpdateVirtualWall","onUpdateThreshold","onUpdateRamp","onUpdateSpot","onUpdateRoomAnchor","onUpdateWayPoint","onUpdateDivider","onDividerOutOfRoom","onUpdateCustomCarpet","onUpdateFurniture","onUpdateCustomZone"]);function Xi(n){return n.charAt(0).toUpperCase()+n.slice(1)}const BC=1,LC=.15,zC=.8,OC=.4,us=class us extends dd{constructor(t=ma){super();y(this,"diagnostics");y(this,"mapState",null);y(this,"components",{});y(this,"managers",{});y(this,"config",ga);y(this,"runtime");y(this,"appService");y(this,"elasticScale");y(this,"coords");y(this,"scaleMin",.5);y(this,"scaleMax",5);y(this,"events",{});y(this,"instanceKey");y(this,"debugInstanceId");y(this,"previousLoggerRuntimeState",null);y(this,"isDestroying",!1);y(this,"hasActiveContextLoss",!1);y(this,"createdAtMs",Date.now());y(this,"lastMapDataAtMs",null);y(this,"lastMapDrawAtMs",null);y(this,"lastPathDataAtMs",null);y(this,"lastVisibilityChangeAtMs",null);y(this,"containerElement");y(this,"onWebGLContextLost",t=>{var r;const i=t;if((r=i.preventDefault)==null||r.call(i),this.hasActiveContextLoss)return;this.hasActiveContextLoss=!0;const s=this.getContextLossDiagnostics(t);M.error("[Pixi] WebGL context lost",s.summary),M.error("[Pixi] WebGL context lost tail",s.recentLifecycleTail),this.recordDebugLifecycleEvent("webglcontextlost",{eventType:t.type,statusMessage:i.statusMessage??null})});y(this,"onWebGLContextRestored",t=>{this.hasActiveContextLoss=!1,M.warn("[Pixi] WebGL context restored, scheduling render",this.getRendererDiagnostics({eventType:t.type})),this.recordDebugLifecycleEvent("webglcontextrestored",{eventType:t.type}),this.renderOnceNextFrame()});y(this,"emitter",mv());y(this,"tickerState",{renderReasons:new Set,renderTimer:null,lastRequestReason:null,lastStopReason:null});y(this,"customCarpetResolvedMaxSizeCache",null);y(this,"pendingAsyncRender",!1);y(this,"isFirstMapDraw",!0);y(this,"isMapDrawn",!1);y(this,"onVisibilityChange",()=>{var i;this.lastVisibilityChangeAtMs=Date.now(),document.visibilityState==="visible"||(i=this.components.interaction)==null||i.forceEndGesture()});y(this,"onRendererResize",()=>{var t,i,s;this.isDestroying||((t=this.components.viewportContainer)==null||t.updateViewport(this.config),(i=this.components.background)==null||i.updateViewportBounds(this.getViewportBounds()),(s=this.components.domOverlayAligner)==null||s.scheduleSync(),this.renderOnceNextFrame())});this.instanceKey=t,this.debugInstanceId=Sh(),this.coords=new Ev(()=>{var i;return((i=this.runtime)==null?void 0:i.unit)??"meter"}),this.appService=new _u(this),this.diagnostics=new Eb(this,t,this.debugInstanceId),this.emitter.on("*",(i,s)=>{var r;return(r=this.diagnostics)==null?void 0:r.record(`emitter:${String(i)}`,s)}),this.recordDebugLifecycleEvent("app:create",{instanceKey:t})}getDiagnostics(t){return this.diagnostics.get(t)}getRendererDiagnostics(t={}){var r,o,a,l,h,c,d,u,p,f,m;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)===pe.WEBGPU?"webgpu":((o=this.renderer)==null?void 0:o.type)===pe.WEBGL?"webgl":"unknown";return{sessionId:zr().getSessionId(),instanceId:this.debugInstanceId,requestedPreference:this.config.global.rendererPreference,rendererType:s,rendererWidth:((a=this.renderer)==null?void 0:a.width)??null,rendererHeight:((l=this.renderer)==null?void 0:l.height)??null,canvasWidth:((h=this.canvas)==null?void 0:h.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:((f=this.mapState)==null?void 0:f.width)??null,mapHeight:((m=this.mapState)==null?void 0:m.height)??null,isMapDrawn:this.isMapDrawn,visibilityState:document.visibilityState,...t}}getElapsedMsSince(t){return typeof t=="number"?Math.max(0,Date.now()-t):null}getDeviceDiagnostics(){const t=globalThis.navigator;return{devicePixelRatio:globalThis.devicePixelRatio??null,userAgent:(t==null?void 0:t.userAgent)??null,hardwareConcurrency:(t==null?void 0:t.hardwareConcurrency)??null,deviceMemory:(t==null?void 0:t.deviceMemory)??null,documentWasDiscarded:"wasDiscarded"in document?document.wasDiscarded:null}}getWebGLDiagnostics(){var r;const t=(r=this.renderer)==null?void 0:r.gl;if(!t)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 t.getParameter!="function")return null;try{return t.getParameter(o)??null}catch{return null}},s=typeof t.getExtension=="function"?t.getExtension("WEBGL_debug_renderer_info"):null;return{contextAttributes:typeof t.getContextAttributes=="function"?t.getContextAttributes()??null:null,isContextLost:typeof t.isContextLost=="function"?t.isContextLost():null,drawingBufferWidth:t.drawingBufferWidth??null,drawingBufferHeight:t.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(t.VERSION),shadingLanguageVersion:i(t.SHADING_LANGUAGE_VERSION),maxTextureSize:i(t.MAX_TEXTURE_SIZE),maxRenderbufferSize:i(t.MAX_RENDERBUFFER_SIZE)}}getRecentLifecycleTail(){return zr().readCurrentSession().slice(-us.CONTEXT_LOSS_TAIL_SIZE).map(t=>({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}))}getContextLossDiagnostics(t){const i=t;return{summary:this.getRendererDiagnostics({eventType:t.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 t,i;if(((t=this.renderer)==null?void 0:t.type)!==pe.WEBGL||typeof((i=this.canvas)==null?void 0:i.addEventListener)!="function"){M.debug("[Pixi] Renderer diagnostics initialized",this.getRendererDiagnostics({contextListeners:!1}));return}this.canvas.addEventListener("webglcontextlost",this.onWebGLContextLost),this.canvas.addEventListener("webglcontextrestored",this.onWebGLContextRestored),M.debug("[Pixi] Renderer diagnostics initialized",this.getRendererDiagnostics({contextListeners:!0}))}detachRendererDiagnostics(){var t;typeof((t=this.canvas)==null?void 0:t.removeEventListener)=="function"&&(this.canvas.removeEventListener("webglcontextlost",this.onWebGLContextLost),this.canvas.removeEventListener("webglcontextrestored",this.onWebGLContextRestored))}getDebugRendererType(){var t,i;return((t=this.renderer)==null?void 0:t.type)===pe.WEBGPU?"webgpu":((i=this.renderer)==null?void 0:i.type)===pe.WEBGL?"webgl":"unknown"}recordDebugLifecycleEvent(t,i){var s,r;(s=this.diagnostics)==null||s.record(`lifecycle:${t}`,i),zr().record({event:t,instanceId:this.debugInstanceId,visibilityState:typeof document<"u"?document.visibilityState:null,rendererType:this.getDebugRendererType(),mapId:((r=this.mapState)==null?void 0:r.id)??null,detail:i})}async initialize(t){const{resizeTo:i,events:s,config:r,runtime:o={},...a}=t;this.config=bo(lh({},ga,r??{},(f,m)=>{if(Array.isArray(m))return m})),this.validateCustomZoneTypes(this.config),this.previousLoggerRuntimeState=KS(),qS({getLoggerConfig:()=>this.config.logger,getLegacyEnabled:()=>this.config.global.enableLogger}),M.log("Applying config",this.config,r),this.runtime=bo(Object.assign({},Vp,o));const l=this.instanceKey===ma;this.containerElement=i;const h=l&&this.config.interaction.enable,c=this.config.global.performanceMode||!l,d={gcActive:!1,autoStart:!1,sharedTicker:c,eventFeatures:{move:h,globalMove:!1,click:h,wheel:h}},u={resizeTo:l?i:void 0,resolution:this.config.global.resolution,antialias:c?!1:PC(),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(f){M.warn("[Pixi] WebGPU initialization failed, falling back to WebGL:",f),await this.init({...u,preference:"webgl"})}else await this.init({...u,preference:p});this.attachRendererDiagnostics(),this.diagnostics.bindRenderer(),this.recordDebugLifecycleEvent("app:initialized",{isMainInstance:l,isPerformanceMode:c,requestedPreference:p}),M.debug("[Pixi] Renderer initialized",this.getRendererDiagnostics({isMainInstance:l,isPerformanceMode:c})),this.preloadAssets(),this.scaleMax=this.config.interaction.zoomRange.max,this.scaleMin=this.config.interaction.zoomRange.min,this.events=this.diagnostics.wrapCallbacks(s,f=>{var g;return!(typeof f=="string"&&FC.has(f)&&((g=this.components.interaction)!=null&&g.isPointerCleanupActive))}),this.initializeViewportContainer(),this.initializeInteraction(),this.initializeAppContainer(),this.elasticScale=new Vv(this.appService),this.components.domOverlayAligner=new gv(this.appService),this.renderer.on("resize",this.onRendererResize),this.managers.mapManager=new g0(this.appService),this.managers.heatmapManager=new w0(this.appService),this.managers.pathManager=new b0(this.appService),this.managers.controlsManager=new $0(this.appService),this.managers.detectedObjectManager=new Y0(this.appService),this.managers.customElementsManager=new SC(this.appService),this.managers.roomsManager=new _C(this.appService),this.managers.customCarpetManager=new RC(this.appService),this.managers.furnitureManager=new IC(this.appService),this.managers.editControlManager=new DC(this.appService),this.setupMapRotationListener(),this.diagnostics.ready(),document.addEventListener("visibilitychange",this.onVisibilityChange)}async drawMap(t){var a,l,h,c,d,u,p,f,m,g,x;(a=this.diagnostics)==null||a.record("input:map",{format:"structured",id:t.id,size:t.size}),this.lastMapDataAtMs=Date.now(),this.isMapDrawn=!1,M.log("[Map] drawMap",t);const{size:i,resolution:s,origin:r,id:o}=t;((l=this.mapState)==null?void 0:l.id)!==void 0&&this.mapState.id!==o&&this.managers.pathManager.clear(),(r[0]!==((h=this.mapState)==null?void 0:h.origin.x)||r[1]!==((c=this.mapState)==null?void 0:c.origin.y))&&(this.appService.appContainer.updateOriginTrackedLayers(...r),this.managers.pathManager.updatePositionByOrigin(...r),this.managers.heatmapManager.updatePositionByOrigin(...r)),this.mapState={id:t.id,status:t.status===1,origin:{x:r[0],y:r[1]},charger:{x:t.charger.coordinate[0],y:t.charger.coordinate[1]},chargerDirection:t.charger.angle??0,resolution:s,width:i[0],height:i[1],mapType:"structured"},this.coords.setResolution(s),M.debug("[Map] Structured map state updated",{mapId:o,mapWidth:i[0],mapHeight:i[1],mapResolution:s,mapStatus:t.status===1,originX:r[0],originY:r[1]}),this.isFirstMapDraw&&(this.isFirstMapDraw=!1,(u=(d=this.events)==null?void 0:d.onMapFirstDrawed)==null||u.call(d,this.mapState)),(f=(p=this.events)==null?void 0:p.onMapDrawed)==null||f.call(p,this.mapState),this.emitter.emit("mapStateUpdate",this.mapState),(m=this.diagnostics)==null||m.record("draw:map:start",{mapId:this.mapState.id});try{await this.managers.mapManager.drawMap(t),(g=this.diagnostics)==null||g.record("draw:map:end",{mapId:this.mapState.id})}catch(S){throw(x=this.diagnostics)==null||x.record("error",{stage:"draw:map",message:String(S)}),S}i[0]===0||i[1]===0?(M.warn("[Map] Structured map cleared by incoming data",this.getRendererDiagnostics({mapId:o,mapWidth:i[0],mapHeight:i[1],mapResolution:s,mapStatus:t.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(t){var a,l,h,c,d,u,p,f,m,g;(a=this.diagnostics)==null||a.record("input:map",{format:"raster",id:t.mapHeader.id}),this.lastMapDataAtMs=Date.now(),this.isMapDrawn=!1,M.log("[Map] drawRasterMap",t);const{mapHeader:i,mapData:s}=t,{originX:r,originY:o}=i;(r!==((l=this.mapState)==null?void 0:l.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),M.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,(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),(f=this.diagnostics)==null||f.record("draw:map:start",{mapId:this.mapState.id});try{await this.managers.mapManager.drawRasterMap(s.parsed,this.mapState),(m=this.diagnostics)==null||m.record("draw:map:end",{mapId:this.mapState.id})}catch(x){throw(g=this.diagnostics)==null||g.record("error",{stage:"draw:map",message:String(x)}),x}i.mapWidth===0||i.mapHeight===0?(M.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 t,i;(i=(t=this.events)==null?void 0:t.onRoomsDrawed)==null||i.call(t,this.getRoomCenters())}getRoomCenters(){var i;const t=((i=this.mapState)==null?void 0:i.origin)??{x:0,y:0};return this.managers.mapManager.getAllRooms().map(s=>({id:s.id,centerPoint:s.centerPoint,relativeCenterPoint:{x:s.centerPoint.x-t.x,y:s.centerPoint.y-t.y}}))}drawPath(t){var i,s,r,o,a,l;(i=this.diagnostics)==null||i.record("input:path",{header:t.pathHeader,pointCount:t.pathPoints.length}),this.lastPathDataAtMs=Date.now(),M.log("[Path] drawPath",t),(r=(s=this.events)==null?void 0:s.onPathDrawed)==null||r.call(s,{id:t.pathHeader.pathId,type:t.pathHeader.type,direction:t.pathHeader.direction,count:t.pathHeader.count,initFlag:t.pathHeader.initFlag,robotPosition:t.pathPoints[t.pathPoints.length-1]??null}),(o=this.diagnostics)==null||o.record("draw:path:start");try{this.managers.pathManager.draw(t),(a=this.diagnostics)==null||a.record("draw:path:end")}catch(h){throw(l=this.diagnostics)==null||l.record("error",{stage:"draw:path",message:String(h)}),h}this.renderOnce()}async drawRoomProperty(t){var i,s,r,o;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawRoomProperty",count:t.length}),M.log("[Room] drawRoomProperty",t),(r=(s=this.events)==null?void 0:s.onRoomPropertiesDrawed)==null||r.call(s,t),await this.managers.roomsManager.drawRoomProperty(t),(o=this.diagnostics)==null||o.record("input:applied",{operation:"drawRoomProperty"}),this.renderOnceNextFrame()}async drawCustomCarpets(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawCustomCarpets",count:t.length}),M.log("[CustomCarpets] drawCustomCarpets",t),await this.managers.customCarpetManager.drawCustomCarpets(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawCustomCarpets"}),this.renderOnceNextFrame()}async drawFurnitures(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawFurnitures",count:t.length}),M.log("[Furniture] drawFurnitures",t),await this.managers.furnitureManager.drawFurnitures(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawFurnitures"}),this.renderOnceNextFrame()}drawHeatmap(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawHeatmap",count:t.length}),M.log("[Heatmap] drawHeatmap",t),this.managers.heatmapManager.draw(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawHeatmap"}),this.renderOnce()}drawForbiddenSweepZones(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawForbiddenSweepZones",count:t.length}),M.log("[Controls] drawForbiddenSweepZones",t),this.managers.controlsManager.drawForbiddenSweepZones(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawForbiddenSweepZones"}),this.renderOnceNextFrame()}drawForbiddenMopZones(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawForbiddenMopZones",count:t.length}),M.log("[Controls] drawForbiddenMopZones",t),this.managers.controlsManager.drawForbiddenMopZones(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawForbiddenMopZones"}),this.renderOnceNextFrame()}drawCleanZones(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawCleanZones",count:t.length}),M.log("[Controls] drawCleanZones",t),this.managers.controlsManager.drawCleanZones(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawCleanZones"}),this.renderOnceNextFrame()}drawCustomZones(t,i){var s,r;if((s=this.diagnostics)==null||s.record("input:entities",{operation:"drawCustomZones",type:t,count:i.length}),Pe(t)){M.warn(`[MapApplication] drawCustomZones: '${t}' is a built-in type; use draw${Xi(t)}s() instead`);return}M.log("[Controls] drawCustomZones",t,i),this.managers.controlsManager.drawCustomZones(t,i),(r=this.diagnostics)==null||r.record("input:applied",{operation:"drawCustomZones",type:t}),this.renderOnceNextFrame()}getCustomZones(t){return Pe(t)?(M.warn(`[MapApplication] getCustomZones: '${t}' is a built-in type; use get${Xi(t)}s() instead`),[]):this.managers.controlsManager.getCustomZones(t)}clearCustomZones(t){if(Pe(t)){M.warn(`[MapApplication] clearCustomZones: '${t}' is a built-in type; use clearAll${Xi(t)}s() instead`);return}M.log("[Controls] clearCustomZones",t),this.managers.controlsManager.clearCustomZones(t),this.renderOnceNextFrame()}setEditingCustomZones(t,i){if(Pe(t)){M.warn(`[MapApplication] setEditingCustomZones: '${t}' is a built-in type; use runtime.editing${Xi(t)}Ids instead`);return}this.runtime.editingCustomZoneIds={...this.runtime.editingCustomZoneIds??{},[t]:[...i]}}setDisabledCustomZones(t,i){if(Pe(t)){M.warn(`[MapApplication] setDisabledCustomZones: '${t}' is a built-in type; use runtime.disabled${Xi(t)}Ids instead`);return}this.runtime.disabledCustomZoneIds={...this.runtime.disabledCustomZoneIds??{},[t]:[...i]}}drawVirtualWalls(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawVirtualWalls",count:t.length}),M.log("[Controls] drawVirtualWalls",t),this.managers.controlsManager.drawVirtualWalls(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawVirtualWalls"}),this.renderOnceNextFrame()}drawThresholds(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawThresholds",count:t.length}),M.log("[Controls] drawThresholds",t),this.managers.controlsManager.drawThresholds(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawThresholds"}),this.renderOnceNextFrame()}drawRamps(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawRamps",count:t.length}),M.log("[Controls] drawRamps",t),this.managers.controlsManager.drawRamps(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawRamps"}),this.renderOnceNextFrame()}drawSpots(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawSpots",count:t.length}),M.log("[Controls] drawSpots",t),this.managers.controlsManager.drawSpots(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawSpots"}),this.renderOnceNextFrame()}drawRoomAnchors(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawRoomAnchors",count:t.length}),M.log("[Controls] drawRoomAnchors",t),this.managers.controlsManager.drawRoomAnchors(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawRoomAnchors"}),this.renderOnceNextFrame()}getRoomAnchors(){return this.managers.controlsManager.getRoomAnchors()}clearAllRoomAnchors(){this.managers.controlsManager.clearAllRoomAnchors(),this.renderOnceNextFrame()}drawWayPoints(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawWayPoints",count:t.length}),M.log("[Controls] drawWayPoints",t),this.managers.controlsManager.drawWayPoints(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawWayPoints"}),this.renderOnceNextFrame()}async drawDetectedObjects(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawDetectedObjects",count:t.length}),M.log("[DetectedObject] drawDetectedObjects",t),await this.managers.detectedObjectManager.drawDetectedObjects(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawDetectedObjects"}),this.renderOnceNextFrame()}drawCustomCarpet(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawCustomCarpet",count:t.length}),M.log("[CustomCarpet] drawCustomCarpet",t),this.managers.customCarpetManager.drawCustomCarpets(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawCustomCarpet"}),this.renderOnceNextFrame()}async drawCustomElements(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawCustomElements",count:t.length}),M.log("[CustomElements] drawCustomElements",t),await this.managers.customElementsManager.drawCustomElements(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawCustomElements"}),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()}getThresholds(){return this.managers.controlsManager.getThresholds()}getRamps(){return this.managers.controlsManager.getRamps()}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(){M.log("[Map] forceEndGesture"),this.components.interaction.forceEndGesture()}fitMapToView(t,i=!1){if(!t||t.minX===t.maxX||t.minY===t.maxY)return;const s=this.config.map.autoPaddingVerticalPercent,r=this.config.map.autoPaddingHorizontalPercent,o=this.getViewportBounds(),a=this.components.appContainer.getMapRotationRadians(),l=this.calculateRotatedBounds(t,a),h=l.maxX-l.minX,c=l.maxY-l.minY,d=o.width,u=o.height,p=d*(1-r*2),f=u*(1-s*2),m=p/h,g=f/c,x=Math.min(m,g),S=this.config.interaction.fitMinScale,b=this.config.interaction.fitMaxScale,w=Math.max(S,Math.min(b,x));this.setScaleBounds(this.config.interaction.zoomRange.min,this.config.interaction.zoomRange.max),w<this.scaleMin&&(this.setScaleBounds(w,this.scaleMax),M.debug("[MapApplication] scaleMin lowered for fit:",{configured:this.config.interaction.zoomRange.min,adjusted:w})),w>this.scaleMax&&(this.setScaleBounds(this.scaleMin,w),M.debug("[MapApplication] scaleMax raised for fit:",{configured:this.config.interaction.zoomRange.max,adjusted:w}));const _=t.minX+(t.maxX-t.minX)/2,v=t.minY+(t.maxY-t.minY)/2,C=this.config.map.autoFitOffset||{x:0,y:0},P=d/2+(C.x||0),A=u/2+(C.y||0),R=Math.cos(a),T=Math.sin(a),E=_*R-v*T,I=_*T+v*R,F=P-E*w,N=A-I*w;M.debug("[MapApplication] fitMapToView calculated:",{rotation:this.components.appContainer.getMapRotation(),originalBounds:t,rotatedBounds:l,finalScale:w,position:{x:F,y:N}}),this.components.interaction.setPanZoom({targetPosition:{x:F,y:N},targetScale:{x:w,y:w},setCenter:!0,setScale:!0},i)}setScaleBounds(t,i){this.scaleMin=t,this.scaleMax=i,this.components.interaction.scaleMin=t,this.components.interaction.scaleMax=i}validateCustomZoneTypes(t){const i=["minSize","strokeColor","strokeWidth","fillColor","outlineOffset","outlineStrokeColor","outlineStrokeWidth","outlineDashed","outlineDashArray","outlineFillColor","iconWrapperFillColor","textColor","textPosition","textOffset","showRotateButton","showDeleteButton","showScaleButton","showMoveButton","editing","normal"],s=t.customZoneTypes??{},r=fc.cleanZone;for(const[,o]of Object.entries(s))for(const a of i)o[a]===void 0&&(o[a]=r[a])}calculateRotatedBounds(t,i){if(i===0)return t;const s=(t.minX+t.maxX)/2,r=(t.minY+t.maxY)/2,o=[{x:t.minX-s,y:t.minY-r},{x:t.maxX-s,y:t.minY-r},{x:t.maxX-s,y:t.maxY-r},{x:t.minX-s,y:t.maxY-r}],a=Math.cos(i),l=Math.sin(i),h=o.map(f=>({x:f.x*a-f.y*l,y:f.x*l+f.y*a}));let c=1/0,d=1/0,u=-1/0,p=-1/0;return h.forEach(f=>{c=Math.min(c,f.x),d=Math.min(d,f.y),u=Math.max(u,f.x),p=Math.max(p,f.y)}),{minX:c+s,minY:d+r,maxX:u+s,maxY:p+r}}getViewportBounds(){var t;return((t=this.components.viewportContainer)==null?void 0:t.getViewportBounds())||{x:0,y:0,width:this.renderer.width,height:this.renderer.height}}updateRuntime(t){var i,s;(i=this.diagnostics)==null||i.record("input:runtime",{keys:Object.keys(t)}),Object.assign(this.runtime,t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"updateRuntime"}),M.log("[runtime] runtime updated",t),this.renderOnceNextFrame()}updateConfig(t){var a,l,h,c,d,u,p,f,m,g,x,S,b,w,_,v,C,P,A;(a=this.diagnostics)==null||a.record("input:config",{keys:Object.keys(t)}),lh(this.config,t,(R,T)=>{if(Array.isArray(T))return T}),t.customZoneTypes&&this.validateCustomZoneTypes(this.config),(l=this.managers.controlsManager)==null||l.updateRenderOrder(),(t.elasticScale!==void 0||t.room!==void 0||t.detectedObject!==void 0)&&((h=this.managers.roomsManager)==null||h.refreshElasticConfig(),(c=this.managers.detectedObjectManager)==null||c.refreshElasticConfig(),(d=this.elasticScale)==null||d.refresh()),((u=t.controls)==null?void 0:u.spot)!==void 0&&((p=this.managers.controlsManager)==null||p.refreshSpotsEditState()),((f=t.controls)==null?void 0:f.roomAnchor)!==void 0&&((m=this.managers.controlsManager)==null||m.refreshRoomAnchors()),((g=t.controls)==null?void 0:g.wayPoint)!==void 0&&((x=this.managers.controlsManager)==null||x.refreshWayPointsConfig()),((S=t.controls)==null?void 0:S.carpet)!==void 0&&((b=this.managers.customCarpetManager)==null||b.refreshConfig());const r=t.controls;((r==null?void 0:r.forbiddenSweepZone)!==void 0||(r==null?void 0:r.forbiddenMopZone)!==void 0||(r==null?void 0:r.cleanZone)!==void 0||t.customZoneTypes!==void 0)&&((w=this.managers.controlsManager)==null||w.refreshZonesConfig()),t.room!==void 0&&((_=this.managers.roomsManager)==null||_.refreshRoomConfig()),((v=t.map)==null?void 0:v.beautify)!==void 0&&this.runtime.enableBeautify&&((C=this.managers.mapManager)==null||C.reprocessStructuredMap(),(P=this.managers.mapManager)==null||P.reprocessRasterMap()),M.log("[Config] Configuration updated",t),(A=this.diagnostics)==null||A.record("input:applied",{operation:"updateConfig"}),this.renderOnceNextFrame()}metersToPixels(t){return this.coords.toPixels(et(t))}pixelsToMeters(t){return this.coords.toMeters(Gt(t))}toFixedSize(t,i){const s=i??this.components.appContainer.scale.x;return t/s}fromFixedSize(t,i){const s=i??this.components.appContainer.scale.x;return t*s}getViewportCenterPoint(){if(!this.mapState)return M.warn("Map state not available, cannot calculate center point"),null;const t=this.getViewportBounds(),i=t.x+t.width/2,s=t.y+t.height/2,r=this.components.appContainer,o=r.scale.x,a=r.getMapRotationRadians(),l=i-r.x,h=s-r.y,c=l/o,d=h/o,u=Math.cos(a),p=Math.sin(a),f=c*u+d*p,m=-c*p+d*u,g=f-this.mapState.origin.x,x=m-this.mapState.origin.y;return{x:g,y:x}}getMapCenterPoint(){if(!this.mapState)return M.warn("Map state not available, cannot calculate map center point"),null;const t=this.managers.mapManager.mapBounds;if(t.minX===1/0||t.minY===1/0||t.maxX===-1/0||t.maxY===-1/0)return M.warn("Invalid map bounds, cannot calculate map center point"),null;const i=(t.minX+t.maxX)/2,s=(t.minY+t.maxY)/2,r=i-this.mapState.origin.x,o=s-this.mapState.origin.y;return{x:r,y:o}}getWallPointsByViewportCenter(t){var f;const{width:i=this.config.controls.virtualWall.minWidth,direction:s="horizontal",offsetX:r=0,offsetY:o=0}=t||{},a=this.getViewportCenterPoint()||{x:0,y:0},h=this.coords.toPixels(et(i))/2,c=((f=this.components.appContainer)==null?void 0:f.getMapRotationRadians())||0,d=Math.cos(c),u=Math.sin(c);let p;return s==="horizontal"?p=[{vx:-h+r,vy:o},{vx:h+r,vy:o}]:p=[{vx:r,vy:-h+o},{vx:r,vy:h+o}],p.map(m=>({x:a.x+m.vx*d+m.vy*u,y:a.y-m.vx*u+m.vy*d}))}getForbiddenSweepZonePointsByViewportCenter(t){const i=this.config.controls.forbiddenSweepZone,{size:s=i.minSize,offsetX:r=0,offsetY:o=0}=t||{};return this.generateZonePoints(s,r,o)}getForbiddenMopZonePointsByViewportCenter(t){const i=this.config.controls.forbiddenMopZone,{size:s=i.minSize,offsetX:r=0,offsetY:o=0}=t||{};return this.generateZonePoints(s,r,o)}getCleanZonePointsByViewportCenter(t){const i=this.config.controls.cleanZone,{size:s=i.minSize,offsetX:r=0,offsetY:o=0}=t||{};return this.generateZonePoints(s,r,o)}getSpotPointByViewportCenter(t){const{offsetX:i=0,offsetY:s=0}=t||{},r=this.getViewportCenterPoint()||{x:0,y:0},o=r.x+i,a=r.y+s;return{x:o,y:a}}getFurniturePointsByViewportCenter(t){const{furnitureType:i=1,offsetX:s=0,offsetY:r=0}=t||{},o=this.config.furniture.assets.find(l=>l.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 t=this.config.controls.carpet.maxSize;if(this.customCarpetResolvedMaxSizeCache&&this.customCarpetResolvedMaxSizeCache.key===t)return this.customCarpetResolvedMaxSizeCache.value;const i=ne(this.config.controls.carpet.minSize,t,"carpet");return this.customCarpetResolvedMaxSizeCache={key:t,value:i},i}getCustomCarpetPointsByViewportCenter(t){const s=this.config.controls.carpet.minSize,r=this.getResolvedCustomCarpetMaxSize(),{offsetX:o=0,offsetY:a=0}=t||{},l=(f,m)=>{const g=typeof f=="number"&&Number.isFinite(f)?f:m;return r!=null?Math.min(Math.max(g,s),r):Math.max(g,s)},h=(t==null?void 0:t.width)??(t==null?void 0:t.height),c=(t==null?void 0:t.height)??(t==null?void 0:t.width),d=l(h,s),u=l(c,s),p=this.getViewportCenterPoint()||{x:0,y:0};return this.buildRectPoints({center:p,widthMeters:d,heightMeters:u,applyMapRotation:!0,visualOffsetX:o,visualOffsetY:a})}getThresholdPointsByViewportCenter(t){const i=this.config.controls.threshold,{offsetX:s=0,offsetY:r=0}=t||{},o=(c,d,u,p,f)=>{const m=typeof c=="number"&&Number.isFinite(c)&&c>0?c:d,g=ne(u,p,f);return g!=null?Math.min(Math.max(m,u),g):Math.max(m,u)},a=o(t==null?void 0:t.width,BC,i.minLength,i.maxLength,"threshold"),l=o(t==null?void 0:t.height,LC,i.minHeight,i.maxHeight,"threshold.height"),h=this.getViewportCenterPoint()||{x:0,y:0};return this.buildRectPoints({center:h,widthMeters:a,heightMeters:l,applyMapRotation:!0,visualOffsetX:s,visualOffsetY:r})}getRampPointsByViewportCenter(t){const i=this.config.controls.ramp,{offsetX:s=0,offsetY:r=0}=t||{},o=(c,d,u,p,f)=>{const m=typeof c=="number"&&Number.isFinite(c)&&c>0?c:d,g=ne(u,p,f);return g!=null?Math.min(Math.max(m,u),g):Math.max(m,u)},a=o(t==null?void 0:t.width,zC,i.minWidth,i.maxWidth,"ramp"),l=o(t==null?void 0:t.height,OC,i.minHeight,i.maxHeight,"ramp.height"),h=this.getViewportCenterPoint()||{x:0,y:0};return this.buildRectPoints({center:h,widthMeters:a,heightMeters:l,applyMapRotation:!0,visualOffsetX:s,visualOffsetY:r})}getRectPointsByCenter(t){const{center:i,width:s,height:r,applyMapRotation:o=!0}=t;return this.buildRectPoints({center:i,widthMeters:s,heightMeters:r,applyMapRotation:o})}areRoomsAdjacent(t){return!t||t.length===0?(M.warn("[Room] No room IDs provided"),!1):this.managers.mapManager.areRoomsAdjacent(t)}getAdjacentRoomIds(t){return typeof t!="number"||!Number.isFinite(t)?(M.warn("[Room] Invalid room ID provided"),[]):this.managers.mapManager.getAdjacentRoomIds(t)}isPointInAnyRoom(t){return!t||typeof t.x!="number"||typeof t.y!="number"?(M.warn("[Room] Invalid point provided"),null):this.mapState?this.managers.mapManager.isPointInAnyRoom(t):(M.warn("[Room] Map state not available"),null)}isPointInRoom(t,i){return!t||typeof t.x!="number"||typeof t.y!="number"?(M.warn("[Room] Invalid point provided"),!1):this.mapState?this.managers.mapManager.isPointInRoom(t,i):(M.warn("[Room] Map state not available"),!1)}isWallIntersectsAnyRoom(t){return!t||t.length!==2||!t[0]||!t[1]||typeof t[0].x!="number"||typeof t[0].y!="number"||typeof t[1].x!="number"||typeof t[1].y!="number"?(M.warn("[Room] Invalid wall points provided"),!1):this.mapState?this.managers.mapManager.isWallIntersectsAnyRoom(t):(M.warn("[Room] Map state not available"),!1)}isZoneIntersectsAnyRoom(t){return!t||t.length!==4||!t[0]||!t[1]||!t[2]||!t[3]||typeof t[0].x!="number"||typeof t[0].y!="number"||typeof t[1].x!="number"||typeof t[1].y!="number"||typeof t[2].x!="number"||typeof t[2].y!="number"||typeof t[3].x!="number"||typeof t[3].y!="number"?(M.warn("[Room] Invalid zone points provided"),!1):this.mapState?this.managers.mapManager.isZoneIntersectsAnyRoom(t):(M.warn("[Room] Map state not available"),!1)}isNearChargerOrRobot(t,i,s){var l,h;if(!t||t.length<1)return M.warn("[Distance] Invalid points array: must have at least 1 point"),!1;if(t.length!==1&&t.length!==2&&t.length!==4)return M.warn("[Distance] Invalid points array: must have exactly 1 (point), 2 (wall) or 4 (zone) points"),!1;if(i<=0)return M.warn("[Distance] Invalid threshold: must be greater than 0"),!1;if(!this.mapState)return M.warn("[Distance] Map state not available"),!1;const{checkCharger:r=!0,checkRobot:o=!1}=s||{};if(!r&&!o)return M.warn("[Distance] At least one of checkCharger or checkRobot must be true"),!1;const a=this.coords.toPixels(et(i));if(r){const c=this.appService.getChargerPosition();if(c){const d=(l=this.mapState)==null?void 0:l.charger.x,u=(h=this.mapState)==null?void 0:h.charger.y;if(d===0&&u===0)return M.warn("[Distance] Charger position not available"),!1;const p=Kl(c,t);if(p<=a)return M.log(`[Distance] Too close to charger: ${p.toFixed(2)} pixels (threshold: ${a.toFixed(2)} pixels)`),!0}else M.warn("[Distance] Charger position not available")}if(o){const c=this.appService.getRobotPosition();if(c){const d=Kl(c,t);if(d<=a)return M.log(`[Distance] Too close to robot: ${d.toFixed(2)} pixels (threshold: ${a.toFixed(2)} pixels)`),!0}else M.warn("[Distance] Robot position not available")}return!1}async snapshot(t){this.render();const{snapshot:i,global:s}=this.config,r=(t==null?void 0:t.backgroundColor)??s.backgroundColor,o=this.components.appContainer,a=o.getSnapshotBounds(),l=Math.floor(a.x),h=Math.floor(a.y),c=Math.ceil(a.x+a.width)-l,d=Math.ceil(a.y+a.height)-h;if(c<=0||d<=0)return M.error("[MapApplication] Snapshot failed: invalid bounds",a),"";const u=i.resolution||window.devicePixelRatio||2,p=Ko.create({width:c,height:d,resolution:u}),f=new W;f.rect(0,0,c,d).fill(r);const m=new H;m.translate(-l,-h);try{return this.renderer.render({container:f,target:p}),this.renderer.render({container:o,target:p,transform:m,clear:!1}),await this.renderer.extract.base64({target:p,format:i.format,quality:i.quality,antialias:i.antialias})}catch(g){return M.error("[MapApplication] Snapshot failed:",g),""}finally{f.destroy(),p.destroy(!0)}}async snapshotByData({map:t,path:i,roomProperties:s,customElements:r,forbiddenSweepZones:o,forbiddenMopZones:a,virtualWalls:l,detectedObjects:h,furnitures:c,carpets:d},u={},p){const f=`SNAPSHOT_${Sh()}`;M.log(`[MapApplication] ${f} snapshot start`);const m=new us(f);try{if(await m.initialize({config:this.config,runtime:u}),!t)throw new Error("Map data is required");if(t.startsWith("7b22")){const x=$p(t);await m.drawMap(x)}else{const x=Xp(t,{pointsStructured:!0});if(x)await m.drawRasterMap(x);else throw new Error("Failed to decode raster map data")}if(i){const{decodePath:x}=await je(async()=>{const{decodePath:b}=await import("./theme.DhH3-Q9Y.js").then(w=>w.f);return{decodePath:b}},__vite__mapDeps([4,2])),S=x(i);m.drawPath(S)}s&&s.length>0&&await m.drawRoomProperty(s),o&&o.length>0&&m.drawForbiddenSweepZones(o),a&&a.length>0&&m.drawForbiddenMopZones(a),l&&l.length>0&&m.drawVirtualWalls(l),d&&d.length>0&&await m.drawCustomCarpets(d),c&&c.length>0&&await m.drawFurnitures(c),h&&h.length>0&&await m.drawDetectedObjects(h),r&&r.length>0&&await m.drawCustomElements(r);const g=await m.snapshot(p);return M.log(`[MapApplication] ${f} snapshot completed successfully`),g}catch(g){throw M.error(`[MapApplication] ${f} snapshot other map failed:`,g),g}finally{M.log(`[MapApplication] ${f} destroy`),m.destroy()}}renderOnce(){var t,i;M.debug("[Pixi] renderOnce");try{this.render(),(t=this.diagnostics)==null||t.explicitRenderSubmit("renderOnce")}catch(s){(i=this.diagnostics)==null||i.record("error",{stage:"renderOnce",message:String(s)}),M.error("[Pixi] renderOnce failed",this.getRendererDiagnostics({error:s}))}}renderOnceNextFrame(){this.pendingAsyncRender||(this.pendingAsyncRender=!0,requestAnimationFrame(()=>{var t,i;if(this.isDestroying){this.pendingAsyncRender=!1;return}M.debug("[Pixi] renderOnceNextFrame");try{this.render(),(t=this.diagnostics)==null||t.explicitRenderSubmit("renderOnceNextFrame")}catch(s){(i=this.diagnostics)==null||i.record("error",{stage:"renderOnceNextFrame",message:String(s)}),M.error("[Pixi] renderOnceNextFrame failed",this.getRendererDiagnostics({error:s}))}finally{this.pendingAsyncRender=!1}}))}requestRender(t,i=!1){var r;if(this.tickerState.lastRequestReason=t,!i){this.renderOnceNextFrame(),this.emitRenderStateUpdate();return}const s=this.tickerState.renderTimer!==null;this.tickerState.renderReasons.add(t),M.debug("[Ticker] requestRender(continuous)",{reason:t,hadPendingStop:s,reasonsAfterAdd:[...this.tickerState.renderReasons],tickerStarted:(r=this.ticker)==null?void 0:r.started}),this.ticker.started||(M.debug(`🎬 [Ticker] START: ${t}`),this.ticker.start()),this.emitRenderStateUpdate()}stopRender(t){var i;this.tickerState.lastStopReason=t,this.tickerState.renderReasons.delete(t),M.debug("[Ticker] stopRender",{reason:t,reasonsAfterDelete:[...this.tickerState.renderReasons],tickerStarted:(i=this.ticker)==null?void 0:i.started}),this.tickerState.renderReasons.size===0&&this.scheduleStopRender("final",100),this.emitRenderStateUpdate()}getRenderState(){var i;const t=!!((i=this.ticker)!=null&&i.started);return{continuous:t,fps:t?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 t,i,s,r,o,a,l,h,c,d,u,p,f,m,g,x;if(!this.isDestroying){this.isDestroying=!0,(t=this.diagnostics)==null||t.destroy(),M.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(),(i=this.renderer)==null||i.off("resize",this.onRendererResize),document.removeEventListener("visibilitychange",this.onVisibilityChange),(s=this.elasticScale)==null||s.destroy(),(r=this.managers.pathManager)==null||r.destroy(),(o=this.managers.mapManager)==null||o.destroy(),(a=this.managers.controlsManager)==null||a.destroy(),(l=this.managers.furnitureManager)==null||l.destroy(),(h=this.managers.detectedObjectManager)==null||h.destroy(),(c=this.managers.customElementsManager)==null||c.destroy(),(d=this.managers.roomsManager)==null||d.destroy(),(u=this.components.domOverlayAligner)==null||u.destroy(),(p=this.components.interaction)==null||p.destroy(),(f=this.components.background)==null||f.destroy(),(m=this.components.viewportContainer)==null||m.destroy(),(g=this.components.appContainer)==null||g.destroy(),(x=this.managers.heatmapManager)==null||x.destroy(),this.renderer&&this.detachRendererDiagnostics(),QS(this.previousLoggerRuntimeState),this.previousLoggerRuntimeState=null,globalThis.__PIXI_APP__===this&&delete globalThis.__PIXI_APP__,this.renderer&&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"),this.diagnostics.destroy()}}}initializeViewportContainer(){this.components.viewportContainer=new Iv(this.config,this.containerElement),this.stage.addChild(this.components.viewportContainer);const t=this.getViewportBounds();this.components.background=new AC(this.config.global,t,()=>{this.renderOnceNextFrame()}),this.components.viewportContainer.addChild(this.components.background),this.components.viewportContainer.setChildIndex(this.components.background,0),Ln(this.config.global,()=>{var i;(i=this.components.background)==null||i.update(this.config.global)})}initializeAppContainer(){this.components.appContainer=new Lv(this.appService),this.components.interaction.addChild(this.components.appContainer)}initializeInteraction(){this.components.interaction=new fv(this.appService),this.components.viewportContainer.addChild(this.components.interaction)}scheduleStopRender(t,i){this.tickerState.renderTimer&&clearTimeout(this.tickerState.renderTimer),M.debug("[Ticker] scheduleStopRender(set)",{reason:t,delay:i,reasonsNow:[...this.tickerState.renderReasons]}),this.tickerState.renderTimer=setTimeout(()=>{this.tickerState.renderTimer=null,this.tickerState.renderReasons.delete(t),this.tickerState.renderReasons.size===0?(M.debug("⏸️ [Ticker] STOP"),this.ticker&&(this.ticker.stop(),this.emitRenderStateUpdate())):M.debug("[Ticker] stop-timer fired but reasons remain",{reasons:[...this.tickerState.renderReasons]})},i)}generateZonePoints(t,i,s){const r=this.getViewportCenterPoint()||{x:0,y:0};return this.buildRectPoints({center:r,widthMeters:t,heightMeters:t,applyMapRotation:!0,visualOffsetX:i,visualOffsetY:s})}buildRectPoints(t){var m;const{center:i,widthMeters:s,heightMeters:r,applyMapRotation:o,visualOffsetX:a=0,visualOffsetY:l=0}=t,h=this.coords.toPixels(et(s))/2,c=this.coords.toPixels(et(r))/2,d=o&&((m=this.components.appContainer)==null?void 0:m.getMapRotationRadians())||0,u=Math.cos(d),p=Math.sin(d);return[{vx:-h+a,vy:-c+l},{vx:h+a,vy:-c+l},{vx:h+a,vy:c+l},{vx:-h+a,vy:c+l}].map(g=>({x:i.x+g.vx*u+g.vy*p,y:i.y-g.vx*p+g.vy*u}))}preloadAssets(){var a,l,h,c;const t=this.config.robot.icon.src,i=this.config.chargingStation.icon.src,s=[];Y.add({alias:"robot",src:t}),s.push("robot"),Y.add({alias:"chargingStation",src:i}),s.push("chargingStation"),Y.add({alias:"deleteIcon",src:this.config.controls.deleteIconSrc}),s.push("deleteIcon"),Y.add({alias:"rotateIcon",src:this.config.controls.rotateIconSrc}),s.push("rotateIcon"),Y.add({alias:"scaleIcon",src:this.config.controls.scaleIconSrc}),s.push("scaleIcon"),Y.add({alias:"moveIcon",src:this.config.controls.moveIconSrc}),s.push("moveIcon"),Y.add({alias:"checkmark",src:this.config.room.selectionIndicator.iconSrc}),s.push("checkmark"),Y.add({alias:"spotIcon",src:this.config.controls.spot.iconSrc}),s.push("spotIcon");const r=(a=this.config.controls.roomAnchor)==null?void 0:a.iconSrc;r&&(Y.add({alias:"roomAnchorIcon",src:r}),s.push("roomAnchorIcon")),[["forbiddenSweepZone",(l=this.config.controls.forbiddenSweepZone.centerIcon)==null?void 0:l.src],["forbiddenMopZone",(h=this.config.controls.forbiddenMopZone.centerIcon)==null?void 0:h.src],["cleanZone",(c=this.config.controls.cleanZone.centerIcon)==null?void 0:c.src],...Object.entries(this.config.customZoneTypes??{}).map(([d,u])=>{var p;return[d,(p=u==null?void 0:u.centerIcon)==null?void 0:p.src]})].forEach(([d,u])=>{if(!u)return;const p=`zoneCenterIcon_${d}`;Y.add({alias:p,src:u}),s.push(p)}),Y.add({alias:"wayPoint",src:this.config.controls.wayPoint.normal.iconSrc}),s.push("wayPoint"),Y.add({alias:"wayPointActive",src:this.config.controls.wayPoint.editing.iconSrc}),s.push("wayPointActive"),Y.add({alias:"horizontalScaleIcon",src:this.config.controls.horizontalScaleIconSrc}),s.push("horizontalScaleIcon"),Y.add({alias:"verticalScaleIcon",src:this.config.controls.verticalScaleIconSrc}),s.push("verticalScaleIcon"),this.config.room.property.cleanMode.assets.forEach((d,u)=>{const p=`cleanMode_${u}`;Y.add({alias:p,src:d}),s.push(p)}),this.config.room.property.suction.assets.forEach((d,u)=>{const p=`fan_${u}`;Y.add({alias:p,src:d}),s.push(p)}),this.config.room.property.cistern.assets.forEach((d,u)=>{const p=`water_${u}`;Y.add({alias:p,src:d}),s.push(p)}),this.config.room.property.cleanTimes.assets.forEach((d,u)=>{const p=`cleanTimes${u+1}`;Y.add({alias:p,src:d}),s.push(p)}),this.config.room.floorType.assets.forEach((d,u)=>{if(!d)return;const p=`floorType${u}`;Y.add({alias:p,src:d}),s.push(p)}),this.config.room.property.customAssets&&Object.entries(this.config.room.property.customAssets).forEach(([d,u])=>{u.forEach((p,f)=>{const m=`custom_${d}_${f}`;Y.add({alias:m,src:p}),s.push(m)})}),this.config.furniture.assets.forEach(d=>{const u=`furniture_${d.type}`;Y.add({alias:u,src:d.src}),s.push(u)}),Y.backgroundLoad(s)}setupMapRotationListener(){this.applyMapRotation(this.runtime.mapRotation),z(this.runtime,"mapRotation",t=>{this.applyMapRotation(t)})}applyMapRotation(t){const i=(t%360+360)%360;M.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()}};y(us,"CONTEXT_LOSS_TAIL_SIZE",8);let Ao=us;const XC=Object.freeze(Object.defineProperty({__proto__:null,AppService:_u,MapApplication:Ao},Symbol.toStringTag,{value:"Module"}));export{ss as $,es as A,Re as B,Me as C,ko as D,ae as E,Fo as F,W as G,Ux as H,wi as I,Ty as J,In as K,Sy as L,H as M,Xt as N,Dn as O,it as P,Do as Q,st as R,km as S,U as T,Z as U,rd as V,pe as W,Ps as X,Tm as Y,ki as Z,nl as _,bi as a,Bo as a0,id as a1,Ut as a2,Mi as a3,bd as a4,ny as a5,ly as a6,$C as a7,wd as a8,Je as a9,ms as aA,Fm as aB,vd as aC,ry as aD,cy as aE,Hx as aF,Cd as aG,dy as aH,Dx as aI,XC as aJ,on as aa,Sg as ab,rf as ac,Ie as ad,Ci as ae,uy as af,Ft as ag,Ac as ah,Wt as ai,Rn as aj,Ea as ak,re as al,wS as am,Lf as an,Ia as ao,ir as ap,Da as aq,Of as ar,Rc as as,Ko as at,Yo as au,mt as av,od as aw,_s as ax,Vg as ay,Wg as az,fo as b,ht as c,X as d,ee as e,go as f,Xs as g,vt as h,K as i,tg as j,Kf as k,sS as l,B as m,Ix as n,Bl as o,Pr as p,Q as q,Sf as r,O as s,hg as t,vg as u,tt as v,lt as w,St as x,ft as y,at as z};
|
|
744
|
+
`,entryPoint:"main"}})}),h=new Wl({geometry:a,shader:l});return h.alpha=.8,h}updatePositionByOrigin(t,i){this.position.set(t,i)}clear(){this.removeChildren()}destroy(){this.removeChildren(),this.cacheAsTexture(!1)}}class w0{constructor(e){y(this,"heatmap");y(this,"pointsTopLeftOrigin",[]);y(this,"signalGrid",[]);y(this,"cellSize",2);y(this,"maxDistance",14);y(this,"smoothIterations",10);y(this,"heatmapAlpha",.8);y(this,"isHeatmapDrawn",!1);y(this,"loadTimer",null);y(this,"pendingPoints",null);this.appService=e,this.heatmap=new v0(e);const t=e.heatMapConfig;this.cellSize=t.cellSize,this.maxDistance=t.maxDistance,this.smoothIterations=t.smoothIterations,this.heatmapAlpha=t.heatmapAlpha}draw(e){if(e.length===0){this.clear();return}const t=this.appService;if(!t.isMapDrawn){this.pendingPoints=e;return}this.pendingPoints=null;const{minX:i,minY:s}=t.mapManager.mapBounds,r=e.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(e){var p;const t=this.appService,i=((p=t.mapState)==null?void 0:p.origin)||{x:0,y:0};let{minX:s,minY:r,maxX:o,maxY:a}=t.mapManager.mapBounds;r=r-i.y,s=s-i.x,a=a-i.y,o=o-i.x;const l=Math.ceil((a-r)/this.cellSize),h=Math.ceil((o-s)/this.cellSize),c=Array(l).fill(null).map(()=>Array(h).fill(null));for(let f=0;f<l;f++){const m=r+f*this.cellSize+this.cellSize/2,g=Math.min(this.cellSize,a-(m-this.cellSize/2));for(let x=0;x<h;x++){const S=s+x*this.cellSize+this.cellSize/2,b=Math.min(this.cellSize,o-(S-this.cellSize/2));let w=0,_=!1;for(let v=0;v<e.length;v++){const C=e[v];if(Math.abs(S-C.x)<=b/2&&Math.abs(m-C.y)<=g/2){const P=1-C.signal/7;w=Math.round(Math.max(w,P)*10)/10,_=!0}}c[f][x]={x:S,y:m,signal:w,hasPoint:_}}}const d=(f,m)=>{if(e.length===0)return 0;let g=0,x=0;for(const S of e){const b=Math.sqrt((f-S.x)**2+(m-S.y)**2);if(b<=this.maxDistance){const w=1/(1+b),_=1-S.signal/7;x+=w*_,g+=w}}return g===0?0:Math.round(x/g*1e3)/1e3},u=(f,m=1)=>{for(let g=0;g<m;g++){const x=f.map(S=>[...S]);for(let S=1;S<l-1;S++)for(let b=1;b<h-1;b++)if(!f[S][b].hasPoint){let w=0,_=0;const v=4;for(let C=-v;C<=v;C++)for(let P=-v;P<=v;P++){if(C===0&&P===0)continue;const A=S+C,R=b+P;if(A>=0&&A<l&&R>=0&&R<h){const E=1/(1+Math.sqrt(C*C+P*P)*.3);w+=f[A][R].signal*E,_+=E}}if(_>0){const C=w/_,P=.6,A=.4;x[S][b].signal=f[S][b].signal*P+C*A,x[S][b].signal>.1&&(x[S][b].signal=Math.max(x[S][b].signal,.2))}}for(let S=0;S<l;S++)for(let b=0;b<h;b++)f[S][b].signal=x[S][b].signal}};for(let f=0;f<l;f++)for(let m=0;m<h;m++){const g=c[f][m];g.hasPoint||(g.signal=d(g.x,g.y))}return u(c,this.smoothIterations),c}updatePositionByOrigin(e,t){this.heatmap.updatePositionByOrigin(e,t)}destroy(){this.heatmap.destroy()}}const Se=n=>({showRotateButton:n.showRotateButton??!0,showScaleButton:n.showScaleButton??!0,showDeleteButton:n.showDeleteButton??!0,showMoveButton:n.showMoveButton??!0}),C0=n=>({showScaleButton:n.showScaleButton??!0,showDeleteButton:n.showDeleteButton??!0,showMoveButton:n.showMoveButton??!0});function Ii(n,e){return e?"disabled":n?"editing":"idle"}const M0=.4;function Di(n,e){return(n==null?void 0:n.opacity)??(e==null?void 0:e.opacity)??M0}class oa extends W{constructor(t,i){super();y(this,"fillOptions");y(this,"isDragging",!1);y(this,"dragStartPosition",null);y(this,"gestureSession",null);y(this,"handlePointerDown",t=>{t.stopPropagation(),this.startDragging(t)});y(this,"handleDragPointerMove",t=>{var i,s;!this.isDragging||!this.dragStartPosition||(s=(i=this.fillOptions).onDragMove)==null||s.call(i,t)});y(this,"handleDragPointerUp",()=>{var t,i;this.gestureSession=null,this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null,(i=(t=this.fillOptions).onDragEnd)==null||i.call(t))});this.appService=t,this.fillOptions=i,this.setupInteraction(),this.draw()}setupInteraction(){this.fillOptions.enableInteraction&&(this.eventMode="static",this.on("pointerdown",this.handlePointerDown))}startDragging(t){var s,r;this.isDragging=!0;const i=this.parent.toLocal(t.global);this.dragStartPosition={x:i.x,y:i.y},(r=(s=this.fillOptions).onDragStart)==null||r.call(s,t),this.gestureSession=this.appService.gestureController.hijack(t),this.gestureSession.onMove(this.handleDragPointerMove),this.gestureSession.onEnd(this.handleDragPointerUp)}draw(){const{points:t,fillColor:i}=this.fillOptions;if(t.length<3)return;this.clear();const s=t.flatMap(r=>[r.x,r.y]);this.setFillStyle({color:i}).poly(s).fill()}getDragStartPosition(){return this.dragStartPosition}updateOptions(t){this.fillOptions={...this.fillOptions,...t},t.enableInteraction!==void 0&&(this.off("pointerdown",this.handlePointerDown),this.setupInteraction()),this.draw()}updatePoints(t){this.fillOptions.points=t,this.draw()}updateFillColor(t){this.fillOptions.fillColor=t,this.draw()}interruptDragging(){this.isDragging&&(this.gestureSession?this.gestureSession.cancel():this.handleDragPointerUp())}stopDragging(){var t;this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null,(t=this.gestureSession)==null||t.cancel(),this.gestureSession=null)}isCurrentlyDragging(){return this.isDragging}setInteractionEnabled(t){this.fillOptions.enableInteraction=t,t?(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()}}const Qh=24,Jh=.5,_0=.8;class P0 extends Yt{constructor(t,i){super(t);y(this,"iconConfig");y(this,"boxShortSide",0);y(this,"textureReady",!1);y(this,"visualState","idle");y(this,"unsubscribeMapRotation",null);this.iconConfig=i,this.eventMode="none",this.alpha=i.opacity??1,this.anchor.set(i.anchor??Jh),this.visible=!1,this.applyAntiRotation(t.runtime.mapRotation),this.unsubscribeMapRotation=z(t.runtime,"mapRotation",s=>{this.applyAntiRotation(s)}),this.loadIconTexture()}updateGeometry(t,i){this.destroyed||(this.boxShortSide=i,this.position.set(t.x,t.y),this.applyClampedSize())}setVisualState(t){this.visualState=t,this.applyVisibility()}async loadIconTexture(){const{src:t,size:i=Qh,sizeFixed:s=!0,anchor:r=Jh}=this.iconConfig;await this.loadTextureAndSetSize(t,{width:i,height:i,sizeFixed:s}),!this.destroyed&&(this.anchor.set(r),this.textureReady=!0,this.applyClampedSize(),this.applyVisibility())}updateScale(t){this.applyClampedSize(),super.updateScale(t)}applyAntiRotation(t){this.destroyed||(this.rotation=-t*Math.PI/180)}applyVisibility(){if(this.destroyed)return;const{showInEditing:t=!0,showInNormal:i=!0,showInDisabled:s}=this.iconConfig,r=this.visualState==="editing"?t:this.visualState==="disabled"?s??i:i;this.visible=this.textureReady&&r}applyClampedSize(){if(this.destroyed||!this.textureReady)return;const t=this.clampToBox(this.iconConfig.size??Qh);this.setFixedSize(t,t)}clampToBox(t){if(this.boxShortSide<=0)return t;const r=(this.iconConfig.sizeFixed??!0?this.boxShortSide*this.appService.currentScale:this.boxShortSide)*_0;return r>0?Math.min(t,r):t}destroy(t){var i;(i=this.unsubscribeMapRotation)==null||i.call(this),this.unsubscribeMapRotation=null,super.destroy(t)}}class Es{constructor(e){y(this,"id",null);y(this,"layer",null);y(this,"editingState",{});y(this,"idleState",{});y(this,"host",null);y(this,"onHostDestroyed",null);y(this,"detached",!1);this.deps=e}attach(e,t){this.layer&&this.detach(),this.detached=!1,this.host=e,this.id=t.id,this.editingState=t.editingState,this.idleState=t.idleState??{},this.layer=this.deps.editControls.registerEditControl(t.id,t.layerOptions);const i=()=>this.detach();return this.onHostDestroyed=i,e.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(e){if(this.id==null){M.warn("[EditableShape] setEditing called before attach; ignoring");return}this.deps.editControls.updateEditState(this.id,e?this.editingState:this.idleState)}applyEditState(e){if(this.id==null){M.warn("[EditableShape] applyEditState called before attach; ignoring");return}this.deps.editControls.updateEditState(this.id,e)}updatePoints(e,t=!0){var i;(i=this.layer)==null||i.updatePoints(e,t)}getLayer(){return this.layer}getMoveButton(){var e;return((e=this.layer)==null?void 0:e.getMoveButton())??null}}class Tn extends xs{constructor(t,{text:i,style:s}){super({text:i,style:s});y(this,"throttledUpdateScale");this.appService=t,this.throttledUpdateScale=Pt(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(t){t<=0||this.scale.set(1/t)}setBaseFontSize(t){this.style.fontSize=t}updateText(t){this.text=t}destroy(t){this.appService.emitter.off("antiScale",this.throttledUpdateScale),this.throttledUpdateScale.cancel(),super.destroy(t)}}class ap extends O{constructor(t){super();y(this,"throttledUpdateScale");this.appService=t,this.throttledUpdateScale=Pt(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(t){t!==0&&this.scale.set(1/t)}destroy(t){this.appService.emitter.off("antiScale",this.throttledUpdateScale),this.throttledUpdateScale.cancel(),super.destroy(t)}}class Wn extends ap{constructor(t,i){super(t);y(this,"background");y(this,"icon");y(this,"options");this.appService=t,this.options=i,this.background=new W,this.addChild(this.background),this.icon=new Yt(t),this.addChild(this.icon),this.eventMode="static",this.render(),this.setupHitArea(),this.setupEvents()}setupHitArea(){const t=this.appService,i=this.options.config||t.controlsConfig,s=8,r=i.iconWrapperWidth+s*2,o=i.iconWrapperHeight+s*2;this.hitArea=new st(-r/2,-o/2,r,o)}async render(){this.renderBackground(),this.renderIcon()}renderBackground(){const t=this.appService,i=this.options.config||t.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 t=this.appService,i=this.options.config||t.controlsConfig;await this.icon.loadTextureAndSetSize(this.options.iconAlias,{width:i.iconWidth,height:i.iconHeight,sizeFixed:!1}),this.icon.visible=!0}catch(t){M.error(`Failed to load icon: ${this.options.iconAlias}`,t)}}destroy(){super.destroy()}}class lp extends Wn{constructor(t,i){super(t,i);y(this,"isMoving",!1);y(this,"dragStartPosition",null);y(this,"gestureSession",null);y(this,"handleMovePointerMove",t=>{var i,s;!this.isMoving||!this.dragStartPosition||(s=(i=this.options).onMoveMove)==null||s.call(i,t)});y(this,"handleMovePointerUp",()=>{var t,i;this.gestureSession=null,this.isMoving&&(this.isMoving=!1,this.dragStartPosition=null,(i=(t=this.options).onMoveEnd)==null||i.call(t))});this.appService=t}setupEvents(){this.on("pointerdown",this.handlePointerDown.bind(this))}handlePointerDown(t){t.stopPropagation(),this.startMoving(t)}startMoving(t){var i,s;this.isMoving=!0,this.dragStartPosition=this.parent.toLocal(t.global),(s=(i=this.options).onMoveStart)==null||s.call(i),this.gestureSession=this.appService.gestureController.hijack(t),this.gestureSession.onMove(this.handleMovePointerMove),this.gestureSession.onEnd(this.handleMovePointerUp)}isCurrentlyMoving(){return this.isMoving}getDragStartPosition(){return this.dragStartPosition?{...this.dragStartPosition}:null}stopMoving(){var t,i;this.isMoving&&(this.gestureSession?this.gestureSession.cancel():(this.isMoving=!1,this.dragStartPosition=null,(i=(t=this.options).onMoveEnd)==null||i.call(t)))}destroy(){this.stopMoving(),this.gestureSession=null,this.off("pointerdown",this.handlePointerDown),super.destroy()}}class hp extends Wn{constructor(t,i){super(t,i);y(this,"clickHandler",null);this.appService=t}setupEvents(){this.clickHandler=new yt(this,{onClick:this.options.onClick,stopPropagation:!0})}destroy(){var t;(t=this.clickHandler)==null||t.destroy(),super.destroy()}}const A0=10;class T0 extends Wn{constructor(t,i){super(t,i);y(this,"isRotating",!1);y(this,"hasRotated",!1);y(this,"rotationCenter",{x:0,y:0});y(this,"downPosition",{x:0,y:0});y(this,"lastAngle",0);y(this,"clickHandler",null);y(this,"gestureSession",null);y(this,"handleRotationPointerMove",t=>{var o,a,l,h;if(!this.isRotating||!this.options.onRotationMove)return;if(!this.hasRotated){const c=t.global.x-this.downPosition.x,d=t.global.y-this.downPosition.y;if(Math.sqrt(c*c+d*d)<=A0)return;this.hasRotated=!0,(a=(o=this.options).onRotationStart)==null||a.call(o,this.rotationCenter)}const i=this.parent.toLocal(t.global),s=Math.atan2(i.y-this.rotationCenter.y,i.x-this.rotationCenter.x),r=s-this.lastAngle;(h=(l=this.options).onRotationMove)==null||h.call(l,r),this.lastAngle=s});y(this,"handleRotationPointerUp",()=>{var t,i;this.gestureSession=null,this.isRotating&&(this.isRotating=!1,this.hasRotated&&((i=(t=this.options).onRotationEnd)==null||i.call(t)),this.hasRotated=!1)});this.appService=t}setupEvents(){this.options.onClick&&(this.clickHandler=new yt(this,{onClick:()=>{var t,i;this.hasRotated||(i=(t=this.options).onClick)==null||i.call(t)},stopPropagation:!1})),this.on("pointerdown",this.handlePointerDown.bind(this))}handlePointerDown(t){t.stopPropagation(),this.startRotation(t)}startRotation(t){this.isRotating=!0,this.hasRotated=!1,this.downPosition={x:t.global.x,y:t.global.y};const i=this.options.getTargetPoints();this.rotationCenter=oe(i);const s=this.parent.toLocal(t.global);this.lastAngle=Math.atan2(s.y-this.rotationCenter.y,s.x-this.rotationCenter.x),this.gestureSession=this.appService.gestureController.hijack(t),this.gestureSession.onMove(this.handleRotationPointerMove),this.gestureSession.onEnd(this.handleRotationPointerUp)}isCurrentlyRotating(){return this.isRotating}stopRotation(){var t,i;this.isRotating&&(this.gestureSession?this.gestureSession.cancel():(this.isRotating=!1,this.hasRotated&&((i=(t=this.options).onRotationEnd)==null||i.call(t)),this.hasRotated=!1))}destroy(){var t;this.stopRotation(),this.gestureSession=null,(t=this.clickHandler)==null||t.destroy(),this.off("pointerdown",this.handlePointerDown),super.destroy()}}class pn extends Wn{constructor(t,i){super(t,i);y(this,"isScaling",!1);y(this,"initialButtonPosition",null);y(this,"dragStartPosition",null);y(this,"gestureSession",null);y(this,"handleScalePointerMove",t=>{var o,a;if(!this.isScaling||!this.initialButtonPosition||!this.dragStartPosition)return;const i=this.parent.toLocal(t.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})});y(this,"handleScalePointerUp",()=>{var t,i;this.gestureSession=null,this.isScaling&&(this.isScaling=!1,this.initialButtonPosition=null,this.dragStartPosition=null,(i=(t=this.options).onScaleEnd)==null||i.call(t))});this.appService=t}setupEvents(){this.on("pointerdown",this.handlePointerDown.bind(this))}handlePointerDown(t){t.stopPropagation(),this.startScaling(t)}startScaling(t){var i,s,r,o;if(this.isScaling=!0,this.dragStartPosition=this.parent.toLocal(t.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(),l=this.options.getButtonIndex();l>=0&&l<a.length&&(this.initialButtonPosition={...a[l]}),(o=(r=this.options).onScaleStart)==null||o.call(r,l)}this.gestureSession=this.appService.gestureController.hijack(t),this.gestureSession.onMove(this.handleScalePointerMove),this.gestureSession.onEnd(this.handleScalePointerUp)}isCurrentlyScaling(){return this.isScaling}stopScaling(){var t,i;this.isScaling&&(this.gestureSession?this.gestureSession.cancel():(this.isScaling=!1,this.initialButtonPosition=null,this.dragStartPosition=null,(i=(t=this.options).onScaleEnd)==null||i.call(t)))}destroy(){this.stopScaling(),this.gestureSession=null,this.off("pointerdown",this.handlePointerDown),super.destroy()}}const xt={REMOVE:0,ROTATE:1,SCALE:2,MOVE:3};class R0 extends O{constructor(t,i){super();y(this,"config");y(this,"events");y(this,"zonePoints",[]);y(this,"outlinePoints");y(this,"minSize",.1);y(this,"maxSize");y(this,"sizeConstraintPerEdge");y(this,"initialZonePoints",[]);y(this,"scaleCache",null);y(this,"rotationCache",null);y(this,"outlineBorder");y(this,"moveLine");y(this,"sizeText");y(this,"controlButtons");y(this,"deleteButton",null);y(this,"rotateButton",null);y(this,"scaleButton",null);y(this,"moveButton",null);y(this,"horizontalScaleButton",null);y(this,"verticalScaleButton",null);y(this,"horizontalScaleInitialPosition",null);y(this,"verticalScaleInitialPosition",null);y(this,"clickHandler",null);y(this,"throttledUpdateOutline");this.appService=t,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=Pt(this.updateOutlineForScale.bind(this),30,{leading:!0,trailing:!0}),this.initializeComponents(),this.registerScaleListener()}getDiagnosticPart(t){return{delete:this.deleteButton,rotate:this.rotateButton,scale:this.scaleButton,move:this.moveButton,"scale-x":this.horizontalScaleButton,"scale-y":this.verticalScaleButton}[t]??null}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 O,this.addChild(this.controlButtons),this.createControlButtons(),this.setupClickHandler()}createOutlineBorder(){const{outlineStrokeColor:t,outlineStrokeWidth:i,outlineDashed:s,outlineDashArray:r,outlineFillColor:o}=this.config;return new De(this.appService,{points:this.outlinePoints,closePath:!0,style:{color:t,width:i,isDashed:s,dashArray:r,fillColor:o}})}createMoveLine(){const{outlineStrokeColor:t,outlineStrokeWidth:i,outlineDashed:s,outlineDashArray:r}=this.config,o=this.calculateMoveLinePoints();return new De(this.appService,{points:o,closePath:!1,style:{color:t,width:i,isDashed:s,dashArray:r}})}createSizeText(){const t=this.calculateSizeText(),i=new Tn(this.appService,{text:t,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 t=new hp(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 t.position.set(this.outlinePoints[xt.REMOVE].x,this.outlinePoints[xt.REMOVE].y),t}createRotateButton(){const t=this.config.rotateMode==="step",i=new T0(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:t?void 0:s=>{var o,a;const r=this.handleInternalRotationMove(s);(a=(o=this.events).onRotateMove)==null||a.call(o,r??void 0)},onClick:t?()=>{var o,a,l,h;const s=this.config.stepRotateAngle??Math.PI/2,r=this.onClickRotateButton(s);(a=(o=this.events).onRotateMove)==null||a.call(o,r??void 0),(h=(l=this.events).onClickRotate)==null||h.call(l,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[xt.ROTATE].x,this.outlinePoints[xt.ROTATE].y),i}onClickRotateButton(t){this.rotationCache||this.initializeRotationCache(this.calculateRotationCenter());const i=this.handleInternalRotationMove(t);return this.resetRotationState(),i}createScaleButton(){const t=new pn(this.appService,{iconAlias:"scaleIcon",backgroundColor:this.config.iconWrapperFillColor,initialButtonPosition:this.outlinePoints[xt.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 t.position.set(this.outlinePoints[xt.SCALE].x,this.outlinePoints[xt.SCALE].y),t}createHorizontalScaleButton(){const[,t,i]=this.outlinePoints,s=this.getEdgeCenter(t,i),r=new pn(this.appService,{iconAlias:"horizontalScaleIcon",backgroundColor:this.config.iconWrapperFillColor,config:{iconWrapperWidth:18,iconWrapperHeight:18,iconWrapperBorderRadius:18,iconWidth:10,iconHeight:8},initialButtonPosition:s,onScaleStart:()=>{var l,h;const[,o,a]=this.zonePoints;this.horizontalScaleInitialPosition=this.getEdgeCenter(o,a),this.initializeScaleCache(),(h=(l=this.events).onScaleStart)==null||h.call(l)},onScaleMove:({deltaX:o,deltaY:a})=>{var h,c;const l=this.handleInternalHorizontalScaleMove(o,a);(c=(h=this.events).onScaleMoveHorizontal)==null||c.call(h,l??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[,,t,i]=this.outlinePoints,s=this.getEdgeCenter(t,i),r=new pn(this.appService,{iconAlias:"verticalScaleIcon",backgroundColor:this.config.iconWrapperFillColor,config:{iconWrapperWidth:18,iconWrapperHeight:18,iconWrapperBorderRadius:18,iconWidth:8,iconHeight:10},initialButtonPosition:s,onScaleStart:()=>{var l,h;const[,,o,a]=this.zonePoints;this.verticalScaleInitialPosition=this.getEdgeCenter(o,a),this.initializeScaleCache(),(h=(l=this.events).onScaleStart)==null||h.call(l)},onScaleMove:({deltaX:o,deltaY:a})=>{var h,c;const l=this.handleInternalVerticalScaleMove(o,a);(c=(h=this.events).onScaleMoveVertical)==null||c.call(h,l??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 t=this.calculateMoveButtonPosition(),i=new lp(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(t.x,t.y),i}createAndAddButton(t,i){return t.visible=i,this.controlButtons.addChild(t),t}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 t=this.zonePoints;if(t.length<4)return t;const s=this.appService.getApp().toFixedSize(this.config.outlineOffset);return gb(t,s)}calculateMoveButtonPosition(){const t=this.calculateOutlinePoints();if(t.length<4)return{x:0,y:0};const s=this.appService.getApp().toFixedSize(this.config.moveButtonOffset),r=t[xt.MOVE],o=t[xt.SCALE],a=t[xt.REMOVE];return gu(r,o,a,s)}calculateMoveLinePoints(){const t=this.calculateOutlinePoints();if(t.length<4)return[];const i=t[xt.MOVE],s=this.calculateMoveButtonPosition();return[i,s]}calculateSizeText(){const t=this.zonePoints;if(t.length<4)return"0m*0m";const[i,s,,r]=t,o=q(i,s),a=q(i,r),{coords:l}=this.appService,h=l.toMeters(Gt(o)),c=l.toMeters(Gt(a)),d=l.toDisplayUnit(h),u=l.toDisplayUnit(c),p=this.appService.runtimeSnapshot.unitLabel;return`${d.toFixed(1)}${p}*${u.toFixed(1)}${p}`}getEdgeCenter(t,i){return{x:(t.x+i.x)/2,y:(t.y+i.y)/2}}calculatePerpendicularOffset(t,i,s,r=!1){const o=se(Mt(i,t)),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:l,textOffset:h}=this.config,d=this.appService.getApp().toFixedSize(h);let u,p;switch(l){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 t=this.zonePoints;if(t.length<4)return 0;const[i,s,r,o]=t,{textPosition:a}=this.config;let l,h;switch(a){case"top":l=i,h=s;break;case"right":l=s,h=r;break;case"bottom":l=r,h=o;break;case"left":l=o,h=i;break;default:l=i,h=s;break}const c=this.appService.appContainer.getMapRotationRadians();return hn(l,h,c)}calculateHorizontalScaleButtonRotation(){const t=this.zonePoints;if(t.length<4)return 0;const[,i,s]=t,r=this.appService.appContainer.getMapRotationRadians();return hn(i,s,r)+Math.PI/2}calculateVerticalScaleButtonRotation(){const t=this.zonePoints;if(t.length<4)return 0;const[,,i,s]=t,r=this.appService.appContainer.getMapRotationRadians();return hn(s,i,r)}updatePoints(t,i=!0){this.zonePoints=t,this.updateOutlineBorder(),this.moveLine&&this.updateMoveLine(),this.updateControlButtonsPosition(),this.updateSizeText(i)}updateOutlineBorder(){const t=this.calculateOutlinePoints();this.outlinePoints=t,this.outlineBorder.updatePoints(t)}updateMoveLine(){if(!this.moveLine)return;const t=this.calculateMoveLinePoints();this.moveLine.updatePoints(t)}updateSizeText(t=!0){if(this.sizeText){if(t){const i=this.calculateSizeText();this.sizeText.updateText(i)}this.updateSizeTextPosition()}}updateSizeTextPosition(){if(!this.sizeText)return;const t=this.calculateSizeTextPosition();this.sizeText.position.set(t.x,t.y);const i=this.calculateSizeTextRotation();this.sizeText.rotation=i}updateControlButtonsPosition(){if(!this.deleteButton||!this.scaleButton||!this.moveButton)return;const t=this.calculateOutlinePoints();if(t.length<4)return;const i=this.calculateMoveButtonPosition(),s=[{button:this.deleteButton,point:t[xt.REMOVE]},{button:this.scaleButton,point:t[xt.SCALE]},{button:this.moveButton,point:i}];if(this.rotateButton&&s.push({button:this.rotateButton,point:t[xt.ROTATE]}),this.horizontalScaleButton){const r=t[xt.ROTATE],o=t[xt.SCALE],a=pu(r,o,0);s.push({button:this.horizontalScaleButton,point:a})}if(this.verticalScaleButton){const r=t[xt.SCALE],o=t[xt.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 yt(this,{onClick:()=>{var t,i;(i=(t=this.events).onClick)==null||i.call(t)},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 t={...this.initialZonePoints[xt.SCALE]};if(!t)return;const i=xt.REMOVE,{x:s,y:r}=this.initialZonePoints[i],[,o,,a]=this.initialZonePoints,l={x:s,y:r},h=Mt(l,o),c=Mt(l,a),d=bs(h),u=bs(c);d===0||u===0||(this.scaleCache={fixedPoint:l,edge1:h,edge2:c,edge1Len:d,edge2Len:u,initialButtonPosition:t})}sizeConstraintPixels(){const{coords:t}=this.appService,i=(r,o)=>({minSizePixels:t.toPixels(et(r)),maxSizePixels:o!=null?t.toPixels(et(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(t,i){if(this.initialZonePoints.length!==4||!this.scaleCache)return null;const{edge1:s,edge2:r}=this.sizeConstraintPixels(),{fixedPoint:o,edge1:a,edge2:l,edge1Len:h,edge2Len:c,initialButtonPosition:d}=this.scaleCache,u={x:d.x+t,y:d.y+i},p=Mt(o,u);let f=qs(p,a,h,s.minSizePixels,s.maxSizePixels),m=qs(p,l,c,r.minSizePixels,r.maxSizePixels);if(this.config.scaleMode==="ratioLocked"){const g=Math.min(f,m);f=g,m=g}return this.calculatePointsFromScale(o,a,l,f,m)}resetScaleState(){this.scaleCache=null}handleInternalHorizontalScaleMove(t,i){if(this.initialZonePoints.length!==4||!this.scaleCache||!this.horizontalScaleInitialPosition)return null;const{fixedPoint:s,edge1:r,edge2:o,edge1Len:a}=this.scaleCache,{edge1:l}=this.sizeConstraintPixels(),h={x:this.horizontalScaleInitialPosition.x+t,y:this.horizontalScaleInitialPosition.y+i},c=Mt(s,h),d=qs(c,r,a,l.minSizePixels,l.maxSizePixels);return this.calculatePointsFromScale(s,r,o,d,1)}handleInternalVerticalScaleMove(t,i){if(this.initialZonePoints.length!==4||!this.scaleCache||!this.verticalScaleInitialPosition)return null;const{fixedPoint:s,edge1:r,edge2:o,edge2Len:a}=this.scaleCache,{edge2:l}=this.sizeConstraintPixels(),h={x:this.verticalScaleInitialPosition.x+t,y:this.verticalScaleInitialPosition.y+i},c=Mt(s,h),d=1,u=qs(c,o,a,l.minSizePixels,l.maxSizePixels);return this.calculatePointsFromScale(s,r,o,d,u)}calculatePointsFromScale(t,i,s,r,o){const{x:a,y:l}=t;return[t,{x:a+i.x*r,y:l+i.y*r},{x:a+i.x*r+s.x*o,y:l+i.y*r+s.y*o},{x:a+s.x*o,y:l+s.y*o}]}initializeRotationCache(t){this.zonePoints.length<3||(this.rotationCache={rotationCenter:t,initialPoints:this.zonePoints.map(i=>({...i})),totalAngle:0})}handleInternalRotationMove(t){if(!this.rotationCache||this.rotationCache.initialPoints.length<3)return null;const{rotationCenter:i,initialPoints:s}=this.rotationCache;return this.rotationCache.totalAngle+=t,pb(s,i,this.rotationCache.totalAngle)}resetRotationState(){this.rotationCache=null}calculateRotationCenter(){return this.zonePoints.length===0?{x:0,y:0}:oe(this.zonePoints)}updateEditState({showRotateButton:t=!1,showScaleButton:i=!1,showRadialScaleButton:s=!1,showDeleteButton:r=!1,showMoveButton:o=!1,showBorder:a=!1,showSizeText:l=!1,borderStyle:h}){this.rotateButton&&(this.rotateButton.visible=t),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=t||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=l),a&&(this.updateOutlineBorder(),c&&(this.moveLine&&o&&this.updateMoveLine(),this.updateControlButtonsPosition()),l&&this.updateSizeTextPosition()),h&&this.outlineBorder.updateStyle({isDashed:h.isDashed,dashArray:h.dashArray})}getOperationState(){var r,o,a,l,h;const t=((r=this.scaleButton)==null?void 0:r.isCurrentlyScaling())||((o=this.horizontalScaleButton)==null?void 0:o.isCurrentlyScaling())||((a=this.verticalScaleButton)==null?void 0:a.isCurrentlyScaling())||!1,i=((l=this.rotateButton)==null?void 0:l.isCurrentlyRotating())||!1,s=((h=this.moveButton)==null?void 0:h.isCurrentlyMoving())||!1;return{isDragging:!1,isScaling:t,isRotating:i,isMoving:s,hasAnyOperation:t||i||s}}stopAllOperations(){var t,i,s,r,o;(t=this.scaleButton)==null||t.stopScaling(),(i=this.horizontalScaleButton)==null||i.stopScaling(),(s=this.verticalScaleButton)==null||s.stopScaling(),(r=this.rotateButton)==null||r.stopRotation(),(o=this.moveButton)==null||o.stopMoving()}getControlButtonsContainer(){return this.controlButtons}getMoveButton(){return this.moveButton}calculateEdgeMidpoint(t,i){const s=this.calculateOutlinePoints();if(s.length<4)return{x:0,y:0};const r=s[t],o=s[i];return{x:(r.x+o.x)/2,y:(r.y+o.y)/2}}destroy(){var t,i,s,r,o,a,l,h,c,d,u;this.appService.emitter.off("antiScale",this.throttledUpdateOutline),this.throttledUpdateOutline.cancel(),this.appService.emitter.off("mapRotationUpdate",this.throttledUpdateOutline),(t=this.clickHandler)==null||t.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(),(l=this.verticalScaleButton)==null||l.destroy(),this.deleteButton=null,this.rotateButton=null,this.scaleButton=null,this.moveButton=null,this.horizontalScaleButton=null,this.verticalScaleButton=null,(h=this.outlineBorder)==null||h.destroy(),(c=this.moveLine)==null||c.destroy(),(d=this.sizeText)==null||d.destroy(),(u=this.controlButtons)==null||u.destroy(),super.destroy()}}function E0(n,e,t){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,...Se({showRotateButton:(t==null?void 0:t.showRotateButton)??n.showRotateButton,showScaleButton:(t==null?void 0:t.showScaleButton)??n.showScaleButton,showDeleteButton:(t==null?void 0:t.showDeleteButton)??n.showDeleteButton,showMoveButton:(t==null?void 0:t.showMoveButton)??n.showMoveButton}),showRadialScaleButton:t==null?void 0:t.showRadialScaleButton,rotateMode:t==null?void 0:t.rotateMode,scaleMode:"free",textColor:String(n.textColor),textPosition:n.textPosition,textOffset:n.textOffset,moveButtonOffset:e.moveButtonOffset,textFontSize:e.textFontSize,textFontFamily:e.textFontFamily,textFontWeight:e.textFontWeight}}function Gn(n,e){return{coords:n.coords,editControls:n.editControlManager,getZoneConfig:t=>k0(n,t),controlsConfig:n.getConfig().controls,makeControlFill:t=>new oa(n,t),makeBorder:t=>new De(n,t),makeCenterIcon:t=>new P0(n,t),render:{request:t=>n.getApp().requestRender(t,!0),stop:t=>n.getApp().stopRender(t)},events:e}}function k0(n,e){var i;const t=n.getConfig();if(Pe(e)){const s=t.controls[e];if(s)return s}else{const s=(i=t.customZoneTypes)==null?void 0:i[e];if(s)return s}return fc.cleanZone}class Un extends O{constructor(t){super();y(this,"zoneData");y(this,"zoneType");y(this,"zoneConfig");y(this,"controlsConfig");y(this,"zoneEvents");y(this,"deps");y(this,"controlFill");y(this,"zoneBorder");y(this,"editableShape");y(this,"centerIcon",null);y(this,"clickHandler",null);y(this,"initialZonePoints",[]);y(this,"dragStartPosition",null);y(this,"editing",!1);y(this,"disabled",!1);y(this,"resolvedMaxSizeCache",null);y(this,"handleDragStart",()=>{this.resolveVisualState()==="editing"&&(this.initialZonePoints=this.zoneData.points.map(t=>({...t})),this.dragStartPosition=this.controlFill.getDragStartPosition(),this.deps.render.request("zone-drag"))});y(this,"handleDragMove",t=>{if(this.resolveVisualState()!=="editing"||this.initialZonePoints.length===0||!this.dragStartPosition)return;const i=this.parent.toLocal(t.global),s=i.x-this.dragStartPosition.x,r=i.y-this.dragStartPosition.y;this.applyTranslation(s,r)});y(this,"handleDragEnd",()=>{var t,i;this.initialZonePoints=[],this.dragStartPosition=null,this.deps.render.stop("zone-drag"),(i=(t=this.zoneEvents).onUpdate)==null||i.call(t,this.getZoneData())});y(this,"handleRotationStart",()=>{this.deps.render.request("zone-rotate")});y(this,"handleRotationMove",t=>{t&&(this.zoneData.points=t,this.drawZone(!1))});y(this,"handleScaleStart",()=>{this.deps.render.request("zone-scale")});y(this,"handleScaleMove",t=>{t&&(this.zoneData.points=t,this.drawZone())});y(this,"handleMoveStart",()=>{this.initialZonePoints=this.zoneData.points.map(t=>({...t})),this.deps.render.request("zone-move")});y(this,"handleMove",t=>{var a;if(this.resolveVisualState()!=="editing"||this.initialZonePoints.length===0)return;const i=this.parent.toLocal(t.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)});y(this,"handleMoveEnd",()=>{var t,i;this.initialZonePoints=[],this.deps.render.stop("zone-move"),(i=(t=this.zoneEvents).onUpdate)==null||i.call(t,this.getZoneData())});y(this,"handleTransformEnd",()=>{var t,i;this.initialZonePoints=[],this.deps.render.stop("zone-rotate"),this.deps.render.stop("zone-scale"),(i=(t=this.zoneEvents).onUpdate)==null||i.call(t,this.getZoneData())});y(this,"handleDelete",()=>{var t,i;(i=(t=this.zoneEvents).onRemove)==null||i.call(t,this.zoneData.id)});y(this,"handleClick",()=>{var t,i;this.resolveVisualState()!=="editing"&&((i=(t=this.zoneEvents)==null?void 0:t.onClick)==null||i.call(t,this.getZoneData()))});const{deps:i,zoneData:s,zoneType:r}=t;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.applyVisualState()}getResolvedMaxSize(){const t=this.zoneConfig.maxSize;if(this.resolvedMaxSizeCache&&this.resolvedMaxSizeCache.key===t)return this.resolvedMaxSizeCache.value;const i=ne(this.zoneConfig.minSize,t,this.zoneType);return this.resolvedMaxSizeCache={key:t,value:i},i}validateZoneShape(t){if(t.length<4)return t;const i=this.getResolvedMaxSize();return this.deps.coords.validateShape(Fn(t),{minSize:et(this.zoneConfig.minSize),maxSize:i!=null?et(i):void 0})}initializeComponents(){this.controlFill=this.createControlFill(),this.addChild(this.controlFill),this.zoneBorder=this.createBorder(),this.addChild(this.zoneBorder);const t=this.zoneConfig.centerIcon;t&&(this.centerIcon=this.deps.makeCenterIcon(t),this.addChild(this.centerIcon),this.updateCenterIcon(this.zoneData.points))}createControlFill(){return this.deps.makeControlFill({points:this.zoneData.points,fillColor:this.zoneConfig.fillColor,enableInteraction:this.resolveVisualState()==="editing",onDragStart:this.handleDragStart,onDragMove:this.handleDragMove,onDragEnd:this.handleDragEnd})}createBorder(){return this.deps.makeBorder({points:this.zoneData.points,closePath:!0,style:this.resolveBorderStyle(this.resolveVisualState())})}createEditControlLayer(){const t=E0(this.zoneConfig,this.controlsConfig,{showRotateButton:this.zoneConfig.showRotateButton,showRadialScaleButton:!1,rotateMode:"free"});this.editableShape=new Es({editControls:this.deps.editControls});const i=this.getResolvedMaxSize(),s={config:t,zonePoints:this.zoneData.points,minSize:this.zoneConfig.minSize,maxSize:i??void 0,contentLayer:Te,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:{...Se(this.zoneConfig),showRadialScaleButton:!1,showBorder:!0,showSizeText:!0},idleState:{showRotateButton:!1,showScaleButton:!1,showRadialScaleButton:!1,showDeleteButton:!1,showMoveButton:!1,showBorder:!1,showSizeText:!1}})}applyTranslation(t,i){this.zoneData.points=this.initialZonePoints.map(s=>({x:s.x+t,y:s.y+i})),this.drawZone()}setupClickHandler(){this.interactiveChildren=!0,this.clickHandler=new yt(this,{onClick:this.handleClick,stopPropagation:!1})}drawZone(t=!0){const{points:i}=this.zoneData;i.length<4||(this.controlFill.updatePoints(i),this.zoneBorder.updatePoints(i),this.updateCenterIcon(i),this.editableShape.updatePoints(i,t))}updateCenterIcon(t){this.centerIcon&&this.centerIcon.updateGeometry(oe(t),I0(t))}resolveVisualState(){return Ii(this.editing,this.disabled)}applyVisualState(){var i,s;const t=this.resolveVisualState();t==="disabled"&&this.controlFill.interruptDragging(),this.controlFill.setInteractionEnabled(t==="editing"),this.controlFill.updateFillColor(t==="disabled"?((i=this.zoneConfig.disabled)==null?void 0:i.fillColor)??this.zoneConfig.fillColor:this.zoneConfig.fillColor),this.updateBorderStyle(this.resolveBorderStyle(t)),this.editableShape.setEditing(t==="editing"),(s=this.centerIcon)==null||s.setVisualState(t),this.alpha=t==="disabled"?Di(this.zoneConfig.disabled,this.controlsConfig.disabledStyle):1}resolveBorderStyle(t){if(t==="disabled"){const s=this.zoneConfig.disabled;return{color:(s==null?void 0:s.strokeColor)??this.zoneConfig.strokeColor,width:(s==null?void 0:s.strokeWidth)??this.zoneConfig.strokeWidth,isDashed:(s==null?void 0:s.isDashed)??this.zoneConfig.normal.isDashed,dashArray:(s==null?void 0:s.dashArray)??this.zoneConfig.normal.dashArray}}const i=t==="editing"?this.zoneConfig.editing:this.zoneConfig.normal;return{color:this.zoneConfig.strokeColor,width:this.zoneConfig.strokeWidth,isDashed:i.isDashed,dashArray:i.dashArray}}updateBorderStyle(t){this.zoneBorder.updateStyle(t)}setEditing(t){this.editing!==t&&(this.editing=t,this.applyVisualState())}isEditing(){return this.editing}setDisabled(t){this.disabled!==t&&(this.disabled=t,this.applyVisualState())}isDisabled(){return this.disabled}isLiftedForEditing(){return this.resolveVisualState()==="editing"}updateZoneData(t){const i=this.validateZoneShape(t.points);this.zoneData={...t,points:i},this.drawZone()}getZoneData(){return{...this.zoneData}}refreshDisplay(){this.drawZone()}destroy(){var t,i,s,r;this.editableShape.detach(),(t=this.clickHandler)==null||t.destroy(),this.clickHandler=null,(i=this.centerIcon)==null||i.destroy(),this.centerIcon=null,(s=this.zoneBorder)==null||s.destroy(),(r=this.controlFill)==null||r.destroy(),super.destroy()}}function I0(n){if(n.length<4)return 0;const e=(t,i)=>Math.hypot(i.x-t.x,i.y-t.y);return Math.min(e(n[0],n[1]),e(n[1],n[2]))}class aa extends Un{constructor(e,t){super({deps:Gn(e,{onRemove:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onRemoveForbiddenSweepZone)==null||r.call(s,i)},onUpdate:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onUpdateForbiddenSweepZone)==null||r.call(s,i)},onClick:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onClickForbiddenSweepZone)==null||r.call(s,i)}}),zoneData:t.zoneData,zoneType:"forbiddenSweepZone"})}static create(e,t){return new aa(e,{zoneData:t})}}class la extends Un{constructor(e,t){super({deps:Gn(e,{onRemove:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onRemoveForbiddenMopZone)==null||r.call(s,i)},onUpdate:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onUpdateForbiddenMopZone)==null||r.call(s,i)},onClick:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onClickForbiddenMopZone)==null||r.call(s,i)}}),zoneData:t.zoneData,zoneType:"forbiddenMopZone"})}static create(e,t){return new la(e,{zoneData:t})}}class ha extends Un{constructor(e,t){super({deps:Gn(e,{onRemove:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onRemoveCleanZone)==null||r.call(s,i)},onUpdate:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onUpdateCleanZone)==null||r.call(s,i)},onClick:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onClickCleanZone)==null||r.call(s,i)}}),zoneData:t.zoneData,zoneType:"cleanZone"})}static create(e,t){return new ha(e,{zoneData:t})}}class ci extends W{constructor(t,i){super();y(this,"lineOptions");y(this,"strokeContext",null);y(this,"drawDashLine",()=>{const{start:t,end:i,style:s}=this.lineOptions;this.clear(),this.strokeContext&&this.strokeContext.destroy();const r=this.appService;this.strokeContext=new J;const o=r.getApp().toFixedSize(s.width);this.strokeContext.setStrokeStyle({color:s.color,width:o}),this.drawDashedLineToContext(this.strokeContext,t.x,t.y,i.x,i.y,s.dashArray[0],s.dashArray[1]),this.strokeContext.stroke(),this.context=this.strokeContext});this.appService=t,this.lineOptions={...i},this.eventMode="static",this.drawDashLine(),this.setupAntiScaleListener()}setupAntiScaleListener(){this.appService.emitter.on("antiScale",this.drawDashLine)}drawDashedLineToContext(t,i,s,r,o,a,l){const h=r-i,c=o-s,d=Math.sqrt(h*h+c*c);if(d===0)return;const u=this.appService,p=u.getApp().toFixedSize(a),f=u.getApp().toFixedSize(l),m=p+f,g=d/m,x=Math.round(g);if(x===0){t.moveTo(i,s),t.lineTo(r,o);return}const S=d/x,b=S*(p/m),w=h/d,_=c/d;for(let v=0;v<x;v++){const C=v*S,P=C+b;if(C>=d)break;const A=Math.min(P,d),R=i+C*w,T=s+C*_,E=i+A*w,I=s+A*_;t.moveTo(R,T),t.lineTo(E,I)}}updatePoints(t,i){this.lineOptions.start=t,this.lineOptions.end=i,this.drawDashLine()}updateStyle(t){this.lineOptions.style={...this.lineOptions.style,...t},this.drawDashLine()}getOptions(){return{...this.lineOptions}}destroy(){this.appService.emitter.off("antiScale",this.drawDashLine),this.strokeContext&&this.strokeContext.destroy(),super.destroy()}}const te=class te extends O{constructor(t){super();y(this,"wallData");y(this,"wallConfig");y(this,"controlsConfig");y(this,"wallEvents");y(this,"appService");y(this,"wallLine");y(this,"outlineBorder");y(this,"moveLine");y(this,"lengthText");y(this,"controlButtons");y(this,"removeButton",null);y(this,"scaleButton",null);y(this,"moveButton",null);y(this,"initialWallPoints",[]);y(this,"initialButtonPosition",null);y(this,"isDragging",!1);y(this,"dragStartPosition",null);y(this,"gestureSession",null);y(this,"resolvedMaxWidthCache",null);y(this,"throttledUpdateOutline");y(this,"throttledHandleScaleChange");y(this,"wallLineClickHandler",null);y(this,"handleRemove",()=>{var t,i;(i=(t=this.wallEvents).onRemove)==null||i.call(t,this.wallData.id)});y(this,"initializeOperation",()=>{this.initialWallPoints=this.wallData.points.map(t=>({...t}))});y(this,"finalizeOperation",()=>{var t,i;this.initialWallPoints=[],(i=(t=this.wallEvents).onUpdate)==null||i.call(t,this.getWallData())});y(this,"handleScaleStart",()=>{this.initializeOperation();const t=this.calculateOutlinePoints();t.length>te.BUTTON_INDICES.SCALE&&(this.initialButtonPosition={...t[te.BUTTON_INDICES.SCALE]}),this.appService.getApp().requestRender("virtualwall-scale",!0)});y(this,"handleScaleMove",({deltaX:t,deltaY:i})=>{if(this.initialWallPoints.length===0||!this.initialButtonPosition)return;const s={x:this.initialButtonPosition.x+t,y:this.initialButtonPosition.y+i};this.applyScaleAndRotation(s)});y(this,"handleScaleEnd",()=>{this.finalizeOperation(),this.initialButtonPosition=null,this.appService.getApp().stopRender("virtualwall-scale")});y(this,"handleMoveStart",()=>{this.initializeOperation(),this.appService.getApp().requestRender("virtualwall-move",!0)});y(this,"handleMove",t=>{var a;if(this.initialWallPoints.length===0)return;const i=this.parent.toLocal(t.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)});y(this,"handleMoveEnd",()=>{this.finalizeOperation(),this.appService.getApp().stopRender("virtualwall-move")});y(this,"handleScaleChange",()=>{this.redrawSolidLine(),this.setupWallLineHitArea()});y(this,"handleWallLinePointerDown",t=>{this.resolveVisualState()==="editing"&&(t.stopPropagation(),this.startDragging(t))});y(this,"handleDragPointerMove",t=>{!this.isDragging||!this.dragStartPosition||this.handleMove(t)});y(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={}}=t;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=Pt(this.handleScaleChange.bind(this),30,{leading:!0,trailing:!0}),this.throttledUpdateOutline=Pt(this.updateOutlineForScale.bind(this),30,{leading:!0,trailing:!0}),this.initializeComponents(),this.updateEditState(),this.registerScaleListener()}getDiagnosticPart(t){return{delete:this.removeButton,scale:this.scaleButton,move:this.moveButton}[t]??null}registerScaleListener(){this.appService.emitter.on("antiScale",this.throttledUpdateOutline),this.appService.emitter.on("antiScale",this.throttledHandleScaleChange),this.appService.emitter.on("mapRotationUpdate",this.throttledUpdateOutline)}getResolvedMaxWidth(){const t=this.wallConfig.maxWidth;if(this.resolvedMaxWidthCache&&this.resolvedMaxWidthCache.key===t)return this.resolvedMaxWidthCache.value;const i=ne(this.wallConfig.minWidth,t,"virtualWall");return this.resolvedMaxWidthCache={key:t,value:i},i}validateAndCorrectWallLength(t){if(t.length<2)return t;const[i,s]=t,{coords:r}=this.appService,o=r.toPixels(et(this.wallConfig.minWidth)),a=this.getResolvedMaxWidth(),l=a!=null?r.toPixels(et(a)):void 0,h=q(i,s),c=h<o,d=l!=null&&h>l;if(!c&&!d)return t;if(h===0)return[i,{x:i.x+o,y:i.y}];const u=se(Mt(i,s));let p=h;return l!=null&&(p=Math.min(p,l)),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)}isDisabledEnabled(){return this.appService.runtimeSnapshot.disabledVirtualWallIds.includes(this.wallData.id)}resolveVisualState(){return Ii(this.isEditingEnabled(),this.isDisabledEnabled())}isLiftedForEditing(){return this.resolveVisualState()==="editing"}updateOutlineForScale(){this.resolveVisualState()==="editing"&&(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 O,this.controlButtons.visible=this.resolveVisualState()==="editing",this.addChild(this.controlButtons),this.createControlButtons()}createWallLine(t=!0){const{points:i}=this.wallData;if(i.length<2)return;const s=this.resolveWallLineStyle();s.isDashed?this.wallLine=new ci(this.appService,{start:i[0],end:i[1],style:{color:s.color,width:s.width,dashArray:s.dashArray}}):this.wallLine=this.createSolidLine(i[0],i[1],s.width,s.color),t&&this.setupWallLineInteraction()}createLengthText(){const t=this.calculateWallLengthInMeters(),i=this.formatLengthText(t),s=new Tn(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:t}=this.wallData;if(t.length<2)return 0;const i=q(t[0],t[1]);return this.appService.coords.toMeters(Gt(i))}formatLengthText(t){const i=this.appService.coords.toDisplayUnit(et(t)),s=this.appService.runtimeSnapshot.unitLabel;return`${i.toFixed(1)}${s}`}calculateTextPosition(){const{points:t}=this.wallData;if(t.length<2)return{x:0,y:0};const[i,s]=t,r=this.appService.getApp().toFixedSize(this.wallConfig.textOffset);return pu(i,s,r)}calculateTextRotation(){const{points:t}=this.wallData;if(t.length<2)return 0;const[i,s]=t,r=this.appService.appContainer.getMapRotationRadians();return hn(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 t=this.calculateOutlinePoints();return new De(this.appService,{points:t,closePath:!0,style:this.getOutlineStyle()})}createMoveLine(){const t=this.calculateOutlinePoints(),i=this.calculateMoveLinePoints(t);return new De(this.appService,{points:i,closePath:!1,style:this.getOutlineStyle()})}calculateOutlinePoints(t){const i=t||this.wallData.points;if(i.length<2)return i;const s=this.appService.getApp().toFixedSize(this.wallConfig.outlineOffset),r=fb(i[0],i[1],s);return[r[3],r[2],r[1],r[0]]}calculateMoveLinePoints(t){if(t.length<4)return[];const{MOVE:i}=te.BUTTON_INDICES,s=t[i],r=this.calculateMoveButtonPosition();return[s,r]}calculateMoveButtonPosition(){const{moveButtonOffset:t}=this.controlsConfig,i=this.calculateOutlinePoints();if(i.length<4)return{x:0,y:0};const{MOVE:s}=te.BUTTON_INDICES,r=i[s],o=i[(s+3)%4],a=i[(s+1)%4],l=this.appService.getApp().toFixedSize(t);return gu(r,a,o,l)}createControlButtons(){const t=this.calculateOutlinePoints();if(t.length<4)return;const{REMOVE:i,SCALE:s}=te.BUTTON_INDICES;this.removeButton=new hp(this.appService,{iconAlias:"deleteIcon",backgroundColor:this.wallConfig.iconWrapperFillColor,onClick:this.handleRemove}),this.removeButton.position.set(t[i].x,t[i].y),this.scaleButton=new pn(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(t[s].x,t[s].y);const r=this.calculateMoveButtonPosition();this.moveButton=new lp(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(t){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[te.BUTTON_INDICES.SCALE],l=s,h=Mt(r,l),c=q(r,l),d=Math.atan2(h.y,h.x),u=Mt(r,a),p=u.x*Math.cos(d)+u.y*Math.sin(d),f=-u.x*Math.sin(d)+u.y*Math.cos(d),m=p-c,g=Mt(r,t),x=q(r,t),{coords:S}=this.appService,b=S.toPixels(et(this.wallConfig.minWidth)),w=this.getResolvedMaxWidth(),_=w!=null?S.toPixels(et(w)):void 0;let v,C;if(x<1e-4)v=d,C=0;else{const E=Math.atan2(g.y,g.x),I=Math.sqrt(Math.max(0,x*x-f*f)),F=Math.atan2(f,Math.max(0,I));v=E-F,C=I-m}let P=C;P<b?P=b:_!=null&&P>_&&(P=_);const A=r.x+P*Math.cos(v),R=r.y+P*Math.sin(v),T={x:Math.abs(A)<1e-10?0:A,y:Math.abs(R)<1e-10?0:R};this.wallData.points=[r,T],this.drawVirtualWall(),this.updateControlButtonsPosition()}applyTranslation(t,i){this.wallData.points=this.initialWallPoints.map(s=>({x:s.x+t,y:s.y+i})),this.drawVirtualWall(),this.updateControlButtonsPosition()}drawVirtualWall(){this.updateWallLine(),this.updateLengthText(),this.updateOutlineComponents()}updateWallLine(){const{points:t}=this.wallData;t.length<2||(this.wallLine instanceof ci?this.wallLine.updatePoints(t[0],t[1]):this.redrawSolidLine(),this.setupWallLineHitArea())}updateLengthText(){if(!this.lengthText)return;const t=this.calculateWallLengthInMeters(),i=this.formatLengthText(t);this.lengthText.updateText(i),this.updateLengthTextPosition()}updateLengthTextPosition(){if(!this.lengthText)return;const t=this.calculateTextPosition();this.lengthText.position.set(t.x,t.y);const i=this.calculateTextRotation();this.lengthText.rotation=i}updateOutlineComponents(){const t=this.calculateOutlinePoints();this.outlineBorder.updatePoints(t);const i=this.calculateMoveLinePoints(t);this.moveLine.updatePoints(i)}updateControlButtonsPosition(){if(!this.removeButton||!this.scaleButton||!this.moveButton)return;const t=this.calculateOutlinePoints();if(t.length<4)return;const{REMOVE:i,SCALE:s}=te.BUTTON_INDICES,r=this.calculateMoveButtonPosition();this.removeButton.position.set(t[i].x,t[i].y),this.scaleButton.position.set(t[s].x,t[s].y),this.moveButton.position.set(r.x,r.y)}updateEditState(){const t=this.resolveVisualState(),i=t==="editing",s=C0(this.wallConfig);t==="disabled"&&this.interruptActiveOperations(),this.controlButtons.visible=i,this.removeButton&&(this.removeButton.visible=s.showDeleteButton),this.scaleButton&&(this.scaleButton.visible=s.showScaleButton),this.moveButton&&(this.moveButton.visible=s.showMoveButton),this.outlineBorder.visible=i,this.moveLine.visible=i&&s.showMoveButton,this.lengthText&&(this.lengthText.visible=i),i&&(this.updateOutlineComponents(),this.updateControlButtonsPosition(),this.updateLengthTextPosition()),this.updateWallLineStyle(),this.setupWallLineInteraction(),this.alpha=t==="disabled"?Di(this.wallConfig.disabled,this.controlsConfig.disabledStyle):1}interruptActiveOperations(){var t,i,s;(t=this.gestureSession)==null||t.cancel(),(i=this.scaleButton)==null||i.stopScaling(),(s=this.moveButton)==null||s.stopMoving()}createSolidLine(t,i,s,r){const o=new W;o.eventMode="static";const a=this.appService.getApp().toFixedSize(s);return o.moveTo(t.x,t.y),o.lineTo(i.x,i.y),o.stroke({color:r,width:a}),o}updateWallLineStyle(){const t=this.resolveWallLineStyle();this.wallLine instanceof ci!==t.isDashed?(this.removeChild(this.wallLine),this.wallLine.destroy(),this.createWallLine(!1),this.addChild(this.wallLine)):this.wallLine instanceof ci?this.wallLine.updateStyle({color:t.color,width:t.width,dashArray:t.dashArray}):this.redrawSolidLine()}resolveWallLineStyle(){const{editing:t,normal:i,lineWidth:s,lineColor:r,disabled:o}=this.wallConfig,a=this.resolveVisualState();if(a==="disabled")return{color:((o==null?void 0:o.lineColor)??r).toString(),width:(o==null?void 0:o.lineWidth)??s,isDashed:(o==null?void 0:o.isDashed)??i.isDashed,dashArray:(o==null?void 0:o.dashArray)??i.dashArray};const l=a==="editing"?t:i;return{color:r.toString(),width:s,isDashed:l.isDashed,dashArray:l.dashArray}}redrawSolidLine(){const t=this.appService;if(!this.wallLine||this.wallLine instanceof ci)return;const{points:i}=this.wallData;if(i.length<2)return;const s=this.resolveWallLineStyle(),r=t.getApp().toFixedSize(s.width);this.wallLine.clear(),this.wallLine.setStrokeStyle({color:s.color,width:r}).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 t=this.resolveVisualState()==="editing";(i=this.wallLineClickHandler)==null||i.destroy(),this.wallLineClickHandler=null,this.wallLine.off("pointerdown",this.handleWallLinePointerDown),t?this.wallLine.on("pointerdown",this.handleWallLinePointerDown):this.wallLineClickHandler=new yt(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(t){const i=this.appService;this.isDragging=!0;const s=this.parent.toLocal(t.global);this.dragStartPosition={x:s.x,y:s.y},this.initializeOperation(),i.getApp().requestRender("virtualwall-drag",!0),this.gestureSession=this.appService.gestureController.hijack(t),this.gestureSession.onMove(this.handleDragPointerMove),this.gestureSession.onEnd(this.handleDragPointerUp)}getDragStartPosition(){return this.dragStartPosition}setupWallLineHitArea(){if(!this.wallLine)return;const{points:t}=this.wallData;if(t.length<2)return;const{hitAreaThickness:i}=this.wallConfig,s=this.appService.getApp().toFixedSize(i),r=fu(t[0],t[1],s);if(r.length===0)return;const o=new Ze(r);this.wallLine.hitArea=o}getWallData(){return{...this.wallData}}updateWallData(t){this.wallData={...t,points:this.validateAndCorrectWallLength(t.points)},this.drawVirtualWall(),this.updateControlButtonsPosition()}updateEditingState(){this.updateEditState()}refreshDisplay(){this.drawVirtualWall()}destroy(){var t,i,s,r,o,a,l,h,c,d;this.appService.emitter.off("antiScale",this.throttledUpdateOutline),this.appService.emitter.off("antiScale",this.throttledHandleScaleChange),this.throttledUpdateOutline.cancel(),this.throttledHandleScaleChange.cancel(),this.appService.emitter.off("mapRotationUpdate",this.throttledUpdateOutline),this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null),(t=this.gestureSession)==null||t.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(),(l=this.controlButtons)==null||l.destroy(),(h=this.removeButton)==null||h.destroy(),(c=this.scaleButton)==null||c.destroy(),(d=this.moveButton)==null||d.destroy(),this.removeButton=null,this.scaleButton=null,this.moveButton=null,super.destroy()}};y(te,"BUTTON_INDICES",{REMOVE:0,SCALE:2,MOVE:3});let Mo=te;class D0 extends O{constructor(t){super();y(this,"thresholdData");y(this,"thresholdConfig");y(this,"thresholdEvents");y(this,"appService");y(this,"band");y(this,"bandFill");y(this,"bandStripes");y(this,"bandBorder");y(this,"stripesMask");y(this,"editableShape");y(this,"bandClickHandler",null);y(this,"lastVisualState",null);y(this,"initialPoints",null);y(this,"isDragging",!1);y(this,"hasDragMoved",!1);y(this,"dragStartPosition",null);y(this,"gestureSession",null);y(this,"resolvedMaxLengthCache",null);y(this,"resolvedMaxHeightCache",null);y(this,"throttledRedraw");y(this,"resolveSizeConstraintPerEdge",()=>({edge1:{min:this.thresholdConfig.minLength,max:this.getResolvedMaxLength()},edge2:{min:this.thresholdConfig.minHeight,max:this.getResolvedMaxHeight()}}));y(this,"handleRemove",()=>{var t,i;(i=(t=this.thresholdEvents).onRemove)==null||i.call(t,this.thresholdData.id)});y(this,"handleRotateStart",()=>{this.appService.getApp().requestRender("threshold-rotate",!0)});y(this,"handleRotateMove",t=>{t&&(this.setFromQuad(t),this.refreshAfterGeometryChange())});y(this,"handleRotateEnd",()=>{var t,i;this.appService.getApp().stopRender("threshold-rotate"),(i=(t=this.thresholdEvents).onUpdate)==null||i.call(t,this.getThresholdData())});y(this,"handleScaleStart",()=>{this.appService.getApp().requestRender("threshold-scale",!0)});y(this,"handleScaleMove",t=>{t&&(this.setFromQuad(t),this.refreshAfterGeometryChange())});y(this,"handleScaleEnd",()=>{var t,i;this.appService.getApp().stopRender("threshold-scale"),(i=(t=this.thresholdEvents).onUpdate)==null||i.call(t,this.getThresholdData())});y(this,"handleMoveStart",()=>{this.initialPoints=this.clonePoints(),this.appService.getApp().requestRender("threshold-move",!0)});y(this,"handleMoveMove",t=>{var r;if(!this.initialPoints||!this.parent)return;const i=this.parent.toLocal(t.global),s=(r=this.editableShape.getMoveButton())==null?void 0:r.getDragStartPosition();s&&this.applyTranslation(i.x-s.x,i.y-s.y)});y(this,"handleMoveEnd",()=>{var t,i;this.initialPoints=null,this.appService.getApp().stopRender("threshold-move"),(i=(t=this.thresholdEvents).onUpdate)==null||i.call(t,this.getThresholdData())});y(this,"handleBandPointerDown",t=>{this.resolveVisualState()==="editing"&&(t.stopPropagation(),this.startDragging(t))});y(this,"handleDragPointerMove",t=>{if(!this.isDragging||!this.dragStartPosition||!this.initialPoints)return;this.hasDragMoved=!0;const i=this.parent.toLocal(t.global);this.applyTranslation(i.x-this.dragStartPosition.x,i.y-this.dragStartPosition.y)});y(this,"handleDragPointerUp",()=>{var t,i;this.gestureSession=null,this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null,this.initialPoints=null,this.appService.getApp().stopRender("threshold-drag"),this.hasDragMoved&&(this.hasDragMoved=!1,(i=(t=this.thresholdEvents).onUpdate)==null||i.call(t,this.getThresholdData())))});const{appService:i,thresholdData:s,events:r={}}=t;this.appService=i,this.thresholdEvents=r,this.thresholdConfig=i.controlsConfig.threshold,this.thresholdData=this.validateAndCorrect(s),this.band=new O,this.bandFill=new W,this.bandStripes=new W,this.bandBorder=new W,this.stripesMask=new W,this.bandFill.eventMode="none",this.bandStripes.eventMode="none",this.bandBorder.eventMode="none",this.stripesMask.eventMode="none",this.bandStripes.mask=this.stripesMask,this.band.addChild(this.bandFill),this.band.addChild(this.bandStripes),this.band.addChild(this.bandBorder),this.band.addChild(this.stripesMask),this.addChild(this.band),this.drawBand(),this.eventMode="passive",this.setupBandInteraction(),this.editableShape=this.createEditControls(),this.updateEditState(),this.throttledRedraw=Pt(this.handleScaleChange.bind(this),30,{leading:!0,trailing:!0}),this.appService.emitter.on("antiScale",this.throttledRedraw)}getThresholdData(){return{...this.thresholdData,points:this.clonePoints()}}updateThresholdData(t){this.thresholdData=this.validateAndCorrect(t),this.refreshAfterGeometryChange()}updateEditingState(){this.updateEditState()}refreshDisplay(){this.editableShape.updatePoints(this.getQuadPoints())}isEditingEnabled(){return this.appService.runtimeSnapshot.editingThresholdIds.includes(this.thresholdData.id)}isDisabledEnabled(){return this.appService.runtimeSnapshot.disabledThresholdIds.includes(this.thresholdData.id)}resolveVisualState(){return Ii(this.isEditingEnabled(),this.isDisabledEnabled())}isLiftedForEditing(){return this.resolveVisualState()==="editing"}resolveEditingState(){return{...Se(this.thresholdConfig),showRadialScaleButton:!1,showBorder:!0,showSizeText:!0}}updateEditState(){var o;const t=this.resolveVisualState(),i=t==="editing";t==="disabled"&&((o=this.gestureSession)==null||o.cancel()),i?this.editableShape.applyEditState(this.resolveEditingState()):this.editableShape.setEditing(!1);const s=this.lastVisualState==="disabled",r=t==="disabled";this.lastVisualState=t,this.alpha=r?Di(this.thresholdConfig.disabled,this.appService.controlsConfig.disabledStyle):1,s!==r&&this.drawBand()}getQuadPoints(){return this.clonePoints()}setFromQuad(t){t.length<4||(this.thresholdData={...this.thresholdData,points:t.map(i=>({...i}))})}getBandFrame(){const[t,i,s,r]=this.thresholdData.points,o={x:(t.x+r.x)/2,y:(t.y+r.y)/2},a={x:(i.x+s.x)/2,y:(i.y+s.y)/2};return{origin:o,rotation:Math.atan2(a.y-o.y,a.x-o.x),length:q(o,a),thickness:q(t,r)}}createEditControls(){const t=this.thresholdConfig,i=this.appService.controlsConfig,s=new Es({editControls:this.appService.editControlManager}),r={config:{outlineStrokeColor:t.outlineStrokeColor,outlineStrokeWidth:t.outlineStrokeWidth,outlineDashed:t.outlineDashed,outlineDashArray:t.outlineDashArray,outlineFillColor:t.outlineFillColor,outlineOffset:t.outlineOffset,iconWrapperFillColor:t.iconWrapperFillColor,...Se(t),showRadialScaleButton:!1,rotateMode:"free",scaleMode:"free",textColor:t.textColor,textPosition:"top",textOffset:t.textOffset,moveButtonOffset:i.moveButtonOffset,textFontSize:i.textFontSize,textFontFamily:i.textFontFamily,textFontWeight:i.textFontWeight},zonePoints:this.getQuadPoints(),sizeConstraintPerEdge:this.resolveSizeConstraintPerEdge,contentLayer:Pi,events:{onRemove:this.handleRemove,onRotateStart:this.handleRotateStart,onRotateMove:this.handleRotateMove,onRotateEnd:this.handleRotateEnd,onScaleStart:this.handleScaleStart,onScaleMove:this.handleScaleMove,onScaleEnd:this.handleScaleEnd,onMoveStart:this.handleMoveStart,onMoveMove:this.handleMoveMove,onMoveEnd:this.handleMoveEnd}};return s.attach(this,{id:this.thresholdData.id,topology:"quad",layerOptions:r,editingState:this.resolveEditingState(),idleState:{showRotateButton:!1,showScaleButton:!1,showRadialScaleButton:!1,showDeleteButton:!1,showMoveButton:!1,showBorder:!1,showSizeText:!1}}),s}setupBandInteraction(){this.updateBandHitArea(),this.bandClickHandler=new yt(this.band,{onClick:()=>{var t,i;this.appService.gestureController.suppressMapClick(),(i=(t=this.thresholdEvents).onClick)==null||i.call(t,this.getThresholdData())},stopPropagation:!1}),this.band.on("pointerdown",this.handleBandPointerDown)}updateBandHitArea(){const t=this.getBandFrame(),i=this.appService.getApp().toFixedSize(this.thresholdConfig.hitAreaPadding),s=t.thickness+i*2;this.band.hitArea=new st(0,-s/2,t.length,s)}startDragging(t){this.isDragging=!0,this.hasDragMoved=!1;const i=this.parent.toLocal(t.global);this.dragStartPosition={x:i.x,y:i.y},this.initialPoints=this.clonePoints(),this.appService.getApp().requestRender("threshold-drag",!0),this.gestureSession=this.appService.gestureController.hijack(t),this.gestureSession.onMove(this.handleDragPointerMove),this.gestureSession.onEnd(this.handleDragPointerUp)}applyTranslation(t,i){this.initialPoints&&(this.thresholdData={...this.thresholdData,points:this.initialPoints.map(s=>({x:s.x+t,y:s.y+i}))},this.refreshAfterGeometryChange())}refreshAfterGeometryChange(){this.drawBand(),this.updateBandHitArea(),this.editableShape.updatePoints(this.getQuadPoints())}clonePoints(){return this.thresholdData.points.map(t=>({...t}))}handleScaleChange(){this.drawBand(),this.updateBandHitArea()}getResolvedMaxLength(){const t=this.thresholdConfig.maxLength;if(this.resolvedMaxLengthCache&&this.resolvedMaxLengthCache.key===t)return this.resolvedMaxLengthCache.value;const i=ne(this.thresholdConfig.minLength,t,"threshold");return this.resolvedMaxLengthCache={key:t,value:i},i}getResolvedMaxHeight(){const t=this.thresholdConfig.maxHeight;if(this.resolvedMaxHeightCache&&this.resolvedMaxHeightCache.key===t)return this.resolvedMaxHeightCache.value;const i=ne(this.thresholdConfig.minHeight,t,"threshold.height");return this.resolvedMaxHeightCache={key:t,value:i},i}validateAndCorrect(t){return{...t,points:this.normalizeQuad(t.points),type:t.type??"passable"}}normalizeQuad(t){if(!Jo(t))return t.map(a=>({...a}));const i=db(lu(Fn(t))),s=ou(i),r=this.getResolvedMaxLength(),o=this.getResolvedMaxHeight();return this.appService.coords.validateShape(s,{edge1:{min:et(this.thresholdConfig.minLength),max:r!=null?et(r):void 0},edge2:{min:et(this.thresholdConfig.minHeight),max:o!=null?et(o):void 0}})}getTypeStyle(){var r,o;const t=this.thresholdData.type==="passable",i=t?this.thresholdConfig.passable:this.thresholdConfig.impassable;if(this.resolveVisualState()!=="disabled")return i;const s=t?(r=this.thresholdConfig.disabled)==null?void 0:r.passable:(o=this.thresholdConfig.disabled)==null?void 0:o.impassable;return s?{...i,...s}:i}drawBand(){const{stripeWidth:t,stripeGap:i,stripeDirection:s,borderWidth:r,cornerRadius:o}=this.thresholdConfig,a=this.getTypeStyle(),l=this.appService.getApp(),h=this.getBandFrame(),{length:c,thickness:d}=h,u=l.toFixedSize(r);if(this.bandFill.clear(),this.bandStripes.clear(),this.bandBorder.clear(),this.stripesMask.clear(),c===0||d===0)return;this.band.position.set(h.origin.x,h.origin.y),this.band.rotation=h.rotation;const p=d/2,f=Math.min(l.toFixedSize(o),p,c/2);this.bandFill.roundRect(0,-p,c,d,f).fill(a.fillColor),this.bandBorder.roundRect(0,-p,c,d,f).stroke({color:a.color,width:u}),this.stripesMask.roundRect(0,-p,c,d,f).fill(16777215);const m=t*d,g=m+i*d;if(g<=0)return;const x=s==="backward"?1:-1,b=p+m,w=2*b/Math.tan(this.getStripeAngleRadians());let _=!1;for(let v=-w;v<c;v+=g)this.bandStripes.moveTo(v,-b*x).lineTo(v+w,b*x),_=!0;_&&this.bandStripes.stroke({color:a.color,width:m})}getStripeAngleRadians(){const t=this.thresholdConfig.stripeAngle;return(Number.isFinite(t)?Math.min(90,Math.max(10,t)):45)*Math.PI/180}destroy(){var t,i;this.appService.emitter.off("antiScale",this.throttledRedraw),this.throttledRedraw.cancel(),this.editableShape.detach(),this.isDragging&&(this.isDragging=!1,this.hasDragMoved=!1,this.dragStartPosition=null,this.initialPoints=null),(t=this.gestureSession)==null||t.cancel(),this.gestureSession=null,this.band.off("pointerdown",this.handleBandPointerDown),(i=this.bandClickHandler)==null||i.destroy(),this.bandClickHandler=null,this.bandStripes.mask=null,this.bandFill.destroy(),this.bandStripes.destroy(),this.bandBorder.destroy(),this.stripesMask.destroy(),this.band.destroy(),super.destroy()}}const F0=6,B0=160,L0=32,tc=(n,e)=>Math.max(1,Math.min(Math.round(n)||1,e));class z0 extends O{constructor(t){super();y(this,"rampData");y(this,"rampConfig");y(this,"rampEvents");y(this,"appService");y(this,"body");y(this,"bodyFill");y(this,"bodyStripes");y(this,"bodyBorder");y(this,"stripesMask");y(this,"editableShape");y(this,"bodyClickHandler",null);y(this,"lastVisualState",null);y(this,"initialPoints",null);y(this,"isDragging",!1);y(this,"hasDragMoved",!1);y(this,"dragStartPosition",null);y(this,"gestureSession",null);y(this,"resolvedMaxWidthCache",null);y(this,"resolvedMaxHeightCache",null);y(this,"throttledRedraw");y(this,"resolveSizeConstraintPerEdge",()=>({edge1:{min:this.rampConfig.minWidth,max:this.getResolvedMaxWidth()},edge2:{min:this.rampConfig.minHeight,max:this.getResolvedMaxHeight()}}));y(this,"handleRemove",()=>{var t,i;(i=(t=this.rampEvents).onRemove)==null||i.call(t,this.rampData.id)});y(this,"handleRotateStart",()=>{this.appService.getApp().requestRender("ramp-rotate",!0)});y(this,"handleRotateMove",t=>{t&&(this.setFromQuad(t),this.refreshAfterGeometryChange())});y(this,"handleRotateEnd",()=>{var t,i;this.appService.getApp().stopRender("ramp-rotate"),(i=(t=this.rampEvents).onUpdate)==null||i.call(t,this.getRampData())});y(this,"handleScaleStart",()=>{this.appService.getApp().requestRender("ramp-scale",!0)});y(this,"handleScaleMove",t=>{t&&(this.setFromQuad(t),this.refreshAfterGeometryChange())});y(this,"handleScaleEnd",()=>{var t,i;this.appService.getApp().stopRender("ramp-scale"),(i=(t=this.rampEvents).onUpdate)==null||i.call(t,this.getRampData())});y(this,"handleMoveStart",()=>{this.initialPoints=this.clonePoints(),this.appService.getApp().requestRender("ramp-move",!0)});y(this,"handleMoveMove",t=>{var r;if(!this.initialPoints||!this.parent)return;const i=this.parent.toLocal(t.global),s=(r=this.editableShape.getMoveButton())==null?void 0:r.getDragStartPosition();s&&this.applyTranslation(i.x-s.x,i.y-s.y)});y(this,"handleMoveEnd",()=>{var t,i;this.initialPoints=null,this.appService.getApp().stopRender("ramp-move"),(i=(t=this.rampEvents).onUpdate)==null||i.call(t,this.getRampData())});y(this,"handleBodyPointerDown",t=>{this.resolveVisualState()==="editing"&&(t.stopPropagation(),this.startDragging(t))});y(this,"handleDragPointerMove",t=>{if(!this.isDragging||!this.dragStartPosition||!this.initialPoints)return;this.hasDragMoved=!0;const i=this.parent.toLocal(t.global);this.applyTranslation(i.x-this.dragStartPosition.x,i.y-this.dragStartPosition.y)});y(this,"handleDragPointerUp",()=>{var t,i;this.gestureSession=null,this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null,this.initialPoints=null,this.appService.getApp().stopRender("ramp-drag"),this.hasDragMoved&&(this.hasDragMoved=!1,(i=(t=this.rampEvents).onUpdate)==null||i.call(t,this.getRampData())))});const{appService:i,rampData:s,events:r={}}=t;this.appService=i,this.rampEvents=r,this.rampConfig=i.controlsConfig.ramp,this.rampData=this.validateAndCorrect(s),this.body=new O,this.bodyFill=new W,this.bodyStripes=new W,this.bodyBorder=new W,this.stripesMask=new W,this.bodyFill.eventMode="none",this.bodyStripes.eventMode="none",this.bodyBorder.eventMode="none",this.stripesMask.eventMode="none",this.bodyStripes.mask=this.stripesMask,this.body.addChild(this.bodyFill),this.body.addChild(this.bodyStripes),this.body.addChild(this.bodyBorder),this.body.addChild(this.stripesMask),this.addChild(this.body),this.drawBody(),this.eventMode="passive",this.setupBodyInteraction(),this.editableShape=this.createEditControls(),this.updateEditState(),this.throttledRedraw=Pt(this.handleScaleChange.bind(this),30,{leading:!0,trailing:!0}),this.appService.emitter.on("antiScale",this.throttledRedraw)}getRampData(){return{...this.rampData,points:this.clonePoints()}}updateRampData(t){this.rampData=this.validateAndCorrect(t),this.refreshAfterGeometryChange()}updateEditingState(){this.updateEditState()}refreshDisplay(){this.editableShape.updatePoints(this.getQuadPoints())}isEditingEnabled(){return this.appService.runtimeSnapshot.editingRampIds.includes(this.rampData.id)}isDisabledEnabled(){return this.appService.runtimeSnapshot.disabledRampIds.includes(this.rampData.id)}resolveVisualState(){return Ii(this.isEditingEnabled(),this.isDisabledEnabled())}isLiftedForEditing(){return this.resolveVisualState()==="editing"}resolveEditingState(){return{...Se(this.rampConfig),showRadialScaleButton:!1,showBorder:!0,showSizeText:!0}}updateEditState(){var o;const t=this.resolveVisualState(),i=t==="editing";t==="disabled"&&((o=this.gestureSession)==null||o.cancel()),i?this.editableShape.applyEditState(this.resolveEditingState()):this.editableShape.setEditing(!1);const s=this.lastVisualState==="disabled",r=t==="disabled";this.lastVisualState=t,this.alpha=r?Di(this.rampConfig.disabled,this.appService.controlsConfig.disabledStyle):1,s!==r&&this.drawBody()}getQuadPoints(){return this.clonePoints()}setFromQuad(t){t.length<4||(this.rampData={...this.rampData,points:t.map(i=>({...i}))})}getFrame(){const[t,i,,s]=this.rampData.points;return{origin:t,rotation:Math.atan2(i.y-t.y,i.x-t.x),width:q(t,i),height:q(t,s)}}createEditControls(){const t=this.rampConfig,i=this.appService.controlsConfig,s=new Es({editControls:this.appService.editControlManager}),r={config:{outlineStrokeColor:t.outlineStrokeColor,outlineStrokeWidth:t.outlineStrokeWidth,outlineDashed:t.outlineDashed,outlineDashArray:t.outlineDashArray,outlineFillColor:t.outlineFillColor,outlineOffset:t.outlineOffset,iconWrapperFillColor:t.iconWrapperFillColor,...Se(t),showRadialScaleButton:!1,rotateMode:"free",scaleMode:"free",textColor:t.textColor,textPosition:"top",textOffset:t.textOffset,moveButtonOffset:i.moveButtonOffset,textFontSize:i.textFontSize,textFontFamily:i.textFontFamily,textFontWeight:i.textFontWeight},zonePoints:this.getQuadPoints(),sizeConstraintPerEdge:this.resolveSizeConstraintPerEdge,contentLayer:Pi,events:{onRemove:this.handleRemove,onRotateStart:this.handleRotateStart,onRotateMove:this.handleRotateMove,onRotateEnd:this.handleRotateEnd,onScaleStart:this.handleScaleStart,onScaleMove:this.handleScaleMove,onScaleEnd:this.handleScaleEnd,onMoveStart:this.handleMoveStart,onMoveMove:this.handleMoveMove,onMoveEnd:this.handleMoveEnd}};return s.attach(this,{id:this.rampData.id,topology:"quad",layerOptions:r,editingState:this.resolveEditingState(),idleState:{showRotateButton:!1,showScaleButton:!1,showRadialScaleButton:!1,showDeleteButton:!1,showMoveButton:!1,showBorder:!1,showSizeText:!1}}),s}setupBodyInteraction(){this.updateBodyHitArea(),this.bodyClickHandler=new yt(this.body,{onClick:()=>{var t,i;this.appService.gestureController.suppressMapClick(),(i=(t=this.rampEvents).onClick)==null||i.call(t,this.getRampData())},stopPropagation:!1}),this.body.on("pointerdown",this.handleBodyPointerDown)}updateBodyHitArea(){const t=this.getFrame();this.body.hitArea=new st(0,0,t.width,t.height)}startDragging(t){this.isDragging=!0,this.hasDragMoved=!1;const i=this.parent.toLocal(t.global);this.dragStartPosition={x:i.x,y:i.y},this.initialPoints=this.clonePoints(),this.appService.getApp().requestRender("ramp-drag",!0),this.gestureSession=this.appService.gestureController.hijack(t),this.gestureSession.onMove(this.handleDragPointerMove),this.gestureSession.onEnd(this.handleDragPointerUp)}applyTranslation(t,i){this.initialPoints&&(this.rampData={...this.rampData,points:this.initialPoints.map(s=>({x:s.x+t,y:s.y+i}))},this.refreshAfterGeometryChange())}refreshAfterGeometryChange(){this.drawBody(),this.updateBodyHitArea(),this.editableShape.updatePoints(this.getQuadPoints())}clonePoints(){return this.rampData.points.map(t=>({...t}))}handleScaleChange(){this.drawBody()}getResolvedMaxWidth(){const t=this.rampConfig.maxWidth;if(this.resolvedMaxWidthCache&&this.resolvedMaxWidthCache.key===t)return this.resolvedMaxWidthCache.value;const i=ne(this.rampConfig.minWidth,t,"ramp");return this.resolvedMaxWidthCache={key:t,value:i},i}getResolvedMaxHeight(){const t=this.rampConfig.maxHeight;if(this.resolvedMaxHeightCache&&this.resolvedMaxHeightCache.key===t)return this.resolvedMaxHeightCache.value;const i=ne(this.rampConfig.minHeight,t,"ramp.height");return this.resolvedMaxHeightCache={key:t,value:i},i}validateAndCorrect(t){return{...t,points:this.normalizeQuad(t.points)}}normalizeQuad(t){if(!au(t))return t.map(o=>({...o}));const i=lu(Fn(t)),s=this.getResolvedMaxWidth(),r=this.getResolvedMaxHeight();return this.appService.coords.validateShape(i,{edge1:{min:et(this.rampConfig.minWidth),max:s!=null?et(s):void 0},edge2:{min:et(this.rampConfig.minHeight),max:r!=null?et(r):void 0}})}resolveBodyStyle(){const t=this.rampConfig;return this.resolveVisualState()!=="disabled"||!t.disabled?t:{fillColor:t.disabled.fillColor??t.fillColor,strokeColor:t.disabled.strokeColor??t.strokeColor,strokeWidth:t.disabled.strokeWidth??t.strokeWidth,arrowColor:t.disabled.arrowColor??t.arrowColor}}drawBody(){const t=this.rampConfig,i=this.resolveBodyStyle(),s=this.appService.getApp(),r=this.getFrame(),{width:o,height:a}=r,l=s.toFixedSize(i.strokeWidth);if(this.bodyFill.clear(),this.bodyStripes.clear(),this.bodyBorder.clear(),this.stripesMask.clear(),o===0||a===0)return;this.body.position.set(r.origin.x,r.origin.y),this.body.rotation=r.rotation,this.bodyFill.rect(0,0,o,a).fill(i.fillColor),this.bodyBorder.rect(0,0,o,a).stroke({color:i.strokeColor,width:l});const h=s.toFixedSize(t.arrowThickness),c=h+s.toFixedSize(t.arrowGap);if(!Number.isFinite(h)||h<=0||!Number.isFinite(c)||c<=0)return;const d=s.toFixedSize(t.arrowInset),u=Math.min(Math.max(Number.isFinite(d)?d:0,0),o/2,a/2),p=o-u*2,f=a-u*2;if(p<=0||f<=0)return;this.stripesMask.rect(u,u,p,f).fill(16777215);const{columns:m,columnGap:g,arrowWidth:x,rows:S,rise:b,spacing:w,thickness:_}=this.layoutArrows(p,f,h,c),v=this.getMiterOvershoot(_),C=v+b+_/2,P=S>1?u+v+b:u+(f-C)/2+v+b;for(let A=0;A<S;A++){const R=P+w*A;for(let T=0;T<m;T++){const E=u+(x+g)*T;this.bodyStripes.moveTo(E,R).lineTo(E+x/2,R-b).lineTo(E+x,R)}}this.bodyStripes.stroke({color:this.resolveBodyStyle().arrowColor,width:_})}layoutArrows(t,i,s,r){const o=Math.min(t,i),a=this.rampConfig.arrowDensity,l=Number.isFinite(a)?Math.max(1,Math.floor(a)):F0,h=Math.max(o/l,r),c=this.getArrowThicknessRatio(),d=Math.max(h*(1-c),0),u=Math.floor((t+d)/(r+d)),p=tc(Math.min(Math.round(t/o),u),L0),f=p>1?d:0,m=(t-f*(p-1))/p,g=m/2*Math.tan(this.getArrowAngleRadians()),x=Math.floor((i-g-s)/r)+1,S=tc(Math.min(Math.round(i/h),x),B0),b=(1/Math.cos(this.getArrowAngleRadians())+1)/2;if(S<=1){const v=(i-g)/b;return{columns:p,columnGap:f,arrowWidth:m,rows:1,rise:g,spacing:0,thickness:Math.max(Math.min(h*c,v),s)}}let w=(i-g)/(S-1+c*b),_=w*c;return _<s&&(_=s,w=(i-g-_*b)/(S-1)),{columns:p,columnGap:f,arrowWidth:m,rows:S,rise:g,spacing:w,thickness:_}}getMiterOvershoot(t){return t/2/Math.cos(this.getArrowAngleRadians())}getArrowThicknessRatio(){const t=this.rampConfig.arrowThicknessRatio;return!Number.isFinite(t)||t<=0?0:t}getArrowAngleRadians(){const t=this.rampConfig.arrowAngle;return(Number.isFinite(t)?Math.min(60,Math.max(1,t)):9)*Math.PI/180}destroy(){var t,i;this.appService.emitter.off("antiScale",this.throttledRedraw),this.throttledRedraw.cancel(),this.editableShape.detach(),this.isDragging&&(this.isDragging=!1,this.hasDragMoved=!1,this.dragStartPosition=null,this.initialPoints=null),(t=this.gestureSession)==null||t.cancel(),this.gestureSession=null,this.body.off("pointerdown",this.handleBodyPointerDown),(i=this.bodyClickHandler)==null||i.destroy(),this.bodyClickHandler=null,this.bodyStripes.mask=null,this.bodyFill.destroy(),this.bodyStripes.destroy(),this.bodyBorder.destroy(),this.stripesMask.destroy(),this.body.destroy(),super.destroy()}}const O0={fontSize:12,fontFamily:"system-ui, -apple-system, sans-serif",fontWeight:"400",color:"#5d68fe",position:"top",offset:-8,editing:{visible:!0},normal:{visible:!0}};class ca extends O{constructor(t){super();y(this,"spotData");y(this,"spotConfig");y(this,"controlsConfig");y(this,"spotEvents");y(this,"appService");y(this,"controlFill");y(this,"spotBorder");y(this,"centerIcon");y(this,"sizeText");y(this,"nameText");y(this,"clickHandler",null);y(this,"initialSpotPoint",null);y(this,"dragStartMousePosition",null);y(this,"throttledUpdateScale");y(this,"unsubscribeMapRotation",null);y(this,"iconAlias");y(this,"editingIdsKey");y(this,"handleDragStart",t=>{this.isEditingEnabled()&&(this.initialSpotPoint={...this.spotData.point},this.dragStartMousePosition=this.parent.toLocal(t.global),this.appService.getApp().requestRender("spot-drag",!0))});y(this,"handleDragMove",t=>{if(!this.isEditingEnabled()||!this.initialSpotPoint||!this.dragStartMousePosition||!this.controlFill)return;const i=this.parent.toLocal(t.global),s=i.x-this.dragStartMousePosition.x,r=i.y-this.dragStartMousePosition.y;this.applyTranslation(s,r)});y(this,"handleDragEnd",()=>{var t,i;this.initialSpotPoint=null,this.dragStartMousePosition=null,this.appService.getApp().stopRender("spot-drag"),(i=(t=this.spotEvents).onUpdate)==null||i.call(t,this.getSpotData())});const{appService:i,spotData:s,events:r={},config:o,iconAlias:a,editingIdsKey:l}=t;this.appService=i,this.spotData=s,this.spotEvents=r,this.controlsConfig=this.appService.controlsConfig,this.spotConfig=o??this.appService.controlsConfig.spot,this.iconAlias=a??"spotIcon",this.editingIdsKey=l??"editingSpotIds",this.position.set(s.point.x,s.point.y),this.throttledUpdateScale=Pt(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[this.editingIdsKey].includes(this.spotData.id)}isLiftedForEditing(){return this.isEditingEnabled()}shouldShowIcon(){return(this.isEditingEnabled()?this.spotConfig.editing:this.spotConfig.normal).showIcon}calculateRectanglePoints(){const{size:t}=this.spotConfig;if(t===0)return[{x:0,y:0},{x:0,y:0},{x:0,y:0},{x:0,y:0}];const s=this.appService.coords.toPixels(et(t))/2;return[{x:-s,y:-s},{x:s,y:-s},{x:s,y:s},{x:-s,y:s}]}initializeComponents(){const t=this.calculateRectanglePoints();this.spotConfig.size>0&&(this.controlFill=this.createControlFill(t),this.addChild(this.controlFill),this.spotBorder=this.createBorder(t),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(t){const i=this.isEditingEnabled();return new oa(this.appService,{points:t,fillColor:this.spotConfig.fillColor,enableInteraction:i,onDragStart:this.handleDragStart,onDragMove:this.handleDragMove,onDragEnd:this.handleDragEnd})}createBorder(t){const s=this.isEditingEnabled()?this.spotConfig.editing:this.spotConfig.normal;return new De(this.appService,{points:t,closePath:!0,style:{color:this.spotConfig.strokeColor,width:this.spotConfig.strokeWidth,isDashed:s.isDashed,dashArray:s.dashArray}})}createCenterIcon(){const t=new Yt(this.appService);return this.loadIconTexture(t),t.position.set(0,0),t.eventMode="static",this.setupIconDrag(t),t.visible=!1,t}async loadIconTexture(t){const{iconSize:i,iconSizeFixed:s,iconAnchor:r}=this.spotConfig;await t.loadTextureAndSetSize(this.iconAlias,{width:i,height:i,sizeFixed:s}),r&&t.anchor.set(r.x,r.y),this.applyAntiRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation||(this.unsubscribeMapRotation=z(this.appService.runtime,"mapRotation",o=>{this.applyAntiRotation(o)})),t.visible=this.shouldShowIcon()}applyAntiRotation(t){const i=-t*Math.PI/180;this.rotation=i}setupIconDrag(t){let i=null,s=!1;const r=a=>{if(!s||!this.initialSpotPoint||!i)return;const l=this.parent.toLocal(a.global),h=l.x-i.x,c=l.y-i.y;this.applyTranslation(h,c)},o=()=>{var a,l;s&&(s=!1,this.initialSpotPoint=null,i=null,this.appService.getApp().stopRender("spot-drag"),(l=(a=this.spotEvents).onUpdate)==null||l.call(a,this.getSpotData()))};t.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 l=this.appService.gestureController.hijack(a);l.onMove(r),l.onEnd(o)})}createSizeText(){const t=this.calculateSpotSizeText(),i=new Tn(this.appService,{text:t,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:t}=this.spotConfig,i=this.appService.coords.toDisplayUnit(et(t)),s=this.appService.runtimeSnapshot.unitLabel;return`${i.toFixed(1)}${s}*${i.toFixed(1)}${s}`}calculateSizeTextPosition(){const{textPosition:t,textOffset:i}=this.spotConfig;return this.calculateTextPosition(t,i)}calculateTextPosition(t,i){const s=this.calculateRectanglePoints();if(s.length<4)return{x:0,y:0};const[r,o,a,l]=s,h=this.appService.getApp().toFixedSize(i);let c,d;switch(t){case"top":{c={x:(r.x+o.x)/2,y:(r.y+o.y)/2},d={x:c.x,y:c.y+h};break}case"right":{c={x:(o.x+a.x)/2,y:(o.y+a.y)/2},d={x:c.x+h,y:c.y};break}case"bottom":{c={x:(l.x+a.x)/2,y:(l.y+a.y)/2},d={x:c.x,y:c.y+h};break}case"left":{c={x:(r.x+l.x)/2,y:(r.y+l.y)/2},d={x:c.x-h,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+h};break}}return d}getNameLabelConfig(){return this.spotConfig.nameLabel??O0}createNameText(){const t=this.getNameLabelConfig(),i=new Tn(this.appService,{text:this.calculateSpotNameText(),style:{fontSize:t.fontSize,fontFamily:t.fontFamily,fontWeight:t.fontWeight,fill:t.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 t;return((t=this.spotData.name)==null?void 0:t.trim())??""}calculateNameTextPosition(){const{position:t,offset:i}=this.getNameLabelConfig();return this.calculateTextPosition(t,i)}shouldShowNameText(){if(!this.calculateSpotNameText())return!1;const i=this.isEditingEnabled(),s=this.getNameLabelConfig();return(i?s.editing:s.normal).visible}applyTranslation(t,i){if(!this.initialSpotPoint)return;const s={x:this.initialSpotPoint.x+t,y:this.initialSpotPoint.y+i};this.spotData.roomId!==void 0&&!this.appService.mapManager.isPointInRoom(s,this.spotData.roomId)||(this.spotData.point=s,this.drawSpot())}setupClickHandler(){const t=this.spotConfig.size>0?this:this.centerIcon;this.clickHandler=new yt(t,{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 t=this.calculateRectanglePoints();this.position.set(this.spotData.point.x,this.spotData.point.y),this.spotConfig.size>0&&(this.controlFill&&this.controlFill.updatePoints(t),this.spotBorder&&this.spotBorder.updatePoints(t)),this.spotConfig.showText&&this.sizeText&&this.updateSizeText(),this.nameText&&this.updateNameText()}updateSizeText(){if(!this.sizeText)return;const t=this.calculateSpotSizeText();this.sizeText.updateText(t),this.updateSizeTextPosition()}updateSizeTextPosition(){if(!this.sizeText)return;const t=this.calculateSizeTextPosition();this.sizeText.position.set(t.x,t.y)}updateNameText(){this.nameText&&(this.nameText.updateText(this.calculateSpotNameText()),this.updateNameTextPosition())}updateNameTextPosition(){if(!this.nameText)return;const t=this.calculateNameTextPosition();this.nameText.position.set(t.x,t.y)}updateEditState(){const t=this.isEditingEnabled(),i=t?this.spotConfig.editing:this.spotConfig.normal;if(this.sizeText&&(this.sizeText.visible=t&&this.spotConfig.showText),this.nameText&&(this.nameText.visible=this.shouldShowNameText()),this.centerIcon){this.centerIcon.visible=this.shouldShowIcon();const s=this.spotConfig.iconAnchor;s&&this.centerIcon.anchor.set(s.x,s.y)}this.sizeText&&(this.sizeText.visible=this.spotConfig.showText),this.controlFill&&(this.controlFill.setInteractionEnabled(t),this.controlFill.visible=i.showFill??i.showFrame),this.spotBorder&&(this.spotBorder.updateStyle({isDashed:i.isDashed,dashArray:i.dashArray}),this.spotBorder.visible=i.showFrame)}updateSpotData(t){this.spotData={...t},!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 t,i,s,r,o,a;this.appService.emitter.off("antiScale",this.throttledUpdateScale),this.throttledUpdateScale.cancel(),this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),(t=this.clickHandler)==null||t.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(t,i,s){return new ca({appService:t,spotData:i,config:s==null?void 0:s.config,iconAlias:s==null?void 0:s.iconAlias,editingIdsKey:s==null?void 0:s.editingIdsKey,events:(s==null?void 0:s.events)??{onUpdate:r=>{var o,a;(a=(o=t.events)==null?void 0:o.onUpdateSpot)==null||a.call(o,r)},onClick:r=>{var o,a;(a=(o=t.events)==null?void 0:o.onClickSpot)==null||a.call(o,r)}}})}}const Gr=3,W0={fontSize:12,fontFamily:"system-ui, -apple-system, sans-serif",fontWeight:"400",color:"#333333",position:"bottom",offset:4,editing:{visible:!0,color:"#ff4d4f",fontWeight:"600"},normal:{visible:!0,color:"#333333",fontWeight:"400"}},nn={normal:{radius:6,color:"#00B578",strokeColor:"#ffffff",strokeWidth:2,halo:!1},editing:{radius:6,color:"#ff4d4f",strokeColor:"#ffffff",strokeWidth:2,halo:{radius:10,color:"#ff4d4f",alpha:.2}}};class G0 extends ap{constructor(t){const{appService:i,wayPointData:s,order:r,events:o={}}=t;super(i);y(this,"wayPointData");y(this,"order");y(this,"wayPointConfig");y(this,"controlsConfig");y(this,"wayPointEvents");y(this,"icon");y(this,"dotNode");y(this,"orderContainer");y(this,"orderBackground");y(this,"orderText");y(this,"nameText");y(this,"clickHandler",null);y(this,"dotClickHandler",null);y(this,"didDrag",!1);y(this,"initialWayPointPoint",null);y(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.setupAntiRotation(),this.initializeComponents(),this.updateEditState(),this.setupClickHandler()}setupAntiRotation(){this.applyAntiRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation||(this.unsubscribeMapRotation=z(this.appService.runtime,"mapRotation",t=>{this.applyAntiRotation(t)}))}isEditingEnabled(){return(this.appService.runtimeSnapshot.editingWayPointIds||[]).includes(this.wayPointData.id)}isDragEnabled(){return this.wayPointData.canDrag!==void 0?this.wayPointData.canDrag:this.wayPointConfig.canDrag??!0}initializeComponents(){this.getShape()==="dot"?this.ensureDotNode():(this.ensureIcon(),this.wayPointConfig.showOrder&&this.ensureOrderContainer()),this.calculateWayPointNameText()&&(this.nameText=this.createNameText(),this.addChild(this.nameText))}ensureDotNode(){return this.dotNode||(this.dotNode=this.createDotNode(),this.addChild(this.dotNode),this.setupClickHandler()),this.dotNode}ensureIcon(){return this.icon||(this.icon=this.createIcon(),this.addChild(this.icon),this.setupClickHandler()),this.icon}ensureOrderContainer(){return this.orderContainer||(this.createOrderContainer(),this.addChild(this.orderContainer)),this.orderContainer}createDotNode(){const t=new W;return t.position.set(0,0),t.eventMode="static",this.setupIconDrag(t),t}createIcon(){const t=new Yt(this.appService);return this.loadIconTexture(t),t.position.set(0,0),t.anchor.set(.5,1),t.eventMode="static",this.setupIconDrag(t),t}async loadIconTexture(t){const i=this.isEditingEnabled(),s=i?this.wayPointConfig.editing:this.wayPointConfig.normal,{iconSize:r}=s,o=i?"wayPointActive":"wayPoint";await t.loadTextureAndSetSize(o,{width:r,height:r,sizeFixed:!1}),!(this.destroyed||t.destroyed||this.getShape()!=="pin")&&(t.visible=!0,this.orderContainer&&this.updateOrderPosition(),this.nameText&&this.updateNamePosition())}applyAntiRotation(t){const i=-t*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 O,this.orderBackground=new W,this.orderText=new xs({text:this.order.toString(),style:new ee({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)}getNameLabelConfig(){return this.wayPointConfig.nameLabel??W0}calculateWayPointNameText(){var t;return((t=this.wayPointData.name)==null?void 0:t.trim())??""}shouldShowNameText(){if(!this.calculateWayPointNameText())return!1;const i=this.isEditingEnabled(),s=this.getNameLabelConfig(),r=i?s.editing:s.normal;return(r==null?void 0:r.visible)!==!1}resolveNameLabelStyle(){var h,c;const t=this.getNameLabelConfig(),i=this.isEditingEnabled(),s=i?t.editing:t.normal,r=(s==null?void 0:s.fontSize)??t.fontSize,o=(s==null?void 0:s.fontWeight)??t.fontWeight,a=(s==null?void 0:s.fontFamily)??t.fontFamily,l=i?((h=t.editing)==null?void 0:h.color)??t.color??"#ff4444":((c=t.normal)==null?void 0:c.color)??t.color??"#333333";return{fontSize:r,fontFamily:a,fontWeight:o,fill:l}}createNameText(){var l,h,c;const{fontSize:t,fontFamily:i,fontWeight:s,fill:r}=this.resolveNameLabelStyle(),o=new xs({text:this.calculateWayPointNameText(),style:new ee({fontSize:t,fontFamily:i,fontWeight:s,fill:r,align:"center"})}),a=(h=(l=this.appService).getApp)==null?void 0:h.call(l);return(c=a==null?void 0:a.renderer)!=null&&c.resolution&&(o.resolution=a.renderer.resolution),o.eventMode="none",this.updateNamePosition(o),o.visible=this.shouldShowNameText(),o}updateNamePosition(t=this.nameText){if(!t)return;const i=this.getNameLabelConfig(),s=i.position??"bottom",r=i.offset??4,o=this.isEditingEnabled();if(this.getShape()==="dot"){const c=this.wayPointConfig.dot,d=o?c==null?void 0:c.editing:c==null?void 0:c.normal,u=o?nn.editing:nn.normal,p=(d==null?void 0:d.radius)??u.radius,f=(d==null?void 0:d.halo)!==void 0?d.halo:u.halo,m=f&&f.alpha!==0?f.radius??p+4:p,g=Math.max(p,m);switch(s){case"top":{t.anchor.set(.5,1),t.position.set(0,-g-r);break}case"left":{t.anchor.set(1,.5),t.position.set(-g-r,0);break}case"right":{t.anchor.set(0,.5),t.position.set(g+r,0);break}case"bottom":default:{t.anchor.set(.5,0),t.position.set(0,g+r);break}}return}const l=o?this.wayPointConfig.editing:this.wayPointConfig.normal,{iconSize:h}=l;switch(s){case"top":{t.anchor.set(.5,1);let c=h;if(this.wayPointConfig.showOrder&&l.orderContainer){const d=l.orderContainer.offsetY+l.orderContainer.size/2;c=Math.max(h,d)}t.position.set(0,-c-r);break}case"left":{t.anchor.set(1,.5),t.position.set(-h/2-r,-h/2);break}case"right":{t.anchor.set(0,.5),t.position.set(h/2+r,-h/2);break}case"bottom":default:{t.anchor.set(.5,0),t.position.set(0,r);break}}}setupIconDrag(t){let i=null,s=null,r=null,o=!1,a=!1;const l=c=>{if(!(!o||!i||!s||!r)&&this.parent){const d=this.parent.toLocal(c.global),u=d.x-i.x,p=d.y-i.y,f=Math.hypot(c.global.x-s.x,c.global.y-s.y);if(!a&&f<=Gr)return;a=!0,this.didDrag=!0;const m={x:r.x+u,y:r.y+p};this.wayPointData.point=m,this.position.set(m.x,m.y),this.orderContainer&&this.updateOrderPosition()}},h=()=>{var c,d;o&&(o=!1,i=null,s=null,r=null,a&&(a=!1,(d=(c=this.wayPointEvents).onUpdate)==null||d.call(c,this.wayPointData)))};t.on("pointerdown",c=>{if(this.didDrag=!1,!(!this.isEditingEnabled()||!this.isDragEnabled())&&(c.stopPropagation(),r={...this.wayPointData.point},s={x:c.global.x,y:c.global.y},this.parent&&(i=this.parent.toLocal(c.global)),o=!0,a=!1,this.parent)){const d=this.appService.gestureController.hijack(c);d.onMove(l),d.onEnd(h)}})}setupClickHandler(){const t=()=>{var i,s;this.didDrag||(this.appService.gestureController.suppressMapClick(),(s=(i=this.wayPointEvents).onClick)==null||s.call(i,this.wayPointData))};this.icon&&!this.clickHandler&&(this.clickHandler=new yt(this.icon,{stopPropagation:!1,clickThreshold:Gr,onClick:t})),this.dotNode&&!this.dotClickHandler&&(this.dotClickHandler=new yt(this.dotNode,{stopPropagation:!1,clickThreshold:Gr,onClick:t}))}updateWayPoint(t){this.wayPointData=t,this.nameText?(this.nameText.text=this.calculateWayPointNameText(),this.nameText.visible=this.shouldShowNameText(),this.updateNamePosition()):this.calculateWayPointNameText()&&(this.nameText=this.createNameText(),this.addChild(this.nameText),this.setupClickHandler()),this.drawWayPoint()}updateOrder(t){this.order=t,this.orderText&&(this.orderText.text=t.toString())}getWayPointData(){return{...this.wayPointData}}drawWayPoint(){this.position.set(this.wayPointData.point.x,this.wayPointData.point.y),this.orderContainer&&this.updateOrderPosition(),this.nameText&&this.updateNamePosition()}getShape(){return this.wayPointConfig.shape??"pin"}updateDotNode(){if(!this.dotNode)return;const t=this.isEditingEnabled(),i=this.wayPointConfig.dot,s=t?i==null?void 0:i.editing:i==null?void 0:i.normal,r=t?nn.editing:nn.normal,o=(s==null?void 0:s.radius)??r.radius,a=(s==null?void 0:s.color)??r.color,l=(s==null?void 0:s.strokeColor)??r.strokeColor,h=(s==null?void 0:s.strokeWidth)??r.strokeWidth,c=(s==null?void 0:s.halo)!==void 0?s.halo:r.halo;if(this.dotNode.clear(),c&&c.alpha!==0){const p=c.radius??o+4,f=c.color??a,m=c.alpha??.2;this.dotNode.circle(0,0,p),this.dotNode.fill({color:f,alpha:m})}this.dotNode.circle(0,0,o),this.dotNode.fill({color:a}),h>0&&this.dotNode.stroke({color:l,width:h});const d=c&&c.alpha!==0?c.radius??o+4:o,u=Math.max(o+8,d,16);this.dotNode.hitArea=new As(0,0,u),this.dotNode.cursor="pointer",this.dotNode.visible=!0}updateEditState(){var s,r;(r=(s=this.appService)==null?void 0:s.controlsConfig)!=null&&r.wayPoint&&(this.wayPointConfig=this.appService.controlsConfig.wayPoint);const t=this.isEditingEnabled();if(this.getShape()==="dot")this.icon&&(this.icon.visible=!1),this.orderContainer&&(this.orderContainer.visible=!1),this.ensureDotNode(),this.updateDotNode();else{this.dotNode&&(this.dotNode.visible=!1);const o=this.ensureIcon();if(o.visible=!0,this.loadIconTexture(o),this.wayPointConfig.showOrder&&this.ensureOrderContainer(),this.orderContainer&&this.orderText&&this.orderBackground){const a=t?this.wayPointConfig.editing:this.wayPointConfig.normal;this.orderText.style=new ee({fontSize:a.orderText.fontSize,fontFamily:a.orderText.fontFamily,fontWeight:a.orderText.fontWeight,fill:a.orderText.color,align:"center",trim:!0});const{size:l,backgroundColor:h}=a.orderContainer;this.orderBackground.clear(),this.orderBackground.circle(0,0,l/2).fill(h),this.orderContainer.visible=this.wayPointConfig.showOrder,this.updateOrderPosition()}}if(this.nameText){const{fontSize:o,fontFamily:a,fontWeight:l,fill:h}=this.resolveNameLabelStyle();this.nameText.style=new ee({fontSize:o,fontFamily:a,fontWeight:l,fill:h,align:"center"}),this.nameText.visible=this.shouldShowNameText(),this.updateNamePosition()}}onEditStateChange(){this.updateEditState()}isLiftedForEditing(){return this.isEditingEnabled()}destroy(){this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null),this.dotClickHandler&&(this.dotClickHandler.destroy(),this.dotClickHandler=null),this.icon&&this.icon.removeAllListeners(),this.dotNode&&(this.dotNode.removeAllListeners(),this.dotNode.destroy()),this.nameText&&(this.nameText.destroy(),this.nameText=void 0),super.destroy()}}class ec extends W{constructor(t,i){super();y(this,"isDragging",!1);y(this,"dragStartPosition",null);y(this,"initialPosition");y(this,"gestureSession",null);y(this,"unsubscribeMapRotation",null);y(this,"handleDragPointerMove",t=>{var a,l;if(!this.isDragging||!this.dragStartPosition)return;const i=this.parent.toLocal(t.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),(l=(a=this.options).onDragMove)==null||l.call(a,o)});y(this,"handleDragPointerUp",()=>{var i,s;if(this.gestureSession=null,!this.isDragging)return;const t=this.appService;this.isDragging=!1,this.dragStartPosition=null,t.getApp().stopRender("endpoint-drag"),(s=(i=this.options).onDragEnd)==null||s.call(i)});this.appService=t,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.setupAntiRotation(),this.draw()}setupAntiRotation(){if(this.options.config.endPointShape!=="diamond")return;const{runtime:t}=this.appService;this.applyAntiRotation(t.mapRotation),this.unsubscribeMapRotation=z(t,"mapRotation",i=>{this.applyAntiRotation(i)})}applyAntiRotation(t){this.destroyed||(this.rotation=-t*Math.PI/180)}draw(){const t=this.appService,{config:i}=this.options,s=t.getApp().toFixedSize(i.endPointSize),r=t.getApp().toFixedSize(i.endPointStrokeWidth);this.clear();const o=s/2;i.endPointShape==="diamond"?this.poly([0,-o,o,0,0,o,-o,0]):this.circle(0,0,o),this.fill({color:i.endPointColor}),this.stroke({color:i.endPointStrokeColor,width:r}),this.setupHitArea()}setupHitArea(){const t=this.appService,{config:i}=this.options,s=Math.max(i.endPointSize/2+10,20),r=t.getApp().toFixedSize(s);this.hitArea=new As(0,0,r)}setupEvents(){this.on("pointerdown",this.handlePointerDown.bind(this))}handlePointerDown(t){t.stopPropagation(),this.startDragging(t)}startDragging(t){var s,r;const i=this.appService;this.isDragging=!0,this.dragStartPosition=this.parent.toLocal(t.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(t),this.gestureSession.onMove(this.handleDragPointerMove),this.gestureSession.onEnd(this.handleDragPointerUp)}updatePosition(t){this.position.set(t.x,t.y),this.initialPosition={...t}}getPosition(){return{x:this.x,y:this.y}}redraw(){this.draw()}destroy(){var t,i;this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null),(t=this.gestureSession)==null||t.cancel(),this.gestureSession=null,(i=this.unsubscribeMapRotation)==null||i.call(this),this.unsubscribeMapRotation=null,this.off("pointerdown",this.handlePointerDown),super.destroy()}}class U0 extends O{constructor(t){super();y(this,"endPoints");y(this,"dividerConfig");y(this,"dividerEvents");y(this,"roomId");y(this,"appService");y(this,"roomGeometry",null);y(this,"dashLine");y(this,"solidLine",null);y(this,"startEndPoint");y(this,"endEndPoint");y(this,"solidLinePoints",null);y(this,"initialDividerPoints",[]);y(this,"isDragging",!1);y(this,"dragStartPosition",null);y(this,"gestureSession",null);y(this,"throttledHandleScaleChange");y(this,"handleEndPointDragStart",()=>{this.initialDividerPoints=this.endPoints.map(t=>({...t})),this.clearSolidLine(),this.appService.getApp().requestRender("divider-endpoint-drag",!0)});y(this,"handleEndPointDragMove",(t,i)=>{this.initialDividerPoints.length!==0&&(this.endPoints[t]=i,this.updateDashLine(),this.updateSolidLine(),this.setupDashLineHitArea())});y(this,"handleEndPointDragEnd",()=>{this.initialDividerPoints=[],this.appService.getApp().stopRender("divider-endpoint-drag"),this.finalizeDragUpdate()});y(this,"handleDashLinePointerDown",t=>{t.stopPropagation(),this.startDragging(t)});y(this,"handleDragPointerMove",t=>{if(!this.isDragging||!this.dragStartPosition||this.initialDividerPoints.length===0)return;const i=this.parent.toLocal(t.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()});y(this,"handleDragPointerUp",()=>{this.gestureSession=null,this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null,this.initialDividerPoints=[],this.appService.getApp().stopRender("divider-drag"),this.finalizeDragUpdate())});y(this,"handleScaleChange",()=>{var t,i;(t=this.startEndPoint)==null||t.redraw(),(i=this.endEndPoint)==null||i.redraw(),this.updateSolidLine(),this.setupDashLineHitArea()});const{appService:i,endPoints:s,roomId:r,events:o={}}=t;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=Pt(this.handleScaleChange.bind(this),30,{leading:!0,trailing:!0}),this.initializeComponents(),this.calculateAndCreateSolidLine(),this.registerScaleListener()}validateDividerPoints(t){if(t.length>=2)return t.slice(0,2);const i=t[0]||{x:0,y:0},s={x:i.x+50,y:i.y};return[i,s]}createDefaultdividerPoints(){if(!this.roomGeometry)return M.warn("Room geometry not available, creating fallback divider"),[{x:0,y:0},{x:100,y:0}];const t=this.appService.getApp().mapState;if(!t)return M.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,l=r==="horizontal"?i.width+2*s:i.height+2*s;return Cb(o,a,l,r).map(c=>({x:c.x-t.origin.x,y:c.y-t.origin.y}))}initializeComponents(){this.createDashLine(),this.addChild(this.dashLine),this.createEndPoints(),this.addChild(this.startEndPoint),this.addChild(this.endEndPoint),this.setupDashLineInteraction()}createDashLine(){const t=this.endPoints;if(t.length<2)return;const{dashLineWidth:i,dashLineDashArray:s,lineColor:r}=this.dividerConfig;this.dashLine=new ci(this.appService,{start:t[0],end:t[1],style:{color:r.toString(),width:i,dashArray:s}})}createEndPoints(){const t=this.endPoints;this.startEndPoint=new ec(this.appService,{position:t[0],config:this.dividerConfig,onDragStart:this.handleEndPointDragStart,onDragMove:i=>this.handleEndPointDragMove(0,i),onDragEnd:this.handleEndPointDragEnd}),this.endEndPoint=new ec(this.appService,{position:t[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 t=this.endPoints;if(t.length<2)return;const{hitAreaThickness:i}=this.dividerConfig,s=this.appService.getApp().toFixedSize(i),r=fu(t[0],t[1],s);if(r.length===0)return;const o=new Ze(r);this.dashLine.hitArea=o}startDragging(t){this.isDragging=!0;const i=this.parent.toLocal(t.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(t),this.gestureSession.onMove(this.handleDragPointerMove),this.gestureSession.onEnd(this.handleDragPointerUp)}finalizeDragUpdate(){var s,r,o,a;this.calculateAndCreateSolidLine();const t=this.getDividerEndPoints();this.checkAndResetIfOutOfRoom()&&((r=(s=this.dividerEvents).onOutOfRoom)==null||r.call(s,t)),(a=(o=this.dividerEvents).onUpdate)==null||a.call(o,this.getDividerEndPoints())}updateAllComponents(){this.updateDashLine(),this.updateSolidLine(),this.updateEndPoints(),this.setupDashLineHitArea()}updateDashLine(){const t=this.endPoints;t.length<2||!this.dashLine||this.dashLine.updatePoints(t[0],t[1])}updateSolidLine(){if(!this.solidLine||!this.solidLinePoints)return;const{solidLineWidth:t,lineColor:i}=this.dividerConfig,s=this.appService.getApp().toFixedSize(t);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 t=this.endPoints;this.startEndPoint&&this.startEndPoint.updatePosition(t[0]),this.endEndPoint&&this.endEndPoint.updatePosition(t[1])}registerScaleListener(){const{emitter:t}=this.appService;t.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 t=this.appService.mapManager.roomFill;return!t||typeof this.roomId!="number"?null:t.getRoomGraphicsMap().get(this.roomId)||null}calculateLineRoomIntersection(){const t=this.endPoints;if(t.length<2||typeof this.roomId!="number")return null;const[i,s]=t,r=this.isPointInRoomFill(i),o=this.isPointInRoomFill(s);if(r||o)return null;const a=rb(i,s),l=[];for(const p of a)this.isPointInRoomFill(p)&&l.push(p);if(l.length===0)return null;const h=l[0],c=l[l.length-1];return q(h,c)<3?null:Mb(h,c,.5)}isPointInRoomFill(t){if(typeof this.roomId!="number")return!1;const i=this.appService.getApp().mapState;if(!i)return!1;const s={x:t.x+i.origin.x,y:t.y+i.origin.y};return i.mapType==="raster"?this.isPointInRasterRoomFill(s):this.isPointInStructuredRoomFill(s)}isPointInRasterRoomFill(t){t.x-=.5,t.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(t.x),l=Math.round(t.y);if(a<0||l<0||a>=o)return!1;const h=l*o+a;for(let c=0;c<r.pixelIndices.length;c++)if(r.pixelIndices[c]===h)return!0;return!1}isPointInStructuredRoomFill(t){const i={x:Math.round(t.x),y:Math.round(t.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:t}=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!wb(r,o,t.x,t.y,t.width,t.height)}isDividerUnableToSplitRoom(){return!this.roomGeometry||typeof this.roomId!="number"||!this.getRoomGraphics()||!this.appService.getApp().mapState||this.endPoints.length<2?!1:this.solidLinePoints===null}checkAndResetIfOutOfRoom(){const t=this.appService.dividerConfig.outOfRoomCriterion==="solidLine"?this.isDividerUnableToSplitRoom():this.isDividerCompletelyOutOfRoom();return t&&this.appService.dividerConfig.resetDividerWhenOutOfRoom&&this.resetToDefaultState(),t}resetToDefaultState(){this.endPoints=this.createDefaultdividerPoints(),this.calculateAndCreateSolidLine(),this.updateComponents()}updateComponents(){const t=this.endPoints;t.length>=2&&(this.dashLine.updatePoints(t[0],t[1]),this.startEndPoint.position.set(t[0].x,t[0].y),this.endEndPoint.position.set(t[1].x,t[1].y),this.setupDashLineInteraction())}createSolidLine(){if(!this.solidLinePoints)return;const{solidLineWidth:t,lineColor:i}=this.dividerConfig;this.solidLine=new W,this.solidLine.eventMode="none";const s=this.appService.getApp().toFixedSize(t);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(t){this.endPoints=this.validateDividerPoints(t),this.updateAllComponents(),this.calculateAndCreateSolidLine()}destroy(){var t,i,s,r;this.appService.emitter.off("antiScale",this.throttledHandleScaleChange),this.throttledHandleScaleChange.cancel(),this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null,this.initialDividerPoints=[]),(t=this.gestureSession)==null||t.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 _o=["forbiddenSweepZone","forbiddenMopZone","cleanZone","virtualWall","spot","wayPoint","divider"],H0=["ramp","threshold"],N0=999;function ic(n,e,t,i){const s=i?e:n,r=i?n:e;!s||s.children.includes(t)||(r==null||r.removeChild(t),s.addChild(t))}function V0(n){if(!n||n.length===0)return[..._o];const e=new Set,t=[];for(const i of n)e.has(i)||(e.add(i),t.push(i));for(const i of _o)e.has(i)||t.push(i);return t}class $0{constructor(e){y(this,"zoneMaps",new Map);y(this,"virtualWallMap",new Map);y(this,"thresholdMap",new Map);y(this,"rampMap",new Map);y(this,"spotMap",new Map);y(this,"roomAnchorMap",new Map);y(this,"roomAnchorsData",[]);y(this,"wayPointMap",new Map);y(this,"divider",null);y(this,"controlContainers",new Map);y(this,"floorMarkContainers",new Map);y(this,"editingContainers",new Map);y(this,"unsubscribeFns",[]);y(this,"builtinZoneFactories",{forbiddenSweepZone:e=>aa.create(this.appService,e),forbiddenMopZone:e=>la.create(this.appService,e),cleanZone:e=>ha.create(this.appService,e)});this.appService=e,this.initializeControlContainers();const t=z(e.runtime,"editingForbiddenSweepZoneIds",v=>{M.log(`[runtime] editingForbiddenSweepZoneIds: ${v}`);const C=this.zoneMaps.get("forbiddenSweepZone");C&&this.updateZonesEditState("forbiddenSweepZone",C)}),i=z(e.runtime,"editingForbiddenMopZoneIds",v=>{M.log(`[runtime] editingForbiddenMopZoneIds: ${v}`);const C=this.zoneMaps.get("forbiddenMopZone");C&&this.updateZonesEditState("forbiddenMopZone",C)}),s=z(e.runtime,"editingCleanZoneIds",v=>{M.log(`[runtime] editingCleanZoneIds: ${v}`);const C=this.zoneMaps.get("cleanZone");C&&this.updateZonesEditState("cleanZone",C)}),r=z(e.runtime,"editingCustomZoneIds",v=>{M.log(`[runtime] editingCustomZoneIds: ${JSON.stringify(v??{})}`);for(const[C,P]of this.zoneMaps)Pe(C)||P.size&&this.updateZonesEditState(C,P)}),o=z(e.runtime,"editingVirtualWallIds",v=>{M.log(`[runtime] editingVirtualWallIds: ${v}`),this.updateVirtualWallsEditState(this.virtualWallMap)}),a=z(e.runtime,"editingThresholdIds",v=>{M.log(`[runtime] editingThresholdIds: ${v}`),this.updateThresholdsEditState(this.thresholdMap)}),l=z(e.runtime,"editingRampIds",v=>{M.log(`[runtime] editingRampIds: ${v}`),this.updateRampsEditState(this.rampMap)}),h=z(e.runtime,"editingSpotIds",v=>{M.log(`[runtime] editingSpotIds: ${v}`),this.updateSpotsEditState(this.spotMap,"spot")}),c=z(e.runtime,"editingRoomAnchorIds",v=>{M.log(`[runtime] editingRoomAnchorIds: ${v}`),this.updateSpotsEditState(this.roomAnchorMap,"roomAnchor")}),d=z(e.runtime,"editingWayPointIds",v=>{M.log(`[runtime] editingWayPointIds: ${v}`),this.updateWayPointsEditState(this.wayPointMap)}),u=z(e.runtime,"disabledForbiddenSweepZoneIds",v=>{M.log(`[runtime] disabledForbiddenSweepZoneIds: ${v}`);const C=this.zoneMaps.get("forbiddenSweepZone");C&&this.updateZonesEditState("forbiddenSweepZone",C)}),p=z(e.runtime,"disabledForbiddenMopZoneIds",v=>{M.log(`[runtime] disabledForbiddenMopZoneIds: ${v}`);const C=this.zoneMaps.get("forbiddenMopZone");C&&this.updateZonesEditState("forbiddenMopZone",C)}),f=z(e.runtime,"disabledCleanZoneIds",v=>{M.log(`[runtime] disabledCleanZoneIds: ${v}`);const C=this.zoneMaps.get("cleanZone");C&&this.updateZonesEditState("cleanZone",C)}),m=z(e.runtime,"disabledCustomZoneIds",v=>{M.log(`[runtime] disabledCustomZoneIds: ${JSON.stringify(v??{})}`);for(const[C,P]of this.zoneMaps)Pe(C)||P.size&&this.updateZonesEditState(C,P)}),g=z(e.runtime,"disabledVirtualWallIds",v=>{M.log(`[runtime] disabledVirtualWallIds: ${v}`),this.updateVirtualWallsEditState(this.virtualWallMap)}),x=z(e.runtime,"disabledThresholdIds",v=>{M.log(`[runtime] disabledThresholdIds: ${v}`),this.updateThresholdsEditState(this.thresholdMap)}),S=z(e.runtime,"disabledRampIds",v=>{M.log(`[runtime] disabledRampIds: ${v}`),this.updateRampsEditState(this.rampMap)}),b=z(e.runtime,"dividingRoomId",v=>{M.log(`[runtime] dividingRoomId: ${v}`),this.handleDividingRoomIdChange(v)}),w=z(e.runtime,"unit",v=>{M.log(`[runtime] unit changed: ${v}`),this.handleUnitChange()}),_=z(e.runtime,"unitLabel",v=>{M.log(`[runtime] unitLabel changed: ${v}`),this.handleUnitChange()});this.unsubscribeFns.push(t,i,u,p,f,m,g,x,S,s,r,o,a,l,h,c,d,b,w,_)}getDiagnosticObjects(e=201){let t=this.virtualWallMap.size+this.thresholdMap.size+this.rampMap.size+this.spotMap.size+this.roomAnchorMap.size+this.wayPointMap.size;if(this.zoneMaps.forEach(s=>{t+=s.size}),t>e)throw new Error("BUDGET_EXCEEDED: entities");const i=[];return this.zoneMaps.forEach((s,r)=>s.forEach((o,a)=>i.push({type:r,id:a,container:o,read:()=>o.getZoneData()}))),this.virtualWallMap.forEach((s,r)=>i.push({type:"virtualWall",id:r,container:s,read:()=>s.getWallData(),part:o=>s.getDiagnosticPart(o)})),this.thresholdMap.forEach((s,r)=>i.push({type:"threshold",id:r,container:s,read:()=>s.getThresholdData()})),this.rampMap.forEach((s,r)=>i.push({type:"ramp",id:r,container:s,read:()=>s.getRampData()})),this.spotMap.forEach((s,r)=>i.push({type:"spot",id:r,container:s,read:()=>s.getSpotData()})),this.roomAnchorMap.forEach((s,r)=>i.push({type:"roomAnchor",id:r,container:s,read:()=>s.getSpotData()})),this.wayPointMap.forEach((s,r)=>i.push({type:"wayPoint",id:r,container:s,read:()=>s.getWayPointData()})),i}updateRenderOrder(){this.applyRenderOrder()}initializeControlContainers(){const e=this.appService.appContainer.getLayer(Te);if(!e){M.warn("[ControlsManager] LAYER_CONTROLS not found during init");return}for(const t of _o){const i=new O;i.label=`controls:${t}`,this.controlContainers.set(t,i),e.addChild(i)}this.applyRenderOrder()}applyRenderOrder(){const e=this.appService.appContainer.getLayer(Te);if(!e)return;V0(this.appService.getConfig().controls.renderOrder).forEach((i,s)=>{const r=this.controlContainers.get(i);r&&(r.zIndex=s)}),e.sortableChildren=!0,e.sortChildren()}addToControlLayer(e,t){let i=this.controlContainers.get(e);if(!i){const s=this.appService.appContainer.getLayer(Te);if(!s){M.warn("[ControlsManager] LAYER_CONTROLS not found");return}i=new O,i.label=`controls:${e}`,this.controlContainers.set(e,i),s.addChild(i),this.applyRenderOrder()}i.addChild(t)}addToFloorMarkLayer(e,t){let i=this.floorMarkContainers.get(e);if(!i){const s=this.appService.appContainer.getLayer(Pi);if(!s){M.warn("[ControlsManager] LAYER_FLOOR_MARK not found");return}i=new O,i.label=`floorMark:${e}`,i.zIndex=H0.indexOf(e),this.floorMarkContainers.set(e,i),s.addChild(i),s.sortableChildren=!0,s.sortChildren()}i.addChild(t)}syncControlEditingLayer(e,t){const i=t.isLiftedForEditing();ic(this.controlContainers.get(e),this.editingContainerFor("controls",Te,i),t,i)}syncFloorMarkEditingLayer(e,t){const i=t.isLiftedForEditing();ic(this.floorMarkContainers.get(e),this.editingContainerFor("floorMark",Pi,i),t,i)}editingContainerFor(e,t,i){const s=this.editingContainers.get(e);if(s||!i)return s;const r=this.appService.appContainer.getLayer(t);if(!r){M.warn(`[ControlsManager] ${t} not found`);return}const o=new O;return o.label=`${e}:editing`,o.zIndex=N0,r.addChild(o),r.sortableChildren=!0,r.sortChildren(),this.editingContainers.set(e,o),o}drawForbiddenSweepZones(e){this.drawZonesByType("forbiddenSweepZone",e)}getForbiddenSweepZones(){return this.getZonesDataByType("forbiddenSweepZone")}clearAllForbiddenSweepZones(){this.clearAllZonesByType("forbiddenSweepZone")}drawForbiddenMopZones(e){this.drawZonesByType("forbiddenMopZone",e)}getForbiddenMopZones(){return this.getZonesDataByType("forbiddenMopZone")}clearAllForbiddenMopZones(){this.clearAllZonesByType("forbiddenMopZone")}drawCleanZones(e){this.drawZonesByType("cleanZone",e)}getCleanZones(){return this.getZonesDataByType("cleanZone")}clearAllCleanZones(){this.clearAllZonesByType("cleanZone")}drawVirtualWalls(e){var r;const t=this.appService,i=this.virtualWallMap,s=new Set(e.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));e.forEach(o=>{const a=i.get(o.id);if(a)this.isWallDataEqual(a.getWallData(),o)||a.updateWallData(o);else{const l=new Mo({appService:t,wallData:o,events:{onRemove:h=>{var c,d;(d=(c=t.events)==null?void 0:c.onRemoveVirtualWall)==null||d.call(c,h)},onUpdate:h=>{var c,d;(d=(c=t.events)==null?void 0:c.onUpdateVirtualWall)==null||d.call(c,h)},onClick:h=>{var c,d;(d=(c=t.events)==null?void 0:c.onClickVirtualWall)==null||d.call(c,h)}}});i.set(o.id,l),this.addToControlLayer("virtualWall",l),this.syncControlEditingLayer("virtualWall",l)}})}getVirtualWalls(){return this.getWallsData(this.virtualWallMap)}clearAllVirtualWalls(){this.clearAllWalls(this.virtualWallMap)}drawThresholds(e){var o;const t=this.appService,i=this.thresholdMap,s=e.filter(a=>{var l;return Jo(a.points)?!0:(M.warn(`[Controls] threshold "${a.id}" ignored: points must be 4 corner coordinates (clockwise 左上→右上→右下→左下), got ${((l=a.points)==null?void 0:l.length)??0}`),!1)}),r=new Set(s.map(a=>a.id));for(const[a,l]of i)r.has(a)||((o=l.parent)==null||o.removeChild(l),l.destroy(),i.delete(a));s.forEach(a=>{const l=i.get(a.id);if(l)this.isThresholdDataEqual(l.getThresholdData(),a)||l.updateThresholdData(a);else{const h=new D0({appService:t,thresholdData:a,events:{onRemove:c=>{var d,u;(u=(d=t.events)==null?void 0:d.onRemoveThreshold)==null||u.call(d,c)},onUpdate:c=>{var d,u;(u=(d=t.events)==null?void 0:d.onUpdateThreshold)==null||u.call(d,c)},onClick:c=>{var d,u;(u=(d=t.events)==null?void 0:d.onClickThreshold)==null||u.call(d,c)}}});i.set(a.id,h),this.addToFloorMarkLayer("threshold",h),this.syncFloorMarkEditingLayer("threshold",h)}})}getThresholds(){return Array.from(this.thresholdMap.values()).map(e=>e.getThresholdData())}clearAllThresholds(){var e;for(const t of this.thresholdMap.values())(e=t.parent)==null||e.removeChild(t),t.destroy();this.thresholdMap.clear()}drawRamps(e){var o;const t=this.appService,i=this.rampMap,s=e.filter(a=>{var l;return au(a.points)?!0:(M.warn(`[Controls] ramp "${a.id}" ignored: points must be 4 corner coordinates (clockwise 左上→右上→右下→左下), got ${((l=a.points)==null?void 0:l.length)??0}`),!1)}),r=new Set(s.map(a=>a.id));for(const[a,l]of i)r.has(a)||((o=l.parent)==null||o.removeChild(l),l.destroy(),i.delete(a));s.forEach(a=>{const l=i.get(a.id);if(l)this.isRampDataEqual(l.getRampData(),a)||l.updateRampData(a);else{const h=new z0({appService:t,rampData:a,events:{onRemove:c=>{var d,u;(u=(d=t.events)==null?void 0:d.onRemoveRamp)==null||u.call(d,c)},onUpdate:c=>{var d,u;(u=(d=t.events)==null?void 0:d.onUpdateRamp)==null||u.call(d,c)},onClick:c=>{var d,u;(u=(d=t.events)==null?void 0:d.onClickRamp)==null||u.call(d,c)}}});i.set(a.id,h),this.addToFloorMarkLayer("ramp",h),this.syncFloorMarkEditingLayer("ramp",h)}})}getRamps(){return Array.from(this.rampMap.values()).map(e=>e.getRampData())}clearAllRamps(){var e;for(const t of this.rampMap.values())(e=t.parent)==null||e.removeChild(t),t.destroy();this.rampMap.clear()}drawSpots(e){this.drawSpotsInto(e,this.spotMap,{layer:"spot"})}getSpots(){return this.getSpotsData(this.spotMap)}clearAllSpots(){this.clearAllSpotsInternal(this.spotMap)}drawRoomAnchors(e){this.roomAnchorsData=e?[...e]:[],this.renderRoomAnchors()}getRoomAnchors(){return[...this.roomAnchorsData]}clearAllRoomAnchors(){this.roomAnchorsData=[],this.clearAllSpotsInternal(this.roomAnchorMap)}syncRoomAnchorData(e){this.roomAnchorsData.findIndex(i=>i.id===e.id)!==-1&&(this.roomAnchorsData=this.roomAnchorsData.map(i=>i.id===e.id?{...i,...e}:i))}refreshRoomAnchors(){this.clearAllSpotsInternal(this.roomAnchorMap),this.renderRoomAnchors()}renderRoomAnchors(){const e=this.appService.getConfig().controls.roomAnchor;if(!(e!=null&&e.show)){this.clearAllSpotsInternal(this.roomAnchorMap);return}this.drawSpotsInto(this.roomAnchorsData,this.roomAnchorMap,{layer:"roomAnchor",createOverrides:{config:e,iconAlias:"roomAnchorIcon",editingIdsKey:"editingRoomAnchorIds",events:{onUpdate:t=>{var s,r;const i={id:t.id,point:t.point,name:t.name,roomId:t.roomId};this.syncRoomAnchorData(i),(r=(s=this.appService.events)==null?void 0:s.onUpdateRoomAnchor)==null||r.call(s,i)},onClick:t=>{var i,s;(s=(i=this.appService.events)==null?void 0:i.onClickRoomAnchor)==null||s.call(i,{id:t.id,point:t.point,name:t.name,roomId:t.roomId})}}}})}getZoneMap(e){let t=this.zoneMaps.get(e);return t||(t=new Map,this.zoneMaps.set(e,t)),t}resolveZoneFactory(e){var s;const t=this.builtinZoneFactories[e];return t||((s=this.appService.getConfig().customZoneTypes)!=null&&s[e]?r=>new Un({deps:Gn(this.appService,{onRemove:o=>{var a,l;return(l=(a=this.appService.events)==null?void 0:a.onRemoveCustomZone)==null?void 0:l.call(a,e,o)},onUpdate:o=>{var a,l;return(l=(a=this.appService.events)==null?void 0:a.onUpdateCustomZone)==null?void 0:l.call(a,e,o)},onClick:o=>{var a,l;return(l=(a=this.appService.events)==null?void 0:a.onClickCustomZone)==null?void 0:l.call(a,e,o)}}),zoneData:r,zoneType:e}):null)}drawCustomZones(e,t){this.drawZonesByType(e,t)}getCustomZones(e){return this.getZonesDataByType(e)}clearCustomZones(e){this.clearAllZonesByType(e)}drawZonesByType(e,t){const i=this.resolveZoneFactory(e);if(!i){M.warn(`[ControlsManager] Unknown zone type: ${e}`);return}const s=this.getZoneMap(e);this.drawZonesImpl(t,s,i,e)}getZonesDataByType(e){const t=this.zoneMaps.get(e);return t?this.getZonesData(t):[]}clearAllZonesByType(e){const t=this.zoneMaps.get(e);t&&this.clearAllZones(t)}refreshZonesConfig(){for(const[e,t]of this.zoneMaps){if(t.size===0)continue;const i=this.resolveZoneFactory(e);if(!i)continue;const s=this.getZonesData(t);this.clearAllZones(t),this.drawZonesImpl(s,t,i,e)}}drawZonesImpl(e,t,i,s){if(!e||e.length===0){this.clearAllZones(t);return}const r=new Set(t.keys()),o=new Set(e.map(a=>a.id));for(const a of r)o.has(a)||this.removeZone(a,t);e.forEach(a=>{const l=t.get(a.id);l?this.isZoneDataEqual(l.getZoneData(),a)||l.updateZoneData(a):this.addNewZone(a,t,i,s)})}addNewZone(e,t,i,s){const r=i(e);t.set(e.id,r),this.addToControlLayer(s,r),r.setDisabled(this.getDisabledZoneIds(String(s)).includes(e.id)),r.setEditing(this.getEditingZoneIds(String(s)).includes(e.id)),this.syncControlEditingLayer(s,r)}removeZone(e,t){var s;const i=t.get(e);i&&((s=i.parent)==null||s.removeChild(i),i.destroy(),t.delete(e))}getZonesData(e){const t=[];return e.forEach(i=>{t.push(i.getZoneData())}),t}clearAllZones(e){e.forEach((t,i)=>{var r;const s=e.get(i);s&&((r=s.parent)==null||r.removeChild(s),s.destroy())}),e.clear()}getEditingZoneIds(e){var i;const t=this.appService.runtimeSnapshot;switch(e){case"forbiddenSweepZone":return t.editingForbiddenSweepZoneIds;case"forbiddenMopZone":return t.editingForbiddenMopZoneIds;case"cleanZone":return t.editingCleanZoneIds;default:return((i=t.editingCustomZoneIds)==null?void 0:i[e])??[]}}getDisabledZoneIds(e){var i;const t=this.appService.runtimeSnapshot;switch(e){case"forbiddenSweepZone":return t.disabledForbiddenSweepZoneIds;case"forbiddenMopZone":return t.disabledForbiddenMopZoneIds;case"cleanZone":return t.disabledCleanZoneIds;default:return((i=t.disabledCustomZoneIds)==null?void 0:i[e])??[]}}updateZonesEditState(e,t){const i=this.getEditingZoneIds(e),s=this.getDisabledZoneIds(e);t.forEach((r,o)=>{r.setDisabled(s.includes(o)),r.setEditing(i.includes(o)),this.syncControlEditingLayer(e,r)})}updateVirtualWallsEditState(e){e.forEach(t=>{t.updateEditingState(),this.syncControlEditingLayer("virtualWall",t)})}updateThresholdsEditState(e){e.forEach(t=>{t.updateEditingState(),this.syncFloorMarkEditingLayer("threshold",t)})}updateRampsEditState(e){e.forEach(t=>{t.updateEditingState(),this.syncFloorMarkEditingLayer("ramp",t)})}isZoneDataEqual(e,t){if(e.id!==t.id||e.points.length!==t.points.length)return!1;for(let i=0;i<e.points.length;i++){const s=e.points[i],r=t.points[i];if(Math.abs(s.x-r.x)>.1||Math.abs(s.y-r.y)>.1)return!1}return!0}getWallsData(e){return Array.from(e.values()).map(t=>t.getWallData())}clearAllWalls(e){for(const t of e.values())t.destroy();e.clear()}isWallDataEqual(e,t){if(e.id!==t.id||e.points.length!==t.points.length)return!1;for(let i=0;i<e.points.length;i++){const s=e.points[i],r=t.points[i];if(Math.abs(s.x-r.x)>.1||Math.abs(s.y-r.y)>.1)return!1}return!0}isThresholdDataEqual(e,t){if(e.id!==t.id||(e.type??"passable")!==(t.type??"passable")||e.points.length!==t.points.length)return!1;for(let i=0;i<e.points.length;i++){const s=e.points[i],r=t.points[i];if(Math.abs(s.x-r.x)>.1||Math.abs(s.y-r.y)>.1)return!1}return!0}isRampDataEqual(e,t){if(e.id!==t.id||e.points.length!==t.points.length)return!1;for(let i=0;i<e.points.length;i++){const s=e.points[i],r=t.points[i];if(Math.abs(s.x-r.x)>.1||Math.abs(s.y-r.y)>.1)return!1}return!0}drawSpotsInto(e,t,i){if(!e||e.length===0){this.clearAllSpotsInternal(t);return}const s=new Set(t.keys()),r=new Set(e.map(o=>o.id));for(const o of s)r.has(o)||this.removeSpot(o,t);e.forEach(o=>{const a=t.get(o.id);a?this.isSpotDataEqual(a.getSpotData(),o)||a.updateSpotData(o):this.addNewSpot(o,t,i)})}addNewSpot(e,t,i){const s=ca.create(this.appService,e,i.createOverrides);t.set(e.id,s),this.addToControlLayer(i.layer,s),this.syncControlEditingLayer(i.layer,s)}removeSpot(e,t){var s;const i=t.get(e);i&&((s=i.parent)==null||s.removeChild(i),i.destroy(),t.delete(e))}getSpotsData(e){const t=[];return e.forEach(i=>{t.push(i.getSpotData())}),t}clearAllSpotsInternal(e){e.forEach((t,i)=>{var r;const s=e.get(i);s&&((r=s.parent)==null||r.removeChild(s),s.destroy())}),e.clear()}updateSpotsEditState(e,t){e.forEach(i=>{i.updateEditState(),this.syncControlEditingLayer(t,i)})}refreshSpotsEditState(){this.updateSpotsEditState(this.spotMap,"spot")}isSpotDataEqual(e,t){if(e.id!==t.id)return!1;const i=e.point,s=t.point;return Math.abs(i.x-s.x)>.1||Math.abs(i.y-s.y)>.1||e.roomId!==t.roomId?!1:e.name===t.name}drawWayPoints(e){M.log("[ControlsManager] drawWayPoints",e);const t=Array.from(this.wayPointMap.keys()),i=e.map(r=>r.id);t.filter(r=>!i.includes(r)).forEach(r=>{this.removeWayPoint(r,this.wayPointMap)}),e.forEach((r,o)=>{const a=o+1,l=this.wayPointMap.get(r.id);l?(this.isWayPointDataEqual(l.getWayPointData(),r)||l.updateWayPoint(r),l.updateOrder(a)):this.addNewWayPoint(r,a,this.wayPointMap)})}clearAllWayPoints(){M.log("[ControlsManager] clearAllWayPoints"),this.clearAllWayPointsInternal(this.wayPointMap)}getWayPoints(){return this.getWayPointsData(this.wayPointMap)}refreshWayPointsConfig(){this.updateWayPointsEditState(this.wayPointMap)}addNewWayPoint(e,t,i){var o,a;const s=this.appService,r=new G0({appService:s,wayPointData:e,order:t,events:{onUpdate:(o=s.events)==null?void 0:o.onUpdateWayPoint,onClick:(a=s.events)==null?void 0:a.onClickWayPoint}});i.set(e.id,r),this.addToControlLayer("wayPoint",r),this.syncControlEditingLayer("wayPoint",r)}removeWayPoint(e,t){var s;const i=t.get(e);i&&((s=i.parent)==null||s.removeChild(i),i.destroy(),t.delete(e))}getWayPointsData(e){const t=[];return e.forEach(i=>{t.push(i.getWayPointData())}),t}clearAllWayPointsInternal(e){e.forEach((t,i)=>{var r;const s=e.get(i);s&&((r=s.parent)==null||r.removeChild(s),s.destroy())}),e.clear()}updateWayPointsEditState(e){e.forEach(t=>{t.onEditStateChange(),this.syncControlEditingLayer("wayPoint",t)})}isWayPointDataEqual(e,t){if(e.id!==t.id)return!1;const i=e.point,s=t.point;return Math.abs(i.x-s.x)>.1||Math.abs(i.y-s.y)>.1?!1:e.name===t.name&&e.canDrag===t.canDrag}handleDividingRoomIdChange(e){if(e==null||e===-1){this.clearDivider();return}if(!this.getRoomGeometry(e)){this.clearDivider();return}this.createDefaultDivider(e)}getRoomGeometry(e){return this.appService.mapManager.getRoomById(e)}createDefaultDivider(e){const t=this.appService;this.clearDivider(),this.divider=new U0({appService:this.appService,roomId:e,events:{onUpdate:i=>{var s,r;(r=(s=t.events)==null?void 0:s.onUpdateDivider)==null||r.call(s,i)},onOutOfRoom:i=>{var s,r;(r=(s=t.events)==null?void 0:s.onDividerOutOfRoom)==null||r.call(s,i)}}}),this.addToControlLayer("divider",this.divider)}clearDivider(){var e;this.divider&&((e=this.divider.parent)==null||e.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(){M.debug("[ControlsManager] Unit changed, refreshing all size texts");for(const e of this.zoneMaps.values())e.forEach(t=>{t.refreshDisplay()});this.virtualWallMap.forEach(e=>{e.refreshDisplay()}),this.thresholdMap.forEach(e=>{e.refreshDisplay()}),this.rampMap.forEach(e=>{e.refreshDisplay()}),this.spotMap.forEach(e=>{e.refreshDisplay()}),this.roomAnchorMap.forEach(e=>{e.refreshDisplay()})}destroy(){this.unsubscribeFns.forEach(e=>e()),this.unsubscribeFns=[];for(const e of this.zoneMaps.keys())this.clearAllZonesByType(e);this.clearAllVirtualWalls(),this.clearAllThresholds(),this.clearAllRamps(),this.clearAllSpots(),this.clearAllRoomAnchors(),this.clearDivider(),this.controlContainers.forEach(e=>{e.removeFromParent(),e.destroy({children:!0})}),this.controlContainers.clear(),this.floorMarkContainers.forEach(e=>{e.removeFromParent(),e.destroy({children:!0})}),this.floorMarkContainers.clear(),this.editingContainers.forEach(e=>{e.removeFromParent(),e.destroy({children:!0})}),this.editingContainers.clear()}}class X0 extends Yt{constructor(t,i){super(t);y(this,"objectData");y(this,"clickHandler",null);y(this,"unsubscribeMapRotation",null);this.appService=t,this.objectData=i}async initializeSprite(){const t=this.appService.detectedObjectConfig,i=this.objectData.width||t.width,s=this.objectData.height||t.height;this.refreshElasticConfig(),await this.loadTextureAndSetSize(this.objectData.src,{width:i,height:s}),this.anchor.set(t.anchor.x,t.anchor.y),this.position.set(this.objectData.x,this.objectData.y),this.visible=!0,this.applyAntiRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation=z(this.appService.runtime,"mapRotation",r=>{this.applyAntiRotation(r)}),t.interactive?this.setupClickHandler():this.eventMode="none"}refreshElasticConfig(){var t;if(!((t=this.appService.elasticScale)!=null&&t.isAvailable())){this.setElasticFactors(null);return}this.setElasticFactors(Uv(this.appService.detectedObjectConfig,this.appService.elasticScaleConfig.breakpoints))}applyAntiRotation(t){const i=-t*Math.PI/180;this.rotation=i}setupClickHandler(){this.clickHandler&&this.clickHandler.destroy(),this.clickHandler=new yt(this,{onClick:()=>this.handleClick(),stopPropagation:!1})}handleClick(){var t,i;(i=(t=this.appService.events)==null?void 0:t.onClickDetectedObject)==null||i.call(t,this.getObjectData())}getObjectData(){return{...this.objectData}}async updateObjectData(t){const i=this.objectData;this.objectData=t;const s=this.appService.detectedObjectConfig;if(this.refreshElasticConfig(),i.src!==t.src){const r=t.width||s.width,o=t.height||s.height;await this.loadTextureAndSetSize(t.src,{width:r,height:o})}if(i.width!==t.width||i.height!==t.height){const r=t.width||s.width,o=t.height||s.height;this.setFixedSize(r,o)}this.position.set(t.x,t.y),s.interactive?this.clickHandler||this.setupClickHandler():this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null)}isSameData(t){return this.objectData.id===t.id&&this.objectData.src===t.src&&this.objectData.x===t.x&&this.objectData.y===t.y&&this.objectData.width===t.width&&this.objectData.height===t.height}destroy(){this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null),super.destroy()}}class Y0{constructor(e){y(this,"detectedObjectMap",new Map);y(this,"unsubscribeShowDetectedObjects",null);this.appService=e,this.applyLayerVisibility(this.appService.runtime.showDetectedObjects),this.unsubscribeShowDetectedObjects=z(this.appService.runtime,"showDetectedObjects",t=>{this.applyLayerVisibility(t)})}getDiagnosticObjects(e=201){if(this.detectedObjectMap.size>e)throw new Error("BUDGET_EXCEEDED: entities");return Array.from(this.detectedObjectMap.entries(),([t,i])=>({type:"detectedObject",id:t,container:i,read:()=>i.getObjectData()}))}async drawDetectedObjects(e){if(!e||e.length===0){this.clearAllDetectedObjects();return}const t=new Set(e.map(s=>s.id)),i=Array.from(this.detectedObjectMap.keys());for(const s of i)t.has(s)||this.removeDetectedObject(s);for(const s of e){const r=this.detectedObjectMap.get(s.id);r?r.isSameData(s)||await r.updateObjectData(s):await this.addNewDetectedObject(s)}}refreshElasticConfig(){this.detectedObjectMap.forEach(e=>{e.refreshElasticConfig()})}applyLayerVisibility(e){const t=this.appService.appContainer.getLayer(pi);t&&(t.visible=e)}clearAllDetectedObjects(){const e=this.appService;this.detectedObjectMap.forEach(t=>{e.appContainer.removeFromLayer(pi,t),t.destroy()}),this.detectedObjectMap.clear()}async addNewDetectedObject(e){const t=this.appService,i=new X0(this.appService,e);await i.initializeSprite(),this.detectedObjectMap.set(e.id,i),t.appContainer.addToLayer(pi,i)}removeDetectedObject(e){const t=this.appService,i=this.detectedObjectMap.get(e);i&&(t.appContainer.removeFromLayer(pi,i),i.destroy(),this.detectedObjectMap.delete(e))}destroy(){this.unsubscribeShowDetectedObjects&&(this.unsubscribeShowDetectedObjects(),this.unsubscribeShowDetectedObjects=null),this.clearAllDetectedObjects()}}var Ke={},cp={},ye={};Object.defineProperty(ye,"__esModule",{value:!0});ye.loop=ye.conditional=ye.parse=void 0;var j0=function n(e,t){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(t))t.forEach(function(o){return n(e,o,i,s)});else if(typeof t=="function")t(e,i,s,n);else{var r=Object.keys(t)[0];Array.isArray(t[r])?(s[r]={},n(e,t[r],i,s[r])):s[r]=t[r](e,i,s,n)}return i};ye.parse=j0;var Z0=function(e,t){return function(i,s,r,o){t(i,s,r)&&o(i,e,s,r)}};ye.conditional=Z0;var q0=function(e,t){return function(i,s,r,o){for(var a=[],l=i.pos;t(i,s,r);){var h={};if(o(i,e,s,h),i.pos===l)break;l=i.pos,a.push(h)}return a}};ye.loop=q0;var gt={};Object.defineProperty(gt,"__esModule",{value:!0});gt.readBits=gt.readArray=gt.readUnsigned=gt.readString=gt.peekBytes=gt.readBytes=gt.peekByte=gt.readByte=gt.buildStream=void 0;var K0=function(e){return{data:e,pos:0}};gt.buildStream=K0;var dp=function(){return function(e){return e.data[e.pos++]}};gt.readByte=dp;var Q0=function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return function(t){return t.data[t.pos+e]}};gt.peekByte=Q0;var Hn=function(e){return function(t){return t.data.subarray(t.pos,t.pos+=e)}};gt.readBytes=Hn;var J0=function(e){return function(t){return t.data.subarray(t.pos,t.pos+e)}};gt.peekBytes=J0;var tC=function(e){return function(t){return Array.from(Hn(e)(t)).map(function(i){return String.fromCharCode(i)}).join("")}};gt.readString=tC;var eC=function(e){return function(t){var i=Hn(2)(t);return e?(i[1]<<8)+i[0]:(i[0]<<8)+i[1]}};gt.readUnsigned=eC;var iC=function(e,t){return function(i,s,r){for(var o=typeof t=="function"?t(i,s,r):t,a=Hn(e),l=new Array(o),h=0;h<o;h++)l[h]=a(i);return l}};gt.readArray=iC;var sC=function(e,t,i){for(var s=0,r=0;r<i;r++)s+=e[t+r]&&Math.pow(2,i-r-1);return s},nC=function(e){return function(t){for(var i=dp()(t),s=new Array(8),r=0;r<8;r++)s[7-r]=!!(i&1<<r);return Object.keys(e).reduce(function(o,a){var l=e[a];return l.length?o[a]=sC(s,l.index,l.length):o[a]=s[l.index],o},{})}};gt.readBits=nC;(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var e=ye,t=gt,i={blocks:function(u){for(var p=0,f=[],m=u.data.length,g=0,x=(0,t.readByte)()(u);x!==p&&x;x=(0,t.readByte)()(u)){if(u.pos+x>=m){var S=m-u.pos;f.push((0,t.readBytes)(S)(u)),g+=S;break}f.push((0,t.readBytes)(x)(u)),g+=x}for(var b=new Uint8Array(g),w=0,_=0;_<f.length;_++)b.set(f[_],w),w+=f[_].length;return b}},s=(0,e.conditional)({gce:[{codes:(0,t.readBytes)(2)},{byteSize:(0,t.readByte)()},{extras:(0,t.readBits)({future:{index:0,length:3},disposal:{index:3,length:3},userInput:{index:6},transparentColorGiven:{index:7}})},{delay:(0,t.readUnsigned)(!0)},{transparentColorIndex:(0,t.readByte)()},{terminator:(0,t.readByte)()}]},function(d){var u=(0,t.peekBytes)(2)(d);return u[0]===33&&u[1]===249}),r=(0,e.conditional)({image:[{code:(0,t.readByte)()},{descriptor:[{left:(0,t.readUnsigned)(!0)},{top:(0,t.readUnsigned)(!0)},{width:(0,t.readUnsigned)(!0)},{height:(0,t.readUnsigned)(!0)},{lct:(0,t.readBits)({exists:{index:0},interlaced:{index:1},sort:{index:2},future:{index:3,length:2},size:{index:5,length:3}})}]},(0,e.conditional)({lct:(0,t.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,t.readByte)()},i]}]},function(d){return(0,t.peekByte)()(d)===44}),o=(0,e.conditional)({text:[{codes:(0,t.readBytes)(2)},{blockSize:(0,t.readByte)()},{preData:function(u,p,f){return(0,t.readBytes)(f.text.blockSize)(u)}},i]},function(d){var u=(0,t.peekBytes)(2)(d);return u[0]===33&&u[1]===1}),a=(0,e.conditional)({application:[{codes:(0,t.readBytes)(2)},{blockSize:(0,t.readByte)()},{id:function(u,p,f){return(0,t.readString)(f.blockSize)(u)}},i]},function(d){var u=(0,t.peekBytes)(2)(d);return u[0]===33&&u[1]===255}),l=(0,e.conditional)({comment:[{codes:(0,t.readBytes)(2)},i]},function(d){var u=(0,t.peekBytes)(2)(d);return u[0]===33&&u[1]===254}),h=[{header:[{signature:(0,t.readString)(3)},{version:(0,t.readString)(3)}]},{lsd:[{width:(0,t.readUnsigned)(!0)},{height:(0,t.readUnsigned)(!0)},{gct:(0,t.readBits)({exists:{index:0},resolution:{index:1,length:3},sort:{index:4},size:{index:5,length:3}})},{backgroundColorIndex:(0,t.readByte)()},{pixelAspectRatio:(0,t.readByte)()}]},(0,e.conditional)({gct:(0,t.readArray)(3,function(d,u){return Math.pow(2,u.lsd.gct.size+1)})},function(d,u){return u.lsd.gct.exists}),{frames:(0,e.loop)([s,a,l,r,o],function(d){var u=(0,t.peekByte)()(d);return u===33||u===44})}],c=h;n.default=c})(cp);var Nn={};Object.defineProperty(Nn,"__esModule",{value:!0});Nn.deinterlace=void 0;var rC=function(e,t){for(var i=new Array(e.length),s=e.length/t,r=function(u,p){var f=e.slice(p*t,(p+1)*t);i.splice.apply(i,[u*t,t].concat(f))},o=[0,4,2,1],a=[8,8,4,2],l=0,h=0;h<4;h++)for(var c=o[h];c<s;c+=a[h])r(c,l),l++;return i};Nn.deinterlace=rC;var Vn={};Object.defineProperty(Vn,"__esModule",{value:!0});Vn.lzw=void 0;var oC=function(e,t,i){var s=4096,r=-1,o=i,a,l,h,c,d,u,p,v,f,m,_,g,C,P,R,A,x=new Array(i),S=new Array(s),b=new Array(s),w=new Array(s+1);for(g=e,l=1<<g,d=l+1,a=l+2,p=r,c=g+1,h=(1<<c)-1,f=0;f<l;f++)S[f]=0,b[f]=f;var _,v,C,P,A,R;for(_=v=C=P=A=R=0,m=0;m<o;){if(P===0){if(v<c){_+=t[R]<<v,v+=8,R++;continue}if(f=_&h,_>>=c,v-=c,f>a||f==d)break;if(f==l){c=g+1,h=(1<<c)-1,a=l+2,p=r;continue}if(p==r){w[P++]=b[f],p=f,C=f;continue}for(u=f,f==a&&(w[P++]=C,f=p);f>l;)w[P++]=b[f],f=S[f];C=b[f]&255,w[P++]=C,a<s&&(S[a]=p,b[a]=C,a++,!(a&h)&&a<s&&(c++,h+=a)),p=u}P--,x[A++]=w[P],m++}for(m=A;m<o;m++)x[m]=0;return x};Vn.lzw=oC;Object.defineProperty(Ke,"__esModule",{value:!0});var up=Ke.decompressFrames=Ke.decompressFrame=pp=Ke.parseGIF=void 0,aC=uC(cp),lC=ye,hC=gt,cC=Nn,dC=Vn;function uC(n){return n&&n.__esModule?n:{default:n}}var pC=function(e){var t=new Uint8Array(e);return(0,lC.parse)((0,hC.buildStream)(t),aC.default)},pp=Ke.parseGIF=pC,fC=function(e){for(var t=e.pixels.length,i=new Uint8ClampedArray(t*4),s=0;s<t;s++){var r=s*4,o=e.pixels[s],a=e.colorTable[o]||[0,0,0];i[r]=a[0],i[r+1]=a[1],i[r+2]=a[2],i[r+3]=o!==e.transparentIndex?255:0}return i},fp=function(e,t,i){if(!e.image){console.warn("gif frame does not have associated image.");return}var s=e.image,r=s.descriptor.width*s.descriptor.height,o=(0,dC.lzw)(s.data.minCodeSize,s.data.blocks,r);s.descriptor.lct.interlaced&&(o=(0,cC.deinterlace)(o,s.descriptor.width));var a={pixels:o,dims:{top:e.image.descriptor.top,left:e.image.descriptor.left,width:e.image.descriptor.width,height:e.image.descriptor.height}};return s.descriptor.lct&&s.descriptor.lct.exists?a.colorTable=s.lct:a.colorTable=t,e.gce&&(a.delay=(e.gce.delay||10)*10,a.disposalType=e.gce.extras.disposal,e.gce.extras.transparentColorGiven&&(a.transparentIndex=e.gce.transparentColorIndex)),i&&(a.patch=fC(a)),a};Ke.decompressFrame=fp;var gC=function(e,t){return e.frames.filter(function(i){return i.image}).map(function(i){return fp(i,e.gct,t)})};up=Ke.decompressFrames=gC;class $n{constructor(e){if(!e||!e.length)throw new Error("Invalid frames");const[{texture:{width:t,height:i}}]=e;this.width=t,this.height=i,this.frames=e,this.textures=this.frames.map(s=>s.texture),this.totalFrames=this.frames.length,this.duration=this.frames[this.totalFrames-1].end}destroy(){for(const e of this.textures)e.destroy(!0);for(const e of this.frames)e.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(e,t){if(!e||e.byteLength===0)throw new Error("Invalid buffer");const i=S=>{let b=null;for(const w of S.frames)b=w.gce??b,"image"in w&&!("gce"in w)&&(w.gce=b)},s=pp(e);i(s);const r=up(s,!0),o=[],a=s.lsd.width,l=s.lsd.height,h=Z.get().createCanvas(a,l),c=h.getContext("2d",{willReadFrequently:!0}),d=Z.get().createCanvas(),u=d.getContext("2d");let p=0,f=null;const{fps:m=30,...g}=t??{},x=1e3/m;for(let S=0;S<r.length;S++){const{disposalType:b=2,delay:w=x,patch:_,dims:{width:v,height:C,left:P,top:A}}=r[S];d.width=v,d.height=C,u.clearRect(0,0,v,C);const R=u.createImageData(v,C);R.data.set(_),u.putImageData(R,0,0),b===3&&(f=c.getImageData(0,0,a,l)),c.drawImage(d,P,A);const T=c.getImageData(0,0,a,l);b===2?c.clearRect(0,0,a,l):b===3&&c.putImageData(f,0,0);const E=Z.get().createCanvas(T.width,T.height);E.getContext("2d").putImageData(T,0,0),o.push({start:p,end:p+w,texture:new U({source:new Do({resource:E,...g})})}),p+=w}return h.width=h.height=0,d.width=d.height=0,new $n(o)}}const mC={extension:B.Asset,detection:{test:async()=>!0,add:async n=>[...n,"gif"],remove:async n=>n.filter(e=>e!=="gif")},loader:{name:"gifLoader",id:"gif",test:n=>It.extname(n)===".gif"||n.startsWith("data:image/gif"),load:async(n,e)=>{const i=await(await Z.get().fetch(n)).arrayBuffer();return $n.from(i,e==null?void 0:e.data)},unload:async n=>{n.destroy()}}},gp=class Po extends re{constructor(...e){const t=e[0]instanceof $n?{source:e[0]}:e[0],{source:i,fps:s,loop:r,animationSpeed:o,autoPlay:a,autoUpdate:l,onComplete:h,onFrameChange:c,onLoop:d,...u}=Object.assign({},Po.defaultOptions,t);super({texture:U.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:l,onComplete:h,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,ke.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(e){var o,a;if(!this._playing)return;const t=this.animationSpeed*e.deltaTime/mt.targetFPMS,i=this._currentTime+t,s=i%this.duration,r=this._source.frames.findIndex(l=>l.start<=s&&l.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(e){e!==this._autoUpdate&&(this._autoUpdate=e,!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(e){this._updateFrameIndex(e),this._currentTime=this._source.frames[e].start}get source(){return this._source}_updateFrameIndex(e){var t;if(e<0||e>=this.totalFrames)throw new Error(`Frame index out of range, expecting 0 to ${this.totalFrames}, got ${e}`);this._currentFrame!==e&&(this._currentFrame=e,this.dirty=!0,(t=this.onFrameChange)==null||t.call(this,e))}get totalFrames(){return this._source.totalFrames}destroy(e=!1){this.stop(),super.destroy(),e&&this._source.destroy();const t=null;this._source=t,this.onComplete=t,this.onFrameChange=t,this.onLoop=t}clone(){const e=new Po({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 e.dirty=!0,e}};gp.defaultOptions={fps:30,loop:!0,animationSpeed:1,autoPlay:!0,autoUpdate:!0,onComplete:null,onFrameChange:null,onLoop:null};let yC=gp;Q.add(mC);class da extends yC{constructor(t,i){super(i);y(this,"throttledUpdateScale");y(this,"fixedWidth",0);y(this,"fixedHeight",0);y(this,"isFixedSizeSet",!1);y(this,"sizeFixed",!0);y(this,"baselineScale",1);y(this,"basePositionX",0);y(this,"basePositionY",0);y(this,"pixelOffset",null);this.appService=t,this.anchor.set(.5),this.visible=!1,this.throttledUpdateScale=Pt(this.updateScale.bind(this),30,{leading:!0,trailing:!0}),this.registerScaleListener()}setFixedSize(t,i){this.fixedWidth=t,this.fixedHeight=i,this.isFixedSizeSet=!0,this.applySize()}setSizeFixed(t){this.sizeFixed=t,this.baselineScale=1,t&&this.isFixedSizeSet?this.applySize():!t&&this.isFixedSizeSet&&this.applySize()}setBasePosition(t,i){this.basePositionX=t,this.basePositionY=i,this.pixelOffset?this.applyPixelOffset():this.position.set(t,i)}setPixelOffset(t){this.pixelOffset=t,t?this.applyPixelOffset():this.position.set(this.basePositionX,this.basePositionY)}applyPixelOffset(){if(this.destroyed||!this.pixelOffset)return;if(!this.sizeFixed){this.position.set(this.basePositionX,this.basePositionY);return}const t=this.appService.currentScale,i=this.appService.appContainer.getMapRotationRadians(),s=Bn(this.pixelOffset,t,i);this.position.set(this.basePositionX+s.x,this.basePositionY+s.y)}set width(t){if(this.isFixedSizeSet){M.warn("EnhancedGifSprite: 使用 setFixedSize() 方法来设置宽度");return}this.setFixedSize(t,this.fixedHeight||t)}set height(t){if(this.isFixedSizeSet){M.warn("EnhancedGifSprite: 使用 setFixedSize() 方法来设置高度");return}this.setFixedSize(this.fixedWidth||t,t)}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 t=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=t/s,o=i/s;super.scale.set(r,o)}else super.scale.set(t/this.baselineScale,i/this.baselineScale)}updateScale(t){this.sizeFixed&&(this.isFixedSizeSet?this.applySize():t!==0&&super.scale.set(1/t),this.applyPixelOffset())}static async createFromSrc(t,i,s){try{const r=await Y.load(i),o=new da(t,{source:r});return s.sizeFixed!==void 0&&o.setSizeFixed(s.sizeFixed),o.setFixedSize(s.width,s.height),o}catch(r){throw M.error(`Failed to load GIF "${i}":`,r),r}}draw(t,i){const{x:s,y:r,rotation:o=0}=t;i&&!this.visible?this.visible=i():!i&&!this.visible&&(this.visible=!0),this.rotation=o,this.position.set(s,r)}destroy(t){this.appService.emitter.off("antiScale",this.throttledUpdateScale),this.throttledUpdateScale.cancel(),super.destroy(t)}}class li extends da{constructor(t,i,s){super(t,{source:i});y(this,"elementData");y(this,"clickHandler",null);y(this,"unsubscribeMapRotation",null);y(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 t=this.elementData.anchor||{x:.5,y:.5};this.anchor.set(t.x,t.y),this.setPixelOffset(this.elementData.pixelOffset??null),this.setBasePosition(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=z(this.appService.runtime,"mapRotation",i=>{this.applyRotation(i),this.applyPixelOffset()}),this.visible=!0,this.elementData.interactive?this.setupClickHandler():this.eventMode="none"}applyRotation(t){const i=-t*Math.PI/180;this.rotation=this.userRotation+i}setupClickHandler(){this.clickHandler&&this.clickHandler.destroy(),this.clickHandler=new yt(this,{onClick:()=>this.handleClick(),stopPropagation:!1})}handleClick(){var t,i;(i=(t=this.appService.events)==null?void 0:t.onClickCustomElement)==null||i.call(t,this.getElementData())}getElementData(){return{...this.elementData}}async updateElementData(t){const i=this.elementData;if(this.elementData=t,i.src!==t.src)throw new Error("GIF source change requires recreation of instance");i.sizeFixed!==t.sizeFixed&&t.sizeFixed!==void 0&&this.setSizeFixed(t.sizeFixed),(i.width!==t.width||i.height!==t.height)&&this.setFixedSize(t.width,t.height);const s=t.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.setPixelOffset(t.pixelOffset??null),this.setBasePosition(t.x,t.y),t.rotation!==void 0&&(this.userRotation=t.rotation,this.applyRotation(this.appService.runtime.mapRotation)),t.opacity!==void 0&&(this.alpha=t.opacity),t.interactive?this.clickHandler||this.setupClickHandler():(this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null),this.eventMode="none")}isSameData(t){const i=this.elementData.anchor||{x:.5,y:.5},s=t.anchor||{x:.5,y:.5},r=this.elementData.pixelOffset,o=t.pixelOffset;return this.elementData.id===t.id&&this.elementData.type===t.type&&this.elementData.src===t.src&&this.elementData.x===t.x&&this.elementData.y===t.y&&this.elementData.width===t.width&&this.elementData.height===t.height&&this.elementData.rotation===t.rotation&&this.elementData.opacity===t.opacity&&this.elementData.interactive===t.interactive&&this.elementData.sizeFixed===t.sizeFixed&&i.x===s.x&&i.y===s.y&&((r==null?void 0:r.x)??0)===((o==null?void 0:o.x)??0)&&((r==null?void 0:r.y)??0)===((o==null?void 0:o.y)??0)}destroy(){this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null),super.destroy()}}class Ur extends Yt{constructor(t,i){super(t);y(this,"elementData");y(this,"clickHandler",null);y(this,"unsubscribeMapRotation",null);y(this,"userRotation",0);this.appService=t,this.elementData=i}async initialize(){await this.loadTextureAndSetSize(this.elementData.src,{width:this.elementData.width,height:this.elementData.height,sizeFixed:this.elementData.sizeFixed});const t=this.elementData.anchor||{x:.5,y:.5};this.anchor.set(t.x,t.y),this.setPixelOffset(this.elementData.pixelOffset??null),this.setBasePosition(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=z(this.appService.runtime,"mapRotation",i=>{this.applyRotation(i),this.applyPixelOffset()}),this.visible=!0,this.elementData.interactive?this.setupClickHandler():this.eventMode="none"}applyRotation(t){const i=-t*Math.PI/180;this.rotation=this.userRotation+i}setupClickHandler(){this.clickHandler&&this.clickHandler.destroy(),this.clickHandler=new yt(this,{onClick:()=>this.handleClick(),stopPropagation:!1})}handleClick(){var t,i;(i=(t=this.appService.events)==null?void 0:t.onClickCustomElement)==null||i.call(t,this.getElementData())}getElementData(){return{...this.elementData}}async updateElementData(t){const i=this.elementData;this.elementData=t,i.src!==t.src?await this.loadTextureAndSetSize(t.src,{width:t.width,height:t.height,sizeFixed:t.sizeFixed}):(i.sizeFixed!==t.sizeFixed&&t.sizeFixed!==void 0&&this.setSizeFixed(t.sizeFixed),(i.width!==t.width||i.height!==t.height)&&this.setFixedSize(t.width,t.height));const s=t.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.setPixelOffset(t.pixelOffset??null),this.setBasePosition(t.x,t.y),t.rotation!==void 0&&(this.userRotation=t.rotation,this.applyRotation(this.appService.runtime.mapRotation)),t.opacity!==void 0&&(this.alpha=t.opacity),t.interactive?this.clickHandler||this.setupClickHandler():(this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null),this.eventMode="none")}isSameData(t){const i=this.elementData.anchor||{x:.5,y:.5},s=t.anchor||{x:.5,y:.5},r=this.elementData.pixelOffset,o=t.pixelOffset;return this.elementData.id===t.id&&this.elementData.type===t.type&&this.elementData.src===t.src&&this.elementData.x===t.x&&this.elementData.y===t.y&&this.elementData.width===t.width&&this.elementData.height===t.height&&this.elementData.rotation===t.rotation&&this.elementData.opacity===t.opacity&&this.elementData.interactive===t.interactive&&this.elementData.sizeFixed===t.sizeFixed&&i.x===s.x&&i.y===s.y&&((r==null?void 0:r.x)??0)===((o==null?void 0:o.x)??0)&&((r==null?void 0:r.y)??0)===((o==null?void 0:o.y)??0)}destroy(){this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null),super.destroy()}}class xC extends Ex{constructor(t,i){super(i);y(this,"throttledUpdateScale");y(this,"fixedWidth",0);y(this,"fixedHeight",0);y(this,"isFixedSizeSet",!1);y(this,"userCenterX",0);y(this,"userCenterY",0);y(this,"sizeFixed",!0);y(this,"pixelOffset",null);this.appService=t,this.anchor.set(0,0),this.throttledUpdateScale=Pt(this.updateScale.bind(this),30,{leading:!0,trailing:!0}),this.registerScaleListener()}setFixedSize(t,i){this.fixedWidth=t,this.fixedHeight=i,this.isFixedSizeSet=!0,this.applyFixedSize(),this.updatePositionFromCenter()}setCenterPosition(t,i){this.userCenterX=t,this.userCenterY=i,this.updatePositionFromCenter()}setPixelOffset(t){this.pixelOffset=t,this.isFixedSizeSet&&this.updatePositionFromCenter()}applyPixelOffset(){this.isFixedSizeSet&&this.updatePositionFromCenter()}setSizeFixed(t){this.sizeFixed=t,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);let o=this.userCenterX,a=this.userCenterY;if(this.sizeFixed&&this.pixelOffset){const l=this.appService.appContainer.getMapRotationRadians(),h=Bn(this.pixelOffset,i,l);o+=h.x,a+=h.y}this.position.set(o-s,a-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(t){this.isFixedSizeSet&&t!==0&&(this.applyFixedSize(),this.updatePositionFromCenter())}updateTransform(t){return super.updateTransform(t)}destroy(t){this.appService.emitter.off("antiScale",this.throttledUpdateScale),this.throttledUpdateScale.cancel(),super.destroy(t)}}class ds extends xC{constructor(t,i){const s=document.createElement("div");ds.setupDefaultStyles(s,i),s.innerHTML=i.htmlContent;super(t,{element:s});y(this,"elementData");y(this,"domClickHandler",null);y(this,"resizeObserver",null);y(this,"debugMarker",null);y(this,"unsubscribeMapRotation",null);y(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.setPixelOffset(this.elementData.pixelOffset??null),this.elementData.rotation!==void 0&&(this.userRotation=this.elementData.rotation),this.applyRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation=z(this.appService.runtime,"mapRotation",t=>{this.applyRotation(t),this.applyPixelOffset()}),this.elementData.interactive?this.setupClickHandler():this.eventMode="none"}applyRotation(t){const i=-t*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 t=()=>{this.element&&(this.element.isConnected?this.showElement():requestAnimationFrame(t))};requestAnimationFrame(t)}waitForElementDimensions(){this.element&&(typeof ResizeObserver<"u"?(this.resizeObserver=new ResizeObserver(t=>{var s;const i=t[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 t=()=>{if(!this.element)return;if(!this.element.isConnected){requestAnimationFrame(t);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(t)};requestAnimationFrame(t)}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.syncDomOverlay(),this.appService.getApp().renderOnceNextFrame()}setupClickHandler(){this.element&&(this.domClickHandler=t=>{t.preventDefault(),t.stopPropagation(),this.handleClick()},this.element.addEventListener("click",this.domClickHandler))}handleClick(){var t,i;(i=(t=this.appService.events)==null?void 0:t.onClickCustomElement)==null||i.call(t,this.getElementData())}getElementData(){return{...this.elementData}}async updateElementData(t){const i=this.elementData;this.elementData=t,i.htmlContent!==t.htmlContent&&this.element&&(this.element.innerHTML=t.htmlContent,(!t.width||!t.height)&&this.waitForElementDimensions()),(i.width!==t.width||i.height!==t.height)&&(t.width&&t.height?(this.setFixedSize(t.width,t.height),this.element&&(this.element.style.width=`${t.width}px`,this.element.style.height=`${t.height}px`)):this.setupAutoSize()),this.setPixelOffset(t.pixelOffset??null),t.width&&t.height?this.setCenterPosition(t.x,t.y):this.getIsFixedSizeSet()?this.setCenterPosition(t.x,t.y):this.position.set(t.x,t.y),i.sizeFixed!==t.sizeFixed&&t.sizeFixed!==void 0&&this.setSizeFixed(t.sizeFixed),this.userRotation=t.rotation??0,this.applyRotation(this.appService.runtime.mapRotation),this.alpha=t.opacity??1,t.interactive?this.domClickHandler||this.setupClickHandler():(this.eventMode="none",this.domClickHandler&&this.element&&(this.element.removeEventListener("click",this.domClickHandler),this.domClickHandler=null))}isSameData(t){const i=this.elementData.pixelOffset,s=t.pixelOffset;return this.elementData.id===t.id&&this.elementData.type===t.type&&this.elementData.htmlContent===t.htmlContent&&this.elementData.x===t.x&&this.elementData.y===t.y&&this.elementData.width===t.width&&this.elementData.height===t.height&&this.elementData.rotation===t.rotation&&this.elementData.opacity===t.opacity&&this.elementData.interactive===t.interactive&&this.elementData.sizeFixed===t.sizeFixed&&((i==null?void 0:i.x)??0)===((s==null?void 0:s.x)??0)&&((i==null?void 0:i.y)??0)===((s==null?void 0:s.y)??0)}static setupDefaultStyles(t,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(t.style,s),t.style.setProperty("-webkit-tap-highlight-color","transparent"),t.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 SC{constructor(e){y(this,"customElementsMap",new Map);y(this,"gifTicker",null);y(this,"gifElements",new Set);this.appService=e}getDiagnosticObjects(e=201){if(this.customElementsMap.size>e)throw new Error("BUDGET_EXCEEDED: entities");return Array.from(this.customElementsMap.entries(),([t,i])=>({type:"customElement",id:t,container:i,read:()=>i.getElementData()}))}async drawCustomElements(e){if(!e||e.length===0){this.clearAllCustomElements();return}const t=new Set(e.map(r=>r.id)),i=Array.from(this.customElementsMap.keys());for(const r of i)t.has(r)||this.removeCustomElement(r);const s=e.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 e=this.appService;this.customElementsMap.forEach(t=>{t instanceof li?e.appContainer.removeFromLayer(hs,t):e.appContainer.removeFromLayer(ls,t),t.destroy()}),this.customElementsMap.clear(),this.gifElements.clear(),this.stopGifTicker()}async addNewCustomElement(e){const t=this.appService;let i;switch(e.type){case"image":i=new Ur(this.appService,e);break;case"gif":{const s=await Y.load(e.src);i=new li(this.appService,s,e);break}case"html":i=new ds(this.appService,e);break;default:throw new Error(`Unsupported custom element type: ${e.type}`)}await i.initialize(),this.customElementsMap.set(e.id,i),i instanceof li?(t.appContainer.addToLayer(hs,i),this.gifElements.add(i)):t.appContainer.addToLayer(ls,i)}removeCustomElement(e){const t=this.appService,i=this.customElementsMap.get(e);i&&(i instanceof li?(this.gifElements.delete(i),t.appContainer.removeFromLayer(hs,i)):t.appContainer.removeFromLayer(ls,i),i.destroy(),this.customElementsMap.delete(e))}isSameData(e,t){return e.getElementData().type!==t.type?!1:t.type==="image"&&e instanceof Ur||t.type==="gif"&&e instanceof li||t.type==="html"&&e instanceof ds?e.isSameData(t):!1}async updateElementData(e,t){if(t.type==="image"&&e instanceof Ur)await e.updateElementData(t);else if(t.type==="gif"&&e instanceof li)await e.updateElementData(t);else if(t.type==="html"&&e instanceof ds)await e.updateElementData(t);else throw new Error("Element type mismatch during update")}updateGifTicker(){this.gifElements.size>0?this.startGifTicker():this.stopGifTicker()}startGifTicker(){var e;(e=this.gifTicker)!=null&&e.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 e;(e=this.gifTicker)!=null&&e.started&&(M.log("⏸️ [GifTicker] 停止 GIF 专用渲染"),this.gifTicker.stop())}renderGifContainer(){const e=this.appService;if(this.gifElements.size===0)return;const t=e.getApp();t.renderer.render(t.stage)}destroy(){this.stopGifTicker(),this.gifTicker&&(this.gifTicker.destroy(),this.gifTicker=null),this.clearAllCustomElements()}}class bC extends O{constructor(t,i){super();y(this,"roomId");y(this,"roomIndex");y(this,"appService");y(this,"nameText");y(this,"iconSprite",null);y(this,"iconWrapper",null);y(this,"iconBg",null);this.appService=t,this.roomId=i.id,this.roomIndex=i.index;const{nameLabel:s,type:r}=t.roomConfig,{showRoomType:o}=t.runtime,a=i.colorIndex??i.index,l=this.getRoomNameColor(a),h=new ee({fontSize:s.fontSize,fontFamily:s.fontFamily,fontWeight:s.fontWeight,fill:l,align:"center"}),c=i.name||"Unknown";this.nameText=new xs({text:c,style:h}),this.nameText.anchor.set(.5),o&&i.type!=null&&(r!=null&&r.assets)&&r.assets[i.type]&&this.createIcon(i.type,l),this.addChild(this.nameText),this.layout()}createIcon(t,i){const{type:s}=this.appService.roomConfig,r=s.iconSize||14;this.iconWrapper||(this.iconWrapper=new O,this.addChild(this.iconWrapper)),s.container.visible?(this.iconBg||(this.iconBg=new W,this.iconWrapper.addChild(this.iconBg)),this.drawIconBg(i)):this.iconBg&&(this.iconBg.destroy(),this.iconBg=null),this.iconSprite||(this.iconSprite=new Yt(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[t],{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(t){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(t)}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,l=-(o+i+r)/2;s==="left"?(this.iconWrapper.x=l+o/2,this.nameText.x=l+o+i+r/2):(this.nameText.x=l+r/2,this.iconWrapper.x=l+r+i+o/2),this.iconWrapper.y=0,this.nameText.y=0}updateName(t){this.nameText.text=t,this.layout()}refreshColor(t){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,t);this.nameText.style.fill=o,this.iconBg&&this.drawIconBg(o),this.iconSprite&&(this.iconSprite.tint=i.container.visible?"#ffffff":o)}getRoomNameColor(t,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[t%s.nameInactive.length]:s.name[t%s.name.length];const a=s.nameNormal||s.name;return a[t%a.length]}async updateRoomType(t){const{type:i}=this.appService.roomConfig;if(!this.appService.runtime.showRoomType||t==null||!(i!=null&&i.assets)||!i.assets[t])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(t,a),this.iconWrapper&&(this.iconWrapper.visible=!0)}this.layout()}updateRoomTypeVisibility(t){if(this.iconWrapper)this.iconWrapper.visible=t,this.layout();else if(t){const i=this.appService.getRoomData(this.roomId);i&&this.updateRoomType(i.type??null)}}destroy(t){this.iconBg&&(this.iconBg.destroy(),this.iconBg=null),this.iconSprite&&(this.iconSprite.destroy(),this.iconSprite=null),this.iconWrapper&&(this.iconWrapper.destroy(),this.iconWrapper=null),this.nameText.destroy({texture:!0,textureSource:!0}),super.destroy(t)}}class vC extends O{constructor(t,i){super();y(this,"background");y(this,"foldedIndicator");y(this,"propertyIcons",new Map);y(this,"orderContainer");y(this,"orderBackground");y(this,"orderText");y(this,"isFolded",!1);y(this,"roomId");y(this,"roomIndex");y(this,"isDestroyed",!1);this.appService=t;const s=this.appService.roomConfig;this.roomId=i.id,this.roomIndex=i.index,this.background=new W,this.foldedIndicator=new W,this.foldedIndicator.visible=!1;const{property:r}=s,o=i.colorIndex??i.index,a=this.getIconColor(o);this.initializePropertyIcons(r.displayOrders,a);const l=this.resolveOrderTextColor(o);this.orderContainer=new O,this.orderBackground=new W,this.orderText=new xs({text:"",style:new ee({fontSize:r.cleanOrder.fontSize,fontFamily:r.cleanOrder.fontFamily,fontWeight:r.cleanOrder.fontWeight,fill:l,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:h})=>{this.addChild(h)}),this.addChild(this.orderContainer),this.visible=this.appService.runtimeSnapshot.showRoomProperty}initializePropertyIcons(t,i){const s=["cleanMode","suction","cistern","cleanTimes"];t.forEach(r=>{const o=s.includes(r),a=new Yt(this.appService);a.tint=i,a.anchor.set(0,0),this.propertyIcons.set(r,{fieldName:r,sprite:a,isBuiltin:o})})}async updateProperty(t){this.isDestroyed||this.destroyed||(await this.updateIcons(t),!(this.isDestroyed||this.destroyed)&&this.updateBackground())}getFieldValue(t,i){if(["cleanMode","suction","cistern","cleanTimes"].includes(i))return t[i]??null;if(t.customData&&i in t.customData){const r=t.customData[i];return typeof r=="number"?r:null}return null}getAssetAlias(t,i){const s={cleanMode:r=>`cleanMode_${r}`,suction:r=>`fan_${r}`,cistern:r=>`water_${r}`,cleanTimes:r=>`cleanTimes${r}`};return t in s?s[t](i):`custom_${t}_${i}`}shouldShowField(t,i,s){const{showRoomProperty:r}=this.appService.runtimeSnapshot;return!(s===null||!r||i==="cleanTimes"&&s<=0)}getDisplayElements(t){const{displayOrders:i}=this.appService.roomConfig.property,{showRoomOrder:s}=this.appService.runtimeSnapshot,r=t.order||0,o=s&&r>0,a=[];return o&&a.push({element:this.orderContainer,show:!0,isOrder:!0,fieldName:"order"}),i.forEach(l=>{const h=this.propertyIcons.get(l);if(!h||!h.sprite)return;const c=this.getFieldValue(t,l);this.shouldShowField(t,l,c)&&c!==null&&a.push({element:h.sprite,show:!0,isOrder:!1,fieldName:l,value:c})}),{elementsToShow:a,orderValue:r}}async updateIcons(t){if(this.isDestroyed||this.destroyed||this.isFolded)return;const{iconWidth:i,iconHeight:s,container:r,cleanOrder:o,iconGap:a}=this.appService.roomConfig.property,{paddingHorizontal:l,paddingVertical:h}=r,{elementsToShow:c,orderValue:d}=this.getDisplayElements(t);this.orderContainer.visible=!1,this.propertyIcons.forEach(({sprite:f})=>{f.visible=!1});const u=[];if(c.forEach(f=>{if(f.isOrder){this.orderContainer.visible=!0,this.orderText.text=d.toString();const m=t.colorIndex??this.roomIndex;this.orderBackground.clear(),this.orderBackground.setFillStyle({color:this.resolveOrderBackgroundColor(m)}),this.orderBackground.circle(i/2,s/2,i/2).fill();const g=this.resolveOrderTextColor(m);this.orderText.style.fill=g,this.orderText.position.set(i/2,s/2)}else{const m=this.propertyIcons.get(f.fieldName);if(m&&m.sprite){m.sprite.visible=!0;const g=this.getAssetAlias(f.fieldName,f.value);u.push(m.sprite.loadTextureAndSetSize(g,{width:i,height:s,sizeFixed:!1}))}}}),await Promise.all(u),this.isDestroyed||this.destroyed)return;let p=l;c.forEach((f,m)=>{const{element:g,isOrder:x}=f;!g||!g.position||(g.position.set(p,h),p+=i,m<c.length-1&&(x?p+=o.gapRight:p+=a))})}updateBackground(){if(this.isDestroyed||this.destroyed)return;const t=this.appService.roomConfig,{container:i,foldable:s}=t.property,{borderRadius:r,tailHeight:o,tailWidth:a,backgroundColor:l}=i,h=this.calculateContentWidth(),c=this.calculateContentHeight(),d=Math.min(r,h/2,c/2),u=d*.8,p=Math.max(h-u*2,a*.5),f=Math.min(a,h/2,p);if(this.background.clear(),this.background.setFillStyle({color:l}),s){const m=(h-f)/2,g=c+o;this.background.moveTo(d,0),this.background.lineTo(h-d,0),this.background.arcTo(h,0,h,d,d),this.background.lineTo(h,c-d),this.background.arcTo(h,c,h-d,c,d),this.background.lineTo(m+f,c),this.background.lineTo(m+f/2,g),this.background.lineTo(m,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,h,c,d);this.background.fill()}calculateContentWidth(){const{iconWidth:t,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:l}=this.getDisplayElements(a);let h=o;return l.forEach((c,d)=>{const{isOrder:u}=c;h+=t,d<l.length-1&&(u?h+=s.gapRight:h+=r)}),h+=o,h}calculateContentHeight(){const t=this.appService.roomConfig,{iconHeight:i,container:s}=t.property;return s.paddingVertical+i+s.paddingVertical}getTotalHeight(){const{foldable:t,container:i}=this.appService.roomConfig.property,{tailHeight:s}=i;return this.isFolded?s:this.calculateContentHeight()+(t?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(t){const{foldable:i}=this.appService.roomConfig.property;if(!i){(this.isFolded||this.foldedIndicator.visible)&&await this.expand();return}this.isFolded=t,t?(this.background.visible=!1,this.orderContainer.visible=!1,this.propertyIcons.forEach(({sprite:s})=>{s.visible=!1}),this.foldedIndicator.visible=!0,this.updateFoldedIndicator()):await this.expand()}async expand(){this.isFolded=!1,this.background.visible=!0,this.foldedIndicator.visible=!1,this.foldedIndicator.position.set(0,0),this.updateBackground();const t=this.appService.getRoomData(this.roomId);t&&await this.updateIcons(t)}isFoldedState(){const{foldable:t}=this.appService.roomConfig.property;return t?this.isFolded:!1}updateFoldedIndicator(){if(!this.appService.runtimeSnapshot.showRoomPropertyFoldIndicator){this.foldedIndicator.clear(),this.foldedIndicator.visible=!1;return}const t=this.appService.roomConfig,{tailHeight:i,tailWidth:s,backgroundColor:r}=t.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(t){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[t%o.length]}return i.cleanOrder.color}resolveOrderBackgroundColor(t){const{property:i}=this.appService.roomConfig;return i.cleanOrder.backgroundColor==="auto"?this.getIconColor(t):i.cleanOrder.backgroundColor}getIconColor(t){const{colors:i}=this.appService.roomConfig,{propertyTheme:s,propertyThemeInactive:r,propertyThemeNormal:o}=i,{enableRoomSelection:a,selectRoomIds:l}=this.appService.runtime;if(a)return!l.includes(this.roomId)&&r?r[t%r.length]:s[t%s.length];const h=o||s;return h[t%h.length]}refreshColor(){const t=this.appService.getRoomData(this.roomId),i=(t==null?void 0:t.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:this.resolveOrderBackgroundColor(i)}),this.orderBackground.circle(o/2,a/2,o/2).fill();const l=this.resolveOrderTextColor(i);this.orderText.style.fill=l}}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.propertyIcons.forEach(({sprite:t})=>{t.destroy()}),this.propertyIcons.clear(),super.destroy({children:!0,context:!0}))}}class wC extends O{constructor(t,i){super();y(this,"background");y(this,"checkmarkIcon");y(this,"bubble");y(this,"roomIndex");y(this,"roomId");this.appService=t;const s=this.appService.roomConfig;this.roomId=i.id,this.roomIndex=i.index,this.background=new W,this.bubble=new W;const{colors:{selectionIndicatorIcon:r}}=s;this.checkmarkIcon=new Yt(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(t){const{roomSelectionMode:i,enableRoomSelection:s,selectRoomIds:r}=this.appService.runtimeSnapshot;if(!s||i!=="checkmark"){this.visible=!1;return}const o=r.includes(t.id);await this.showCheckmarkMode(o),this.updateBackground()}async showCheckmarkMode(t){const{selectionIndicator:i}=this.appService.roomConfig,{iconWidth:s,iconHeight:r}=i;if(t){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:t,colors:i}=this.appService.roomConfig,{containerWidth:s,containerHeight:r,strokeWidth:o,strokeColor:a,borderRadius:l,tailHeight:h,tailWidth:c}=t,d=this.appService.getRoomData(this.roomId),u=(d==null?void 0:d.colorIndex)??this.roomIndex,p=i.selectionIndicatorBackground[u%i.selectionIndicatorBackground.length],f=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,l).fill().setStrokeStyle({color:f,width:o,alignment:0}).stroke(),h>0&&c>0){const m=(s-c)/2;this.bubble.setFillStyle({color:f});const g=r+o;this.bubble.poly([m,g-1,m+c,g-1,m+c/2,g+h]).fill()}}getTotalHeight(){const{selectionIndicator:t}=this.appService.roomConfig,{containerHeight:i,tailHeight:s,strokeWidth:r}=t;return i+r+(s>0?s:0)}getTotalWidth(){const{selectionIndicator:t}=this.appService.roomConfig;return t.containerWidth}async refreshColor(){const t=this.appService.getRoomData(this.roomId);t&&await this.updateIndicator(t)}destroy(){var t;(t=this.checkmarkIcon)==null||t.destroy(),super.destroy({children:!0,context:!0})}}class CC extends O{constructor(t,i){super();y(this,"roomId");y(this,"roomName");y(this,"roomProperty",null);y(this,"roomSelectionIndicator",null);y(this,"clickHandler",null);y(this,"unsubscribeMapRotation",null);y(this,"updateScaleBound",null);y(this,"elasticUpdateBound",null);y(this,"elasticFactors",null);this.appService=t,this.enableRenderGroup(),this.roomId=i.id,this.updateScaleBound=s=>this.updateScale(s),this.appService.emitter.on("antiScale",this.updateScaleBound),this.elasticUpdateBound=()=>this.updateScale(this.appService.currentScale),this.appService.emitter.on("elasticScaleUpdate",this.elasticUpdateBound),this.refreshElasticConfig(),this.updateScale(this.appService.currentScale),i.centerPoint&&this.position.set(i.centerPoint.x,i.centerPoint.y),this.roomName=new bC(this.appService,i),this.roomName.visible=this.appService.runtimeSnapshot.showRoomName,this.applyAntiRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation=z(this.appService.runtime,"mapRotation",s=>{this.applyAntiRotation(s)}),this.clickHandler=new yt(this,{onClick:()=>{var s,r;(r=(s=this.appService.events)==null?void 0:s.onClickRoomProperties)==null||r.call(s,i)}})}async initialize(t){await this.createRoomProperty(t),await this.createRoomSelectionIndicator(t),this.updateLayout()}applyAntiRotation(t){const i=-t*Math.PI/180;this.rotation=i}refreshElasticConfig(){var t;if(!((t=this.appService.elasticScale)!=null&&t.isAvailable())){this.elasticFactors=null;return}this.elasticFactors=Gv(this.appService.roomConfig,this.appService.elasticScaleConfig.breakpoints)}updateScale(t){var s;if(!t)return;const i=((s=this.appService.elasticScale)==null?void 0:s.getFactor(this.elasticFactors))??1;this.scale.set(1/t*i)}shouldShowRoomProperty(){const{showRoomOrder:t,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 l=t&&(a.order||0)>0;let h=!1;if(i){const{displayOrders:c}=this.appService.roomConfig.property;h=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 l||h}shouldShowRoomSelectionIndicator(){const{enableRoomSelection:t,roomSelectionMode:i}=this.appService.runtimeSnapshot;return t&&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(t){this.roomProperty&&(this.removeChild(this.roomProperty),this.roomProperty.destroy()),this.roomProperty=new vC(this.appService,t),await this.roomProperty.updateProperty(t),this.addChild(this.roomProperty),this.addChild(this.roomName),await this.updateRoomPropertyVisibility(),this.updateLayout()}async createRoomSelectionIndicator(t){this.roomSelectionIndicator&&(this.removeChild(this.roomSelectionIndicator),this.roomSelectionIndicator.destroy()),this.roomSelectionIndicator=new wC(this.appService,t),await this.updateRoomSelectionIndicatorVisibility(),this.addChild(this.roomSelectionIndicator)}updateLayout(){var h,c,d,u,p,f;if(this.destroyed)return;const{property:{offsetY:t,offsetX:i},selectionIndicator:{offsetY:s,offsetX:r}}=this.appService.roomConfig,o=((h=this.roomProperty)==null?void 0:h.visible)||!1,a=((c=this.roomName)==null?void 0:c.visible)||!1,l=((d=this.roomSelectionIndicator)==null?void 0:d.visible)||!1;if(o&&this.roomProperty){const m=this.roomProperty.getTotalHeight(),g=this.roomProperty.getTotalWidth();if(this.roomProperty.isFoldedState()){const S=-g/2+i,b=-m/2-t;this.roomProperty.position.set(S,b)}else a&&((u=this.roomName)!=null&&u.position)?(this.roomProperty.position.set(-g/2+i,-t-m),this.roomName.position.set(0,0)):this.roomProperty.position.set(-g/2+i,-m/2-t)}if(l&&this.roomSelectionIndicator){const m=this.roomSelectionIndicator.getTotalHeight(),g=this.roomSelectionIndicator.getTotalWidth();a&&((p=this.roomName)!=null&&p.position)?(this.roomSelectionIndicator.position.set(-g/2+r,-s-m),this.roomName.position.set(0,0)):this.roomSelectionIndicator.position.set(-g/2+r,-m/2-s)}a&&!o&&!l&&((f=this.roomName)!=null&&f.position)&&this.roomName.position.set(0,0)}updateName(t){this.roomName.updateName(t)}async updateRoomType(t){await this.roomName.updateRoomType(t),this.updateLayout()}updateRoomNameVisibility(t){this.roomName.visible=t,this.updateLayout()}updateRoomTypeVisibility(t){this.roomName.updateRoomTypeVisibility(t),this.updateLayout()}updatePosition(t){this.position.set(t.x,t.y)}async refreshColor(){this.roomName&&this.roomName.refreshColor(),this.roomProperty&&this.roomProperty.refreshColor(),this.roomSelectionIndicator&&await this.roomSelectionIndicator.refreshColor()}destroy(){var t,i,s,r;(t=this.clickHandler)==null||t.destroy(),this.clickHandler=null,this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),this.updateScaleBound&&(this.appService.emitter.off("antiScale",this.updateScaleBound),this.updateScaleBound=null),this.elasticUpdateBound&&(this.appService.emitter.off("elasticScaleUpdate",this.elasticUpdateBound),this.elasticUpdateBound=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(),this.isRenderGroup&&(this.isRenderGroup=!1),super.destroy()}}class MC extends O{constructor(t){super({isRenderGroup:!0});y(this,"floorTypeMap",new Map);y(this,"floorTypeMasks",new Map);y(this,"floorTypeContexts",new Map);y(this,"floorTypeToRooms",new Map);this.appService=t,this.appService.appContainer.addToLayer(sa,this)}async createFloorTypes(t){if(!this.appService.runtimeSnapshot.showRoomFloorType)return;this.clearFloorTypes();const s=this.groupRoomsByFloorType(t),r=[];for(const[o,a]of s)r.push(this.createMergedFloorType(o,a));await Promise.all(r)}groupRoomsByFloorType(t){const i=new Map,s=this.appService;return t.forEach((r,o)=>{const a=s.getRoomData(o),l=(a==null?void 0:a.floorType)||0;l>=0&&(i.has(l)||i.set(l,[]),i.get(l).push({roomId:o,graphics:r}))}),i}async createMergedFloorType(t,i){const s=this.appService,{assets:r,opacity:o,scale:a}=s.roomConfig.floorType,l=t%r.length,h=`floorType${l}`;if(!r[l]){M.warn(`No texture asset configured for floorType: ${t}`);return}const c=await Y.load(h);if(!c){M.warn(`Floor material texture not found: ${h}`);return}const d=i.map(({graphics:g})=>g.getLocalBounds()),u=bb(d),p=new Sn({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:f,contexts:m}=this.createMergedMask(i.map(({graphics:g})=>g));p.mask=f,this.addChild(p),this.floorTypeMap.set(t,p),this.floorTypeMasks.set(t,f),this.floorTypeContexts.set(t,m),this.floorTypeToRooms.set(t,new Set(i.map(({roomId:g})=>g)))}createMergedMask(t){const i=new O,s=[];return t.forEach(r=>{const o=new W,a=r.context.clone();o.context=a,s.push(a),i.addChild(o)}),{maskContainer:i,contexts:s}}clearFloorTypes(){this.floorTypeMasks.forEach(t=>{try{t.destroy({children:!0})}catch(i){M.warn("Error destroying floor mask:",i)}}),this.floorTypeMasks.clear(),this.floorTypeContexts.forEach(t=>{try{t.forEach(i=>{try{i.destroy()}catch(s){M.warn("Error destroying cloned graphics context:",s)}})}catch(i){M.warn("Error destroying graphics contexts:",i)}}),this.floorTypeContexts.clear(),this.floorTypeMap.forEach(t=>{try{this.removeChild(t),t.destroy()}catch(i){M.warn("Error destroying floor material:",i)}}),this.floorTypeMap.clear(),this.floorTypeToRooms.clear()}destroy(){this.clearFloorTypes(),super.destroy()}}const Hr=(n,e)=>n&&e?{x:n.x-e.x,y:n.y-e.y}:null;class _C{constructor(e){y(this,"unsubscribeFns",[]);y(this,"roomInfoContainer",new O);y(this,"roomInfoMap",new Map);y(this,"roomDisplayMap",new Map);y(this,"roomFloorType");this.appService=e,this.roomFloorType=new MC(e),e.appContainer.addToLayer(Iu,this.roomInfoContainer);const t=z(e.runtime,"showRoomFloorType",u=>{M.log(`[runtime] showRoomFloorType: ${u}`),u?this.updateFloorTypes():this.roomFloorType.clearFloorTypes()}),i=z(e.runtime,"showRoomProperty",u=>{M.log(`[runtime] showRoomProperty: ${u}`),this.updateAllRoomPropertyVisibility()}),s=z(e.runtime,"showRoomPropertyFoldIndicator",u=>{M.log(`[runtime] showRoomPropertyFoldIndicator: ${u}`),this.updateAllRoomPropertyVisibility()}),r=z(e.runtime,"showRoomOrder",u=>{M.log(`[runtime] showRoomOrder: ${u}`),this.updateAllRoomPropertyVisibility()}),o=z(e.runtime,"roomPropertyFoldIds",u=>{M.log(`[runtime] roomPropertyFoldIds: ${u}`),this.updateAllRoomPropertyVisibility()}),a=z(e.runtime,"showRoomName",u=>{M.log(`[runtime] showRoomName: ${u}`),this.updateAllRoomNameVisibility(u)}),l=z(e.runtime,"showRoomType",u=>{M.log(`[runtime] showRoomType: ${u}`),this.updateAllRoomTypeVisibility(u)}),h=z(e.runtime,"enableRoomSelection",u=>{M.log(`[runtime] enableRoomSelection: ${u}`),this.updateAllRoomPropertyVisibility(),this.updateAllRoomSelectionIndicatorVisibility(),this.refreshAllRoomColors()}),c=z(e.runtime,"selectRoomIds",u=>{M.log(`[runtime] selectRoomIds: ${u}`),this.updateAllRoomPropertyVisibility(),this.updateAllRoomSelectionIndicatorVisibility(),this.refreshAllRoomColors()}),d=z(e.runtime,"roomSelectionMode",u=>{M.log(`[runtime] roomSelectionMode: ${u}`),this.updateAllRoomPropertyVisibility(),this.updateAllRoomSelectionIndicatorVisibility(),this.refreshAllRoomColors()});this.unsubscribeFns.push(t,i,s,r,o,a,l,h,c,d)}async drawRoomProperty(e){var s;const t=this.appService;this.roomDisplayMap.clear();const i=((s=t.getApp().mapState)==null?void 0:s.origin)??null;return e.forEach((r,o)=>{const a=t.mapManager.getRoomById(r.id),l=(a==null?void 0:a.centerPoint)||null,h={...r,centerPoint:l,relativeCenterPoint:Hr(l,i),index:o,colorIndex:a==null?void 0:a.colorIndex};this.roomDisplayMap.set(r.id,h)}),await this.updateRoomInfoDisplay(),await this.updateFloorTypes(),!0}async updateRoomInfoDisplay(){if(this.roomDisplayMap.size===0){this.appService.mapManager.getAllRooms().length===0&&this.clearRoomInfos();return}const e=Array.from(this.roomDisplayMap.values()).filter(t=>t.centerPoint!==null);this.clearRoomInfos(),await Promise.all(e.map(t=>this.createRoomInfo(t)))}async createRoomInfo(e){var s,r;const t=new CC(this.appService,e);this.roomInfoContainer.addChild(t),this.roomInfoMap.set(e.id,t);const i=(r=(s=this.appService.mapManager).getRoomLabelAnchor)==null?void 0:r.call(s,e.id);i&&e.centerPoint&&(i.x!==e.centerPoint.x||i.y!==e.centerPoint.y)&&t.updatePosition(i),await t.initialize(e)}updateRoomName(e,t){const i=this.roomInfoMap.get(e);i&&i.updateName(t)}async updateRoomType(e,t){const i=this.roomDisplayMap.get(e);i&&(i.type=t);const s=this.roomInfoMap.get(e);s&&await s.updateRoomType(t)}updateRoomPosition(e,t){var r;const i=this.roomDisplayMap.get(e);if(i){i.centerPoint=t;const o=((r=this.appService.getApp().mapState)==null?void 0:r.origin)??null;i.relativeCenterPoint=Hr(t,o)}const s=this.roomInfoMap.get(e);s&&s.updatePosition(t)}clearRoomInfos(){if(this.roomInfoMap.size===0)return;const e=Array.from(this.roomInfoMap.values());this.roomInfoContainer.removeChildren(),e.forEach(t=>{try{t.destroy()}catch(i){M.warn(`[RoomManager] Error destroying RoomInfo for room ${t.roomId}:`,i)}}),this.roomInfoMap.clear()}getRoomPropertyById(e){return this.roomDisplayMap.get(e)}async refresh(){var i;const e=this.appService;this.roomFloorType.clearFloorTypes();const t=((i=e.getApp().mapState)==null?void 0:i.origin)??null;this.roomDisplayMap.forEach((s,r)=>{const o=e.mapManager.getRoomById(r),a=(o==null?void 0:o.centerPoint)||null;if(s.centerPoint!==a){s.centerPoint=a,s.relativeCenterPoint=Hr(a,t);const h=this.roomInfoMap.get(r);h&&a&&h.updatePosition(a)}const l=o==null?void 0:o.colorIndex;if(s.colorIndex!==l&&l!==void 0){s.colorIndex=l;const h=this.roomInfoMap.get(r);h&&h.refreshColor()}}),await this.updateRoomInfoDisplay(),await this.updateFloorTypes()}async refreshRoomConfig(){this.roomInfoMap.size!==0&&(this.refreshAllRoomColors(),await this.updateAllRoomPropertyVisibility())}refreshElasticConfig(){this.roomInfoMap.forEach(e=>{e.refreshElasticConfig()})}async updateAllRoomPropertyVisibility(){this.roomInfoMap.size!==0&&await Promise.all(Array.from(this.roomInfoMap.values()).map(async e=>{try{await e.updateRoomPropertyVisibility()}catch(t){console.warn(`[RoomManager] Failed to update room property visibility for room ${e.roomId}`,t)}}))}updateAllRoomNameVisibility(e){this.roomInfoMap.size!==0&&this.roomInfoMap.forEach(t=>{t.updateRoomNameVisibility(e)})}updateAllRoomTypeVisibility(e){this.roomInfoMap.size!==0&&this.roomInfoMap.forEach(t=>{t.updateRoomTypeVisibility(e)})}updateAllRoomSelectionIndicatorVisibility(){this.roomInfoMap.size!==0&&this.roomInfoMap.forEach(e=>{e.updateRoomSelectionIndicatorVisibility()})}refreshAllRoomColors(){this.roomInfoMap.size!==0&&this.roomInfoMap.forEach(e=>{e.refreshColor()})}async updateFloorTypes(){const e=this.appService,t=e.mapManager.roomFill.getRoomGraphicsMap();t.size>0?(await this.roomFloorType.createFloorTypes(t),e.getApp().renderOnceNextFrame()):e.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(e=>e()),this.unsubscribeFns=[],this.clearRoomInfos(),this.roomInfoContainer.destroy(),this.roomFloorType.destroy()}}var oc,ac;(oc=navigator==null?void 0:navigator.userAgent)!=null&&oc.includes("tuya-ark-ide")||((ac=navigator==null?void 0:navigator.userAgent)==null||ac.includes("miniProgram"));const PC=()=>{var i,s;if(!tg.any)return!0;const n=navigator.userAgent.toLowerCase(),e=()=>{const r=navigator.deviceMemory;return r?r>=4:!0};let t=!1;if(/iphone|ipad|ipod/.test(n)){const r=(i=n.match(/os (\d+)_/))==null?void 0:i[1];t=(r?parseInt(r):0)>=12}else if(/android/.test(n)){const r=(s=n.match(/android (\d+)/))==null?void 0:s[1];t=(r?parseInt(r):0)>=10}return t&&e()};class AC extends O{constructor(t,i,s){super();y(this,"graphics");y(this,"sprite",null);y(this,"viewportBounds");y(this,"lastConfig",null);y(this,"onImageLoaded");this.label="background",this.viewportBounds=i,this.onImageLoaded=s,this.graphics=new W,this.graphics.label="backgroundGraphics",this.addChild(this.graphics),this.render(t)}async render(t){if(this.lastConfig=t,this.clear(),t.backgroundImage){await this.renderImage(t.backgroundImage,t.backgroundAlpha);return}if(t.backgroundGradient){this.renderGradient(t.backgroundGradient);return}if(t.backgroundColor!==void 0){this.renderSolidColor(t.backgroundColor,t.backgroundAlpha);return}M.warn("[Background] No background configuration provided")}clear(){this.graphics.clear(),this.sprite&&(this.removeChild(this.sprite),this.sprite.destroy(),this.sprite=null)}renderSolidColor(t,i){this.graphics.clear(),this.graphics.rect(0,0,this.viewportBounds.width,this.viewportBounds.height).fill({color:t,alpha:i}),M.debug("[Background] Rendered solid color background",{color:t,alpha:i})}renderGradient(t){const{width:i,height:s}=this.viewportBounds;if(this.graphics.clear(),t.type==="linear"){const r=t.x0??0,o=t.y0??0,a=t.x1??1,l=t.y1??1,h=new Xt({type:"linear",start:{x:r,y:o},end:{x:a,y:l},colorStops:t.colorStops});this.graphics.rect(0,0,i,s).fill(h),M.debug("[Background] Rendered linear gradient background",{x0:r,y0:o,x1:a,y1:l,colorStops:t.colorStops.length})}else if(t.type==="radial"){const r=t.cx??.5,o=t.cy??.5,a=t.r??.5,l=new Xt({type:"radial",center:{x:r,y:o},innerRadius:0,outerCenter:{x:r,y:o},outerRadius:a,colorStops:t.colorStops});this.graphics.rect(0,0,i,s).fill(l),M.debug("[Background] Rendered radial gradient background",{cx:r,cy:o,r:a,colorStops:t.colorStops.length})}}async renderImage(t,i){var s,r,o,a;try{const l=await Y.load(t.src);if(!l){M.error("[Background] Failed to load image:",t.src),(s=this.lastConfig)!=null&&s.backgroundColor&&this.renderSolidColor(this.lastConfig.backgroundColor,i);return}this.sprite=new re(l),this.sprite.label="backgroundSprite",this.sprite.alpha=i;const{width:h,height:c}=this.viewportBounds,d=t.fit||"cover",u=((r=t.position)==null?void 0:r.x)??.5,p=((o=t.position)==null?void 0:o.y)??.5,f=l.width,m=l.height,g=f/m,x=h/c;switch(d){case"fill":this.sprite.width=h,this.sprite.height=c,this.sprite.x=0,this.sprite.y=0;break;case"contain":g>x?(this.sprite.width=h,this.sprite.height=h/g):(this.sprite.height=c,this.sprite.width=c*g),this.sprite.x=(h-this.sprite.width)*u,this.sprite.y=(c-this.sprite.height)*p;break;case"cover":g>x?(this.sprite.height=c,this.sprite.width=c*g):(this.sprite.width=h,this.sprite.height=h/g),this.sprite.x=(h-this.sprite.width)*u,this.sprite.y=(c-this.sprite.height)*p;break;case"none":this.sprite.width=f,this.sprite.height=m,this.sprite.x=(h-f)*u,this.sprite.y=(c-m)*p;break}t.repeat&&M.warn("[Background] Repeat mode not yet implemented"),this.addChild(this.sprite),M.debug("[Background] Rendered image background",{src:t.src,fit:d,position:{x:u,y:p},spriteSize:{width:this.sprite.width,height:this.sprite.height}}),this.onImageLoaded&&this.onImageLoaded()}catch(l){M.error("[Background] Error loading background image:",l),(a=this.lastConfig)!=null&&a.backgroundColor&&this.renderSolidColor(this.lastConfig.backgroundColor,i)}}async update(t){await this.render(t)}async updateViewportBounds(t){this.viewportBounds=t,this.lastConfig&&await this.render(this.lastConfig)}destroy(){this.clear(),super.destroy()}}class TC extends O{constructor(t){super();y(this,"carpetData");y(this,"carpetConfig");y(this,"controlsConfig");y(this,"carpetEvents");y(this,"appService");y(this,"controlFill");y(this,"editableShape");y(this,"clickHandler",null);y(this,"maskContainer",null);y(this,"maskGraphics",null);y(this,"texture",null);y(this,"textureMap",new Map);y(this,"tilingSprite",null);y(this,"initialZonePoints",[]);y(this,"unsubscribeFns",[]);y(this,"resolvedMaxSizeCache",null);y(this,"handleDragStart",()=>{this.resolveVisualState()==="editing"&&(this.carpetData.points&&this.carpetData.points.length>0?this.initialZonePoints=this.carpetData.points.map(t=>({...t})):this.initialZonePoints=[],this.appService.getApp().requestRender("zone-drag",!0))});y(this,"handleDragMove",t=>{if(this.resolveVisualState()!=="editing"||this.initialZonePoints.length===0||this.carpetData.shape==="custom")return;const i=this.parent.toLocal(t.global),s=this.controlFill.getDragStartPosition();if(!s)return;const r=i.x-s.x,o=i.y-s.y;this.applyTranslation(r,o)});y(this,"handleDragEnd",()=>{var t,i;this.initialZonePoints=[],this.appService.getApp().stopRender("zone-drag"),(i=(t=this.carpetEvents).onUpdate)==null||i.call(t,this.getCarpetData())});y(this,"handleMoveStart",()=>{this.carpetData.points&&this.carpetData.points.length>0?this.initialZonePoints=this.carpetData.points.map(t=>({...t})):this.initialZonePoints=[],this.appService.getApp().requestRender("zone-move",!0)});y(this,"handleMove",t=>{var a,l;if(this.resolveVisualState()!=="editing"||this.initialZonePoints.length===0)return;const i=this.parent.toLocal(t.global),s=(l=(a=this.editableShape)==null?void 0:a.getMoveButton())==null?void 0:l.getDragStartPosition();if(!s)return;const r=i.x-s.x,o=i.y-s.y;this.applyTranslation(r,o)});y(this,"handleMoveEnd",()=>{var t,i;this.initialZonePoints=[],this.appService.getApp().stopRender("zone-move"),(i=(t=this.carpetEvents).onUpdate)==null||i.call(t,this.getCarpetData())});y(this,"handleRotationStart",()=>{this.appService.getApp().requestRender("zone-rotate",!0)});y(this,"handleRotationMove",t=>{t&&(this.carpetData.points=t,this.drawCarpet())});y(this,"handleRotationEnd",()=>{var t,i;this.appService.getApp().stopRender("zone-rotate"),(i=(t=this.carpetEvents).onUpdate)==null||i.call(t,this.getCarpetData())});y(this,"handleClickRotate",t=>{var i,s;t&&(this.carpetData.points=t,this.drawCarpet()),this.appService.getApp().renderOnce(),(s=(i=this.carpetEvents).onUpdate)==null||s.call(i,this.getCarpetData())});y(this,"handleScaleStart",()=>{this.appService.getApp().requestRender("zone-scale",!0)});y(this,"handleScaleMove",t=>{t&&(this.carpetData.points=t,this.drawCarpet())});y(this,"handleScaleMoveHorizontal",t=>{t&&(this.carpetData.points=t,this.drawCarpet())});y(this,"handleScaleMoveVertical",t=>{t&&(this.carpetData.points=t,this.drawCarpet())});y(this,"handleScaleEnd",()=>{var t,i;this.appService.getApp().stopRender("zone-scale"),(i=(t=this.carpetEvents).onUpdate)==null||i.call(t,this.getCarpetData())});y(this,"handleDelete",()=>{var t,i;(i=(t=this.carpetEvents).onRemove)==null||i.call(t,this.carpetData.id)});y(this,"handleClick",()=>{var t,i;this.resolveVisualState()!=="editing"&&((i=(t=this.carpetEvents)==null?void 0:t.onClick)==null||i.call(t,this.getCarpetData()))});y(this,"handlePointsUpdate",t=>{this.carpetData.points=t,this.drawCarpet()});const{appService:i,carpetData:s,events:r={},textureMap:o}=t;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 t=this.carpetConfig.maxSize;if(this.resolvedMaxSizeCache&&this.resolvedMaxSizeCache.key===t)return this.resolvedMaxSizeCache.value;const i=ne(this.carpetConfig.minSize,t,"carpet");return this.resolvedMaxSizeCache={key:t,value:i},i}validateCarpetShape(t){const i=this.getResolvedMaxSize();return this.appService.coords.validateShape(Fn(t),{minSize:et(this.carpetConfig.minSize),maxSize:i!=null?et(i):void 0})}processCarpetData(t){if(t.points&&t.points.length>=2)if(t.shape==="custom")this.carpetData={...t,points:t.points};else{const s=this.validateCarpetShape(t.points);this.carpetData={...t,points:s}}else this.carpetData={...t,points:[],shape:t.shape||"rectangle"}}getControlsConfig(){const{controls:t}=this.appService.getConfig();return t}isEditingEnabled(){return this.appService.runtimeSnapshot.editingCarpetIds.includes(this.carpetData.id)}isSelected(){return this.appService.runtimeSnapshot.selectedCarpetIds.includes(this.carpetData.id)}isDisabledEnabled(){return this.appService.runtimeSnapshot.disabledCarpetIds.includes(this.carpetData.id)}resolveVisualState(){return Ii(this.isEditingEnabled(),this.isDisabledEnabled())}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 t=new O;return this.maskGraphics=new W,this.updateMaskShape(),t.addChild(this.maskGraphics),t.mask=this.maskGraphics,t}createControlFill(){return new oa(this.appService,{points:this.carpetData.points||[],fillColor:this.carpetConfig.fillColor,enableInteraction:this.resolveVisualState()==="editing",onDragStart:this.handleDragStart,onDragMove:this.handleDragMove,onDragEnd:this.handleDragEnd})}createEditControlLayer(){const t=this.isEditingEnabled(),i=this.carpetData.shape==="custom",s=Se(this.carpetConfig),r=!!t&&!i&&s.showScaleButton&&this.carpetConfig.scaleMode==="ratioLocked",o={...Dr(this.carpetConfig,["outlineStrokeWidth","outlineDashed","outlineDashArray","outlineFillColor","outlineOffset","outlineStrokeColor"]),...Dr(this.carpetConfig,["textColor","textPosition","textOffset"]),...Dr(this.controlsConfig,["textFontSize","textFontFamily","textFontWeight"]),showRotateButton:!!t&&!i&&s.showRotateButton,showScaleButton:!!t&&!i&&s.showScaleButton,showDeleteButton:!!t&&s.showDeleteButton,showMoveButton:!!t&&!i&&s.showMoveButton,showRadialScaleButton:r,iconWrapperFillColor:this.carpetConfig.iconWrapperFillColor,deleteIconWrapperFillColor:this.carpetConfig.deleteIconWrapperFillColor,rotateMode:this.carpetConfig.rotateMode,scaleMode:this.carpetConfig.scaleMode,moveButtonOffset:this.controlsConfig.moveButtonOffset},a=i?this.calculateBoundingRectanglePoints():this.carpetData.points||[];this.editableShape=new Es({editControls:this.appService.editControlManager});const l=this.getResolvedMaxSize();this.editableShape.attach(this,{id:this.carpetData.id,topology:"quad",layerOptions:{config:o,zonePoints:a,minSize:this.carpetConfig.minSize,maxSize:l??void 0,contentLayer:yi,events:{onRemove:this.handleDelete,onRotateStart:this.handleRotationStart,onRotateMove:this.handleRotationMove,onClickRotate:this.handleClickRotate,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&&s.showRotateButton,showScaleButton:!i&&s.showScaleButton,showDeleteButton:s.showDeleteButton,showMoveButton:!i&&s.showMoveButton,showBorder:!0,showSizeText:!0,borderStyle:this.carpetConfig.editing,showRadialScaleButton:!i&&s.showScaleButton&&this.carpetConfig.scaleMode==="ratioLocked"},idleState:{showRotateButton:!1,showScaleButton:!1,showDeleteButton:!1,showMoveButton:!1,showBorder:!1,showSizeText:!1}})}setupClickHandler(){this.interactiveChildren=!0,this.clickHandler=new yt(this,{onClick:()=>{var t,i;this.resolveVisualState()!=="editing"&&((i=(t=this.carpetEvents)==null?void 0:t.onClick)==null||i.call(t,this.getCarpetData()))},stopPropagation:!1})}setupEnableRoomSelectionListener(){const t=z(this.appService.runtime,"enableRoomSelection",s=>{this.updateClickHandlerState(s)});this.unsubscribeFns.push(t);const i=this.appService.runtimeSnapshot.enableRoomSelection;this.updateClickHandlerState(i)}isRoomSelectionEnabled(){return this.appService.runtimeSnapshot.enableRoomSelection}updateClickHandlerState(t){if(t){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:t}=this.carpetData;let i=1/0,s=1/0,r=-1/0,o=-1/0;if(t&&t.length>0)for(const a of t)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:t}=this.carpetData;if(!t||t.length===0)return[];const{minX:i,minY:s,maxX:r,maxY:o}=bn(t);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:t,shape:i}=this.carpetData;if(!(!t||!Array.isArray(t)||t.length<2)){if(i==="round"){if(t.length<4)return;const r=oe(t),[o,a,,l]=t,h=q(o,a),c=q(o,l),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,h/2,c/2)}else{const r=t.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:t,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,t),this.appService.getApp().renderOnce())}catch(r){console.warn("Failed to load carpet texture:",r)}}createTilingSprite(t,i){if(!this.texture||!this.maskContainer)return;const s=this.calculateBounds();this.tilingSprite=new Sn({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(t),this.tilingSprite.alpha=i,this.maskContainer.addChild(this.tilingSprite)}updateTilingSprite(){if(!this.tilingSprite)return;const t=this.calculateBounds();this.tilingSprite.position.set(t.minX-50,t.minY-50),this.tilingSprite.width=t.maxX-t.minX+100,this.tilingSprite.height=t.maxY-t.minY+100}applyTranslation(t,i){this.carpetData.points=this.initialZonePoints.map(s=>({x:s.x+t,y:s.y+i})),this.drawCarpet()}drawCarpet(){const{points:t}=this.carpetData;if(!(!t||t.length<2)&&(this.updateMaskShape(),this.updateTilingSprite(),this.controlFill.updatePoints(t),this.editableShape)){const r=this.carpetData.shape==="custom"?this.calculateBoundingRectanglePoints():t;this.editableShape.updatePoints(r)}}updateEditState(){var a;const t=this.resolveVisualState(),i=t==="editing",s=t==="disabled",r=this.isSelected()&&!s,o=this.shouldShowEditControl()&&!s||!1;s&&this.controlFill.interruptDragging(),this.controlFill.setInteractionEnabled(i),this.controlFill.updateFillColor(s?((a=this.carpetConfig.disabled)==null?void 0:a.fillColor)??this.carpetConfig.fillColor:this.carpetConfig.fillColor),this.alpha=s?Di(this.carpetConfig.disabled,this.controlsConfig.disabledStyle):1,this.editableShape&&(r&&!i?this.editableShape.applyEditState({showRotateButton:!1,showScaleButton:!1,showDeleteButton:!1,showMoveButton:!1,showBorder:!0,showSizeText:!1,borderStyle:this.carpetConfig.normal}):this.editableShape.setEditing(i)),this.zIndex=o?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(t){const s=this.carpetData.type;if(t.points&&t.points.length>=2)if(t.shape==="custom")this.carpetData={...t,points:t.points};else{const r=this.validateCarpetShape(t.points);this.carpetData={...t,points:r}}else this.carpetData={...t,points:t.points||[]};s!==this.carpetData.type&&this.loadTexture(),this.drawCarpet(),this.updateEditState()}getCarpetData(){return{...this.carpetData}}refreshDisplay(){this.drawCarpet()}destroy(){var t,i,s,r,o;this.editableShape.detach(),this.unsubscribeFns.forEach(a=>a()),this.unsubscribeFns=[],(t=this.tilingSprite)==null||t.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 RC{constructor(e){y(this,"customCarpetMap",new Map);y(this,"unsubscribeFns",[]);y(this,"textureMap",new Map);y(this,"texturesLoaded",!1);y(this,"texturesLoadingPromise",null);this.appService=e,this.applyLayerVisibility(e.runtime.showCustomCarpets);const t=z(e.runtime,"editingCarpetIds",o=>{M.log(`[runtime] editingCarpetIds: ${o}`),this.updateCarpetsEditState()}),i=z(e.runtime,"selectedCarpetIds",o=>{M.log(`[runtime] selectedCarpetIds: ${o}`),this.updateCarpetsEditState()}),s=z(e.runtime,"disabledCarpetIds",o=>{M.log(`[runtime] disabledCarpetIds: ${o}`),this.updateCarpetsEditState()}),r=z(e.runtime,"showCustomCarpets",o=>{M.log(`[runtime] showCustomCarpets: ${o}`),this.applyLayerVisibility(o)});this.unsubscribeFns.push(t,i,s,r)}getDiagnosticObjects(e=201){if(this.customCarpetMap.size>e)throw new Error("BUDGET_EXCEEDED: entities");return Array.from(this.customCarpetMap.entries(),([t,i])=>({type:"customCarpet",id:t,container:i,read:()=>i.getCarpetData()}))}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 e=this.appService,{material:t,src:i}=e.carpetConfig;if(t)for(const s of t){const r=await Y.load(s.src);this.textureMap.set(s.type,r)}if(i){const s=await Y.load(i);this.textureMap.set(-1,s)}}async drawCustomCarpets(e){if(await this.loadTextures(),!e||e.length===0){this.clearAllCustomCarpets();return}const t=new Set(this.customCarpetMap.keys()),i=new Set(e.map(s=>s.id));for(const s of t)i.has(s)||this.removeCustomCarpet(s);e.forEach(s=>{const r=this.customCarpetMap.get(s.id.toString());r?this.isCarpetDataEqual(r.getCarpetData(),s)||r.updateCarpetData(s):this.addNewCustomCarpet(s)})}getCustomCarpets(){const e=[];return this.customCarpetMap.forEach(t=>{e.push(t.getCarpetData())}),e}getCustomCarpetById(e){return this.customCarpetMap.get(e)}clearAllCustomCarpets(){this.customCarpetMap.forEach((e,t)=>{var s;const i=this.customCarpetMap.get(t);i&&((s=i.parent)==null||s.removeChild(i),i.destroy())}),this.customCarpetMap.clear()}addNewCustomCarpet(e){const t=this.appService,i=new TC({appService:t,carpetData:e,textureMap:this.textureMap,events:{onRemove:s=>{var r,o;(o=(r=t.events)==null?void 0:r.onDeleteCustomCarpet)==null||o.call(r,{id:s})},onUpdate:s=>{var r,o;(o=(r=t.events)==null?void 0:r.onUpdateCustomCarpet)==null||o.call(r,s)},onClick:s=>{var r,o;(o=(r=t.events)==null?void 0:r.onClickCarpet)==null||o.call(r,{id:s.id})}}});this.customCarpetMap.set(e.id.toString(),i),t.appContainer.addToLayer(yi,i)}removeCustomCarpet(e){const t=this.appService,i=this.customCarpetMap.get(e);i&&(t.appContainer.removeFromLayer(yi,i),i.destroy(),this.customCarpetMap.delete(e))}updateCarpetsEditState(){this.customCarpetMap.forEach(e=>{e.updateEditState()})}applyLayerVisibility(e){const t=this.appService.appContainer.getLayer(yi);t&&(t.visible=e)}isCarpetDataEqual(e,t){if(e.id!==t.id||e.type!==t.type||e.shape!==t.shape)return!1;const i=e.points||[],s=t.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(e=>{e.refreshDisplay()})}refreshConfig(){this.customCarpetMap.forEach(e=>{e.refreshConfig()})}destroy(){this.unsubscribeFns.forEach(e=>e()),this.unsubscribeFns=[],this.clearAllCustomCarpets()}}function EC(n,e){return{coords:n.coords,editControls:n.editControlManager,furnitureConfig:n.furnitureConfig,controlsConfig:n.controlsConfig,gestures:n.gestureController,render:{request:t=>n.getApp().requestRender(t,!0),stop:t=>n.getApp().stopRender(t),once:t=>n.getApp().requestRender(t,!1)},events:e}}const sc="furniture-drag",nc="furniture-scale",rc="furniture-move",Nr="furniture-rotate";class kC extends O{constructor(t){super();y(this,"deps");y(this,"config");y(this,"controlsConfig");y(this,"furnitureEvents");y(this,"data");y(this,"textureAlias");y(this,"sprite");y(this,"editableShape");y(this,"editing",!1);y(this,"disabled",!1);y(this,"clickHandler",null);y(this,"dragStartPosition",null);y(this,"initialPoints",[]);y(this,"isDragging",!1);y(this,"gestureSession",null);y(this,"originalSizeMeters",null);y(this,"resolveSizeConstraintPerEdge",()=>{var o,a;const{minScaleRatio:t,maxScaleRatio:i}=this.config,s=i===1/0||i==null?void 0:i,r=l=>{if(!l||l<=0)return{min:.1,max:void 0};const h=l*(t||0);return{min:h>0?h:.1,max:s!=null?l*s:void 0}};return{edge1:r((o=this.originalSizeMeters)==null?void 0:o.width),edge2:r((a=this.originalSizeMeters)==null?void 0:a.height)}});y(this,"onDragStart",t=>{if(this.resolveVisualState()!=="editing"||!this.parent||t.target!==this&&t.target!==this.sprite)return;t.stopPropagation();const i=this.parent.toLocal(t.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(t),this.gestureSession.onMove(this.onDragMove),this.gestureSession.onEnd(this.onDragEnd)});y(this,"onDragMove",t=>{if(!this.dragStartPosition||!this.parent)return;const i=this.parent.toLocal(t.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(sc)),this.data.points=this.initialPoints.map(o=>({x:o.x+s,y:o.y+r})),this.redraw())});y(this,"onDragEnd",()=>{var t,i;this.gestureSession=null,this.dragStartPosition&&(this.isDragging&&((i=(t=this.furnitureEvents).onUpdate)==null||i.call(t,this.getData()),this.deps.render.stop(sc)),this.dragStartPosition=null,this.initialPoints=[],this.isDragging=!1)});y(this,"handleRotateStart",()=>{this.deps.render.request(Nr)});y(this,"handleRotateMove",t=>{t&&(this.data.points=t,this.redraw())});y(this,"handleTapRotate",t=>{var i,s;t&&(this.data.points=t,this.redraw()),this.captureOriginalSize(),this.deps.render.once(Nr),(s=(i=this.furnitureEvents).onUpdate)==null||s.call(i,this.getData())});y(this,"handleScaleStart",()=>{this.deps.render.request(nc)});y(this,"handleScaleMove",t=>{t&&(this.data.points=t,this.redraw())});y(this,"handleMoveStart",()=>{this.initialPoints=this.data.points.map(t=>({...t})),this.deps.render.request(rc)});y(this,"handleMove",t=>{var a;if(this.resolveVisualState()!=="editing"||this.initialPoints.length===0||!this.parent)return;const i=this.parent.toLocal(t.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(l=>({x:l.x+r,y:l.y+o})),this.redraw()});y(this,"handleMoveEnd",()=>{var t,i;this.initialPoints=[],this.deps.render.stop(rc),(i=(t=this.furnitureEvents).onUpdate)==null||i.call(t,this.getData())});y(this,"handleTransformEnd",()=>{var t,i;this.deps.render.stop(Nr),this.deps.render.stop(nc),(i=(t=this.furnitureEvents).onUpdate)==null||i.call(t,this.getData())});y(this,"handleDelete",()=>{var t,i;(i=(t=this.furnitureEvents).onRemove)==null||i.call(t,this.data.id)});y(this,"handleClick",()=>{var t,i;this.resolveVisualState()!=="editing"&&((i=(t=this.furnitureEvents).onClick)==null||i.call(t,this.getData()))});const{deps:i,data:s,textureAlias:r}=t;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.applyVisualState()}captureOriginalSize(){const t=this.data.points;if(t.length<4){this.originalSizeMeters=null;return}const i=q(t[0],t[1]),s=q(t[1],t[2]);this.originalSizeMeters={width:this.deps.coords.toMeters(Gt(i)),height:this.deps.coords.toMeters(Gt(s))}}createSprite(){const t=Y.get(this.textureAlias);this.sprite=new re(t),this.sprite.anchor.set(.5),this.sprite.alpha=this.config.opacity,this.sprite.eventMode="passive",this.addChild(this.sprite)}updateSpriteTransform(){const t=this.data.points;if(t.length<4)return;const i=oe(t),s=t[1].x-t[0].x,r=t[1].y-t[0].y,o=Math.atan2(r,s),a=q(t[0],t[1]),l=q(t[1],t[2]);this.sprite.position.set(i.x,i.y),this.sprite.rotation=o,this.sprite.width=a,this.sprite.height=l}createEditControlLayer(){const t={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),...Se(this.config),showRadialScaleButton:!1,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 Es({editControls:this.deps.editControls});const i={config:t,zonePoints:this.data.points,sizeConstraintPerEdge:this.resolveSizeConstraintPerEdge,contentLayer:ws,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:this.resolveEditingState(),idleState:{showRotateButton:!1,showScaleButton:!1,showRadialScaleButton:!1,showDeleteButton:!1,showMoveButton:!1,showBorder:!1,showSizeText:!1}})}setupInteraction(){this.clickHandler=new yt(this,{onClick:t=>{!this.isDragging&&((t==null?void 0:t.target)===this||(t==null?void 0:t.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))}resolveEditingState(){return{...Se(this.config),showRadialScaleButton:!1,showBorder:!0,showSizeText:this.config.showSizeText}}resolveVisualState(){return Ii(this.editing,this.disabled)}applyVisualState(){var i;const t=this.resolveVisualState();t==="disabled"&&((i=this.gestureSession)==null||i.cancel()),t==="editing"?this.editableShape.applyEditState(this.resolveEditingState()):this.editableShape.setEditing(!1),this.alpha=t==="disabled"?Di(this.config.disabled,this.controlsConfig.disabledStyle):1,this.zIndex=t==="editing"?1e3:0}updateEditState(t){this.editing!==t&&(this.editing=t,this.applyVisualState())}isEditing(){return this.editing}setDisabled(t){this.disabled!==t&&(this.disabled=t,this.applyVisualState())}isDisabled(){return this.disabled}getData(){return{id:this.data.id,furnitureType:this.data.furnitureType,points:this.data.points.map(t=>({...t}))}}updateData(t){this.data={...t,points:t.points.map(i=>({...i}))},this.captureOriginalSize(),this.data.points.length>=4&&(this.updateSpriteTransform(),this.editableShape.updatePoints(this.data.points))}destroy(){var t,i,s;(t=this.editableShape)==null||t.detach(),(i=this.gestureSession)==null||i.cancel(),this.gestureSession=null,(s=this.clickHandler)==null||s.destroy(),this.clickHandler=null,super.destroy({children:!0})}}class IC{constructor(e){y(this,"furnitureMap",new Map);y(this,"unsubscribeFns",[]);this.appService=e,this.applyLayerVisibility(e.runtime.showFurnitures);const t=z(e.runtime,"editingFurnitureIds",r=>{M.log(`[runtime] editingFurnitureIds: ${r}`),this.updateEditState()}),i=z(e.runtime,"disabledFurnitureIds",r=>{M.log(`[runtime] disabledFurnitureIds: ${r}`),this.updateEditState()}),s=z(e.runtime,"showFurnitures",r=>{M.log(`[runtime] showFurnitures: ${r}`),this.applyLayerVisibility(r)});this.unsubscribeFns.push(t,i,s)}getDiagnosticObjects(e=201){if(this.furnitureMap.size>e)throw new Error("BUDGET_EXCEEDED: entities");return Array.from(this.furnitureMap.entries(),([t,i])=>({type:"furniture",id:t,container:i,read:()=>i.getData()}))}async drawFurnitures(e){if(!e||e.length===0){this.clearAll();return}const t=new Set(this.furnitureMap.keys()),i=new Set(e.map(r=>r.id));for(const r of t)i.has(r)||this.removeFurniture(r);const s=[];for(const r of e){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(e){const t=this.appService;if(!t.furnitureConfig.assets.find(c=>c.type===e.furnitureType)){M.warn(`[FurnitureManager] No asset found for furnitureType: ${e.furnitureType}`);return}const r=`furniture_${e.furnitureType}`;await Y.load(r);const o=EC(t,{onRemove:c=>{var d,u;(u=(d=t.events)==null?void 0:d.onRemoveFurniture)==null||u.call(d,c)},onUpdate:c=>{var d,u;(u=(d=t.events)==null?void 0:d.onUpdateFurniture)==null||u.call(d,c)},onClick:c=>{var d,u;(u=(d=t.events)==null?void 0:d.onClickFurniture)==null||u.call(d,c)}}),a=new kC({deps:o,data:e,textureAlias:r});this.furnitureMap.set(e.id,a),t.appContainer.addToLayer(ws,a);const l=t.runtime.editingFurnitureIds,h=t.runtime.disabledFurnitureIds;a.setDisabled(h.includes(e.id)),a.updateEditState(l.includes(e.id))}removeFurniture(e){var i;const t=this.furnitureMap.get(e);t&&((i=t.parent)==null||i.removeChild(t),t.destroy(),this.furnitureMap.delete(e))}clearAll(){var e;for(const[,t]of this.furnitureMap)(e=t.parent)==null||e.removeChild(t),t.destroy();this.furnitureMap.clear()}applyLayerVisibility(e){const t=this.appService.appContainer.getLayer(ws);t&&(t.visible=e)}updateEditState(){const e=this.appService.runtime.editingFurnitureIds,t=this.appService.runtime.disabledFurnitureIds;this.furnitureMap.forEach((i,s)=>{i.setDisabled(t.includes(s)),i.updateEditState(e.includes(s))})}getFurnitures(){const e=[];return this.furnitureMap.forEach(t=>{e.push(t.getData())}),e}isDataEqual(e,t){if(e.id!==t.id||e.furnitureType!==t.furnitureType||e.points.length!==t.points.length)return!1;for(let i=0;i<e.points.length;i++)if(Math.abs(e.points[i].x-t.points[i].x)>.1||Math.abs(e.points[i].y-t.points[i].y)>.1)return!1;return!0}destroy(){this.unsubscribeFns.forEach(e=>e()),this.unsubscribeFns=[],this.clearAll()}}class DC{constructor(e){y(this,"editControlLayers",new Map);this.appService=e}registerEditControl(e,t){const i=this.appService;this.editControlLayers.has(e)&&this.unregisterEditControl(e);const s=new R0(i,t);if(!i.appContainer.addToLayer(xi,s))throw M.warn(`[EditControlManager] Failed to add edit control layer for id: ${e}`),s.destroy(),new Error(`Failed to register edit control for id: ${e}`);if(this.editControlLayers.set(e,s),t.contentLayer){const o=i.appContainer.getLayer(xi),a=i.appContainer.getLayer(t.contentLayer);o&&a&&(o.position.x!==a.position.x||o.position.y!==a.position.y)&&M.warn(`[EditControlManager] Edit layer position does not match content layer "${t.contentLayer}" position — edit controls will appear misaligned. Ensure "${t.contentLayer}" is in ORIGIN_TRACKED_LAYERS.`,{edit:o.position,content:a.position})}return s}unregisterEditControl(e){const t=this.editControlLayers.get(e);if(!t)return;this.appService.appContainer.removeFromLayer(xi,t),t.destroy(),this.editControlLayers.delete(e)}getEditControl(e){return this.editControlLayers.get(e)}updateEditState(e,t){const i=this.editControlLayers.get(e);i&&i.updateEditState(t)}clearAll(){Array.from(this.editControlLayers.keys()).forEach(t=>this.unregisterEditControl(t))}getAllEditControls(){return Array.from(this.editControlLayers.values())}hasEditControl(e){return this.editControlLayers.has(e)}}const FC=new Set(["onUpdateForbiddenSweepZone","onUpdateForbiddenMopZone","onUpdateCleanZone","onUpdateVirtualWall","onUpdateThreshold","onUpdateRamp","onUpdateSpot","onUpdateRoomAnchor","onUpdateWayPoint","onUpdateDivider","onDividerOutOfRoom","onUpdateCustomCarpet","onUpdateFurniture","onUpdateCustomZone"]);function Xi(n){return n.charAt(0).toUpperCase()+n.slice(1)}const BC=1,LC=.15,zC=.8,OC=.4,us=class us extends dd{constructor(t=ma){super();y(this,"diagnostics");y(this,"mapState",null);y(this,"components",{});y(this,"managers",{});y(this,"config",ga);y(this,"runtime");y(this,"appService");y(this,"elasticScale");y(this,"coords");y(this,"scaleMin",.5);y(this,"scaleMax",5);y(this,"events",{});y(this,"instanceKey");y(this,"debugInstanceId");y(this,"previousLoggerRuntimeState",null);y(this,"isDestroying",!1);y(this,"hasActiveContextLoss",!1);y(this,"createdAtMs",Date.now());y(this,"lastMapDataAtMs",null);y(this,"lastMapDrawAtMs",null);y(this,"lastPathDataAtMs",null);y(this,"lastVisibilityChangeAtMs",null);y(this,"containerElement");y(this,"onWebGLContextLost",t=>{var r;const i=t;if((r=i.preventDefault)==null||r.call(i),this.hasActiveContextLoss)return;this.hasActiveContextLoss=!0;const s=this.getContextLossDiagnostics(t);M.error("[Pixi] WebGL context lost",s.summary),M.error("[Pixi] WebGL context lost tail",s.recentLifecycleTail),this.recordDebugLifecycleEvent("webglcontextlost",{eventType:t.type,statusMessage:i.statusMessage??null})});y(this,"onWebGLContextRestored",t=>{this.hasActiveContextLoss=!1,M.warn("[Pixi] WebGL context restored, scheduling render",this.getRendererDiagnostics({eventType:t.type})),this.recordDebugLifecycleEvent("webglcontextrestored",{eventType:t.type}),this.renderOnceNextFrame()});y(this,"emitter",mv());y(this,"tickerState",{renderReasons:new Set,renderTimer:null,lastRequestReason:null,lastStopReason:null});y(this,"customCarpetResolvedMaxSizeCache",null);y(this,"pendingAsyncRender",!1);y(this,"isFirstMapDraw",!0);y(this,"isMapDrawn",!1);y(this,"onVisibilityChange",()=>{var i;this.lastVisibilityChangeAtMs=Date.now(),document.visibilityState==="visible"||(i=this.components.interaction)==null||i.forceEndGesture()});y(this,"onRendererResize",()=>{var t,i,s;this.isDestroying||((t=this.components.viewportContainer)==null||t.updateViewport(this.config),(i=this.components.background)==null||i.updateViewportBounds(this.getViewportBounds()),(s=this.components.domOverlayAligner)==null||s.scheduleSync(),this.renderOnceNextFrame())});this.instanceKey=t,this.debugInstanceId=Sh(),this.coords=new Ev(()=>{var i;return((i=this.runtime)==null?void 0:i.unit)??"meter"}),this.appService=new _u(this),this.diagnostics=new Eb(this,t,this.debugInstanceId),this.emitter.on("*",(i,s)=>{var r;return(r=this.diagnostics)==null?void 0:r.record(`emitter:${String(i)}`,s)}),this.recordDebugLifecycleEvent("app:create",{instanceKey:t})}getDiagnostics(t){return this.diagnostics.get(t)}getRendererDiagnostics(t={}){var r,o,a,l,h,c,d,u,p,f,m;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)===pe.WEBGPU?"webgpu":((o=this.renderer)==null?void 0:o.type)===pe.WEBGL?"webgl":"unknown";return{sessionId:zr().getSessionId(),instanceId:this.debugInstanceId,requestedPreference:this.config.global.rendererPreference,rendererType:s,rendererWidth:((a=this.renderer)==null?void 0:a.width)??null,rendererHeight:((l=this.renderer)==null?void 0:l.height)??null,canvasWidth:((h=this.canvas)==null?void 0:h.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:((f=this.mapState)==null?void 0:f.width)??null,mapHeight:((m=this.mapState)==null?void 0:m.height)??null,isMapDrawn:this.isMapDrawn,visibilityState:document.visibilityState,...t}}getElapsedMsSince(t){return typeof t=="number"?Math.max(0,Date.now()-t):null}getDeviceDiagnostics(){const t=globalThis.navigator;return{devicePixelRatio:globalThis.devicePixelRatio??null,userAgent:(t==null?void 0:t.userAgent)??null,hardwareConcurrency:(t==null?void 0:t.hardwareConcurrency)??null,deviceMemory:(t==null?void 0:t.deviceMemory)??null,documentWasDiscarded:"wasDiscarded"in document?document.wasDiscarded:null}}getWebGLDiagnostics(){var r;const t=(r=this.renderer)==null?void 0:r.gl;if(!t)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 t.getParameter!="function")return null;try{return t.getParameter(o)??null}catch{return null}},s=typeof t.getExtension=="function"?t.getExtension("WEBGL_debug_renderer_info"):null;return{contextAttributes:typeof t.getContextAttributes=="function"?t.getContextAttributes()??null:null,isContextLost:typeof t.isContextLost=="function"?t.isContextLost():null,drawingBufferWidth:t.drawingBufferWidth??null,drawingBufferHeight:t.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(t.VERSION),shadingLanguageVersion:i(t.SHADING_LANGUAGE_VERSION),maxTextureSize:i(t.MAX_TEXTURE_SIZE),maxRenderbufferSize:i(t.MAX_RENDERBUFFER_SIZE)}}getRecentLifecycleTail(){return zr().readCurrentSession().slice(-us.CONTEXT_LOSS_TAIL_SIZE).map(t=>({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}))}getContextLossDiagnostics(t){const i=t;return{summary:this.getRendererDiagnostics({eventType:t.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 t,i;if(((t=this.renderer)==null?void 0:t.type)!==pe.WEBGL||typeof((i=this.canvas)==null?void 0:i.addEventListener)!="function"){M.debug("[Pixi] Renderer diagnostics initialized",this.getRendererDiagnostics({contextListeners:!1}));return}this.canvas.addEventListener("webglcontextlost",this.onWebGLContextLost),this.canvas.addEventListener("webglcontextrestored",this.onWebGLContextRestored),M.debug("[Pixi] Renderer diagnostics initialized",this.getRendererDiagnostics({contextListeners:!0}))}detachRendererDiagnostics(){var t;typeof((t=this.canvas)==null?void 0:t.removeEventListener)=="function"&&(this.canvas.removeEventListener("webglcontextlost",this.onWebGLContextLost),this.canvas.removeEventListener("webglcontextrestored",this.onWebGLContextRestored))}getDebugRendererType(){var t,i;return((t=this.renderer)==null?void 0:t.type)===pe.WEBGPU?"webgpu":((i=this.renderer)==null?void 0:i.type)===pe.WEBGL?"webgl":"unknown"}recordDebugLifecycleEvent(t,i){var s,r;(s=this.diagnostics)==null||s.record(`lifecycle:${t}`,i),zr().record({event:t,instanceId:this.debugInstanceId,visibilityState:typeof document<"u"?document.visibilityState:null,rendererType:this.getDebugRendererType(),mapId:((r=this.mapState)==null?void 0:r.id)??null,detail:i})}async initialize(t){const{resizeTo:i,events:s,config:r,runtime:o={},...a}=t;this.config=bo(lh({},ga,r??{},(f,m)=>{if(Array.isArray(m))return m})),this.validateCustomZoneTypes(this.config),this.previousLoggerRuntimeState=KS(),qS({getLoggerConfig:()=>this.config.logger,getLegacyEnabled:()=>this.config.global.enableLogger}),M.log("Applying config",this.config,r),this.runtime=bo(Object.assign({},Vp,o));const l=this.instanceKey===ma;this.containerElement=i;const h=l&&this.config.interaction.enable,c=this.config.global.performanceMode||!l,d={gcActive:!1,autoStart:!1,sharedTicker:c,eventFeatures:{move:h,globalMove:!1,click:h,wheel:h}},u={resizeTo:l?i:void 0,resolution:this.config.global.resolution,antialias:c?!1:PC(),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(f){M.warn("[Pixi] WebGPU initialization failed, falling back to WebGL:",f),await this.init({...u,preference:"webgl"})}else await this.init({...u,preference:p});this.attachRendererDiagnostics(),this.diagnostics.bindRenderer(),this.recordDebugLifecycleEvent("app:initialized",{isMainInstance:l,isPerformanceMode:c,requestedPreference:p}),M.debug("[Pixi] Renderer initialized",this.getRendererDiagnostics({isMainInstance:l,isPerformanceMode:c})),this.preloadAssets(),this.scaleMax=this.config.interaction.zoomRange.max,this.scaleMin=this.config.interaction.zoomRange.min,this.events=this.diagnostics.wrapCallbacks(s,f=>{var g;return!(typeof f=="string"&&FC.has(f)&&((g=this.components.interaction)!=null&&g.isPointerCleanupActive))}),this.initializeViewportContainer(),this.initializeInteraction(),this.initializeAppContainer(),this.elasticScale=new Vv(this.appService),this.components.domOverlayAligner=new gv(this.appService),this.renderer.on("resize",this.onRendererResize),this.managers.mapManager=new g0(this.appService),this.managers.heatmapManager=new w0(this.appService),this.managers.pathManager=new b0(this.appService),this.managers.controlsManager=new $0(this.appService),this.managers.detectedObjectManager=new Y0(this.appService),this.managers.customElementsManager=new SC(this.appService),this.managers.roomsManager=new _C(this.appService),this.managers.customCarpetManager=new RC(this.appService),this.managers.furnitureManager=new IC(this.appService),this.managers.editControlManager=new DC(this.appService),this.setupMapRotationListener(),this.diagnostics.ready(),document.addEventListener("visibilitychange",this.onVisibilityChange)}async drawMap(t){var a,l,h,c,d,u,p,f,m,g,x;(a=this.diagnostics)==null||a.record("input:map",{format:"structured",id:t.id,size:t.size}),this.lastMapDataAtMs=Date.now(),this.isMapDrawn=!1,M.log("[Map] drawMap",t);const{size:i,resolution:s,origin:r,id:o}=t;((l=this.mapState)==null?void 0:l.id)!==void 0&&this.mapState.id!==o&&this.managers.pathManager.clear(),(r[0]!==((h=this.mapState)==null?void 0:h.origin.x)||r[1]!==((c=this.mapState)==null?void 0:c.origin.y))&&(this.appService.appContainer.updateOriginTrackedLayers(...r),this.managers.pathManager.updatePositionByOrigin(...r),this.managers.heatmapManager.updatePositionByOrigin(...r)),this.mapState={id:t.id,status:t.status===1,origin:{x:r[0],y:r[1]},charger:{x:t.charger.coordinate[0],y:t.charger.coordinate[1]},chargerDirection:t.charger.angle??0,resolution:s,width:i[0],height:i[1],mapType:"structured"},this.coords.setResolution(s),M.debug("[Map] Structured map state updated",{mapId:o,mapWidth:i[0],mapHeight:i[1],mapResolution:s,mapStatus:t.status===1,originX:r[0],originY:r[1]}),this.isFirstMapDraw&&(this.isFirstMapDraw=!1,(u=(d=this.events)==null?void 0:d.onMapFirstDrawed)==null||u.call(d,this.mapState)),(f=(p=this.events)==null?void 0:p.onMapDrawed)==null||f.call(p,this.mapState),this.emitter.emit("mapStateUpdate",this.mapState),(m=this.diagnostics)==null||m.record("draw:map:start",{mapId:this.mapState.id});try{await this.managers.mapManager.drawMap(t),(g=this.diagnostics)==null||g.record("draw:map:end",{mapId:this.mapState.id})}catch(S){throw(x=this.diagnostics)==null||x.record("error",{stage:"draw:map",message:String(S)}),S}i[0]===0||i[1]===0?(M.warn("[Map] Structured map cleared by incoming data",this.getRendererDiagnostics({mapId:o,mapWidth:i[0],mapHeight:i[1],mapResolution:s,mapStatus:t.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(t){var a,l,h,c,d,u,p,f,m,g;(a=this.diagnostics)==null||a.record("input:map",{format:"raster",id:t.mapHeader.id}),this.lastMapDataAtMs=Date.now(),this.isMapDrawn=!1,M.log("[Map] drawRasterMap",t);const{mapHeader:i,mapData:s}=t,{originX:r,originY:o}=i;(r!==((l=this.mapState)==null?void 0:l.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),M.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,(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),(f=this.diagnostics)==null||f.record("draw:map:start",{mapId:this.mapState.id});try{await this.managers.mapManager.drawRasterMap(s.parsed,this.mapState),(m=this.diagnostics)==null||m.record("draw:map:end",{mapId:this.mapState.id})}catch(x){throw(g=this.diagnostics)==null||g.record("error",{stage:"draw:map",message:String(x)}),x}i.mapWidth===0||i.mapHeight===0?(M.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 t,i;(i=(t=this.events)==null?void 0:t.onRoomsDrawed)==null||i.call(t,this.getRoomCenters())}getRoomCenters(){var i;const t=((i=this.mapState)==null?void 0:i.origin)??{x:0,y:0};return this.managers.mapManager.getAllRooms().map(s=>({id:s.id,centerPoint:s.centerPoint,relativeCenterPoint:{x:s.centerPoint.x-t.x,y:s.centerPoint.y-t.y}}))}drawPath(t){var i,s,r,o,a,l;(i=this.diagnostics)==null||i.record("input:path",{header:t.pathHeader,pointCount:t.pathPoints.length}),this.lastPathDataAtMs=Date.now(),M.log("[Path] drawPath",t),(r=(s=this.events)==null?void 0:s.onPathDrawed)==null||r.call(s,{id:t.pathHeader.pathId,type:t.pathHeader.type,direction:t.pathHeader.direction,count:t.pathHeader.count,initFlag:t.pathHeader.initFlag,robotPosition:t.pathPoints[t.pathPoints.length-1]??null}),(o=this.diagnostics)==null||o.record("draw:path:start");try{this.managers.pathManager.draw(t),(a=this.diagnostics)==null||a.record("draw:path:end")}catch(h){throw(l=this.diagnostics)==null||l.record("error",{stage:"draw:path",message:String(h)}),h}this.renderOnce()}async drawRoomProperty(t){var i,s,r,o;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawRoomProperty",count:t.length}),M.log("[Room] drawRoomProperty",t),(r=(s=this.events)==null?void 0:s.onRoomPropertiesDrawed)==null||r.call(s,t),await this.managers.roomsManager.drawRoomProperty(t),(o=this.diagnostics)==null||o.record("input:applied",{operation:"drawRoomProperty"}),this.renderOnceNextFrame()}async drawCustomCarpets(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawCustomCarpets",count:t.length}),M.log("[CustomCarpets] drawCustomCarpets",t),await this.managers.customCarpetManager.drawCustomCarpets(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawCustomCarpets"}),this.renderOnceNextFrame()}async drawFurnitures(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawFurnitures",count:t.length}),M.log("[Furniture] drawFurnitures",t),await this.managers.furnitureManager.drawFurnitures(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawFurnitures"}),this.renderOnceNextFrame()}drawHeatmap(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawHeatmap",count:t.length}),M.log("[Heatmap] drawHeatmap",t),this.managers.heatmapManager.draw(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawHeatmap"}),this.renderOnce()}drawForbiddenSweepZones(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawForbiddenSweepZones",count:t.length}),M.log("[Controls] drawForbiddenSweepZones",t),this.managers.controlsManager.drawForbiddenSweepZones(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawForbiddenSweepZones"}),this.renderOnceNextFrame()}drawForbiddenMopZones(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawForbiddenMopZones",count:t.length}),M.log("[Controls] drawForbiddenMopZones",t),this.managers.controlsManager.drawForbiddenMopZones(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawForbiddenMopZones"}),this.renderOnceNextFrame()}drawCleanZones(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawCleanZones",count:t.length}),M.log("[Controls] drawCleanZones",t),this.managers.controlsManager.drawCleanZones(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawCleanZones"}),this.renderOnceNextFrame()}drawCustomZones(t,i){var s,r;if((s=this.diagnostics)==null||s.record("input:entities",{operation:"drawCustomZones",type:t,count:i.length}),Pe(t)){M.warn(`[MapApplication] drawCustomZones: '${t}' is a built-in type; use draw${Xi(t)}s() instead`);return}M.log("[Controls] drawCustomZones",t,i),this.managers.controlsManager.drawCustomZones(t,i),(r=this.diagnostics)==null||r.record("input:applied",{operation:"drawCustomZones",type:t}),this.renderOnceNextFrame()}getCustomZones(t){return Pe(t)?(M.warn(`[MapApplication] getCustomZones: '${t}' is a built-in type; use get${Xi(t)}s() instead`),[]):this.managers.controlsManager.getCustomZones(t)}clearCustomZones(t){if(Pe(t)){M.warn(`[MapApplication] clearCustomZones: '${t}' is a built-in type; use clearAll${Xi(t)}s() instead`);return}M.log("[Controls] clearCustomZones",t),this.managers.controlsManager.clearCustomZones(t),this.renderOnceNextFrame()}setEditingCustomZones(t,i){if(Pe(t)){M.warn(`[MapApplication] setEditingCustomZones: '${t}' is a built-in type; use runtime.editing${Xi(t)}Ids instead`);return}this.runtime.editingCustomZoneIds={...this.runtime.editingCustomZoneIds??{},[t]:[...i]}}setDisabledCustomZones(t,i){if(Pe(t)){M.warn(`[MapApplication] setDisabledCustomZones: '${t}' is a built-in type; use runtime.disabled${Xi(t)}Ids instead`);return}this.runtime.disabledCustomZoneIds={...this.runtime.disabledCustomZoneIds??{},[t]:[...i]}}drawVirtualWalls(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawVirtualWalls",count:t.length}),M.log("[Controls] drawVirtualWalls",t),this.managers.controlsManager.drawVirtualWalls(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawVirtualWalls"}),this.renderOnceNextFrame()}drawThresholds(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawThresholds",count:t.length}),M.log("[Controls] drawThresholds",t),this.managers.controlsManager.drawThresholds(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawThresholds"}),this.renderOnceNextFrame()}drawRamps(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawRamps",count:t.length}),M.log("[Controls] drawRamps",t),this.managers.controlsManager.drawRamps(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawRamps"}),this.renderOnceNextFrame()}drawSpots(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawSpots",count:t.length}),M.log("[Controls] drawSpots",t),this.managers.controlsManager.drawSpots(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawSpots"}),this.renderOnceNextFrame()}drawRoomAnchors(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawRoomAnchors",count:t.length}),M.log("[Controls] drawRoomAnchors",t),this.managers.controlsManager.drawRoomAnchors(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawRoomAnchors"}),this.renderOnceNextFrame()}getRoomAnchors(){return this.managers.controlsManager.getRoomAnchors()}clearAllRoomAnchors(){this.managers.controlsManager.clearAllRoomAnchors(),this.renderOnceNextFrame()}drawWayPoints(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawWayPoints",count:t.length}),M.log("[Controls] drawWayPoints",t),this.managers.controlsManager.drawWayPoints(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawWayPoints"}),this.renderOnceNextFrame()}async drawDetectedObjects(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawDetectedObjects",count:t.length}),M.log("[DetectedObject] drawDetectedObjects",t),await this.managers.detectedObjectManager.drawDetectedObjects(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawDetectedObjects"}),this.renderOnceNextFrame()}drawCustomCarpet(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawCustomCarpet",count:t.length}),M.log("[CustomCarpet] drawCustomCarpet",t),this.managers.customCarpetManager.drawCustomCarpets(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawCustomCarpet"}),this.renderOnceNextFrame()}async drawCustomElements(t){var i,s;(i=this.diagnostics)==null||i.record("input:entities",{operation:"drawCustomElements",count:t.length}),M.log("[CustomElements] drawCustomElements",t),await this.managers.customElementsManager.drawCustomElements(t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"drawCustomElements"}),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()}getThresholds(){return this.managers.controlsManager.getThresholds()}getRamps(){return this.managers.controlsManager.getRamps()}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(){M.log("[Map] forceEndGesture"),this.components.interaction.forceEndGesture()}fitMapToView(t,i=!1){if(!t||t.minX===t.maxX||t.minY===t.maxY)return;const s=this.config.map.autoPaddingVerticalPercent,r=this.config.map.autoPaddingHorizontalPercent,o=this.getViewportBounds(),a=this.components.appContainer.getMapRotationRadians(),l=this.calculateRotatedBounds(t,a),h=l.maxX-l.minX,c=l.maxY-l.minY,d=o.width,u=o.height,p=d*(1-r*2),f=u*(1-s*2),m=p/h,g=f/c,x=Math.min(m,g),S=this.config.interaction.fitMinScale,b=this.config.interaction.fitMaxScale,w=Math.max(S,Math.min(b,x));this.setScaleBounds(this.config.interaction.zoomRange.min,this.config.interaction.zoomRange.max),w<this.scaleMin&&(this.setScaleBounds(w,this.scaleMax),M.debug("[MapApplication] scaleMin lowered for fit:",{configured:this.config.interaction.zoomRange.min,adjusted:w})),w>this.scaleMax&&(this.setScaleBounds(this.scaleMin,w),M.debug("[MapApplication] scaleMax raised for fit:",{configured:this.config.interaction.zoomRange.max,adjusted:w}));const _=t.minX+(t.maxX-t.minX)/2,v=t.minY+(t.maxY-t.minY)/2,C=this.config.map.autoFitOffset||{x:0,y:0},P=d/2+(C.x||0),A=u/2+(C.y||0),R=Math.cos(a),T=Math.sin(a),E=_*R-v*T,I=_*T+v*R,F=P-E*w,N=A-I*w;M.debug("[MapApplication] fitMapToView calculated:",{rotation:this.components.appContainer.getMapRotation(),originalBounds:t,rotatedBounds:l,finalScale:w,position:{x:F,y:N}}),this.components.interaction.setPanZoom({targetPosition:{x:F,y:N},targetScale:{x:w,y:w},setCenter:!0,setScale:!0},i)}setScaleBounds(t,i){this.scaleMin=t,this.scaleMax=i,this.components.interaction.scaleMin=t,this.components.interaction.scaleMax=i}validateCustomZoneTypes(t){const i=["minSize","strokeColor","strokeWidth","fillColor","outlineOffset","outlineStrokeColor","outlineStrokeWidth","outlineDashed","outlineDashArray","outlineFillColor","iconWrapperFillColor","textColor","textPosition","textOffset","showRotateButton","showDeleteButton","showScaleButton","showMoveButton","editing","normal"],s=t.customZoneTypes??{},r=fc.cleanZone;for(const[,o]of Object.entries(s))for(const a of i)o[a]===void 0&&(o[a]=r[a])}calculateRotatedBounds(t,i){if(i===0)return t;const s=(t.minX+t.maxX)/2,r=(t.minY+t.maxY)/2,o=[{x:t.minX-s,y:t.minY-r},{x:t.maxX-s,y:t.minY-r},{x:t.maxX-s,y:t.maxY-r},{x:t.minX-s,y:t.maxY-r}],a=Math.cos(i),l=Math.sin(i),h=o.map(f=>({x:f.x*a-f.y*l,y:f.x*l+f.y*a}));let c=1/0,d=1/0,u=-1/0,p=-1/0;return h.forEach(f=>{c=Math.min(c,f.x),d=Math.min(d,f.y),u=Math.max(u,f.x),p=Math.max(p,f.y)}),{minX:c+s,minY:d+r,maxX:u+s,maxY:p+r}}getViewportBounds(){var t;return((t=this.components.viewportContainer)==null?void 0:t.getViewportBounds())||{x:0,y:0,width:this.renderer.width,height:this.renderer.height}}updateRuntime(t){var i,s;(i=this.diagnostics)==null||i.record("input:runtime",{keys:Object.keys(t)}),Object.assign(this.runtime,t),(s=this.diagnostics)==null||s.record("input:applied",{operation:"updateRuntime"}),M.log("[runtime] runtime updated",t),this.renderOnceNextFrame()}updateConfig(t){var a,l,h,c,d,u,p,f,m,g,x,S,b,w,_,v,C,P,A;(a=this.diagnostics)==null||a.record("input:config",{keys:Object.keys(t)}),lh(this.config,t,(R,T)=>{if(Array.isArray(T))return T}),t.customZoneTypes&&this.validateCustomZoneTypes(this.config),(l=this.managers.controlsManager)==null||l.updateRenderOrder(),(t.elasticScale!==void 0||t.room!==void 0||t.detectedObject!==void 0)&&((h=this.managers.roomsManager)==null||h.refreshElasticConfig(),(c=this.managers.detectedObjectManager)==null||c.refreshElasticConfig(),(d=this.elasticScale)==null||d.refresh()),((u=t.controls)==null?void 0:u.spot)!==void 0&&((p=this.managers.controlsManager)==null||p.refreshSpotsEditState()),((f=t.controls)==null?void 0:f.roomAnchor)!==void 0&&((m=this.managers.controlsManager)==null||m.refreshRoomAnchors()),((g=t.controls)==null?void 0:g.wayPoint)!==void 0&&((x=this.managers.controlsManager)==null||x.refreshWayPointsConfig()),((S=t.controls)==null?void 0:S.carpet)!==void 0&&((b=this.managers.customCarpetManager)==null||b.refreshConfig());const r=t.controls;((r==null?void 0:r.forbiddenSweepZone)!==void 0||(r==null?void 0:r.forbiddenMopZone)!==void 0||(r==null?void 0:r.cleanZone)!==void 0||t.customZoneTypes!==void 0)&&((w=this.managers.controlsManager)==null||w.refreshZonesConfig()),t.room!==void 0&&((_=this.managers.roomsManager)==null||_.refreshRoomConfig()),((v=t.map)==null?void 0:v.beautify)!==void 0&&this.runtime.enableBeautify&&((C=this.managers.mapManager)==null||C.reprocessStructuredMap(),(P=this.managers.mapManager)==null||P.reprocessRasterMap()),M.log("[Config] Configuration updated",t),(A=this.diagnostics)==null||A.record("input:applied",{operation:"updateConfig"}),this.renderOnceNextFrame()}metersToPixels(t){return this.coords.toPixels(et(t))}pixelsToMeters(t){return this.coords.toMeters(Gt(t))}toFixedSize(t,i){const s=i??this.components.appContainer.scale.x;return t/s}fromFixedSize(t,i){const s=i??this.components.appContainer.scale.x;return t*s}getViewportCenterPoint(){if(!this.mapState)return M.warn("Map state not available, cannot calculate center point"),null;const t=this.getViewportBounds(),i=t.x+t.width/2,s=t.y+t.height/2,r=this.components.appContainer,o=r.scale.x,a=r.getMapRotationRadians(),l=i-r.x,h=s-r.y,c=l/o,d=h/o,u=Math.cos(a),p=Math.sin(a),f=c*u+d*p,m=-c*p+d*u,g=f-this.mapState.origin.x,x=m-this.mapState.origin.y;return{x:g,y:x}}getMapCenterPoint(){if(!this.mapState)return M.warn("Map state not available, cannot calculate map center point"),null;const t=this.managers.mapManager.mapBounds;if(t.minX===1/0||t.minY===1/0||t.maxX===-1/0||t.maxY===-1/0)return M.warn("Invalid map bounds, cannot calculate map center point"),null;const i=(t.minX+t.maxX)/2,s=(t.minY+t.maxY)/2,r=i-this.mapState.origin.x,o=s-this.mapState.origin.y;return{x:r,y:o}}getWallPointsByViewportCenter(t){var f;const{width:i=this.config.controls.virtualWall.minWidth,direction:s="horizontal",offsetX:r=0,offsetY:o=0}=t||{},a=this.getViewportCenterPoint()||{x:0,y:0},h=this.coords.toPixels(et(i))/2,c=((f=this.components.appContainer)==null?void 0:f.getMapRotationRadians())||0,d=Math.cos(c),u=Math.sin(c);let p;return s==="horizontal"?p=[{vx:-h+r,vy:o},{vx:h+r,vy:o}]:p=[{vx:r,vy:-h+o},{vx:r,vy:h+o}],p.map(m=>({x:a.x+m.vx*d+m.vy*u,y:a.y-m.vx*u+m.vy*d}))}getForbiddenSweepZonePointsByViewportCenter(t){const i=this.config.controls.forbiddenSweepZone,{size:s=i.minSize,offsetX:r=0,offsetY:o=0}=t||{};return this.generateZonePoints(s,r,o)}getForbiddenMopZonePointsByViewportCenter(t){const i=this.config.controls.forbiddenMopZone,{size:s=i.minSize,offsetX:r=0,offsetY:o=0}=t||{};return this.generateZonePoints(s,r,o)}getCleanZonePointsByViewportCenter(t){const i=this.config.controls.cleanZone,{size:s=i.minSize,offsetX:r=0,offsetY:o=0}=t||{};return this.generateZonePoints(s,r,o)}getSpotPointByViewportCenter(t){const{offsetX:i=0,offsetY:s=0}=t||{},r=this.getViewportCenterPoint()||{x:0,y:0},o=r.x+i,a=r.y+s;return{x:o,y:a}}getFurniturePointsByViewportCenter(t){const{furnitureType:i=1,offsetX:s=0,offsetY:r=0}=t||{},o=this.config.furniture.assets.find(l=>l.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 t=this.config.controls.carpet.maxSize;if(this.customCarpetResolvedMaxSizeCache&&this.customCarpetResolvedMaxSizeCache.key===t)return this.customCarpetResolvedMaxSizeCache.value;const i=ne(this.config.controls.carpet.minSize,t,"carpet");return this.customCarpetResolvedMaxSizeCache={key:t,value:i},i}getCustomCarpetPointsByViewportCenter(t){const s=this.config.controls.carpet.minSize,r=this.getResolvedCustomCarpetMaxSize(),{offsetX:o=0,offsetY:a=0}=t||{},l=(f,m)=>{const g=typeof f=="number"&&Number.isFinite(f)?f:m;return r!=null?Math.min(Math.max(g,s),r):Math.max(g,s)},h=(t==null?void 0:t.width)??(t==null?void 0:t.height),c=(t==null?void 0:t.height)??(t==null?void 0:t.width),d=l(h,s),u=l(c,s),p=this.getViewportCenterPoint()||{x:0,y:0};return this.buildRectPoints({center:p,widthMeters:d,heightMeters:u,applyMapRotation:!0,visualOffsetX:o,visualOffsetY:a})}getThresholdPointsByViewportCenter(t){const i=this.config.controls.threshold,{offsetX:s=0,offsetY:r=0}=t||{},o=(c,d,u,p,f)=>{const m=typeof c=="number"&&Number.isFinite(c)&&c>0?c:d,g=ne(u,p,f);return g!=null?Math.min(Math.max(m,u),g):Math.max(m,u)},a=o(t==null?void 0:t.width,BC,i.minLength,i.maxLength,"threshold"),l=o(t==null?void 0:t.height,LC,i.minHeight,i.maxHeight,"threshold.height"),h=this.getViewportCenterPoint()||{x:0,y:0};return this.buildRectPoints({center:h,widthMeters:a,heightMeters:l,applyMapRotation:!0,visualOffsetX:s,visualOffsetY:r})}getRampPointsByViewportCenter(t){const i=this.config.controls.ramp,{offsetX:s=0,offsetY:r=0}=t||{},o=(c,d,u,p,f)=>{const m=typeof c=="number"&&Number.isFinite(c)&&c>0?c:d,g=ne(u,p,f);return g!=null?Math.min(Math.max(m,u),g):Math.max(m,u)},a=o(t==null?void 0:t.width,zC,i.minWidth,i.maxWidth,"ramp"),l=o(t==null?void 0:t.height,OC,i.minHeight,i.maxHeight,"ramp.height"),h=this.getViewportCenterPoint()||{x:0,y:0};return this.buildRectPoints({center:h,widthMeters:a,heightMeters:l,applyMapRotation:!0,visualOffsetX:s,visualOffsetY:r})}getRectPointsByCenter(t){const{center:i,width:s,height:r,applyMapRotation:o=!0}=t;return this.buildRectPoints({center:i,widthMeters:s,heightMeters:r,applyMapRotation:o})}areRoomsAdjacent(t){return!t||t.length===0?(M.warn("[Room] No room IDs provided"),!1):this.managers.mapManager.areRoomsAdjacent(t)}getAdjacentRoomIds(t){return typeof t!="number"||!Number.isFinite(t)?(M.warn("[Room] Invalid room ID provided"),[]):this.managers.mapManager.getAdjacentRoomIds(t)}isPointInAnyRoom(t){return!t||typeof t.x!="number"||typeof t.y!="number"?(M.warn("[Room] Invalid point provided"),null):this.mapState?this.managers.mapManager.isPointInAnyRoom(t):(M.warn("[Room] Map state not available"),null)}isPointInRoom(t,i){return!t||typeof t.x!="number"||typeof t.y!="number"?(M.warn("[Room] Invalid point provided"),!1):this.mapState?this.managers.mapManager.isPointInRoom(t,i):(M.warn("[Room] Map state not available"),!1)}isWallIntersectsAnyRoom(t){return!t||t.length!==2||!t[0]||!t[1]||typeof t[0].x!="number"||typeof t[0].y!="number"||typeof t[1].x!="number"||typeof t[1].y!="number"?(M.warn("[Room] Invalid wall points provided"),!1):this.mapState?this.managers.mapManager.isWallIntersectsAnyRoom(t):(M.warn("[Room] Map state not available"),!1)}isZoneIntersectsAnyRoom(t){return!t||t.length!==4||!t[0]||!t[1]||!t[2]||!t[3]||typeof t[0].x!="number"||typeof t[0].y!="number"||typeof t[1].x!="number"||typeof t[1].y!="number"||typeof t[2].x!="number"||typeof t[2].y!="number"||typeof t[3].x!="number"||typeof t[3].y!="number"?(M.warn("[Room] Invalid zone points provided"),!1):this.mapState?this.managers.mapManager.isZoneIntersectsAnyRoom(t):(M.warn("[Room] Map state not available"),!1)}isNearChargerOrRobot(t,i,s){var l,h;if(!t||t.length<1)return M.warn("[Distance] Invalid points array: must have at least 1 point"),!1;if(t.length!==1&&t.length!==2&&t.length!==4)return M.warn("[Distance] Invalid points array: must have exactly 1 (point), 2 (wall) or 4 (zone) points"),!1;if(i<=0)return M.warn("[Distance] Invalid threshold: must be greater than 0"),!1;if(!this.mapState)return M.warn("[Distance] Map state not available"),!1;const{checkCharger:r=!0,checkRobot:o=!1}=s||{};if(!r&&!o)return M.warn("[Distance] At least one of checkCharger or checkRobot must be true"),!1;const a=this.coords.toPixels(et(i));if(r){const c=this.appService.getChargerPosition();if(c){const d=(l=this.mapState)==null?void 0:l.charger.x,u=(h=this.mapState)==null?void 0:h.charger.y;if(d===0&&u===0)return M.warn("[Distance] Charger position not available"),!1;const p=Kl(c,t);if(p<=a)return M.log(`[Distance] Too close to charger: ${p.toFixed(2)} pixels (threshold: ${a.toFixed(2)} pixels)`),!0}else M.warn("[Distance] Charger position not available")}if(o){const c=this.appService.getRobotPosition();if(c){const d=Kl(c,t);if(d<=a)return M.log(`[Distance] Too close to robot: ${d.toFixed(2)} pixels (threshold: ${a.toFixed(2)} pixels)`),!0}else M.warn("[Distance] Robot position not available")}return!1}async snapshot(t){this.render();const{snapshot:i,global:s}=this.config,r=(t==null?void 0:t.backgroundColor)??s.backgroundColor,o=this.components.appContainer,a=o.getSnapshotBounds(),l=Math.floor(a.x),h=Math.floor(a.y),c=Math.ceil(a.x+a.width)-l,d=Math.ceil(a.y+a.height)-h;if(c<=0||d<=0)return M.error("[MapApplication] Snapshot failed: invalid bounds",a),"";const u=i.resolution||window.devicePixelRatio||2,p=Ko.create({width:c,height:d,resolution:u}),f=new W;f.rect(0,0,c,d).fill(r);const m=new H;m.translate(-l,-h);try{return this.renderer.render({container:f,target:p}),this.renderer.render({container:o,target:p,transform:m,clear:!1}),await this.renderer.extract.base64({target:p,format:i.format,quality:i.quality,antialias:i.antialias})}catch(g){return M.error("[MapApplication] Snapshot failed:",g),""}finally{f.destroy(),p.destroy(!0)}}async snapshotByData({map:t,path:i,roomProperties:s,customElements:r,forbiddenSweepZones:o,forbiddenMopZones:a,virtualWalls:l,detectedObjects:h,furnitures:c,carpets:d},u={},p){const f=`SNAPSHOT_${Sh()}`;M.log(`[MapApplication] ${f} snapshot start`);const m=new us(f);try{if(await m.initialize({config:this.config,runtime:u}),!t)throw new Error("Map data is required");if(t.startsWith("7b22")){const x=$p(t);await m.drawMap(x)}else{const x=Xp(t,{pointsStructured:!0});if(x)await m.drawRasterMap(x);else throw new Error("Failed to decode raster map data")}if(i){const{decodePath:x}=await je(async()=>{const{decodePath:b}=await import("./theme.BEOFMcEN.js").then(w=>w.f);return{decodePath:b}},__vite__mapDeps([4,2])),S=x(i);m.drawPath(S)}s&&s.length>0&&await m.drawRoomProperty(s),o&&o.length>0&&m.drawForbiddenSweepZones(o),a&&a.length>0&&m.drawForbiddenMopZones(a),l&&l.length>0&&m.drawVirtualWalls(l),d&&d.length>0&&await m.drawCustomCarpets(d),c&&c.length>0&&await m.drawFurnitures(c),h&&h.length>0&&await m.drawDetectedObjects(h),r&&r.length>0&&await m.drawCustomElements(r);const g=await m.snapshot(p);return M.log(`[MapApplication] ${f} snapshot completed successfully`),g}catch(g){throw M.error(`[MapApplication] ${f} snapshot other map failed:`,g),g}finally{M.log(`[MapApplication] ${f} destroy`),m.destroy()}}renderOnce(){var t,i;M.debug("[Pixi] renderOnce");try{this.render(),(t=this.diagnostics)==null||t.explicitRenderSubmit("renderOnce")}catch(s){(i=this.diagnostics)==null||i.record("error",{stage:"renderOnce",message:String(s)}),M.error("[Pixi] renderOnce failed",this.getRendererDiagnostics({error:s}))}}renderOnceNextFrame(){this.pendingAsyncRender||(this.pendingAsyncRender=!0,requestAnimationFrame(()=>{var t,i;if(this.isDestroying){this.pendingAsyncRender=!1;return}M.debug("[Pixi] renderOnceNextFrame");try{this.render(),(t=this.diagnostics)==null||t.explicitRenderSubmit("renderOnceNextFrame")}catch(s){(i=this.diagnostics)==null||i.record("error",{stage:"renderOnceNextFrame",message:String(s)}),M.error("[Pixi] renderOnceNextFrame failed",this.getRendererDiagnostics({error:s}))}finally{this.pendingAsyncRender=!1}}))}requestRender(t,i=!1){var r;if(this.tickerState.lastRequestReason=t,!i){this.renderOnceNextFrame(),this.emitRenderStateUpdate();return}const s=this.tickerState.renderTimer!==null;this.tickerState.renderReasons.add(t),M.debug("[Ticker] requestRender(continuous)",{reason:t,hadPendingStop:s,reasonsAfterAdd:[...this.tickerState.renderReasons],tickerStarted:(r=this.ticker)==null?void 0:r.started}),this.ticker.started||(M.debug(`🎬 [Ticker] START: ${t}`),this.ticker.start()),this.emitRenderStateUpdate()}stopRender(t){var i;this.tickerState.lastStopReason=t,this.tickerState.renderReasons.delete(t),M.debug("[Ticker] stopRender",{reason:t,reasonsAfterDelete:[...this.tickerState.renderReasons],tickerStarted:(i=this.ticker)==null?void 0:i.started}),this.tickerState.renderReasons.size===0&&this.scheduleStopRender("final",100),this.emitRenderStateUpdate()}getRenderState(){var i;const t=!!((i=this.ticker)!=null&&i.started);return{continuous:t,fps:t?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 t,i,s,r,o,a,l,h,c,d,u,p,f,m,g,x;if(!this.isDestroying){this.isDestroying=!0,(t=this.diagnostics)==null||t.destroy(),M.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(),(i=this.renderer)==null||i.off("resize",this.onRendererResize),document.removeEventListener("visibilitychange",this.onVisibilityChange),(s=this.elasticScale)==null||s.destroy(),(r=this.managers.pathManager)==null||r.destroy(),(o=this.managers.mapManager)==null||o.destroy(),(a=this.managers.controlsManager)==null||a.destroy(),(l=this.managers.furnitureManager)==null||l.destroy(),(h=this.managers.detectedObjectManager)==null||h.destroy(),(c=this.managers.customElementsManager)==null||c.destroy(),(d=this.managers.roomsManager)==null||d.destroy(),(u=this.components.domOverlayAligner)==null||u.destroy(),(p=this.components.interaction)==null||p.destroy(),(f=this.components.background)==null||f.destroy(),(m=this.components.viewportContainer)==null||m.destroy(),(g=this.components.appContainer)==null||g.destroy(),(x=this.managers.heatmapManager)==null||x.destroy(),this.renderer&&this.detachRendererDiagnostics(),QS(this.previousLoggerRuntimeState),this.previousLoggerRuntimeState=null,globalThis.__PIXI_APP__===this&&delete globalThis.__PIXI_APP__,this.renderer&&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"),this.diagnostics.destroy()}}}initializeViewportContainer(){this.components.viewportContainer=new Iv(this.config,this.containerElement),this.stage.addChild(this.components.viewportContainer);const t=this.getViewportBounds();this.components.background=new AC(this.config.global,t,()=>{this.renderOnceNextFrame()}),this.components.viewportContainer.addChild(this.components.background),this.components.viewportContainer.setChildIndex(this.components.background,0),Ln(this.config.global,()=>{var i;(i=this.components.background)==null||i.update(this.config.global)})}initializeAppContainer(){this.components.appContainer=new Lv(this.appService),this.components.interaction.addChild(this.components.appContainer)}initializeInteraction(){this.components.interaction=new fv(this.appService),this.components.viewportContainer.addChild(this.components.interaction)}scheduleStopRender(t,i){this.tickerState.renderTimer&&clearTimeout(this.tickerState.renderTimer),M.debug("[Ticker] scheduleStopRender(set)",{reason:t,delay:i,reasonsNow:[...this.tickerState.renderReasons]}),this.tickerState.renderTimer=setTimeout(()=>{this.tickerState.renderTimer=null,this.tickerState.renderReasons.delete(t),this.tickerState.renderReasons.size===0?(M.debug("⏸️ [Ticker] STOP"),this.ticker&&(this.ticker.stop(),this.emitRenderStateUpdate())):M.debug("[Ticker] stop-timer fired but reasons remain",{reasons:[...this.tickerState.renderReasons]})},i)}generateZonePoints(t,i,s){const r=this.getViewportCenterPoint()||{x:0,y:0};return this.buildRectPoints({center:r,widthMeters:t,heightMeters:t,applyMapRotation:!0,visualOffsetX:i,visualOffsetY:s})}buildRectPoints(t){var m;const{center:i,widthMeters:s,heightMeters:r,applyMapRotation:o,visualOffsetX:a=0,visualOffsetY:l=0}=t,h=this.coords.toPixels(et(s))/2,c=this.coords.toPixels(et(r))/2,d=o&&((m=this.components.appContainer)==null?void 0:m.getMapRotationRadians())||0,u=Math.cos(d),p=Math.sin(d);return[{vx:-h+a,vy:-c+l},{vx:h+a,vy:-c+l},{vx:h+a,vy:c+l},{vx:-h+a,vy:c+l}].map(g=>({x:i.x+g.vx*u+g.vy*p,y:i.y-g.vx*p+g.vy*u}))}preloadAssets(){var a,l,h,c;const t=this.config.robot.icon.src,i=this.config.chargingStation.icon.src,s=[];Y.add({alias:"robot",src:t}),s.push("robot"),Y.add({alias:"chargingStation",src:i}),s.push("chargingStation"),Y.add({alias:"deleteIcon",src:this.config.controls.deleteIconSrc}),s.push("deleteIcon"),Y.add({alias:"rotateIcon",src:this.config.controls.rotateIconSrc}),s.push("rotateIcon"),Y.add({alias:"scaleIcon",src:this.config.controls.scaleIconSrc}),s.push("scaleIcon"),Y.add({alias:"moveIcon",src:this.config.controls.moveIconSrc}),s.push("moveIcon"),Y.add({alias:"checkmark",src:this.config.room.selectionIndicator.iconSrc}),s.push("checkmark"),Y.add({alias:"spotIcon",src:this.config.controls.spot.iconSrc}),s.push("spotIcon");const r=(a=this.config.controls.roomAnchor)==null?void 0:a.iconSrc;r&&(Y.add({alias:"roomAnchorIcon",src:r}),s.push("roomAnchorIcon")),[["forbiddenSweepZone",(l=this.config.controls.forbiddenSweepZone.centerIcon)==null?void 0:l.src],["forbiddenMopZone",(h=this.config.controls.forbiddenMopZone.centerIcon)==null?void 0:h.src],["cleanZone",(c=this.config.controls.cleanZone.centerIcon)==null?void 0:c.src],...Object.entries(this.config.customZoneTypes??{}).map(([d,u])=>{var p;return[d,(p=u==null?void 0:u.centerIcon)==null?void 0:p.src]})].forEach(([d,u])=>{if(!u)return;const p=`zoneCenterIcon_${d}`;Y.add({alias:p,src:u}),s.push(p)}),Y.add({alias:"wayPoint",src:this.config.controls.wayPoint.normal.iconSrc}),s.push("wayPoint"),Y.add({alias:"wayPointActive",src:this.config.controls.wayPoint.editing.iconSrc}),s.push("wayPointActive"),Y.add({alias:"horizontalScaleIcon",src:this.config.controls.horizontalScaleIconSrc}),s.push("horizontalScaleIcon"),Y.add({alias:"verticalScaleIcon",src:this.config.controls.verticalScaleIconSrc}),s.push("verticalScaleIcon"),this.config.room.property.cleanMode.assets.forEach((d,u)=>{const p=`cleanMode_${u}`;Y.add({alias:p,src:d}),s.push(p)}),this.config.room.property.suction.assets.forEach((d,u)=>{const p=`fan_${u}`;Y.add({alias:p,src:d}),s.push(p)}),this.config.room.property.cistern.assets.forEach((d,u)=>{const p=`water_${u}`;Y.add({alias:p,src:d}),s.push(p)}),this.config.room.property.cleanTimes.assets.forEach((d,u)=>{const p=`cleanTimes${u+1}`;Y.add({alias:p,src:d}),s.push(p)}),this.config.room.floorType.assets.forEach((d,u)=>{if(!d)return;const p=`floorType${u}`;Y.add({alias:p,src:d}),s.push(p)}),this.config.room.property.customAssets&&Object.entries(this.config.room.property.customAssets).forEach(([d,u])=>{u.forEach((p,f)=>{const m=`custom_${d}_${f}`;Y.add({alias:m,src:p}),s.push(m)})}),this.config.furniture.assets.forEach(d=>{const u=`furniture_${d.type}`;Y.add({alias:u,src:d.src}),s.push(u)}),Y.backgroundLoad(s)}setupMapRotationListener(){this.applyMapRotation(this.runtime.mapRotation),z(this.runtime,"mapRotation",t=>{this.applyMapRotation(t)})}applyMapRotation(t){const i=(t%360+360)%360;M.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()}};y(us,"CONTEXT_LOSS_TAIL_SIZE",8);let Ao=us;const XC=Object.freeze(Object.defineProperty({__proto__:null,AppService:_u,MapApplication:Ao},Symbol.toStringTag,{value:"Module"}));export{ss as $,es as A,Re as B,Me as C,ko as D,ae as E,Fo as F,W as G,Ux as H,wi as I,Ty as J,In as K,Sy as L,H as M,Xt as N,Dn as O,it as P,Do as Q,st as R,km as S,U as T,Z as U,rd as V,pe as W,Ps as X,Tm as Y,ki as Z,nl as _,bi as a,Bo as a0,id as a1,Ut as a2,Mi as a3,bd as a4,ny as a5,ly as a6,$C as a7,wd as a8,Je as a9,ms as aA,Fm as aB,vd as aC,ry as aD,cy as aE,Hx as aF,Cd as aG,dy as aH,Dx as aI,XC as aJ,on as aa,Sg as ab,rf as ac,Ie as ad,Ci as ae,uy as af,Ft as ag,Ac as ah,Wt as ai,Rn as aj,Ea as ak,re as al,wS as am,Lf as an,Ia as ao,ir as ap,Da as aq,Of as ar,Rc as as,Ko as at,Yo as au,mt as av,od as aw,_s as ax,Vg as ay,Wg as az,fo as b,ht as c,X as d,ee as e,go as f,Xs as g,vt as h,K as i,tg as j,Kf as k,sS as l,B as m,Ix as n,Bl as o,Pr as p,Q as q,Sf as r,O as s,hg as t,vg as u,tt as v,lt as w,St as x,ft as y,at as z};
|