open-plant 1.4.5 → 1.4.6
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/index.cjs +7 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1350 -1324
- package/dist/index.js.map +1 -1
- package/dist/types/react/draw-layer-label.d.ts +1 -1
- package/dist/types/react/draw-layer-label.d.ts.map +1 -1
- package/dist/types/react/draw-layer-types.d.ts +1 -0
- package/dist/types/react/draw-layer-types.d.ts.map +1 -1
- package/dist/types/react/draw-layer.d.ts.map +1 -1
- package/dist/types/react/region-layer.d.ts.map +1 -1
- package/dist/types/react/viewer-context.d.ts +2 -1
- package/dist/types/react/viewer-context.d.ts.map +1 -1
- package/dist/types/react/wsi-viewer.d.ts.map +1 -1
- package/dist/types/wsi/wsi-tile-renderer.d.ts +1 -0
- package/dist/types/wsi/wsi-tile-renderer.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var bi=Object.defineProperty;var wi=(e,t,n)=>t in e?bi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var R=(e,t,n)=>wi(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
1
|
+
"use strict";var bi=Object.defineProperty;var wi=(e,t,n)=>t in e?bi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var R=(e,t,n)=>wi(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const We=require("react/jsx-runtime"),g=require("react");var st=typeof document<"u"?document.currentScript:null;function Ln(e,t,n){const r=e.createShader(t);if(!r)throw new Error("Failed to create shader.");if(e.shaderSource(r,n),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS)){const o=e.getShaderInfoLog(r)??"unknown shader error";throw e.deleteShader(r),new Error(o)}return r}function wn(e,t,n){const r=Ln(e,e.VERTEX_SHADER,t),i=Ln(e,e.FRAGMENT_SHADER,n),o=e.createProgram();if(!o)throw e.deleteShader(r),e.deleteShader(i),new Error("Failed to create program.");if(e.attachShader(o,r),e.attachShader(o,i),e.linkProgram(o),e.deleteShader(r),e.deleteShader(i),!e.getProgramParameter(o,e.LINK_STATUS)){const a=e.getProgramInfoLog(o)??"unknown link error";throw e.deleteProgram(o),new Error(a)}return o}function Le(e,t,n){const r=e.getUniformLocation(t,n);if(!r)throw new Error(`Failed to get uniform location: ${n}`);return r}function xi(e){const t=e.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,stencil:!1,preserveDrawingBuffer:!1,powerPreference:"high-performance"});if(!t)throw new Error("WebGL2 is not available.");return t}function $t(e){return e*Math.PI/180}class kr{constructor(){R(this,"viewportWidth",1);R(this,"viewportHeight",1);R(this,"viewState",{offsetX:0,offsetY:0,zoom:1,rotationDeg:0})}setViewport(t,n){this.viewportWidth=Math.max(1,t),this.viewportHeight=Math.max(1,n)}getViewportSize(){return{width:this.viewportWidth,height:this.viewportHeight}}setViewState(t){t.offsetX!==void 0&&(this.viewState.offsetX=t.offsetX),t.offsetY!==void 0&&(this.viewState.offsetY=t.offsetY),t.zoom!==void 0&&(this.viewState.zoom=Math.max(1e-4,t.zoom)),typeof t.rotationDeg=="number"&&Number.isFinite(t.rotationDeg)&&(this.viewState.rotationDeg=t.rotationDeg)}getViewState(){return{...this.viewState}}getCenter(){const t=Math.max(1e-6,this.viewState.zoom);return[this.viewState.offsetX+this.viewportWidth/(2*t),this.viewState.offsetY+this.viewportHeight/(2*t)]}setCenter(t,n){const r=Math.max(1e-6,this.viewState.zoom);this.viewState.offsetX=t-this.viewportWidth/(2*r),this.viewState.offsetY=n-this.viewportHeight/(2*r)}screenToWorld(t,n){const r=Math.max(1e-6,this.viewState.zoom),[i,o]=this.getCenter(),s=this.viewState.rotationDeg??0,a=(t-this.viewportWidth*.5)/r,l=(n-this.viewportHeight*.5)/r,u=$t(s),f=Math.cos(u),c=Math.sin(u);return[i+a*f-l*c,o+a*c+l*f]}worldToScreen(t,n){const r=Math.max(1e-6,this.viewState.zoom),[i,o]=this.getCenter(),s=this.viewState.rotationDeg??0,a=t-i,l=n-o,u=$t(s),f=Math.cos(u),c=Math.sin(u),h=a*f+l*c,d=-a*c+l*f;return[this.viewportWidth*.5+h*r,this.viewportHeight*.5+d*r]}getViewCorners(){const t=this.viewportWidth,n=this.viewportHeight;return[this.screenToWorld(0,0),this.screenToWorld(t,0),this.screenToWorld(t,n),this.screenToWorld(0,n)]}getMatrix(){const t=Math.max(1e-6,this.viewState.zoom),n=this.viewState.rotationDeg??0;if(n===0){const m=this.viewportWidth/t,p=this.viewportHeight/t,y=2/m,b=-2/p,x=-1-this.viewState.offsetX*y,C=1-this.viewState.offsetY*b;return new Float32Array([y,0,0,0,b,0,x,C,1])}const[r,i]=this.getCenter(),o=$t(n),s=Math.cos(o),a=Math.sin(o),l=2*t*s/this.viewportWidth,u=2*t*a/this.viewportWidth,f=2*t*a/this.viewportHeight,c=-2*t*s/this.viewportHeight,h=-(l*r+u*i),d=-(f*r+c*i);return new Float32Array([l,f,0,u,c,0,h,d,1])}}const Si=`#version 300 es
|
|
2
2
|
precision highp float;
|
|
3
3
|
|
|
4
4
|
in vec2 aUnit;
|
|
@@ -29,8 +29,8 @@ out vec4 outColor;
|
|
|
29
29
|
void main() {
|
|
30
30
|
outColor = texture(uTexture, vUv);
|
|
31
31
|
}
|
|
32
|
-
`;class Nr{constructor(t){R(this,"canvas");R(this,"gl");R(this,"camera",new kr);R(this,"imageWidth");R(this,"imageHeight");R(this,"clearColor");R(this,"program");R(this,"vao");R(this,"quadBuffer");R(this,"uCameraLocation");R(this,"uBoundsLocation");R(this,"uTextureLocation");R(this,"resizeObserver");R(this,"tiles",[]);R(this,"frameId",null);R(this,"loadVersion",0);R(this,"destroyed",!1);R(this,"fitted",!1);R(this,"controlledViewState",!1);this.canvas=t.canvas,this.imageWidth=Math.max(1,t.imageWidth),this.imageHeight=Math.max(1,t.imageHeight),this.clearColor=t.clearColor??[.03,.05,.08,1],this.gl=xi(this.canvas),this.program=
|
|
33
|
-
`);const o=t+(n?" ":"│ ");e.left&&rn(e.left,o,!1,r,i),e.right&&rn(e.right,o,!0,r,i)}}class wn{constructor(t=Ri){this._root=null,this._size=0,this._comparator=t}insert(t,n){return this._size++,this._root=$t(t,n,this._root,this._comparator)}add(t,n){const r=new Qe(t,n);this._root===null&&(r.left=r.right=null,this._size++,this._root=r);const i=this._comparator,o=$e(t,this._root,i),s=i(t,o.key);return s===0?this._root=o:(s<0?(r.left=o.left,r.right=o,o.left=null):s>0&&(r.right=o.right,r.left=o,o.right=null),this._size++,this._root=r),this._root}remove(t){this._root=this._remove(t,this._root,this._comparator)}_remove(t,n,r){let i;return n===null?null:(n=$e(t,n,r),r(t,n.key)===0?(n.left===null?i=n.right:(i=$e(t,n.left,r),i.right=n.right),this._size--,i):n)}pop(){let t=this._root;if(t){for(;t.left;)t=t.left;return this._root=$e(t.key,this._root,this._comparator),this._root=this._remove(t.key,this._root,this._comparator),{key:t.key,data:t.data}}return null}findStatic(t){let n=this._root;const r=this._comparator;for(;n;){const i=r(t,n.key);if(i===0)return n;i<0?n=n.left:n=n.right}return null}find(t){return this._root&&(this._root=$e(t,this._root,this._comparator),this._comparator(t,this._root.key)!==0)?null:this._root}contains(t){let n=this._root;const r=this._comparator;for(;n;){const i=r(t,n.key);if(i===0)return!0;i<0?n=n.left:n=n.right}return!1}forEach(t,n){let r=this._root;const i=[];let o=!1;for(;!o;)r!==null?(i.push(r),r=r.left):i.length!==0?(r=i.pop(),t.call(n,r),r=r.right):o=!0;return this}range(t,n,r,i){const o=[],s=this._comparator;let a=this._root,l;for(;o.length!==0||a;)if(a)o.push(a),a=a.left;else{if(a=o.pop(),l=s(a.key,n),l>0)break;if(s(a.key,t)>=0&&r.call(i,a))return this;a=a.right}return this}keys(){const t=[];return this.forEach(({key:n})=>{t.push(n)}),t}values(){const t=[];return this.forEach(({data:n})=>{t.push(n)}),t}min(){return this._root?this.minNode(this._root).key:null}max(){return this._root?this.maxNode(this._root).key:null}minNode(t=this._root){if(t)for(;t.left;)t=t.left;return t}maxNode(t=this._root){if(t)for(;t.right;)t=t.right;return t}at(t){let n=this._root,r=!1,i=0;const o=[];for(;!r;)if(n)o.push(n),n=n.left;else if(o.length>0){if(n=o.pop(),i===t)return n;i++,n=n.right}else r=!0;return null}next(t){let n=this._root,r=null;if(t.right){for(r=t.right;r.left;)r=r.left;return r}const i=this._comparator;for(;n;){const o=i(t.key,n.key);if(o===0)break;o<0?(r=n,n=n.left):n=n.right}return r}prev(t){let n=this._root,r=null;if(t.left!==null){for(r=t.left;r.right;)r=r.right;return r}const i=this._comparator;for(;n;){const o=i(t.key,n.key);if(o===0)break;o<0?n=n.left:(r=n,n=n.right)}return r}clear(){return this._root=null,this._size=0,this}toList(){return vi(this._root)}load(t,n=[],r=!1){let i=t.length;const o=this._comparator;if(r&&an(t,n,0,i-1,o),this._root===null)this._root=on(t,n,0,i),this._size=i;else{const s=Ci(this.toList(),Ai(t,n),o);i=this._size+i,this._root=sn({head:s},0,i)}return this}isEmpty(){return this._root===null}get size(){return this._size}get root(){return this._root}toString(t=n=>String(n.key)){const n=[];return rn(this._root,"",!0,r=>n.push(r),t),n.join("")}update(t,n,r){const i=this._comparator;let{left:o,right:s}=Ln(t,this._root,i);i(t,n)<0?s=$t(n,r,s,i):o=$t(n,r,o,i),this._root=Mi(o,s,i)}split(t){return Ln(t,this._root,this._comparator)}*[Symbol.iterator](){let t=this._root;const n=[];let r=!1;for(;!r;)t!==null?(n.push(t),t=t.left):n.length!==0?(t=n.pop(),yield t,t=t.right):r=!0}}function on(e,t,n,r){const i=r-n;if(i>0){const o=n+Math.floor(i/2),s=e[o],a=t[o],l=new Qe(s,a);return l.left=on(e,t,n,o),l.right=on(e,t,o+1,r),l}return null}function Ai(e,t){const n=new Qe(null,null);let r=n;for(let i=0;i<e.length;i++)r=r.next=new Qe(e[i],t[i]);return r.next=null,n.next}function vi(e){let t=e;const n=[];let r=!1;const i=new Qe(null,null);let o=i;for(;!r;)t?(n.push(t),t=t.left):n.length>0?(t=o=o.next=n.pop(),t=t.right):r=!0;return o.next=null,i.next}function sn(e,t,n){const r=n-t;if(r>0){const i=t+Math.floor(r/2),o=sn(e,t,i),s=e.head;return s.left=o,e.head=e.head.next,s.right=sn(e,i+1,n),s}return null}function Ci(e,t,n){const r=new Qe(null,null);let i=r,o=e,s=t;for(;o!==null&&s!==null;)n(o.key,s.key)<0?(i.next=o,o=o.next):(i.next=s,s=s.next),i=i.next;return o!==null?i.next=o:s!==null&&(i.next=s),r.next}function an(e,t,n,r,i){if(n>=r)return;const o=e[n+r>>1];let s=n-1,a=r+1;for(;;){do s++;while(i(e[s],o)<0);do a--;while(i(e[a],o)>0);if(s>=a)break;let l=e[s];e[s]=e[a],e[a]=l,l=t[s],t[s]=t[a],t[a]=l}an(e,t,n,a,i),an(e,t,a+1,r,i)}const Ge=11102230246251565e-32,Ie=134217729,Ii=(3+8*Ge)*Ge;function Kt(e,t,n,r,i){let o,s,a,l,u=t[0],f=r[0],c=0,h=0;f>u==f>-u?(o=u,u=t[++c]):(o=f,f=r[++h]);let d=0;if(c<e&&h<n)for(f>u==f>-u?(s=u+o,a=o-(s-u),u=t[++c]):(s=f+o,a=o-(s-f),f=r[++h]),o=s,a!==0&&(i[d++]=a);c<e&&h<n;)f>u==f>-u?(s=o+u,l=s-o,a=o-(s-l)+(u-l),u=t[++c]):(s=o+f,l=s-o,a=o-(s-l)+(f-l),f=r[++h]),o=s,a!==0&&(i[d++]=a);for(;c<e;)s=o+u,l=s-o,a=o-(s-l)+(u-l),u=t[++c],o=s,a!==0&&(i[d++]=a);for(;h<n;)s=o+f,l=s-o,a=o-(s-l)+(f-l),f=r[++h],o=s,a!==0&&(i[d++]=a);return(o!==0||d===0)&&(i[d++]=o),d}function Pi(e,t){let n=t[0];for(let r=1;r<e;r++)n+=t[r];return n}function gt(e){return new Float64Array(e)}const Ti=(3+16*Ge)*Ge,_i=(2+12*Ge)*Ge,Fi=(9+64*Ge)*Ge*Ge,tt=gt(4),kn=gt(8),Nn=gt(12),Bn=gt(16),Te=gt(4);function Li(e,t,n,r,i,o,s){let a,l,u,f,c,h,d,m,p,y,b,x,C,S,A,T,O,D;const G=e-i,z=n-i,q=t-o,re=r-o;S=G*re,h=Ie*G,d=h-(h-G),m=G-d,h=Ie*re,p=h-(h-re),y=re-p,A=m*y-(S-d*p-m*p-d*y),T=q*z,h=Ie*q,d=h-(h-q),m=q-d,h=Ie*z,p=h-(h-z),y=z-p,O=m*y-(T-d*p-m*p-d*y),b=A-O,c=A-b,tt[0]=A-(b+c)+(c-O),x=S+b,c=x-S,C=S-(x-c)+(b-c),b=C-T,c=C-b,tt[1]=C-(b+c)+(c-T),D=x+b,c=D-x,tt[2]=x-(D-c)+(b-c),tt[3]=D;let I=Pi(4,tt),H=_i*s;if(I>=H||-I>=H||(c=e-G,a=e-(G+c)+(c-i),c=n-z,u=n-(z+c)+(c-i),c=t-q,l=t-(q+c)+(c-o),c=r-re,f=r-(re+c)+(c-o),a===0&&l===0&&u===0&&f===0)||(H=Fi*s+Ii*Math.abs(I),I+=G*f+re*a-(q*u+z*l),I>=H||-I>=H))return I;S=a*re,h=Ie*a,d=h-(h-a),m=a-d,h=Ie*re,p=h-(h-re),y=re-p,A=m*y-(S-d*p-m*p-d*y),T=l*z,h=Ie*l,d=h-(h-l),m=l-d,h=Ie*z,p=h-(h-z),y=z-p,O=m*y-(T-d*p-m*p-d*y),b=A-O,c=A-b,Te[0]=A-(b+c)+(c-O),x=S+b,c=x-S,C=S-(x-c)+(b-c),b=C-T,c=C-b,Te[1]=C-(b+c)+(c-T),D=x+b,c=D-x,Te[2]=x-(D-c)+(b-c),Te[3]=D;const N=Kt(4,tt,4,Te,kn);S=G*f,h=Ie*G,d=h-(h-G),m=G-d,h=Ie*f,p=h-(h-f),y=f-p,A=m*y-(S-d*p-m*p-d*y),T=q*u,h=Ie*q,d=h-(h-q),m=q-d,h=Ie*u,p=h-(h-u),y=u-p,O=m*y-(T-d*p-m*p-d*y),b=A-O,c=A-b,Te[0]=A-(b+c)+(c-O),x=S+b,c=x-S,C=S-(x-c)+(b-c),b=C-T,c=C-b,Te[1]=C-(b+c)+(c-T),D=x+b,c=D-x,Te[2]=x-(D-c)+(b-c),Te[3]=D;const k=Kt(N,kn,4,Te,Nn);S=a*f,h=Ie*a,d=h-(h-a),m=a-d,h=Ie*f,p=h-(h-f),y=f-p,A=m*y-(S-d*p-m*p-d*y),T=l*u,h=Ie*l,d=h-(h-l),m=l-d,h=Ie*u,p=h-(h-u),y=u-p,O=m*y-(T-d*p-m*p-d*y),b=A-O,c=A-b,Te[0]=A-(b+c)+(c-O),x=S+b,c=x-S,C=S-(x-c)+(b-c),b=C-T,c=C-b,Te[1]=C-(b+c)+(c-T),D=x+b,c=D-x,Te[2]=x-(D-c)+(b-c),Te[3]=D;const Z=Kt(k,Nn,4,Te,Bn);return Bn[Z-1]}function ki(e,t,n,r,i,o){const s=(t-o)*(n-i),a=(e-i)*(r-o),l=s-a,u=Math.abs(s+a);return Math.abs(l)>=Ti*u?l:-Li(e,t,n,r,i,o,u)}const at=(e,t)=>e.ll.x<=t.x&&t.x<=e.ur.x&&e.ll.y<=t.y&&t.y<=e.ur.y,ln=(e,t)=>{if(t.ur.x<e.ll.x||e.ur.x<t.ll.x||t.ur.y<e.ll.y||e.ur.y<t.ll.y)return null;const n=e.ll.x<t.ll.x?t.ll.x:e.ll.x,r=e.ur.x<t.ur.x?e.ur.x:t.ur.x,i=e.ll.y<t.ll.y?t.ll.y:e.ll.y,o=e.ur.y<t.ur.y?e.ur.y:t.ur.y;return{ll:{x:n,y:i},ur:{x:r,y:o}}};let Ke=Number.EPSILON;Ke===void 0&&(Ke=Math.pow(2,-52));const Ni=Ke*Ke,Dn=(e,t)=>{if(-Ke<e&&e<Ke&&-Ke<t&&t<Ke)return 0;const n=e-t;return n*n<Ni*e*t?0:e<t?-1:1};class Bi{constructor(){this.reset()}reset(){this.xRounder=new zn,this.yRounder=new zn}round(t,n){return{x:this.xRounder.round(t),y:this.yRounder.round(n)}}}class zn{constructor(){this.tree=new wn,this.round(0)}round(t){const n=this.tree.add(t),r=this.tree.prev(n);if(r!==null&&Dn(n.key,r.key)===0)return this.tree.remove(t),r.key;const i=this.tree.next(n);return i!==null&&Dn(n.key,i.key)===0?(this.tree.remove(t),i.key):t}}const ft=new Bi,Tt=(e,t)=>e.x*t.y-e.y*t.x,Br=(e,t)=>e.x*t.x+e.y*t.y,Un=(e,t,n)=>{const r=ki(e.x,e.y,t.x,t.y,n.x,n.y);return r>0?-1:r<0?1:0},Nt=e=>Math.sqrt(Br(e,e)),Di=(e,t,n)=>{const r={x:t.x-e.x,y:t.y-e.y},i={x:n.x-e.x,y:n.y-e.y};return Tt(i,r)/Nt(i)/Nt(r)},zi=(e,t,n)=>{const r={x:t.x-e.x,y:t.y-e.y},i={x:n.x-e.x,y:n.y-e.y};return Br(i,r)/Nt(i)/Nt(r)},On=(e,t,n)=>t.y===0?null:{x:e.x+t.x/t.y*(n-e.y),y:n},Yn=(e,t,n)=>t.x===0?null:{x:n,y:e.y+t.y/t.x*(n-e.x)},Ui=(e,t,n,r)=>{if(t.x===0)return Yn(n,r,e.x);if(r.x===0)return Yn(e,t,n.x);if(t.y===0)return On(n,r,e.y);if(r.y===0)return On(e,t,n.y);const i=Tt(t,r);if(i==0)return null;const o={x:n.x-e.x,y:n.y-e.y},s=Tt(o,t)/i,a=Tt(o,r)/i,l=e.x+a*t.x,u=n.x+s*r.x,f=e.y+a*t.y,c=n.y+s*r.y,h=(l+u)/2,d=(f+c)/2;return{x:h,y:d}};class Be{static compare(t,n){const r=Be.comparePoints(t.point,n.point);return r!==0?r:(t.point!==n.point&&t.link(n),t.isLeft!==n.isLeft?t.isLeft?1:-1:je.compare(t.segment,n.segment))}static comparePoints(t,n){return t.x<n.x?-1:t.x>n.x?1:t.y<n.y?-1:t.y>n.y?1:0}constructor(t,n){t.events===void 0?t.events=[this]:t.events.push(this),this.point=t,this.isLeft=n}link(t){if(t.point===this.point)throw new Error("Tried to link already linked events");const n=t.point.events;for(let r=0,i=n.length;r<i;r++){const o=n[r];this.point.events.push(o),o.point=this.point}this.checkForConsuming()}checkForConsuming(){const t=this.point.events.length;for(let n=0;n<t;n++){const r=this.point.events[n];if(r.segment.consumedBy===void 0)for(let i=n+1;i<t;i++){const o=this.point.events[i];o.consumedBy===void 0&&r.otherSE.point.events===o.otherSE.point.events&&r.segment.consume(o.segment)}}}getAvailableLinkedEvents(){const t=[];for(let n=0,r=this.point.events.length;n<r;n++){const i=this.point.events[n];i!==this&&!i.segment.ringOut&&i.segment.isInResult()&&t.push(i)}return t}getLeftmostComparator(t){const n=new Map,r=i=>{const o=i.otherSE;n.set(i,{sine:Di(this.point,t.point,o.point),cosine:zi(this.point,t.point,o.point)})};return(i,o)=>{n.has(i)||r(i),n.has(o)||r(o);const{sine:s,cosine:a}=n.get(i),{sine:l,cosine:u}=n.get(o);return s>=0&&l>=0?a<u?1:a>u?-1:0:s<0&&l<0?a<u?-1:a>u?1:0:l<s?-1:l>s?1:0}}}let Oi=0;class je{static compare(t,n){const r=t.leftSE.point.x,i=n.leftSE.point.x,o=t.rightSE.point.x,s=n.rightSE.point.x;if(s<r)return 1;if(o<i)return-1;const a=t.leftSE.point.y,l=n.leftSE.point.y,u=t.rightSE.point.y,f=n.rightSE.point.y;if(r<i){if(l<a&&l<u)return 1;if(l>a&&l>u)return-1;const c=t.comparePoint(n.leftSE.point);if(c<0)return 1;if(c>0)return-1;const h=n.comparePoint(t.rightSE.point);return h!==0?h:-1}if(r>i){if(a<l&&a<f)return-1;if(a>l&&a>f)return 1;const c=n.comparePoint(t.leftSE.point);if(c!==0)return c;const h=t.comparePoint(n.rightSE.point);return h<0?1:h>0?-1:1}if(a<l)return-1;if(a>l)return 1;if(o<s){const c=n.comparePoint(t.rightSE.point);if(c!==0)return c}if(o>s){const c=t.comparePoint(n.rightSE.point);if(c<0)return 1;if(c>0)return-1}if(o!==s){const c=u-a,h=o-r,d=f-l,m=s-i;if(c>h&&d<m)return 1;if(c<h&&d>m)return-1}return o>s?1:o<s||u<f?-1:u>f?1:t.id<n.id?-1:t.id>n.id?1:0}constructor(t,n,r,i){this.id=++Oi,this.leftSE=t,t.segment=this,t.otherSE=n,this.rightSE=n,n.segment=this,n.otherSE=t,this.rings=r,this.windings=i}static fromRing(t,n,r){let i,o,s;const a=Be.comparePoints(t,n);if(a<0)i=t,o=n,s=1;else if(a>0)i=n,o=t,s=-1;else throw new Error(`Tried to create degenerate segment at [${t.x}, ${t.y}]`);const l=new Be(i,!0),u=new Be(o,!1);return new je(l,u,[r],[s])}replaceRightSE(t){this.rightSE=t,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const t=this.leftSE.point.y,n=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:t<n?t:n},ur:{x:this.rightSE.point.x,y:t>n?t:n}}}vector(){return{x:this.rightSE.point.x-this.leftSE.point.x,y:this.rightSE.point.y-this.leftSE.point.y}}isAnEndpoint(t){return t.x===this.leftSE.point.x&&t.y===this.leftSE.point.y||t.x===this.rightSE.point.x&&t.y===this.rightSE.point.y}comparePoint(t){if(this.isAnEndpoint(t))return 0;const n=this.leftSE.point,r=this.rightSE.point,i=this.vector();if(n.x===r.x)return t.x===n.x?0:t.x<n.x?1:-1;const o=(t.y-n.y)/i.y,s=n.x+o*i.x;if(t.x===s)return 0;const a=(t.x-n.x)/i.x,l=n.y+a*i.y;return t.y===l?0:t.y<l?-1:1}getIntersection(t){const n=this.bbox(),r=t.bbox(),i=ln(n,r);if(i===null)return null;const o=this.leftSE.point,s=this.rightSE.point,a=t.leftSE.point,l=t.rightSE.point,u=at(n,a)&&this.comparePoint(a)===0,f=at(r,o)&&t.comparePoint(o)===0,c=at(n,l)&&this.comparePoint(l)===0,h=at(r,s)&&t.comparePoint(s)===0;if(f&&u)return h&&!c?s:!h&&c?l:null;if(f)return c&&o.x===l.x&&o.y===l.y?null:o;if(u)return h&&s.x===a.x&&s.y===a.y?null:a;if(h&&c)return null;if(h)return s;if(c)return l;const d=Ui(o,this.vector(),a,t.vector());return d===null||!at(i,d)?null:ft.round(d.x,d.y)}split(t){const n=[],r=t.events!==void 0,i=new Be(t,!0),o=new Be(t,!1),s=this.rightSE;this.replaceRightSE(o),n.push(o),n.push(i);const a=new je(i,s,this.rings.slice(),this.windings.slice());return Be.comparePoints(a.leftSE.point,a.rightSE.point)>0&&a.swapEvents(),Be.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),r&&(i.checkForConsuming(),o.checkForConsuming()),n}swapEvents(){const t=this.rightSE;this.rightSE=this.leftSE,this.leftSE=t,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let n=0,r=this.windings.length;n<r;n++)this.windings[n]*=-1}consume(t){let n=this,r=t;for(;n.consumedBy;)n=n.consumedBy;for(;r.consumedBy;)r=r.consumedBy;const i=je.compare(n,r);if(i!==0){if(i>0){const o=n;n=r,r=o}if(n.prev===r){const o=n;n=r,r=o}for(let o=0,s=r.rings.length;o<s;o++){const a=r.rings[o],l=r.windings[o],u=n.rings.indexOf(a);u===-1?(n.rings.push(a),n.windings.push(l)):n.windings[u]+=l}r.rings=null,r.windings=null,r.consumedBy=n,r.leftSE.consumedBy=n.leftSE,r.rightSE.consumedBy=n.rightSE}}prevInResult(){return this._prevInResult!==void 0?this._prevInResult:(this.prev?this.prev.isInResult()?this._prevInResult=this.prev:this._prevInResult=this.prev.prevInResult():this._prevInResult=null,this._prevInResult)}beforeState(){if(this._beforeState!==void 0)return this._beforeState;if(!this.prev)this._beforeState={rings:[],windings:[],multiPolys:[]};else{const t=this.prev.consumedBy||this.prev;this._beforeState=t.afterState()}return this._beforeState}afterState(){if(this._afterState!==void 0)return this._afterState;const t=this.beforeState();this._afterState={rings:t.rings.slice(0),windings:t.windings.slice(0),multiPolys:[]};const n=this._afterState.rings,r=this._afterState.windings,i=this._afterState.multiPolys;for(let a=0,l=this.rings.length;a<l;a++){const u=this.rings[a],f=this.windings[a],c=n.indexOf(u);c===-1?(n.push(u),r.push(f)):r[c]+=f}const o=[],s=[];for(let a=0,l=n.length;a<l;a++){if(r[a]===0)continue;const u=n[a],f=u.poly;if(s.indexOf(f)===-1)if(u.isExterior)o.push(f);else{s.indexOf(f)===-1&&s.push(f);const c=o.indexOf(u.poly);c!==-1&&o.splice(c,1)}}for(let a=0,l=o.length;a<l;a++){const u=o[a].multiPoly;i.indexOf(u)===-1&&i.push(u)}return this._afterState}isInResult(){if(this.consumedBy)return!1;if(this._isInResult!==void 0)return this._isInResult;const t=this.beforeState().multiPolys,n=this.afterState().multiPolys;switch(We.type){case"union":{const r=t.length===0,i=n.length===0;this._isInResult=r!==i;break}case"intersection":{let r,i;t.length<n.length?(r=t.length,i=n.length):(r=n.length,i=t.length),this._isInResult=i===We.numMultiPolys&&r<i;break}case"xor":{const r=Math.abs(t.length-n.length);this._isInResult=r%2===1;break}case"difference":{const r=i=>i.length===1&&i[0].isSubject;this._isInResult=r(t)!==r(n);break}default:throw new Error(`Unrecognized operation type found ${We.type}`)}return this._isInResult}}class Wn{constructor(t,n,r){if(!Array.isArray(t)||t.length===0)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=n,this.isExterior=r,this.segments=[],typeof t[0][0]!="number"||typeof t[0][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const i=ft.round(t[0][0],t[0][1]);this.bbox={ll:{x:i.x,y:i.y},ur:{x:i.x,y:i.y}};let o=i;for(let s=1,a=t.length;s<a;s++){if(typeof t[s][0]!="number"||typeof t[s][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");let l=ft.round(t[s][0],t[s][1]);l.x===o.x&&l.y===o.y||(this.segments.push(je.fromRing(o,l,this)),l.x<this.bbox.ll.x&&(this.bbox.ll.x=l.x),l.y<this.bbox.ll.y&&(this.bbox.ll.y=l.y),l.x>this.bbox.ur.x&&(this.bbox.ur.x=l.x),l.y>this.bbox.ur.y&&(this.bbox.ur.y=l.y),o=l)}(i.x!==o.x||i.y!==o.y)&&this.segments.push(je.fromRing(o,i,this))}getSweepEvents(){const t=[];for(let n=0,r=this.segments.length;n<r;n++){const i=this.segments[n];t.push(i.leftSE),t.push(i.rightSE)}return t}}class Yi{constructor(t,n){if(!Array.isArray(t))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");this.exteriorRing=new Wn(t[0],this,!0),this.bbox={ll:{x:this.exteriorRing.bbox.ll.x,y:this.exteriorRing.bbox.ll.y},ur:{x:this.exteriorRing.bbox.ur.x,y:this.exteriorRing.bbox.ur.y}},this.interiorRings=[];for(let r=1,i=t.length;r<i;r++){const o=new Wn(t[r],this,!1);o.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=o.bbox.ll.x),o.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=o.bbox.ll.y),o.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=o.bbox.ur.x),o.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=o.bbox.ur.y),this.interiorRings.push(o)}this.multiPoly=n}getSweepEvents(){const t=this.exteriorRing.getSweepEvents();for(let n=0,r=this.interiorRings.length;n<r;n++){const i=this.interiorRings[n].getSweepEvents();for(let o=0,s=i.length;o<s;o++)t.push(i[o])}return t}}class Xn{constructor(t,n){if(!Array.isArray(t))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");try{typeof t[0][0][0]=="number"&&(t=[t])}catch{}this.polys=[],this.bbox={ll:{x:Number.POSITIVE_INFINITY,y:Number.POSITIVE_INFINITY},ur:{x:Number.NEGATIVE_INFINITY,y:Number.NEGATIVE_INFINITY}};for(let r=0,i=t.length;r<i;r++){const o=new Yi(t[r],this);o.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=o.bbox.ll.x),o.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=o.bbox.ll.y),o.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=o.bbox.ur.x),o.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=o.bbox.ur.y),this.polys.push(o)}this.isSubject=n}getSweepEvents(){const t=[];for(let n=0,r=this.polys.length;n<r;n++){const i=this.polys[n].getSweepEvents();for(let o=0,s=i.length;o<s;o++)t.push(i[o])}return t}}class Bt{static factory(t){const n=[];for(let r=0,i=t.length;r<i;r++){const o=t[r];if(!o.isInResult()||o.ringOut)continue;let s=null,a=o.leftSE,l=o.rightSE;const u=[a],f=a.point,c=[];for(;s=a,a=l,u.push(a),a.point!==f;)for(;;){const h=a.getAvailableLinkedEvents();if(h.length===0){const p=u[0].point,y=u[u.length-1].point;throw new Error(`Unable to complete output ring starting at [${p.x}, ${p.y}]. Last matching segment found ends at [${y.x}, ${y.y}].`)}if(h.length===1){l=h[0].otherSE;break}let d=null;for(let p=0,y=c.length;p<y;p++)if(c[p].point===a.point){d=p;break}if(d!==null){const p=c.splice(d)[0],y=u.splice(p.index);y.unshift(y[0].otherSE),n.push(new Bt(y.reverse()));continue}c.push({index:u.length,point:a.point});const m=a.getLeftmostComparator(s);l=h.sort(m)[0].otherSE;break}n.push(new Bt(u))}return n}constructor(t){this.events=t;for(let n=0,r=t.length;n<r;n++)t[n].segment.ringOut=this;this.poly=null}getGeom(){let t=this.events[0].point;const n=[t];for(let u=1,f=this.events.length-1;u<f;u++){const c=this.events[u].point,h=this.events[u+1].point;Un(c,t,h)!==0&&(n.push(c),t=c)}if(n.length===1)return null;const r=n[0],i=n[1];Un(r,t,i)===0&&n.shift(),n.push(n[0]);const o=this.isExteriorRing()?1:-1,s=this.isExteriorRing()?0:n.length-1,a=this.isExteriorRing()?n.length:-1,l=[];for(let u=s;u!=a;u+=o)l.push([n[u].x,n[u].y]);return l}isExteriorRing(){if(this._isExteriorRing===void 0){const t=this.enclosingRing();this._isExteriorRing=t?!t.isExteriorRing():!0}return this._isExteriorRing}enclosingRing(){return this._enclosingRing===void 0&&(this._enclosingRing=this._calcEnclosingRing()),this._enclosingRing}_calcEnclosingRing(){let t=this.events[0];for(let i=1,o=this.events.length;i<o;i++){const s=this.events[i];Be.compare(t,s)>0&&(t=s)}let n=t.segment.prevInResult(),r=n?n.prevInResult():null;for(;;){if(!n)return null;if(!r)return n.ringOut;if(r.ringOut!==n.ringOut)return r.ringOut.enclosingRing()!==n.ringOut?n.ringOut:n.ringOut.enclosingRing();n=r.prevInResult(),r=n?n.prevInResult():null}}}class Vn{constructor(t){this.exteriorRing=t,t.poly=this,this.interiorRings=[]}addInterior(t){this.interiorRings.push(t),t.poly=this}getGeom(){const t=[this.exteriorRing.getGeom()];if(t[0]===null)return null;for(let n=0,r=this.interiorRings.length;n<r;n++){const i=this.interiorRings[n].getGeom();i!==null&&t.push(i)}return t}}class Wi{constructor(t){this.rings=t,this.polys=this._composePolys(t)}getGeom(){const t=[];for(let n=0,r=this.polys.length;n<r;n++){const i=this.polys[n].getGeom();i!==null&&t.push(i)}return t}_composePolys(t){const n=[];for(let r=0,i=t.length;r<i;r++){const o=t[r];if(!o.poly)if(o.isExteriorRing())n.push(new Vn(o));else{const s=o.enclosingRing();s.poly||n.push(new Vn(s)),s.poly.addInterior(o)}}return n}}class Xi{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:je.compare;this.queue=t,this.tree=new wn(n),this.segments=[]}process(t){const n=t.segment,r=[];if(t.consumedBy)return t.isLeft?this.queue.remove(t.otherSE):this.tree.remove(n),r;const i=t.isLeft?this.tree.add(n):this.tree.find(n);if(!i)throw new Error(`Unable to find segment #${n.id} [${n.leftSE.point.x}, ${n.leftSE.point.y}] -> [${n.rightSE.point.x}, ${n.rightSE.point.y}] in SweepLine tree.`);let o=i,s=i,a,l;for(;a===void 0;)o=this.tree.prev(o),o===null?a=null:o.key.consumedBy===void 0&&(a=o.key);for(;l===void 0;)s=this.tree.next(s),s===null?l=null:s.key.consumedBy===void 0&&(l=s.key);if(t.isLeft){let u=null;if(a){const c=a.getIntersection(n);if(c!==null&&(n.isAnEndpoint(c)||(u=c),!a.isAnEndpoint(c))){const h=this._splitSafely(a,c);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}}let f=null;if(l){const c=l.getIntersection(n);if(c!==null&&(n.isAnEndpoint(c)||(f=c),!l.isAnEndpoint(c))){const h=this._splitSafely(l,c);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}}if(u!==null||f!==null){let c=null;u===null?c=f:f===null?c=u:c=Be.comparePoints(u,f)<=0?u:f,this.queue.remove(n.rightSE),r.push(n.rightSE);const h=n.split(c);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}r.length>0?(this.tree.remove(n),r.push(t)):(this.segments.push(n),n.prev=a)}else{if(a&&l){const u=a.getIntersection(l);if(u!==null){if(!a.isAnEndpoint(u)){const f=this._splitSafely(a,u);for(let c=0,h=f.length;c<h;c++)r.push(f[c])}if(!l.isAnEndpoint(u)){const f=this._splitSafely(l,u);for(let c=0,h=f.length;c<h;c++)r.push(f[c])}}}this.tree.remove(n)}return r}_splitSafely(t,n){this.tree.remove(t);const r=t.rightSE;this.queue.remove(r);const i=t.split(n);return i.push(r),t.consumedBy===void 0&&this.tree.add(t),i}}const Gn=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_QUEUE_SIZE||1e6,Vi=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS||1e6;class Gi{run(t,n,r){We.type=t,ft.reset();const i=[new Xn(n,!0)];for(let c=0,h=r.length;c<h;c++)i.push(new Xn(r[c],!1));if(We.numMultiPolys=i.length,We.type==="difference"){const c=i[0];let h=1;for(;h<i.length;)ln(i[h].bbox,c.bbox)!==null?h++:i.splice(h,1)}if(We.type==="intersection")for(let c=0,h=i.length;c<h;c++){const d=i[c];for(let m=c+1,p=i.length;m<p;m++)if(ln(d.bbox,i[m].bbox)===null)return[]}const o=new wn(Be.compare);for(let c=0,h=i.length;c<h;c++){const d=i[c].getSweepEvents();for(let m=0,p=d.length;m<p;m++)if(o.insert(d[m]),o.size>Gn)throw new Error("Infinite loop when putting segment endpoints in a priority queue (queue size too big).")}const s=new Xi(o);let a=o.size,l=o.pop();for(;l;){const c=l.key;if(o.size===a){const d=c.segment;throw new Error(`Unable to pop() ${c.isLeft?"left":"right"} SweepEvent [${c.point.x}, ${c.point.y}] from segment #${d.id} [${d.leftSE.point.x}, ${d.leftSE.point.y}] -> [${d.rightSE.point.x}, ${d.rightSE.point.y}] from queue.`)}if(o.size>Gn)throw new Error("Infinite loop when passing sweep line over endpoints (queue size too big).");if(s.segments.length>Vi)throw new Error("Infinite loop when passing sweep line over endpoints (too many sweep line segments).");const h=s.process(c);for(let d=0,m=h.length;d<m;d++){const p=h[d];p.consumedBy===void 0&&o.insert(p)}a=o.size,l=o.pop()}ft.reset();const u=Bt.factory(s.segments);return new Wi(u).getGeom()}}const We=new Gi,qi=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return We.run("union",e,n)},Hi=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return We.run("intersection",e,n)},Zi=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return We.run("xor",e,n)},$i=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return We.run("difference",e,n)};var Ki={union:qi,intersection:Hi,xor:Zi,difference:$i};function pt(e){return e==null?null:Dr(e)||zr(e)||ji(e)?e:null}function qn(e){return typeof e=="number"&&Number.isFinite(e)}function _t(e){return Array.isArray(e)&&e.length>=2&&qn(e[0])&&qn(e[1])}function Dr(e){return Array.isArray(e)&&e.length>0&&e.every(t=>_t(t))}function zr(e){return Array.isArray(e)&&e.length>0&&e.every(t=>Dr(t))}function ji(e){return Array.isArray(e)&&e.length>0&&e.every(t=>zr(t))}function Ne(e){if(!Array.isArray(e)||e.length<3)return[];const t=[];for(const i of e){if(!Array.isArray(i)||i.length<2)continue;const o=Number(i[0]),s=Number(i[1]);if(!Number.isFinite(o)||!Number.isFinite(s))continue;const a=t[t.length-1];a&&a[0]===o&&a[1]===s||t.push([o,s])}if(t.length<3)return[];const n=t[0],r=t[t.length-1];return(n[0]!==r[0]||n[1]!==r[1])&&t.push([n[0],n[1]]),t.length>=4?t:[]}function ht(e){if(!Array.isArray(e)||e.length<4)return 0;let t=0;for(let n=0;n<e.length-1;n+=1){const r=e[n],i=e[n+1];t+=r[0]*i[1]-i[0]*r[1]}return t*.5}function jt(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const o of e){const s=Ne(o);s.length>=4&&t.push(s)}if(t.length===0)return[];if(t.length===1)return[t[0]];let n=0,r=0;for(let o=0;o<t.length;o+=1){const s=Math.abs(ht(t[o]));s<=r||(r=s,n=o)}const i=[t[n]];for(let o=0;o<t.length;o+=1)o!==n&&i.push(t[o]);return i}function Ur(e){if(!Array.isArray(e)||e.length===0)return[];const t=e[0];if(_t(t)){const i=jt([e]);return i.length>0?[i]:[]}if(!Array.isArray(t)||t.length===0)return[];const n=t[0];if(_t(n)){const i=jt(e);return i.length>0?[i]:[]}if(!Array.isArray(n)||n.length===0||!_t(n[0]))return[];const r=[];for(const i of e){const o=jt(i);o.length>0&&r.push(o)}return r}function Hn(e,t,n){let r=!1;for(let i=0,o=n.length-1;i<n.length;o=i,i+=1){const s=n[i][0],a=n[i][1],l=n[o][0],u=n[o][1];if(a===u||a>t==u>t)continue;e<(l-s)*(t-a)/(u-a)+s&&(r=!r)}return r}function yt(e){const t=[];for(const n of e??[]){const r=Ur(n);for(const i of r){const o=i[0];if(!o||o.length<4)continue;let s=1/0,a=1/0,l=-1/0,u=-1/0;for(const[c,h]of o)c<s&&(s=c),c>l&&(l=c),h<a&&(a=h),h>u&&(u=h);if(!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(l)||!Number.isFinite(u))continue;let f=Math.abs(ht(o));for(let c=1;c<i.length;c+=1)f-=Math.abs(ht(i[c]));t.push({outer:o,holes:i.slice(1),minX:s,minY:a,maxX:l,maxY:u,area:Math.max(1e-6,f)})}}return t}function Or(e,t,n){if(e<n.minX||e>n.maxX||t<n.minY||t>n.maxY||!Hn(e,t,n.outer))return!1;for(const r of n.holes)if(Hn(e,t,r))return!1;return!0}function Dt(e,t,n){for(const r of n)if(Or(e,t,r))return!0;return!1}const xn=[160,160,160,255];function W(e,t,n){return Math.max(t,Math.min(n,e))}function Sn(e,t,n){const r=Number(e),i=Number(t),o=Number(n);return!Number.isFinite(r)||r<=0?1:!Number.isFinite(i)||!Number.isFinite(o)?r:Math.pow(2,i-o)*r}function Qi(e,t,n){let i=100*Sn(e,t,n);if(Number(e)){let o="μm";return i>1e3&&(i/=1e3,o="mm"),`${i.toPrecision(3)} ${o}`}return`${Math.round(i*1e3)/1e3} pixels`}function be(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function et(e){const t=e.fillModes instanceof Uint8Array?e.fillModes.length:Number.MAX_SAFE_INTEGER;return Math.max(0,Math.min(Math.floor(e.count??0),Math.floor((e.positions?.length??0)/2),e.paletteIndices?.length??0,t))}function cn(e,t){return!e&&!t?!0:!e||!t?!1:Math.abs((e.zoom??0)-(t.zoom??0))<1e-6&&Math.abs((e.offsetX??0)-(t.offsetX??0))<1e-6&&Math.abs((e.offsetY??0)-(t.offsetY??0))<1e-6&&Math.abs((e.rotationDeg??0)-(t.rotationDeg??0))<1e-6}function Ji(e){const t=String(e??"").trim();if(!t)return"";if(/^bearer\s+/i.test(t)){const n=t.replace(/^bearer\s+/i,"").trim();return n?`Bearer ${n}`:""}return`Bearer ${t}`}function Yr(e){const n=String(e??"").trim().match(/^#?([0-9a-fA-F]{6})$/);if(!n)return[...xn];const r=Number.parseInt(n[1],16);return[r>>16&255,r>>8&255,r&255,255]}function eo(e){const t=[[...xn]],n=new Map;for(const i of e??[]){const o=String(i?.termId??"");!o||n.has(o)||(n.set(o,t.length),t.push(Yr(i?.termColor)))}const r=new Uint8Array(t.length*4);for(let i=0;i<t.length;i+=1)r[i*4]=t[i][0],r[i*4+1]=t[i][1],r[i*4+2]=t[i][2],r[i*4+3]=t[i][3];return{colors:r,termToPaletteIndex:n}}const to=[6,4,2],no=64,ro=.04,io=1,oo=4,zt=1e-6,so=.1;function ao(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const n of e){if(!Array.isArray(n)||n.length<2)continue;const r=Number(n[0]),i=Number(n[1]);if(!Number.isFinite(r)||!Number.isFinite(i))continue;const o=t[t.length-1];o&&Math.abs(o[0]-r)<1e-9&&Math.abs(o[1]-i)<1e-9||t.push([r,i])}return t}function Zn(e,t,n){if(t<=zt||n<8)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([e[0]+Math.cos(o)*t,e[1]+Math.sin(o)*t])}return Ne(r)}function lo(e,t,n,r){const i=t[0]-e[0],o=t[1]-e[1],s=Math.sqrt(i*i+o*o);if(!Number.isFinite(s)||s<=r)return[];const a=i/s,u=-(o/s),f=a,c=Math.max(zt,n);return Ne([[e[0]+u*c,e[1]+f*c],[t[0]+u*c,t[1]+f*c],[t[0]-u*c,t[1]-f*c],[e[0]-u*c,e[1]-f*c]])}function $n(e,t){if(!e.length)return[];let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,l]of e)a<n&&(n=a),a>i&&(i=a),l<r&&(r=l),l>o&&(o=l);if(!Number.isFinite(n)||!Number.isFinite(r))return[];const s=Math.max(t,1);return Ne([[n-s,r-s],[i+s,r-s],[i+s,o+s],[n-s,o+s]])}function xt(e,t){return Ne(t?e.map(([n,r])=>[W(n,t[0],t[2]),W(r,t[1],t[3])]):e)}function Kn(e,t){return Number.isFinite(e)?Number(e.toFixed(t)):e}function co(e,t){if(!Array.isArray(e)||e.length===0)return[];const n=[];for(const r of e){if(!Array.isArray(r)||r.length<2)continue;const i=Kn(Number(r[0]),t),o=Kn(Number(r[1]),t);if(!Number.isFinite(i)||!Number.isFinite(o))continue;const s=n[n.length-1];(!s||s[0]!==i||s[1]!==o)&&n.push([i,o])}if(n.length>=2){const r=n[0],i=n[n.length-1];if(!r||!i)return[];(r[0]!==i[0]||r[1]!==i[1])&&n.push([r[0],r[1]])}return n.length>=4?n:[]}function uo(e,t){if(!Array.isArray(e)||e.length===0)return[];const n=e.map(r=>co(r,t)).filter(r=>r.length>=4);return n.length>0?n:[]}function fo(e,t){const n=e.map(i=>uo(i,t)).filter(i=>i.length>0);if(n.length===0)return null;let r=[n[0]];try{for(let i=1;i<n.length;i+=1)if(r=Ki.union(r,[n[i]]),!Array.isArray(r)||r.length===0)return null}catch(i){return console.error("buildBrushStrokePolygon union failed",t,i),null}return r.length>0?r:null}function ho(e){if(e.length===0)return null;for(const t of to){const n=fo(e,t);if(n)return n}return null}function mo(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const n of e){if(!Array.isArray(n)||n.length<2)continue;const r=Number(n[0]),i=Number(n[1]);!Number.isFinite(r)||!Number.isFinite(i)||t.push([r,i])}return Ne(t)}function go(e){let t=[],n=0;for(const r of e){if(!Array.isArray(r)||r.length===0)continue;const i=mo(r[0]??[]);if(i.length<4)continue;const o=Math.abs(ht(i));o<=n||(n=o,t=i)}return t}function po(e,t=1e-9){const n=Ne(e);if(n.length<5)return n;const r=[n[0]];for(let i=1;i<n.length-1;i+=1){const o=r[r.length-1],s=n[i],a=n[i+1],l=(s[0]-o[0])*(a[1]-s[1])-(s[1]-o[1])*(a[0]-s[0]);Math.abs(l)<=t||r.push(s)}return r.push(r[0]),Ne(r)}function yo(e,t,n){const r=n[0]-t[0],i=n[1]-t[1],o=r*r+i*i;if(o<=1e-12){const c=e[0]-t[0],h=e[1]-t[1];return c*c+h*h}const s=W(((e[0]-t[0])*r+(e[1]-t[1])*i)/o,0,1),a=t[0]+r*s,l=t[1]+i*s,u=e[0]-a,f=e[1]-l;return u*u+f*f}function bo(e,t){if(e.length<=2||t<=0)return e.slice();const n=new Uint8Array(e.length);n[0]=1,n[e.length-1]=1;const r=t*t,i=[[0,e.length-1]];for(;i.length>0;){const s=i.pop();if(!s)break;const[a,l]=s;if(l-a<=1)continue;let u=0,f=-1;for(let c=a+1;c<l;c+=1){const h=yo(e[c],e[a],e[l]);h>u&&(u=h,f=c)}f>=0&&u>r&&(n[f]=1,i.push([a,f],[f,l]))}const o=[];for(let s=0;s<e.length;s+=1)n[s]&&o.push(e[s]);return o}function wo(e,t){const n=Ne(e);if(n.length<5||t<=0)return n;const r=n.slice(0,-1),i=bo(r,t);return i.length<3?n:Ne(i)}function xo(e,t){let n=Ne(e);if(t<=0||n.length<5)return n;for(let r=0;r<t;r+=1){const i=n.slice(0,-1);if(i.length<3)break;const o=[];for(let s=0;s<i.length;s+=1){const a=i[s],l=i[(s+1)%i.length];o.push([a[0]*.75+l[0]*.25,a[1]*.75+l[1]*.25],[a[0]*.25+l[0]*.75,a[1]*.25+l[1]*.75])}n=Ne(o)}return n}function So(e,t){const n=ao(e),r=Math.max(zt,Number(t.radius)||0);if(n.length===0||!Number.isFinite(r))return[];const i=Math.max(12,Math.floor(t.circleSides||no));if(n.length===1)return xt(Zn(n[0],r,i),t.clipBounds);const o=[],s=Math.max(zt,r*so);for(let h=0;h<n.length;h+=1){const d=n[h],m=Zn(d,r,i);if(m.length>=4&&o.push([m]),h===0)continue;const p=lo(n[h-1],d,r,s);p.length>=4&&o.push([p])}const a=ho(o),l=a?go(a):[];if(!l.length)return xt($n(n,r),t.clipBounds);const u=typeof t.simplifyTolerance=="number"&&Number.isFinite(t.simplifyTolerance)?Math.max(0,t.simplifyTolerance):Math.max(.25,r*ro),f=typeof t.smoothingPasses=="number"&&Number.isFinite(t.smoothingPasses)?Math.round(W(t.smoothingPasses,0,oo)):io,c=wo(xo(po(l,1e-9),f),u);return c.length<4?xt($n(n,r),t.clipBounds):xt(c,t.clipBounds)}const Je=[],jn=[],Xe={color:"#ff4d4f",width:2,lineDash:Je,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},Wr={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},Xr="rgba(23, 23, 25, 0.1)",Vr=6,Ue={fontFamily:"Pretendard, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:11,fontWeight:600,textColor:"#171719",backgroundColor:"#FFCC00",borderColor:"rgba(0, 0, 0, 0)",borderWidth:0,paddingX:8,paddingY:4,offsetY:10,borderRadius:4},Ze={fontFamily:"Pretendard, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:13,fontWeight:500,textColor:"#FFFFFF",backgroundColor:"rgba(23, 23, 25, 0.5)",borderRadius:4,paddingX:6,paddingY:3},Qn={x:16,y:-24},Eo=20,Jn=1e-6,er="transparent",Ro=3,Mo=2,Gr=96,Ao=1,tr=1e3,qr=2,Hr=2,vo=4096,Co=.2,Io=1.12,Po=.89,To=32,_o="#000000",Fo=.1,Lo="#FFCF00",ko="#FF0000",No=1.5,nr=[2,2],Bo=1,Do=.25,zo=4,Uo=1,Oo=0,Yo=4,Wo=1.5;function Ut(e,t,n){return[W(e[0],0,t),W(e[1],0,n)]}function En(e){if(!Array.isArray(e)||e.length<2)return null;const t=Number(e[0]),n=Number(e[1]);return!Number.isFinite(t)||!Number.isFinite(n)?null:[t,n]}const Oe=En;function Fe(e){return Ne(e)}function Ft(e){return Math.abs(ht(Fe(e)))}function rr(e){if(!Array.isArray(e)||e.length===0)return[0,0,0,0];let t=1/0,n=1/0,r=-1/0,i=-1/0;for(const[o,s]of e)o<t&&(t=o),o>r&&(r=o),s<n&&(n=s),s>i&&(i=s);return[t,n,r,i]}function un(e,t,n=!1){if(t.length!==0){e.moveTo(t[0][0],t[0][1]);for(let r=1;r<t.length;r+=1)e.lineTo(t[r][0],t[r][1]);n&&e.closePath()}}function Pe(e,t,n,r=!1,i=!1,o="rgba(255, 77, 79, 0.16)"){t.length!==0&&(e.beginPath(),un(e,t,r),i&&r&&(e.fillStyle=o,e.fill()),e.strokeStyle=n.color,e.lineWidth=n.width,e.lineJoin=n.lineJoin,e.lineCap=n.lineCap,e.shadowColor=n.shadowColor,e.shadowBlur=n.shadowBlur,e.shadowOffsetX=n.shadowOffsetX,e.shadowOffsetY=n.shadowOffsetY,e.setLineDash(n.lineDash),e.stroke(),e.setLineDash(Je),e.shadowColor="rgba(0, 0, 0, 0)",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0)}function Rn(e){const t=Array.isArray(e?.lineDash)?e.lineDash.filter(s=>Number.isFinite(s)&&s>=0):Je,n=typeof e?.width=="number"&&Number.isFinite(e.width)?Math.max(0,e.width):Xe.width,r=typeof e?.shadowBlur=="number"&&Number.isFinite(e.shadowBlur)?Math.max(0,e.shadowBlur):Xe.shadowBlur,i=typeof e?.shadowOffsetX=="number"&&Number.isFinite(e.shadowOffsetX)?e.shadowOffsetX:Xe.shadowOffsetX,o=typeof e?.shadowOffsetY=="number"&&Number.isFinite(e.shadowOffsetY)?e.shadowOffsetY:Xe.shadowOffsetY;return{color:e?.color||Xe.color,width:n,lineDash:t.length?t:Je,lineJoin:e?.lineJoin||Xe.lineJoin,lineCap:e?.lineCap||Xe.lineCap,shadowColor:e?.shadowColor||Xe.shadowColor,shadowBlur:r,shadowOffsetX:i,shadowOffsetY:o}}function Ve(e,t){return t?Rn({color:t.color??e.color,width:t.width??e.width,lineDash:t.lineDash??e.lineDash,lineJoin:t.lineJoin??e.lineJoin,lineCap:t.lineCap??e.lineCap,shadowColor:t.shadowColor??e.shadowColor,shadowBlur:t.shadowBlur??e.shadowBlur,shadowOffsetX:t.shadowOffsetX??e.shadowOffsetX,shadowOffsetY:t.shadowOffsetY??e.shadowOffsetY}):e}function Ot(e,t){return e==null||t===null||t===void 0?!1:String(e)===String(t)}function ir(e){return typeof e=="number"&&Number.isFinite(e)}function Xo(e){return Array.isArray(e)&&e.length>=2&&ir(e[0])&&ir(e[1])}function Vo(e){return Array.isArray(e)&&e.length>=2&&e.every(t=>Xo(t))}function Zr(e,t){if(!(!Array.isArray(e)||e.length===0)){if(Vo(e)){t.push(e.map(([n,r])=>[n,r]));return}for(const n of e)Zr(n,t)}}function or(e,t){const n=[];Zr(e,n);const r=[];for(const i of n){if(i.length<2)continue;const o=t?Fe(i):i;o.length>=(t?4:2)&&r.push(o)}return r}function ut(e,t){return typeof e!="number"||!Number.isFinite(e)||e<=0?t:e}function Go(e,t){return typeof e!="number"||!Number.isFinite(e)?t:W(e,0,1)}function $r(e,t,n,r,i,o){const s=Math.max(0,Math.min(o,r*.5,i*.5));e.beginPath(),e.moveTo(t+s,n),e.lineTo(t+r-s,n),e.quadraticCurveTo(t+r,n,t+r,n+s),e.lineTo(t+r,n+i-s),e.quadraticCurveTo(t+r,n+i,t+r-s,n+i),e.lineTo(t+s,n+i),e.quadraticCurveTo(t,n+i,t,n+i-s),e.lineTo(t,n+s),e.quadraticCurveTo(t,n,t+s,n),e.closePath()}function qo(e){const t=e[0];return Array.isArray(t)&&Array.isArray(t[0])}function Yt(e,t,n){if(!e||!t)return[];if(n){const r=n.worldToScreen(e[0],e[1]),i=n.worldToScreen(t[0],t[1]);if(r&&i){const o=[[r[0],r[1]],[i[0],r[1]],[i[0],i[1]],[r[0],i[1]]],s=[];for(const a of o){const l=n.screenToWorld(a);if(!l)return Yt(e,t);s.push(l)}return Fe(s)}}return Fe([[e[0],e[1]],[t[0],e[1]],[t[0],t[1]],[e[0],t[1]]])}function fn(e,t,n=Gr){if(!e||!t)return[];const r=(e[0]+t[0])*.5,i=(e[1]+t[1])*.5,o=Math.hypot(t[0]-e[0],t[1]-e[1])*.5;if(o<1)return[];const s=[];for(let a=0;a<=n;a+=1){const l=a/n*Math.PI*2;s.push([r+Math.cos(l)*o,i+Math.sin(l)*o])}return Fe(s)}function Wt(e){const t=Ur(pt(e));if(t.length===0)return[];const n=[];for(const r of t){const i=r[0];if(!i||i.length<4)continue;const o=i.map(([a,l])=>[a,l]),s=[];for(let a=1;a<r.length;a+=1){const l=r[a];!l||l.length<4||s.push(l.map(([u,f])=>[u,f]))}n.push({outer:o,holes:s})}return n}function Ho(e){if(!Array.isArray(e))return nr;const t=e.filter(n=>Number.isFinite(n)&&n>=0);return t.length>0?t:nr}function Zo(e){return typeof e!="number"||!Number.isFinite(e)?Bo:W(e,Do,zo)}function $o(e){return typeof e!="number"||!Number.isFinite(e)?Uo:Math.round(W(e,Oo,Yo))}function Ko(e){const t=ut(e?.radius,To),n=ut(e?.cursorLineWidth,No),r=Zo(e?.edgeDetail),i=$o(e?.edgeSmoothing);return{radius:t,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:e?.clickSelectRoi===!0,fillColor:e?.fillColor||_o,fillOpacity:Go(e?.fillOpacity,Fo),cursorColor:e?.cursorColor||Lo,cursorActiveColor:e?.cursorActiveColor||ko,cursorLineWidth:n,cursorLineDash:Ho(e?.cursorLineDash)}}function jo(e,t,n){if(!t.isDrawing||t.screenPoints.length===0)return;const r=t.screenPoints;if(r.length===0)return;const i=n.radius;if(!(!Number.isFinite(i)||i<=0)){if(e.save(),e.globalAlpha=n.fillOpacity,e.fillStyle=n.fillColor,e.strokeStyle=n.fillColor,e.lineCap="round",e.lineJoin="round",e.lineWidth=i*2,r.length===1)e.beginPath(),e.arc(r[0][0],r[0][1],i,0,Math.PI*2),e.fill();else{e.beginPath(),e.moveTo(r[0][0],r[0][1]);for(let o=1;o<r.length;o+=1)e.lineTo(r[o][0],r[o][1]);e.stroke()}e.restore()}}function Qo(e,t,n,r){const i=t.cursor;if(!i)return;const o=t.cursorScreen??Oe(n?.worldToScreen(i[0],i[1])??[]);if(!o)return;const s=r.radius;!Number.isFinite(s)||s<=0||(e.save(),e.beginPath(),e.arc(o[0],o[1],s,0,Math.PI*2),e.strokeStyle=t.isDrawing?r.cursorActiveColor:r.cursorColor,e.lineWidth=r.cursorLineWidth,e.setLineDash(r.cursorLineDash),e.stroke(),e.setLineDash(Je),e.restore())}const Jo=.58,es=4096,ts=.5;let St=null;const Et=new Map;function ns(){if(St)return St;if(typeof document>"u")return null;const t=document.createElement("canvas").getContext("2d");return t?(St=t,St):null}function Mn(e,t){const n=`${t.fontWeight}|${t.fontSize}|${t.fontFamily}|${e}`,r=Et.get(n);if(r!==void 0)return r;const i=e.length*t.fontSize*Jo,o=ns();let s=i;if(o){o.font=`${t.fontWeight} ${t.fontSize}px ${t.fontFamily}`;const a=o.measureText(e).width;Number.isFinite(a)&&a>=0&&(s=a)}return Et.size>es&&Et.clear(),Et.set(n,s),s}function rs(e,t="top-center"){if(!e.length)return null;let n=1/0;for(const o of e)o[1]<n&&(n=o[1]);if(!Number.isFinite(n))return null;let r=1/0,i=-1/0;for(const o of e)Math.abs(o[1]-n)>ts||(o[0]<r&&(r=o[0]),o[0]>i&&(i=o[0]));return!Number.isFinite(r)||!Number.isFinite(i)?null:t==="top-center"?[(r+i)*.5,n]:[r,n]}function An(e,t="top-center"){let n=null;for(const r of e){const i=rs(r.outer,t);i&&(!n||i[1]<n[1]||i[1]===n[1]&&i[0]<n[0])&&(n=i)}return n}function vn(e){const t=typeof e?.paddingX=="number"&&Number.isFinite(e.paddingX)?Math.max(0,e.paddingX):Ue.paddingX,n=typeof e?.paddingY=="number"&&Number.isFinite(e.paddingY)?Math.max(0,e.paddingY):Ue.paddingY,r=typeof e?.fontSize=="number"&&Number.isFinite(e.fontSize)?Math.max(8,e.fontSize):Ue.fontSize,i=typeof e?.borderWidth=="number"&&Number.isFinite(e.borderWidth)?Math.max(0,e.borderWidth):Ue.borderWidth,o=typeof e?.offsetY=="number"&&Number.isFinite(e.offsetY)?e.offsetY:Ue.offsetY,s=typeof e?.borderRadius=="number"&&Number.isFinite(e.borderRadius)?Math.max(0,e.borderRadius):Ue.borderRadius;return{fontFamily:e?.fontFamily||Ue.fontFamily,fontSize:r,fontWeight:e?.fontWeight||Ue.fontWeight,textColor:e?.textColor||Ue.textColor,backgroundColor:e?.backgroundColor||Ue.backgroundColor,borderColor:e?.borderColor||Ue.borderColor,borderWidth:i,paddingX:t,paddingY:n,offsetY:o,borderRadius:s}}function Cn(e,t){return t?vn({fontFamily:t.fontFamily??e.fontFamily,fontSize:t.fontSize??e.fontSize,fontWeight:t.fontWeight??e.fontWeight,textColor:t.textColor??e.textColor,backgroundColor:t.backgroundColor??e.backgroundColor,borderColor:t.borderColor??e.borderColor,borderWidth:t.borderWidth??e.borderWidth,paddingX:t.paddingX??e.paddingX,paddingY:t.paddingY??e.paddingY,offsetY:t.offsetY??e.offsetY,borderRadius:t.borderRadius??e.borderRadius}):e}function In(e,t,n){if(!e||!n)return 0;const r=Number(n.minZoom),i=Number(n.maxZoom);return!Number.isFinite(r)||!Number.isFinite(i)||i-r<=Jn||!Number.isFinite(t)?0:t>=i-Jn?Eo:0}function is(e){const t=typeof e?.fontSize=="number"&&Number.isFinite(e.fontSize)?Math.max(8,e.fontSize):Ze.fontSize,n=typeof e?.borderRadius=="number"&&Number.isFinite(e.borderRadius)?Math.max(0,e.borderRadius):Ze.borderRadius,r=typeof e?.paddingX=="number"&&Number.isFinite(e.paddingX)?Math.max(0,e.paddingX):Ze.paddingX,i=typeof e?.paddingY=="number"&&Number.isFinite(e.paddingY)?Math.max(0,e.paddingY):Ze.paddingY;return{fontFamily:e?.fontFamily||Ze.fontFamily,fontSize:t,fontWeight:e?.fontWeight||Ze.fontWeight,textColor:e?.textColor||Ze.textColor,backgroundColor:e?.backgroundColor||Ze.backgroundColor,borderRadius:n,paddingX:r,paddingY:i}}function os(e){const t=typeof e?.x=="number"&&Number.isFinite(e.x)?e.x:Qn.x,n=typeof e?.y=="number"&&Number.isFinite(e.y)?e.y:Qn.y;return{x:t,y:n}}function ss(e){return Number.isFinite(e)?`${Math.max(0,e).toFixed(3)} mm²`:"0.000 mm²"}function as(e){const t=typeof e?.format=="function"?e.format:ss,n=os(e?.cursorOffset);return{enabled:e?.enabled===!0,format:t,style:is(e?.style),cursorOffsetX:n.x,cursorOffsetY:n.y}}function Kr(e,t,n,r,i,o,s=!0){const a=t.trim();if(!a)return;e.save(),e.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,e.textAlign="center",e.textBaseline="middle";const u=Mn(a,o)+o.paddingX*2,f=o.fontSize+o.paddingY*2,c=n[0],h=n[1]-o.offsetY,d=s?W(c,u*.5+1,r-u*.5-1):c,m=s?W(h,f*.5+1,i-f*.5-1):h,p=d-u*.5,y=m-f*.5;e.fillStyle=o.backgroundColor,e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,$r(e,p,y,u,f,o.borderRadius),e.fill(),o.borderWidth>0&&e.stroke(),e.fillStyle=o.textColor,e.fillText(a,d,m+.5),e.restore()}function ls(e,t,n,r,i,o,s,a){const l=t.trim();if(!l)return;e.save(),e.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,e.textAlign="center",e.textBaseline="middle";const f=Mn(l,o)+o.paddingX*2,c=o.fontSize+o.paddingY*2,h=W(n[0]+s,f*.5+1,r-f*.5-1),d=W(n[1]+a,c*.5+1,i-c*.5-1),m=h-f*.5,p=d-c*.5;e.fillStyle=o.backgroundColor,$r(e,m,p,f,c,o.borderRadius),e.fill(),e.fillStyle=o.textColor,e.fillText(l,h,d+.5),e.restore()}function cs(e,t,n,r){if(!(t.length<4||n.length===0)){e.save(),e.beginPath(),un(e,t,!0);for(const i of n)i.length<4||un(e,i,!0);e.fillStyle=r,e.fill("evenodd"),e.restore()}}function jr(e){const{ctx:t,overlayShapes:n,imageOuterRing:r,worldToScreenPoints:i,baseStrokeStyle:o,onInvertedFillDebug:s}=e,a=!!globalThis.__OPEN_PLANT_DEBUG_OVERLAY__;for(let l=0;l<n.length;l+=1){const u=n[l];if(!u?.coordinates?.length||u.visible===!1)continue;const f=u.closed??qo(u.coordinates),c=or(u.coordinates,f);if(u.invertedFill?.fillColor){const d=[],m=or(u.coordinates,!0);for(const p of m){const y=i(p);y.length>=4&&d.push(y)}a&&s&&s({id:u.id??l,outerRingPoints:r.length,sourceRingCount:m.length,holeRingCount:d.length,fillColor:u.invertedFill.fillColor}),cs(t,r,d,u.invertedFill.fillColor)}if(c.length===0)continue;const h=Ve(o,u.stroke??u.strokeStyle);for(const d of c){const m=i(d);m.length<2||Pe(t,m,h,f,u.fill??!1)}}}function Rt(e){return typeof e=="string"&&(e==="stamp-rectangle"||e==="stamp-circle"||e==="stamp-rectangle-4096px"||e==="stamp-rectangle-2mm2"||e==="stamp-circle-2mm2"||e==="stamp-circle-hpf-0.2mm2")}function us(e){return{rectangleAreaMm2:ut(e?.rectangleAreaMm2,qr),circleAreaMm2:ut(e?.circleAreaMm2,Hr),rectanglePixelSize:ut(e?.rectanglePixelSize,vo)}}const sr=1e3;function fs(e){return e*sr*sr}function ar(e,t,n){if(!e||!Number.isFinite(t)||t<=0)return[];if(n){const r=n.worldToScreen(e[0],e[1]),i=n.worldToScreen(e[0]+t,e[1]);if(r&&i){const o=Math.hypot(i[0]-r[0],i[1]-r[1]),s=[[r[0]-o,r[1]-o],[r[0]+o,r[1]-o],[r[0]+o,r[1]+o],[r[0]-o,r[1]+o]],a=[];for(const l of s){const u=n.screenToWorld(l);if(!u)throw new Error("Failed to create rectangle");a.push(u)}return Fe(a)}}return Fe([[e[0]-t,e[1]-t],[e[0]+t,e[1]-t],[e[0]+t,e[1]+t],[e[0]-t,e[1]+t]])}function hs(e,t,n=Gr){if(!e||!Number.isFinite(t)||t<=0)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([e[0]+Math.cos(o)*t,e[1]+Math.sin(o)*t])}return Fe(r)}function ds(e){const{stampTool:t,center:n,resolvedStampOptions:r,imageWidth:i,imageHeight:o,micronsToWorldPixels:s,getRectangleProjection:a}=e;if(!n)return[];if(t==="stamp-rectangle-4096px"){const c=r.rectanglePixelSize*.5;return ar(n,c,a()).map(h=>Ut(h,i,o))}let l=0;if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"?l=t==="stamp-rectangle-2mm2"?qr:r.rectangleAreaMm2:(t==="stamp-circle"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2")&&(l=t==="stamp-circle-hpf-0.2mm2"?Co:t==="stamp-circle-2mm2"?Hr:r.circleAreaMm2),!Number.isFinite(l)||l<=0)return[];const u=fs(l);let f=[];if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"){const c=s(Math.sqrt(u)*.5);f=ar(n,c,a())}else if(t==="stamp-circle"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2"){const c=s(Math.sqrt(u/Math.PI));f=hs(n,c)}return f.length?f.map(c=>Ut(c,i,o)):[]}function ms(e){return{color:Xr,width:Vr,lineDash:Je,lineJoin:e.lineJoin,lineCap:e.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function gs(e){if(typeof e!="string")return er;const t=e.trim();return t.length>0?t:er}function lr(e){return Array.isArray(e)&&e.length>=4&&Ft(e)>Ao}function Qr({tool:e,imageWidth:t,imageHeight:n,imageMpp:r,imageZoom:i,stampOptions:o,brushOptions:s,projectorRef:a,onBrushTap:l,onDrawComplete:u,onPatchComplete:f,enabled:c,viewStateSignal:h,persistedRegions:d,patchRegions:m,persistedPolygons:p,drawFillColor:y,regionStrokeStyle:b,regionStrokeHoverStyle:x,regionStrokeActiveStyle:C,patchStrokeStyle:S,resolveRegionStrokeStyle:A,resolveRegionLabelStyle:T,overlayShapes:O,hoveredRegionId:D=null,activeRegionId:G=null,regionLabelStyle:z,drawAreaTooltip:q,autoLiftRegionLabelAtMaxZoom:re=!1,regionLabelAnchor:I="top-center",clampRegionLabelToViewport:H=!0,regionLabelAutoLiftOffsetPx:N,invalidateRef:k,className:Z,style:we}){const se=g.useRef(null),Re=g.useRef(!1),Ce=g.useRef(new Map),xe=g.useRef(e),M=g.useRef({isDrawing:!1,pointerId:null,start:null,current:null,cursor:null,cursorScreen:null,points:[],screenPoints:[],stampCenter:null}),v=c??e!=="cursor",X=g.useMemo(()=>d&&d.length>0?d:!p||p.length===0?jn:p.map((w,E)=>({id:E,coordinates:w})),[d,p]),le=g.useMemo(()=>m??jn,[m]),Q=g.useMemo(()=>{const w=[];for(let E=0;E<X.length;E+=1){const P=X[E],F=Wt(P.coordinates);F.length!==0&&w.push({region:P,regionIndex:E,regionKey:P.id??E,polygons:F})}return w},[X]),ie=g.useMemo(()=>{const w=[];for(let E=0;E<le.length;E+=1){const P=le[E],F=Wt(P.coordinates);F.length!==0&&w.push({region:P,regionIndex:E,regionKey:P.id??E,polygons:F})}return w},[le]),he=g.useMemo(()=>Rn(b),[b]),me=g.useMemo(()=>Ve(he,x),[he,x]),$=g.useMemo(()=>Ve(he,C),[he,C]),pe=g.useMemo(()=>Ve(Wr,S),[S]),ye=g.useMemo(()=>gs(y),[y]),U=g.useMemo(()=>vn(z),[z]),V=g.useMemo(()=>as(q),[q]),ee=g.useMemo(()=>us(o),[o]),B=g.useMemo(()=>Ko(s),[s]),te=g.useMemo(()=>({position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",touchAction:"none",pointerEvents:v?"auto":"none",cursor:v?e==="brush"?"none":"crosshair":"default",...we}),[v,e,we]),de=g.useCallback(()=>{const w=se.current;if(!w)return;const E=w.getBoundingClientRect(),P=Math.max(1,window.devicePixelRatio||1),F=Math.max(1,Math.round(E.width*P)),j=Math.max(1,Math.round(E.height*P));(w.width!==F||w.height!==j)&&(w.width=F,w.height=j)},[]),ae=g.useCallback(w=>{const E=a.current;if(!E||w.length===0)return[];const P=new Array(w.length);for(let F=0;F<w.length;F+=1){const j=Oe(E.worldToScreen(w[F][0],w[F][1]));if(!j)return[];P[F]=j}return P},[a]),Me=g.useCallback(w=>{const E=a.current,P=se.current;if(!E||!P)return null;const F=P.getBoundingClientRect(),j=Oe(E.screenToWorld(F.left+w[0],F.top+w[1]));return j?Ut(j,t,n):null},[a,t,n]),Se=g.useCallback(()=>{const w=a.current,E=w?.getViewState?.().rotationDeg??0;if(!(Math.abs(E%360)<.01||!w))return{worldToScreen:(P,F)=>Oe(w.worldToScreen(P,F)),screenToWorld:Me}},[a,Me]),_=g.useCallback(w=>{if(!Number.isFinite(w)||w<=0)return 0;const E=typeof r=="number"&&Number.isFinite(r)&&r>0?r:1,P=typeof i=="number"&&Number.isFinite(i)?i:0,F=a.current?.getViewState?.().zoom,j=typeof F=="number"&&Number.isFinite(F)&&F>0?F:1,Ae=P+Math.log2(j),fe=Math.max(1e-9,Sn(E,P,Ae));return w/fe/j},[r,i,a]),Y=g.useCallback((w,E)=>ds({stampTool:w,center:E,resolvedStampOptions:ee,imageWidth:t,imageHeight:n,micronsToWorldPixels:_,getRectangleProjection:Se}),[_,t,n,ee,Se]),J=g.useCallback(()=>{const w=M.current;return Rt(e)?Y(e,w.stampCenter):e==="brush"?[]:w.isDrawing?e==="freehand"?w.points:e==="rectangle"?Yt(w.start,w.current,Se()):e==="circular"?fn(w.start,w.current):[]:[]},[e,Y,Se]),oe=g.useCallback(()=>{de();const w=se.current;if(!w)return;const E=w.getContext("2d");if(!E)return;const P=Math.max(1,window.devicePixelRatio||1),F=w.width/P,j=w.height/P;if(E.setTransform(1,0,0,1,0,0),E.clearRect(0,0,w.width,w.height),E.setTransform(P,0,0,P,0,0),Q.length>0)for(const fe of Q){const{region:ge,polygons:Ee,regionIndex:ve,regionKey:Le}=fe,ze=Ot(G,Le)?"active":Ot(D,Le)?"hover":"default";let He=ze==="active"?$:ze==="hover"?me:he;if(A){const wt=A({region:ge,regionId:Le,regionIndex:ve,state:ze});He=Ve(He,wt||void 0)}const bt=ze==="default"?null:ms(He);for(const wt of Ee){const qt=ae(wt.outer);qt.length>=4&&(bt&&Pe(E,qt,bt,!0,!1),Pe(E,qt,He,!0,!1));for(const yi of wt.holes){const Ht=ae(yi);Ht.length>=4&&(bt&&Pe(E,Ht,bt,!0,!1),Pe(E,Ht,He,!0,!1))}}}if(ie.length>0)for(const fe of ie)for(const ge of fe.polygons){const Ee=ae(ge.outer);Ee.length>=4&&Pe(E,Ee,pe,!0,!1);for(const ve of ge.holes){const Le=ae(ve);Le.length>=4&&Pe(E,Le,pe,!0,!1)}}if(Array.isArray(O)&&O.length>0){const fe=ae(Fe([[0,0],[t,0],[t,n],[0,n]]));jr({ctx:E,overlayShapes:O,imageOuterRing:fe,worldToScreenPoints:ae,baseStrokeStyle:he,onInvertedFillDebug:globalThis.__OPEN_PLANT_DEBUG_OVERLAY__?ge=>{const Ee=String(ge.id),ve=`${ge.outerRingPoints}|${ge.sourceRingCount}|${ge.holeRingCount}|${ge.fillColor}`;Ce.current.get(Ee)!==ve&&(Ce.current.set(Ee,ve),console.debug("[open-plant] invertedFill",ge))}:void 0})}const Ae=J();if(v){if(e==="brush")jo(E,M.current,B),Qo(E,M.current,a.current,B);else if(Ae.length>0)if(e==="freehand"){const fe=ae(Ae);fe.length>=2&&Pe(E,fe,he,!1,!1),fe.length>=3&&Pe(E,ae(Fe(Ae)),he,!0,!0,ye)}else{const fe=ae(Ae);fe.length>=4&&Pe(E,fe,he,!0,!0,ye)}}if(Q.length>0){const fe=Math.max(1e-6,a.current?.getViewState?.().zoom??1),ge=typeof N=="number"&&Number.isFinite(N)?Math.max(0,N):In(re,fe,a.current?.getZoomRange?.());for(const Ee of Q){if(!Ee.region.label)continue;const ve=An(Ee.polygons,I);if(!ve)continue;const Le=Oe(a.current?.worldToScreen(ve[0],ve[1])??[]);if(!Le)continue;let ze=Cn(U,T?.({region:Ee.region,regionId:Ee.regionKey,regionIndex:Ee.regionIndex,zoom:fe}));ge>0&&(ze={...ze,offsetY:ze.offsetY+ge}),Kr(E,Ee.region.label,Le,F,j,ze,H)}}if(V.enabled&&v&&(e==="freehand"||e==="rectangle"||e==="circular")){const fe=M.current;if(fe.isDrawing){const ge=e==="freehand"?Fe(Ae):Ae;if(ge.length>=4){const Ee=Ft(ge),ve=typeof r=="number"&&Number.isFinite(r)&&r>0?r:0,Le=ve>0?Ee*ve*ve/(tr*tr):0,ze=V.format(Le),He=fe.cursorScreen??(fe.current?Oe(a.current?.worldToScreen(fe.current[0],fe.current[1])??[]):null);He&&ls(E,ze,He,F,j,V.style,V.cursorOffsetX,V.cursorOffsetY)}}}},[v,e,J,de,ae,t,n,a,Q,O,D,G,he,me,$,ye,ie,pe,A,T,U,V,re,I,H,N,r,B]),L=g.useCallback(()=>{Re.current||(Re.current=!0,requestAnimationFrame(()=>{Re.current=!1,oe()}))},[oe]),K=g.useCallback((w=!1)=>{const E=M.current,P=se.current;P&&E.pointerId!==null&&P.hasPointerCapture(E.pointerId)&&P.releasePointerCapture(E.pointerId),E.isDrawing=!1,E.pointerId=null,E.start=null,E.current=null,E.points=[],E.screenPoints=[],E.stampCenter=null,w||(E.cursor=null,E.cursorScreen=null)},[]),ce=g.useCallback(w=>{const E=a.current;if(!E||t<=0||n<=0)return null;const P=Oe(E.screenToWorld(w.clientX,w.clientY));return P?Ut(P,t,n):null},[a,t,n]),ne=g.useCallback(w=>{const E=se.current;if(!E)return null;const P=E.getBoundingClientRect(),F=W(w.clientX-P.left,0,P.width),j=W(w.clientY-P.top,0,P.height);return!Number.isFinite(F)||!Number.isFinite(j)?null:[F,j]},[]),ue=g.useCallback(()=>{const w=M.current;if(!w.isDrawing){K(!0),L();return}let E=[];if(e==="freehand")w.points.length>=Ro&&(E=Fe(w.points));else if(e==="rectangle")E=Yt(w.start,w.current,Se());else if(e==="circular")E=fn(w.start,w.current);else if(e==="brush"){const P=w.points[w.points.length-1]??w.current??w.start;if(B.clickSelectRoi&&P&&w.points.length<=1&&l?.(P)){K(!0),L();return}const F=Math.max(.25,B.edgeDetail),j=w.screenPoints.length>0?w.screenPoints:ae(w.points),Ae=Math.max(.5,B.radius*.04/F),fe=So(j,{radius:B.radius,circleSides:Math.max(16,Math.round(32*F)),simplifyTolerance:Ae,smoothingPasses:B.edgeSmoothing}),ge=[];for(const Ee of fe){const ve=Me(Ee);ve&&ge.push(ve)}E=Fe(ge)}(e==="freehand"||e==="rectangle"||e==="circular"||e==="brush")&&lr(E)&&u&&u({tool:e,intent:e==="brush"?"brush":"roi",coordinates:E,bbox:rr(E),areaPx:Ft(E)}),K(!0),L()},[e,u,K,L,ae,Me,Se,B.radius,B.edgeDetail,B.edgeSmoothing,B.clickSelectRoi,l]),De=g.useCallback((w,E)=>{const P=Y(w,E);if(!lr(P))return;const F=w==="stamp-rectangle-4096px"?"patch":"roi",j={tool:w,intent:F,coordinates:P,bbox:rr(P),areaPx:Ft(P)};u?.(j),F==="patch"&&f&&f(j)},[Y,u,f]),qe=g.useCallback((w,E,P)=>{const F=Math.max(Wo,B.radius*.1),j=F*F,Ae=w.screenPoints[w.screenPoints.length-1];if(!Ae){w.points.push(E),w.screenPoints.push(P),w.current=E;return}const fe=P[0]-Ae[0],ge=P[1]-Ae[1];fe*fe+ge*ge>=j?(w.points.push(E),w.screenPoints.push(P)):(w.points[w.points.length-1]=E,w.screenPoints[w.screenPoints.length-1]=P),w.current=E},[B.radius]),Gt=g.useCallback(w=>{if(!v||e==="cursor"||w.button!==0)return;const E=ce(w);if(!E)return;const P=ne(w);if(!P)return;if(w.preventDefault(),w.stopPropagation(),Rt(e)){const Ae=M.current;Ae.stampCenter=E,De(e,E),L();return}const F=se.current;F&&F.setPointerCapture(w.pointerId);const j=M.current;j.isDrawing=!0,j.pointerId=w.pointerId,j.start=E,j.current=E,j.cursor=E,j.cursorScreen=P,j.points=e==="freehand"||e==="brush"?[E]:[],j.screenPoints=e==="brush"?[P]:[],L()},[v,e,ce,ne,De,L]),st=g.useCallback(w=>{if(!v||e==="cursor")return;const E=ce(w);if(!E)return;const P=ne(w);if(!P)return;const F=M.current;if(F.cursor=E,F.cursorScreen=P,Rt(e)){F.stampCenter=E,w.preventDefault(),w.stopPropagation(),L();return}if(e==="brush"){if(!F.isDrawing||F.pointerId!==w.pointerId){L();return}w.preventDefault(),w.stopPropagation(),qe(F,E,P),L();return}if(!(!F.isDrawing||F.pointerId!==w.pointerId)){if(w.preventDefault(),w.stopPropagation(),e==="freehand"){const j=a.current,Ae=Math.max(1e-6,j?.getViewState?.().zoom??1),fe=Mo/Ae,ge=fe*fe,Ee=F.points[F.points.length-1];if(!Ee)F.points.push(E);else{const ve=E[0]-Ee[0],Le=E[1]-Ee[1];ve*ve+Le*Le>=ge&&F.points.push(E)}}else F.current=E;L()}},[v,e,ce,ne,L,a,qe]),_n=g.useCallback(w=>{const E=M.current;if(!E.isDrawing||E.pointerId!==w.pointerId)return;w.preventDefault(),w.stopPropagation();const P=ce(w),F=ne(w);P&&(E.cursor=P,F&&(E.cursorScreen=F),e==="brush"?F&&qe(E,P,F):E.current=P);const j=se.current;j&&j.hasPointerCapture(w.pointerId)&&j.releasePointerCapture(w.pointerId),ue()},[ue,ce,ne,e,qe]),pi=g.useCallback(()=>{const w=M.current;let E=!1;e==="brush"&&!w.isDrawing&&w.cursor&&(w.cursor=null,w.cursorScreen=null,E=!0),Rt(e)&&w.stampCenter&&(w.stampCenter=null,E=!0),E&&L()},[e,L]);return g.useEffect(()=>{de(),L();const w=se.current;if(!w)return;const E=new ResizeObserver(()=>{de(),L()});return E.observe(w),()=>{E.disconnect()}},[de,L]),g.useEffect(()=>{v||K(),L()},[v,L,K]),g.useEffect(()=>{xe.current!==e&&(xe.current=e,K(),L())},[e,K,L]),g.useEffect(()=>{L()},[h,X,O,L]),g.useEffect(()=>{if(k)return k.current=L,()=>{k.current===L&&(k.current=null)}},[k,L]),g.useEffect(()=>{if(!v)return;const w=E=>{E.key==="Escape"&&(K(),L())};return window.addEventListener("keydown",w),()=>{window.removeEventListener("keydown",w)}},[v,K,L]),Ye.jsx("canvas",{ref:se,className:Z,style:te,onPointerDown:Gt,onPointerMove:st,onPointerUp:_n,onPointerCancel:_n,onPointerLeave:pi,onContextMenu:w=>{v&&w.preventDefault()},onWheel:w=>{if(!v)return;const E=se.current,P=a.current;if(!E||typeof P?.zoomBy!="function")return;w.preventDefault(),w.stopPropagation();const F=E.getBoundingClientRect(),j=w.clientX-F.left,Ae=w.clientY-F.top;P.zoomBy(w.deltaY<0?Io:Po,j,Ae),L()}})}const Jr=g.createContext(null),ps=Jr.Provider;function ot(){const e=g.useContext(Jr);if(!e)throw new Error("useViewerContext must be used within a <WsiViewer>");return e}function ys({tool:e="cursor",stampOptions:t,brushOptions:n,fillColor:r,areaTooltip:i,onComplete:o,onPatchComplete:s,onBrushTap:a}){const{source:l,rendererRef:u,rendererSerial:f,setInteractionLock:c}=ot(),h=e!=="cursor";g.useEffect(()=>(c("drawing-layer",h),()=>c("drawing-layer",!1)),[h,c]);const d=g.useMemo(()=>u.current?.getViewState(),[f]);return l?Ye.jsx(Qr,{tool:e,enabled:h,imageWidth:l.width,imageHeight:l.height,imageMpp:l.mpp,imageZoom:l.maxTierZoom,stampOptions:t,brushOptions:n,drawFillColor:r,projectorRef:u,onBrushTap:a,viewStateSignal:d,drawAreaTooltip:i,onDrawComplete:o,onPatchComplete:s}):null}const cr="__overlay_layer__";function bs({shapes:e}){const{rendererRef:t,source:n,registerDrawCallback:r,unregisterDrawCallback:i,requestOverlayRedraw:o}=ot(),s=g.useCallback(l=>{const u=t.current;if(!u||l.length===0)return[];const f=new Array(l.length);for(let c=0;c<l.length;c+=1){const h=Oe(u.worldToScreen(l[c][0],l[c][1]));if(!h)return[];f[c]=h}return f},[]),a=g.useRef({shapes:e,worldToScreenPoints:s,source:n});return a.current={shapes:e,worldToScreenPoints:s,source:n},g.useEffect(()=>(r(cr,30,u=>{const{shapes:f,worldToScreenPoints:c,source:h}=a.current;if(!Array.isArray(f)||f.length===0||!h)return;const d=c(Fe([[0,0],[h.width,0],[h.width,h.height],[0,h.height]]));jr({ctx:u,overlayShapes:f,imageOuterRing:d,worldToScreenPoints:c,baseStrokeStyle:Xe})}),()=>i(cr)),[r,i]),g.useEffect(()=>{o()},[e,o]),null}function ur(e){return String(e??"").replace(/\/+$/,"")}function ei(e){const t=String(e??"");return t.startsWith("/")?t:`/${t}`}function ws(e){const t=ur(e);if(!t)return"";if(/\/TileGroup\d+$/i.test(t))return t;let n=null;try{n=new URL(t)}catch{n=null}if(n){const r=`${n.protocol}//${n.host}`,i=ur(n.pathname||"");return/\/ims$/i.test(i)?`${r}${i}`:/\/tiles$/i.test(i)?`${r}${i}`:`${r}${i}/tiles`}return/\/ims$/i.test(t)?"/ims":/\/tiles$/i.test(t)?`${t}`:`${t}/tiles`}function xs(e,t){const n=e?.imsInfo??{},r=!!e?.imsInfo,i=Number(n.width??e?.width??0),o=Number(n.height??e?.height??0),s=Number(n.tileSize??e?.tileSize??0),a=Number(n.zoom??e?.zoom??0),l=String(n.path??e?.path??""),u=Number(n.mpp??e?.mpp??0);if(!i||!o||!s||!l)throw new Error("Incomplete image metadata: width/height/tileSize/path required");const f=Array.isArray(e?.terms)?e.terms.map(m=>({termId:String(m?.termId??""),termName:String(m?.termName??""),termColor:String(m?.termColor??"")})):[],c=ei(l),h=ws(t),d=e?.tileUrlBuilder??(r?(m,p,y)=>`${h}${c}/${m}/${y}_${p}.webp`:void 0);return{id:e?._id||e?.id||"unknown",name:e?.name||"unknown",width:i,height:o,mpp:Number.isFinite(u)&&u>0?u:void 0,tileSize:s,maxTierZoom:Number.isFinite(a)?Math.max(0,Math.floor(a)):0,tilePath:l,tileBaseUrl:t,terms:f,tileUrlBuilder:d}}function Pn(e,t,n,r){if(e.tileUrlBuilder)return e.tileUrlBuilder(t,n,r,e.tilePath,e.tileBaseUrl);const i=ei(e.tilePath);return`${e.tileBaseUrl}${i}/${t}/${r}_${n}.webp`}function Ss(e,t){if(!t)return!1;const n=new URL(e,typeof window<"u"?window.location.href:void 0).hostname.toLowerCase();return!(n.includes("amazonaws.com")||n.startsWith("s3.")||n.includes(".s3."))}const ke={width:200,height:125,margin:16,position:"bottom-right",borderRadius:6,borderWidth:0,backgroundColor:"rgba(4, 10, 18, 0.88)",borderColor:"rgba(230, 244, 255, 0.35)",viewportBorderColor:"rgba(255, 106, 61, 0.95)",viewportBorderStyle:"dash",viewportFillColor:"transparent",interactive:!0,showThumbnail:!0,maxThumbnailTiles:16};function fr(e,t,n,r){const i=t.length;if(!(i<3)){for(let o=0;o<i;o+=1){const s=t[o],a=t[(o+1)%i],l=Math.hypot(a[0]-s[0],a[1]-s[1]);if(l<1e-6)continue;const u=Math.max(1,Math.round((l+r)/(n+r))),f=u*n+(u-1)*r,c=l/Math.max(1e-6,f),h=n*c,d=r*c;e.beginPath(),e.moveTo(s[0],s[1]),e.lineTo(a[0],a[1]),e.setLineDash([h,d]),e.lineDashOffset=0,e.stroke()}e.setLineDash([]),e.lineDashOffset=0}}function hr(e,t,n=1e-4){return Math.abs(e[0]-t[0])<=n&&Math.abs(e[1]-t[1])<=n}function dr(e){const t=[];for(const n of e){const r=t[t.length-1];(!r||!hr(r,n))&&t.push(n)}return t.length>1&&hr(t[0],t[t.length-1])&&t.pop(),t}function mr(e,t,n){const r=t[0]-e[0];if(Math.abs(r)<1e-6)return[n,e[1]];const i=(n-e[0])/r;return[n,e[1]+(t[1]-e[1])*i]}function gr(e,t,n){const r=t[1]-e[1];if(Math.abs(r)<1e-6)return[e[0],n];const i=(n-e[1])/r;return[e[0]+(t[0]-e[0])*i,n]}function Es(e,t,n,r,i){let o=dr(e);if(o.length<3)return[];const s=[{inside:a=>a[0]>=t,intersect:(a,l)=>mr(a,l,t)},{inside:a=>a[0]<=r,intersect:(a,l)=>mr(a,l,r)},{inside:a=>a[1]>=n,intersect:(a,l)=>gr(a,l,n)},{inside:a=>a[1]<=i,intersect:(a,l)=>gr(a,l,i)}];for(const a of s){if(o.length===0)return[];const l=o;o=[];let u=l[l.length-1],f=a.inside(u);for(const c of l){const h=a.inside(c);h?(f||o.push(a.intersect(u,c)),o.push(c)):f&&o.push(a.intersect(u,c)),u=c,f=h}o=dr(o)}return o.length>=3?o:[]}function nt(e,t,n=1){return typeof e!="number"||!Number.isFinite(e)?t:Math.max(n,e)}function lt(e){return Array.isArray(e)&&e.length===4&&Number.isFinite(e[0])&&Number.isFinite(e[1])&&Number.isFinite(e[2])&&Number.isFinite(e[3])}const Rs={position:"absolute",top:4,right:4,zIndex:1,width:18,height:18,borderRadius:999,border:"1px solid rgba(255,255,255,0.4)",background:"rgba(16, 17, 19, 0.85)",color:"#fff",fontSize:12,lineHeight:1,cursor:"pointer",padding:0,display:"flex",alignItems:"center",justifyContent:"center"};function Ms({source:e,projectorRef:t,authToken:n="",options:r,invalidateRef:i,className:o,style:s}){const a=g.useRef(null),l=g.useRef(null),u=g.useRef(null),f=g.useRef({active:!1,pointerId:null}),c=g.useRef(null),h=g.useRef(!1),d=nt(r?.width,ke.width,64),m=nt(r?.height,ke.height,48),p=g.useMemo(()=>{const M=Math.max(1,e.width),v=Math.max(1,e.height),X=M/v,le=d/m;let Q,ie;return X>le?(Q=d,ie=d/X):(ie=m,Q=m*X),{x:(d-Q)/2,y:(m-ie)/2,w:Q,h:ie}},[e.width,e.height,d,m]),y=nt(r?.margin,ke.margin,0),b=nt(r?.borderRadius,ke.borderRadius,0),x=nt(r?.borderWidth,ke.borderWidth,0),C=Math.max(1,Math.round(nt(r?.maxThumbnailTiles,ke.maxThumbnailTiles,1))),S=r?.backgroundColor||ke.backgroundColor,A=r?.borderColor||ke.borderColor,T=r?.viewportBorderColor||ke.viewportBorderColor,O=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:ke.viewportBorderStyle,D=r?.viewportFillColor??ke.viewportFillColor,G=r?.interactive??ke.interactive,z=r?.showThumbnail??ke.showThumbnail,q=r?.position||ke.position,re=r?.onClose,I=r?.closeIcon,H=r?.closeButtonStyle,N=g.useMemo(()=>{const M={};return q==="top-left"||q==="bottom-left"?M.left=y:M.right=y,q==="top-left"||q==="top-right"?M.top=y:M.bottom=y,{position:"absolute",...M,width:d,height:m,borderRadius:b,overflow:"hidden",zIndex:4,pointerEvents:G?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[y,q,d,m,b,G,s]),k=g.useCallback(()=>{const M=a.current;if(!M)return;const v=M.getContext("2d");if(!v)return;const X=d,le=m,Q=Math.max(1,window.devicePixelRatio||1),ie=Math.max(1,Math.round(X*Q)),he=Math.max(1,Math.round(le*Q));(M.width!==ie||M.height!==he)&&(M.width=ie,M.height=he),v.setTransform(1,0,0,1,0,0),v.clearRect(0,0,M.width,M.height),v.setTransform(Q,0,0,Q,0,0),v.fillStyle=S,v.fillRect(0,0,X,le);const{x:me,y:$,w:pe,h:ye}=p,U=l.current;U&&v.drawImage(U,me,$,pe,ye),v.strokeStyle=A,v.lineWidth=x,v.strokeRect(x*.5,x*.5,X-x,le-x);const V=t.current,ee=V?.getViewBounds?.(),B=V?.getViewCorners?.(),te=Array.isArray(B)&&B.length>=4&&B.every(ce=>Array.isArray(ce)&&ce.length>=2&&Number.isFinite(ce[0])&&Number.isFinite(ce[1]))?B:null,de=lt(ee)?ee:lt(u.current)?u.current:null;lt(ee)&&(u.current=ee);const ae=pe/Math.max(1,e.width),Me=ye/Math.max(1,e.height),Se=O==="dash";if(te){const ce=te.map(ue=>[me+ue[0]*ae,$+ue[1]*Me]),ne=Es(ce,me,$,me+pe,$+ye);if(ne.length>=3){v.beginPath();for(let ue=0;ue<ne.length;ue+=1)ue===0?v.moveTo(ne[ue][0],ne[ue][1]):v.lineTo(ne[ue][0],ne[ue][1]);v.closePath(),v.fillStyle=D,v.fill(),v.strokeStyle=T,v.lineWidth=2.25,Se?fr(v,ne,4,3):v.stroke();return}}if(!de)return;const _=W(me+de[0]*ae,me,me+pe),Y=W($+de[1]*Me,$,$+ye),J=W(me+de[2]*ae,me,me+pe),oe=W($+de[3]*Me,$,$+ye),L=Math.max(1,J-_),K=Math.max(1,oe-Y);if(v.fillStyle=D,v.fillRect(_,Y,L,K),v.strokeStyle=T,v.lineWidth=2.25,Se){const ce=[[_+.5,Y+.5],[_+.5+Math.max(1,L-1),Y+.5],[_+.5+Math.max(1,L-1),Y+.5+Math.max(1,K-1)],[_+.5,Y+.5+Math.max(1,K-1)]];fr(v,ce,4,3)}else v.strokeRect(_+.5,Y+.5,Math.max(1,L-1),Math.max(1,K-1))},[d,m,p,S,A,x,t,e.width,e.height,D,T,O]),Z=g.useCallback(()=>{h.current||(h.current=!0,c.current=requestAnimationFrame(()=>{h.current=!1,c.current=null,k()}))},[k]),we=g.useCallback((M,v)=>{const X=a.current;if(!X)return null;const le=X.getBoundingClientRect();if(!le.width||!le.height)return null;const Q=le.width/d,ie=le.height/m,he=p.x*Q,me=p.y*ie,$=p.w*Q,pe=p.h*ie,ye=W((M-le.left-he)/$,0,1),U=W((v-le.top-me)/pe,0,1);return[ye*e.width,U*e.height]},[e.width,e.height,d,m,p]),se=g.useCallback((M,v)=>{const X=t.current;if(!X)return;if(X.setViewCenter){X.setViewCenter(M,v),Z();return}const le=X.getViewBounds?.(),Q=lt(le)?le:lt(u.current)?u.current:null;if(!Q)return;const ie=Math.max(1e-6,Q[2]-Q[0]),he=Math.max(1e-6,Q[3]-Q[1]);X.setViewState({offsetX:M-ie*.5,offsetY:v-he*.5}),Z()},[t,Z]),Re=g.useCallback(M=>{if(!G||M.button!==0)return;const v=a.current;if(!v)return;const X=we(M.clientX,M.clientY);X&&(M.preventDefault(),M.stopPropagation(),v.setPointerCapture(M.pointerId),f.current={active:!0,pointerId:M.pointerId},se(X[0],X[1]))},[G,we,se]),Ce=g.useCallback(M=>{const v=f.current;if(!v.active||v.pointerId!==M.pointerId)return;const X=we(M.clientX,M.clientY);X&&(M.preventDefault(),M.stopPropagation(),se(X[0],X[1]))},[we,se]),xe=g.useCallback(M=>{const v=f.current;if(!v.active||v.pointerId!==M.pointerId)return;const X=a.current;if(X&&X.hasPointerCapture(M.pointerId))try{X.releasePointerCapture(M.pointerId)}catch{}f.current={active:!1,pointerId:null},Z()},[Z]);return g.useEffect(()=>{let M=!1;l.current=null,Z();const v=0,X=2**(e.maxTierZoom-v),le=Math.ceil(e.width/X),Q=Math.ceil(e.height/X),ie=Math.max(1,Math.ceil(le/e.tileSize)),he=Math.max(1,Math.ceil(Q/e.tileSize)),me=ie*he;if(!z||me>C)return;const $=document.createElement("canvas");$.width=Math.max(1,Math.round(p.w)),$.height=Math.max(1,Math.round(p.h));const pe=$.getContext("2d");if(!pe)return;pe.fillStyle=S,pe.fillRect(0,0,$.width,$.height);const ye=[];for(let U=0;U<he;U+=1)for(let V=0;V<ie;V+=1){const ee=V*e.tileSize*X,B=U*e.tileSize*X,te=Math.min((V+1)*e.tileSize,le)*X,de=Math.min((U+1)*e.tileSize,Q)*X;ye.push({url:Pn(e,v,V,U),bounds:[ee,B,te,de]})}return Promise.allSettled(ye.map(async U=>{const V=Ss(U.url,n),ee=await fetch(U.url,{headers:V?{Authorization:n}:void 0});if(!ee.ok)throw new Error(`HTTP ${ee.status}`);const B=await createImageBitmap(await ee.blob());return{tile:U,bitmap:B}})).then(U=>{if(M){for(const B of U)B.status==="fulfilled"&&B.value.bitmap.close();return}const V=$.width/Math.max(1,e.width),ee=$.height/Math.max(1,e.height);for(const B of U){if(B.status!=="fulfilled")continue;const{tile:{bounds:te},bitmap:de}=B.value,ae=te[0]*V,Me=te[1]*ee,Se=Math.max(1,(te[2]-te[0])*V),_=Math.max(1,(te[3]-te[1])*ee);pe.drawImage(de,ae,Me,Se,_),de.close()}l.current=$,Z()}),()=>{M=!0}},[e,n,p,S,z,C,Z]),g.useEffect(()=>{Z()},[Z]),g.useEffect(()=>{if(i)return i.current=Z,()=>{i.current===Z&&(i.current=null)}},[i,Z]),g.useEffect(()=>()=>{f.current={active:!1,pointerId:null},c.current!==null&&(cancelAnimationFrame(c.current),c.current=null),h.current=!1},[]),Ye.jsxs("div",{className:o,style:N,children:[Ye.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:Re,onPointerMove:Ce,onPointerUp:xe,onPointerCancel:xe,onContextMenu:M=>{M.preventDefault()},onWheel:M=>{M.preventDefault(),M.stopPropagation()}}),re&&Ye.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:M=>{M.stopPropagation(),re()},style:H?{...H}:{...Rs},children:I??"×"})]})}const pr="__patch_layer__",As=[];function vs({regions:e,strokeStyle:t}){const{rendererRef:n,registerDrawCallback:r,unregisterDrawCallback:i,requestOverlayRedraw:o}=ot(),s=e??As,a=g.useMemo(()=>Ve(Wr,t),[t]),l=g.useMemo(()=>{const c=[];for(let h=0;h<s.length;h+=1){const d=s[h],m=Wt(d.coordinates);m.length!==0&&c.push({region:d,regionIndex:h,regionKey:d.id??h,polygons:m})}return c},[s]),u=g.useCallback(c=>{const h=n.current;if(!h||c.length===0)return[];const d=new Array(c.length);for(let m=0;m<c.length;m+=1){const p=Oe(h.worldToScreen(c[m][0],c[m][1]));if(!p)return[];d[m]=p}return d},[]),f=g.useRef({prepared:l,resolvedStrokeStyle:a,worldToScreenPoints:u});return f.current={prepared:l,resolvedStrokeStyle:a,worldToScreenPoints:u},g.useEffect(()=>(r(pr,20,h=>{const{prepared:d,resolvedStrokeStyle:m,worldToScreenPoints:p}=f.current;for(const y of d)for(const b of y.polygons){const x=p(b.outer);x.length>=4&&Pe(h,x,m,!0,!1);for(const C of b.holes){const S=p(C);S.length>=4&&Pe(h,S,m,!0,!1)}}}),()=>i(pr)),[r,i]),g.useEffect(()=>{o()},[l,a,o]),null}function dt(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return null;const n=yt(t??[]);if(n.length===0){const m={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return e.fillModes instanceof Uint8Array&&(m.fillModes=new Uint8Array(0)),e.ids instanceof Uint32Array&&(m.ids=new Uint32Array(0)),m}const r=et(e),i=e.positions,o=e.paletteIndices,s=e.fillModes instanceof Uint8Array&&e.fillModes.length>=r?e.fillModes:null,a=e.ids instanceof Uint32Array&&e.ids.length>=r?e.ids:null,l=new Float32Array(r*2),u=new Uint16Array(r),f=s?new Uint8Array(r):null,c=a?new Uint32Array(r):null;let h=0;for(let m=0;m<r;m+=1){const p=i[m*2],y=i[m*2+1];Dt(p,y,n)&&(l[h*2]=p,l[h*2+1]=y,u[h]=o[m],f&&(f[h]=s[m]),c&&(c[h]=a[m]),h+=1)}const d={count:h,positions:l.subarray(0,h*2),paletteIndices:u.subarray(0,h)};return f&&(d.fillModes=f.subarray(0,h)),c&&(d.ids=c.subarray(0,h)),d}function ti(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return new Uint32Array(0);const n=yt(t??[]);if(n.length===0)return new Uint32Array(0);const r=et(e);if(r===0)return new Uint32Array(0);const i=e.positions,o=new Uint32Array(r);let s=0;for(let a=0;a<r;a+=1){const l=i[a*2],u=i[a*2+1];Dt(l,u,n)&&(o[s]=a,s+=1)}return o.subarray(0,s)}let Mt=null;const Cs=`
|
|
32
|
+
`;class Nr{constructor(t){R(this,"canvas");R(this,"gl");R(this,"camera",new kr);R(this,"imageWidth");R(this,"imageHeight");R(this,"clearColor");R(this,"program");R(this,"vao");R(this,"quadBuffer");R(this,"uCameraLocation");R(this,"uBoundsLocation");R(this,"uTextureLocation");R(this,"resizeObserver");R(this,"tiles",[]);R(this,"frameId",null);R(this,"loadVersion",0);R(this,"destroyed",!1);R(this,"fitted",!1);R(this,"controlledViewState",!1);this.canvas=t.canvas,this.imageWidth=Math.max(1,t.imageWidth),this.imageHeight=Math.max(1,t.imageHeight),this.clearColor=t.clearColor??[.03,.05,.08,1],this.gl=xi(this.canvas),this.program=wn(this.gl,Si,Ei);const n=this.gl.createVertexArray(),r=this.gl.createBuffer();if(!n||!r)throw new Error("Failed to create WebGL buffers.");this.vao=n,this.quadBuffer=r,this.gl.bindVertexArray(this.vao),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.quadBuffer);const i=new Float32Array([0,0,0,0,1,0,1,0,0,1,0,1,1,1,1,1]);this.gl.bufferData(this.gl.ARRAY_BUFFER,i,this.gl.STATIC_DRAW);const o=this.gl.getAttribLocation(this.program,"aUnit"),s=this.gl.getAttribLocation(this.program,"aUv");if(o<0||s<0)throw new Error("Failed to get attribute locations.");const a=4*Float32Array.BYTES_PER_ELEMENT;this.gl.enableVertexAttribArray(o),this.gl.vertexAttribPointer(o,2,this.gl.FLOAT,!1,a,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,a,2*Float32Array.BYTES_PER_ELEMENT),this.gl.bindVertexArray(null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.uCameraLocation=Le(this.gl,this.program,"uCamera"),this.uBoundsLocation=Le(this.gl,this.program,"uBounds"),this.uTextureLocation=Le(this.gl,this.program,"uTexture"),t.initialViewState&&(this.controlledViewState=!0,this.camera.setViewState(t.initialViewState)),this.resizeObserver=new ResizeObserver(()=>{this.resize()}),this.resizeObserver.observe(this.canvas),this.resize()}async setTiles(t){if(this.destroyed)return;const n=++this.loadVersion,r=await Promise.all(t.map(async i=>await this.loadTile(i,n)));if(this.destroyed||n!==this.loadVersion){for(const i of r)i&&this.gl.deleteTexture(i.texture);return}this.disposeTiles(this.tiles),this.tiles=r.filter(i=>i!==null),this.requestRender()}setViewState(t){this.controlledViewState=!0,this.camera.setViewState(t),this.requestRender()}getViewState(){return this.camera.getViewState()}destroy(){this.destroyed||(this.destroyed=!0,this.loadVersion+=1,this.frameId!==null&&(cancelAnimationFrame(this.frameId),this.frameId=null),this.resizeObserver.disconnect(),this.disposeTiles(this.tiles),this.tiles=[],this.gl.deleteBuffer(this.quadBuffer),this.gl.deleteVertexArray(this.vao),this.gl.deleteProgram(this.program))}async loadTile(t,n){try{const r=await fetch(t.url);if(!r.ok)throw new Error(`Tile fetch failed: ${r.status} ${r.statusText}`);const i=await r.blob(),o=await createImageBitmap(i);if(this.destroyed||n!==this.loadVersion)return o.close(),null;const s=this.gl.createTexture();if(!s)throw o.close(),new Error("Failed to create tile texture.");return this.gl.bindTexture(this.gl.TEXTURE_2D,s),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,1),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),this.gl.bindTexture(this.gl.TEXTURE_2D,null),o.close(),{id:t.id,bounds:t.bounds,texture:s}}catch(r){return console.error(`[M1TileRenderer] tile load failed: ${t.id}`,r),null}}resize(){if(this.destroyed)return;const t=this.canvas.getBoundingClientRect(),n=Math.max(1,t.width||this.canvas.clientWidth||1),r=Math.max(1,t.height||this.canvas.clientHeight||1),i=Math.max(1,window.devicePixelRatio||1),o=Math.max(1,Math.round(n*i)),s=Math.max(1,Math.round(r*i));(this.canvas.width!==o||this.canvas.height!==s)&&(this.canvas.width=o,this.canvas.height=s),this.camera.setViewport(n,r),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),!this.fitted&&!this.controlledViewState&&(this.fitToImage(),this.fitted=!0),this.requestRender()}fitToImage(){const t=this.camera.getViewportSize(),n=Math.min(t.width/this.imageWidth,t.height/this.imageHeight),r=Number.isFinite(n)&&n>0?n:1,i=t.width/r,o=t.height/r,s=(this.imageWidth-i)*.5,a=(this.imageHeight-o)*.5;this.camera.setViewState({zoom:r,offsetX:s,offsetY:a})}requestRender(){this.frameId!==null||this.destroyed||(this.frameId=requestAnimationFrame(()=>{this.frameId=null,this.render()}))}render(){if(!this.destroyed){this.gl.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.useProgram(this.program),this.gl.bindVertexArray(this.vao),this.gl.uniformMatrix3fv(this.uCameraLocation,!1,this.camera.getMatrix()),this.gl.uniform1i(this.uTextureLocation,0);for(const t of this.tiles)this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,t.texture),this.gl.uniform4f(this.uBoundsLocation,t.bounds[0],t.bounds[1],t.bounds[2],t.bounds[3]),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindVertexArray(null)}}disposeTiles(t){for(const n of t)this.gl.deleteTexture(n.texture)}}class Je{constructor(t,n){this.next=null,this.key=t,this.data=n,this.left=null,this.right=null}}function Ri(e,t){return e>t?1:e<t?-1:0}function Ke(e,t,n){const r=new Je(null,null);let i=r,o=r;for(;;){const s=n(e,t.key);if(s<0){if(t.left===null)break;if(n(e,t.left.key)<0){const a=t.left;if(t.left=a.right,a.right=t,t=a,t.left===null)break}o.left=t,o=t,t=t.left}else if(s>0){if(t.right===null)break;if(n(e,t.right.key)>0){const a=t.right;if(t.right=a.left,a.left=t,t=a,t.right===null)break}i.right=t,i=t,t=t.right}else break}return i.right=t.left,o.left=t.right,t.left=r.right,t.right=r.left,t}function Kt(e,t,n,r){const i=new Je(e,t);if(n===null)return i.left=i.right=null,i;n=Ke(e,n,r);const o=r(e,n.key);return o<0?(i.left=n.left,i.right=n,n.left=null):o>=0&&(i.right=n.right,i.left=n,n.right=null),i}function Fn(e,t,n){let r=null,i=null;if(t){t=Ke(e,t,n);const o=n(t.key,e);o===0?(r=t.left,i=t.right):o<0?(i=t.right,t.right=null,r=t):(r=t.left,t.left=null,i=t)}return{left:r,right:i}}function Mi(e,t,n){return t===null?e:(e===null||(t=Ke(e.key,t,n),t.left=e),t)}function on(e,t,n,r,i){if(e){r(`${t}${n?"└── ":"├── "}${i(e)}
|
|
33
|
+
`);const o=t+(n?" ":"│ ");e.left&&on(e.left,o,!1,r,i),e.right&&on(e.right,o,!0,r,i)}}class xn{constructor(t=Ri){this._root=null,this._size=0,this._comparator=t}insert(t,n){return this._size++,this._root=Kt(t,n,this._root,this._comparator)}add(t,n){const r=new Je(t,n);this._root===null&&(r.left=r.right=null,this._size++,this._root=r);const i=this._comparator,o=Ke(t,this._root,i),s=i(t,o.key);return s===0?this._root=o:(s<0?(r.left=o.left,r.right=o,o.left=null):s>0&&(r.right=o.right,r.left=o,o.right=null),this._size++,this._root=r),this._root}remove(t){this._root=this._remove(t,this._root,this._comparator)}_remove(t,n,r){let i;return n===null?null:(n=Ke(t,n,r),r(t,n.key)===0?(n.left===null?i=n.right:(i=Ke(t,n.left,r),i.right=n.right),this._size--,i):n)}pop(){let t=this._root;if(t){for(;t.left;)t=t.left;return this._root=Ke(t.key,this._root,this._comparator),this._root=this._remove(t.key,this._root,this._comparator),{key:t.key,data:t.data}}return null}findStatic(t){let n=this._root;const r=this._comparator;for(;n;){const i=r(t,n.key);if(i===0)return n;i<0?n=n.left:n=n.right}return null}find(t){return this._root&&(this._root=Ke(t,this._root,this._comparator),this._comparator(t,this._root.key)!==0)?null:this._root}contains(t){let n=this._root;const r=this._comparator;for(;n;){const i=r(t,n.key);if(i===0)return!0;i<0?n=n.left:n=n.right}return!1}forEach(t,n){let r=this._root;const i=[];let o=!1;for(;!o;)r!==null?(i.push(r),r=r.left):i.length!==0?(r=i.pop(),t.call(n,r),r=r.right):o=!0;return this}range(t,n,r,i){const o=[],s=this._comparator;let a=this._root,l;for(;o.length!==0||a;)if(a)o.push(a),a=a.left;else{if(a=o.pop(),l=s(a.key,n),l>0)break;if(s(a.key,t)>=0&&r.call(i,a))return this;a=a.right}return this}keys(){const t=[];return this.forEach(({key:n})=>{t.push(n)}),t}values(){const t=[];return this.forEach(({data:n})=>{t.push(n)}),t}min(){return this._root?this.minNode(this._root).key:null}max(){return this._root?this.maxNode(this._root).key:null}minNode(t=this._root){if(t)for(;t.left;)t=t.left;return t}maxNode(t=this._root){if(t)for(;t.right;)t=t.right;return t}at(t){let n=this._root,r=!1,i=0;const o=[];for(;!r;)if(n)o.push(n),n=n.left;else if(o.length>0){if(n=o.pop(),i===t)return n;i++,n=n.right}else r=!0;return null}next(t){let n=this._root,r=null;if(t.right){for(r=t.right;r.left;)r=r.left;return r}const i=this._comparator;for(;n;){const o=i(t.key,n.key);if(o===0)break;o<0?(r=n,n=n.left):n=n.right}return r}prev(t){let n=this._root,r=null;if(t.left!==null){for(r=t.left;r.right;)r=r.right;return r}const i=this._comparator;for(;n;){const o=i(t.key,n.key);if(o===0)break;o<0?n=n.left:(r=n,n=n.right)}return r}clear(){return this._root=null,this._size=0,this}toList(){return vi(this._root)}load(t,n=[],r=!1){let i=t.length;const o=this._comparator;if(r&&ln(t,n,0,i-1,o),this._root===null)this._root=sn(t,n,0,i),this._size=i;else{const s=Ci(this.toList(),Ai(t,n),o);i=this._size+i,this._root=an({head:s},0,i)}return this}isEmpty(){return this._root===null}get size(){return this._size}get root(){return this._root}toString(t=n=>String(n.key)){const n=[];return on(this._root,"",!0,r=>n.push(r),t),n.join("")}update(t,n,r){const i=this._comparator;let{left:o,right:s}=Fn(t,this._root,i);i(t,n)<0?s=Kt(n,r,s,i):o=Kt(n,r,o,i),this._root=Mi(o,s,i)}split(t){return Fn(t,this._root,this._comparator)}*[Symbol.iterator](){let t=this._root;const n=[];let r=!1;for(;!r;)t!==null?(n.push(t),t=t.left):n.length!==0?(t=n.pop(),yield t,t=t.right):r=!0}}function sn(e,t,n,r){const i=r-n;if(i>0){const o=n+Math.floor(i/2),s=e[o],a=t[o],l=new Je(s,a);return l.left=sn(e,t,n,o),l.right=sn(e,t,o+1,r),l}return null}function Ai(e,t){const n=new Je(null,null);let r=n;for(let i=0;i<e.length;i++)r=r.next=new Je(e[i],t[i]);return r.next=null,n.next}function vi(e){let t=e;const n=[];let r=!1;const i=new Je(null,null);let o=i;for(;!r;)t?(n.push(t),t=t.left):n.length>0?(t=o=o.next=n.pop(),t=t.right):r=!0;return o.next=null,i.next}function an(e,t,n){const r=n-t;if(r>0){const i=t+Math.floor(r/2),o=an(e,t,i),s=e.head;return s.left=o,e.head=e.head.next,s.right=an(e,i+1,n),s}return null}function Ci(e,t,n){const r=new Je(null,null);let i=r,o=e,s=t;for(;o!==null&&s!==null;)n(o.key,s.key)<0?(i.next=o,o=o.next):(i.next=s,s=s.next),i=i.next;return o!==null?i.next=o:s!==null&&(i.next=s),r.next}function ln(e,t,n,r,i){if(n>=r)return;const o=e[n+r>>1];let s=n-1,a=r+1;for(;;){do s++;while(i(e[s],o)<0);do a--;while(i(e[a],o)>0);if(s>=a)break;let l=e[s];e[s]=e[a],e[a]=l,l=t[s],t[s]=t[a],t[a]=l}ln(e,t,n,a,i),ln(e,t,a+1,r,i)}const He=11102230246251565e-32,Pe=134217729,Ii=(3+8*He)*He;function jt(e,t,n,r,i){let o,s,a,l,u=t[0],f=r[0],c=0,h=0;f>u==f>-u?(o=u,u=t[++c]):(o=f,f=r[++h]);let d=0;if(c<e&&h<n)for(f>u==f>-u?(s=u+o,a=o-(s-u),u=t[++c]):(s=f+o,a=o-(s-f),f=r[++h]),o=s,a!==0&&(i[d++]=a);c<e&&h<n;)f>u==f>-u?(s=o+u,l=s-o,a=o-(s-l)+(u-l),u=t[++c]):(s=o+f,l=s-o,a=o-(s-l)+(f-l),f=r[++h]),o=s,a!==0&&(i[d++]=a);for(;c<e;)s=o+u,l=s-o,a=o-(s-l)+(u-l),u=t[++c],o=s,a!==0&&(i[d++]=a);for(;h<n;)s=o+f,l=s-o,a=o-(s-l)+(f-l),f=r[++h],o=s,a!==0&&(i[d++]=a);return(o!==0||d===0)&&(i[d++]=o),d}function Pi(e,t){let n=t[0];for(let r=1;r<e;r++)n+=t[r];return n}function pt(e){return new Float64Array(e)}const Ti=(3+16*He)*He,_i=(2+12*He)*He,Li=(9+64*He)*He*He,rt=pt(4),kn=pt(8),Nn=pt(12),Bn=pt(16),_e=pt(4);function Fi(e,t,n,r,i,o,s){let a,l,u,f,c,h,d,m,p,y,b,x,C,S,A,_,Y,B;const G=e-i,z=n-i,$=t-o,Q=r-o;S=G*Q,h=Pe*G,d=h-(h-G),m=G-d,h=Pe*Q,p=h-(h-Q),y=Q-p,A=m*y-(S-d*p-m*p-d*y),_=$*z,h=Pe*$,d=h-(h-$),m=$-d,h=Pe*z,p=h-(h-z),y=z-p,Y=m*y-(_-d*p-m*p-d*y),b=A-Y,c=A-b,rt[0]=A-(b+c)+(c-Y),x=S+b,c=x-S,C=S-(x-c)+(b-c),b=C-_,c=C-b,rt[1]=C-(b+c)+(c-_),B=x+b,c=B-x,rt[2]=x-(B-c)+(b-c),rt[3]=B;let P=Pi(4,rt),W=_i*s;if(P>=W||-P>=W||(c=e-G,a=e-(G+c)+(c-i),c=n-z,u=n-(z+c)+(c-i),c=t-$,l=t-($+c)+(c-o),c=r-Q,f=r-(Q+c)+(c-o),a===0&&l===0&&u===0&&f===0)||(W=Li*s+Ii*Math.abs(P),P+=G*f+Q*a-($*u+z*l),P>=W||-P>=W))return P;S=a*Q,h=Pe*a,d=h-(h-a),m=a-d,h=Pe*Q,p=h-(h-Q),y=Q-p,A=m*y-(S-d*p-m*p-d*y),_=l*z,h=Pe*l,d=h-(h-l),m=l-d,h=Pe*z,p=h-(h-z),y=z-p,Y=m*y-(_-d*p-m*p-d*y),b=A-Y,c=A-b,_e[0]=A-(b+c)+(c-Y),x=S+b,c=x-S,C=S-(x-c)+(b-c),b=C-_,c=C-b,_e[1]=C-(b+c)+(c-_),B=x+b,c=B-x,_e[2]=x-(B-c)+(b-c),_e[3]=B;const N=jt(4,rt,4,_e,kn);S=G*f,h=Pe*G,d=h-(h-G),m=G-d,h=Pe*f,p=h-(h-f),y=f-p,A=m*y-(S-d*p-m*p-d*y),_=$*u,h=Pe*$,d=h-(h-$),m=$-d,h=Pe*u,p=h-(h-u),y=u-p,Y=m*y-(_-d*p-m*p-d*y),b=A-Y,c=A-b,_e[0]=A-(b+c)+(c-Y),x=S+b,c=x-S,C=S-(x-c)+(b-c),b=C-_,c=C-b,_e[1]=C-(b+c)+(c-_),B=x+b,c=B-x,_e[2]=x-(B-c)+(b-c),_e[3]=B;const k=jt(N,kn,4,_e,Nn);S=a*f,h=Pe*a,d=h-(h-a),m=a-d,h=Pe*f,p=h-(h-f),y=f-p,A=m*y-(S-d*p-m*p-d*y),_=l*u,h=Pe*l,d=h-(h-l),m=l-d,h=Pe*u,p=h-(h-u),y=u-p,Y=m*y-(_-d*p-m*p-d*y),b=A-Y,c=A-b,_e[0]=A-(b+c)+(c-Y),x=S+b,c=x-S,C=S-(x-c)+(b-c),b=C-_,c=C-b,_e[1]=C-(b+c)+(c-_),B=x+b,c=B-x,_e[2]=x-(B-c)+(b-c),_e[3]=B;const K=jt(k,Nn,4,_e,Bn);return Bn[K-1]}function ki(e,t,n,r,i,o){const s=(t-o)*(n-i),a=(e-i)*(r-o),l=s-a,u=Math.abs(s+a);return Math.abs(l)>=Ti*u?l:-Fi(e,t,n,r,i,o,u)}const lt=(e,t)=>e.ll.x<=t.x&&t.x<=e.ur.x&&e.ll.y<=t.y&&t.y<=e.ur.y,cn=(e,t)=>{if(t.ur.x<e.ll.x||e.ur.x<t.ll.x||t.ur.y<e.ll.y||e.ur.y<t.ll.y)return null;const n=e.ll.x<t.ll.x?t.ll.x:e.ll.x,r=e.ur.x<t.ur.x?e.ur.x:t.ur.x,i=e.ll.y<t.ll.y?t.ll.y:e.ll.y,o=e.ur.y<t.ur.y?e.ur.y:t.ur.y;return{ll:{x:n,y:i},ur:{x:r,y:o}}};let je=Number.EPSILON;je===void 0&&(je=Math.pow(2,-52));const Ni=je*je,zn=(e,t)=>{if(-je<e&&e<je&&-je<t&&t<je)return 0;const n=e-t;return n*n<Ni*e*t?0:e<t?-1:1};class Bi{constructor(){this.reset()}reset(){this.xRounder=new Dn,this.yRounder=new Dn}round(t,n){return{x:this.xRounder.round(t),y:this.yRounder.round(n)}}}class Dn{constructor(){this.tree=new xn,this.round(0)}round(t){const n=this.tree.add(t),r=this.tree.prev(n);if(r!==null&&zn(n.key,r.key)===0)return this.tree.remove(t),r.key;const i=this.tree.next(n);return i!==null&&zn(n.key,i.key)===0?(this.tree.remove(t),i.key):t}}const ht=new Bi,_t=(e,t)=>e.x*t.y-e.y*t.x,Br=(e,t)=>e.x*t.x+e.y*t.y,Un=(e,t,n)=>{const r=ki(e.x,e.y,t.x,t.y,n.x,n.y);return r>0?-1:r<0?1:0},Bt=e=>Math.sqrt(Br(e,e)),zi=(e,t,n)=>{const r={x:t.x-e.x,y:t.y-e.y},i={x:n.x-e.x,y:n.y-e.y};return _t(i,r)/Bt(i)/Bt(r)},Di=(e,t,n)=>{const r={x:t.x-e.x,y:t.y-e.y},i={x:n.x-e.x,y:n.y-e.y};return Br(i,r)/Bt(i)/Bt(r)},On=(e,t,n)=>t.y===0?null:{x:e.x+t.x/t.y*(n-e.y),y:n},Yn=(e,t,n)=>t.x===0?null:{x:n,y:e.y+t.y/t.x*(n-e.x)},Ui=(e,t,n,r)=>{if(t.x===0)return Yn(n,r,e.x);if(r.x===0)return Yn(e,t,n.x);if(t.y===0)return On(n,r,e.y);if(r.y===0)return On(e,t,n.y);const i=_t(t,r);if(i==0)return null;const o={x:n.x-e.x,y:n.y-e.y},s=_t(o,t)/i,a=_t(o,r)/i,l=e.x+a*t.x,u=n.x+s*r.x,f=e.y+a*t.y,c=n.y+s*r.y,h=(l+u)/2,d=(f+c)/2;return{x:h,y:d}};class De{static compare(t,n){const r=De.comparePoints(t.point,n.point);return r!==0?r:(t.point!==n.point&&t.link(n),t.isLeft!==n.isLeft?t.isLeft?1:-1:Qe.compare(t.segment,n.segment))}static comparePoints(t,n){return t.x<n.x?-1:t.x>n.x?1:t.y<n.y?-1:t.y>n.y?1:0}constructor(t,n){t.events===void 0?t.events=[this]:t.events.push(this),this.point=t,this.isLeft=n}link(t){if(t.point===this.point)throw new Error("Tried to link already linked events");const n=t.point.events;for(let r=0,i=n.length;r<i;r++){const o=n[r];this.point.events.push(o),o.point=this.point}this.checkForConsuming()}checkForConsuming(){const t=this.point.events.length;for(let n=0;n<t;n++){const r=this.point.events[n];if(r.segment.consumedBy===void 0)for(let i=n+1;i<t;i++){const o=this.point.events[i];o.consumedBy===void 0&&r.otherSE.point.events===o.otherSE.point.events&&r.segment.consume(o.segment)}}}getAvailableLinkedEvents(){const t=[];for(let n=0,r=this.point.events.length;n<r;n++){const i=this.point.events[n];i!==this&&!i.segment.ringOut&&i.segment.isInResult()&&t.push(i)}return t}getLeftmostComparator(t){const n=new Map,r=i=>{const o=i.otherSE;n.set(i,{sine:zi(this.point,t.point,o.point),cosine:Di(this.point,t.point,o.point)})};return(i,o)=>{n.has(i)||r(i),n.has(o)||r(o);const{sine:s,cosine:a}=n.get(i),{sine:l,cosine:u}=n.get(o);return s>=0&&l>=0?a<u?1:a>u?-1:0:s<0&&l<0?a<u?-1:a>u?1:0:l<s?-1:l>s?1:0}}}let Oi=0;class Qe{static compare(t,n){const r=t.leftSE.point.x,i=n.leftSE.point.x,o=t.rightSE.point.x,s=n.rightSE.point.x;if(s<r)return 1;if(o<i)return-1;const a=t.leftSE.point.y,l=n.leftSE.point.y,u=t.rightSE.point.y,f=n.rightSE.point.y;if(r<i){if(l<a&&l<u)return 1;if(l>a&&l>u)return-1;const c=t.comparePoint(n.leftSE.point);if(c<0)return 1;if(c>0)return-1;const h=n.comparePoint(t.rightSE.point);return h!==0?h:-1}if(r>i){if(a<l&&a<f)return-1;if(a>l&&a>f)return 1;const c=n.comparePoint(t.leftSE.point);if(c!==0)return c;const h=t.comparePoint(n.rightSE.point);return h<0?1:h>0?-1:1}if(a<l)return-1;if(a>l)return 1;if(o<s){const c=n.comparePoint(t.rightSE.point);if(c!==0)return c}if(o>s){const c=t.comparePoint(n.rightSE.point);if(c<0)return 1;if(c>0)return-1}if(o!==s){const c=u-a,h=o-r,d=f-l,m=s-i;if(c>h&&d<m)return 1;if(c<h&&d>m)return-1}return o>s?1:o<s||u<f?-1:u>f?1:t.id<n.id?-1:t.id>n.id?1:0}constructor(t,n,r,i){this.id=++Oi,this.leftSE=t,t.segment=this,t.otherSE=n,this.rightSE=n,n.segment=this,n.otherSE=t,this.rings=r,this.windings=i}static fromRing(t,n,r){let i,o,s;const a=De.comparePoints(t,n);if(a<0)i=t,o=n,s=1;else if(a>0)i=n,o=t,s=-1;else throw new Error(`Tried to create degenerate segment at [${t.x}, ${t.y}]`);const l=new De(i,!0),u=new De(o,!1);return new Qe(l,u,[r],[s])}replaceRightSE(t){this.rightSE=t,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const t=this.leftSE.point.y,n=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:t<n?t:n},ur:{x:this.rightSE.point.x,y:t>n?t:n}}}vector(){return{x:this.rightSE.point.x-this.leftSE.point.x,y:this.rightSE.point.y-this.leftSE.point.y}}isAnEndpoint(t){return t.x===this.leftSE.point.x&&t.y===this.leftSE.point.y||t.x===this.rightSE.point.x&&t.y===this.rightSE.point.y}comparePoint(t){if(this.isAnEndpoint(t))return 0;const n=this.leftSE.point,r=this.rightSE.point,i=this.vector();if(n.x===r.x)return t.x===n.x?0:t.x<n.x?1:-1;const o=(t.y-n.y)/i.y,s=n.x+o*i.x;if(t.x===s)return 0;const a=(t.x-n.x)/i.x,l=n.y+a*i.y;return t.y===l?0:t.y<l?-1:1}getIntersection(t){const n=this.bbox(),r=t.bbox(),i=cn(n,r);if(i===null)return null;const o=this.leftSE.point,s=this.rightSE.point,a=t.leftSE.point,l=t.rightSE.point,u=lt(n,a)&&this.comparePoint(a)===0,f=lt(r,o)&&t.comparePoint(o)===0,c=lt(n,l)&&this.comparePoint(l)===0,h=lt(r,s)&&t.comparePoint(s)===0;if(f&&u)return h&&!c?s:!h&&c?l:null;if(f)return c&&o.x===l.x&&o.y===l.y?null:o;if(u)return h&&s.x===a.x&&s.y===a.y?null:a;if(h&&c)return null;if(h)return s;if(c)return l;const d=Ui(o,this.vector(),a,t.vector());return d===null||!lt(i,d)?null:ht.round(d.x,d.y)}split(t){const n=[],r=t.events!==void 0,i=new De(t,!0),o=new De(t,!1),s=this.rightSE;this.replaceRightSE(o),n.push(o),n.push(i);const a=new Qe(i,s,this.rings.slice(),this.windings.slice());return De.comparePoints(a.leftSE.point,a.rightSE.point)>0&&a.swapEvents(),De.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),r&&(i.checkForConsuming(),o.checkForConsuming()),n}swapEvents(){const t=this.rightSE;this.rightSE=this.leftSE,this.leftSE=t,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let n=0,r=this.windings.length;n<r;n++)this.windings[n]*=-1}consume(t){let n=this,r=t;for(;n.consumedBy;)n=n.consumedBy;for(;r.consumedBy;)r=r.consumedBy;const i=Qe.compare(n,r);if(i!==0){if(i>0){const o=n;n=r,r=o}if(n.prev===r){const o=n;n=r,r=o}for(let o=0,s=r.rings.length;o<s;o++){const a=r.rings[o],l=r.windings[o],u=n.rings.indexOf(a);u===-1?(n.rings.push(a),n.windings.push(l)):n.windings[u]+=l}r.rings=null,r.windings=null,r.consumedBy=n,r.leftSE.consumedBy=n.leftSE,r.rightSE.consumedBy=n.rightSE}}prevInResult(){return this._prevInResult!==void 0?this._prevInResult:(this.prev?this.prev.isInResult()?this._prevInResult=this.prev:this._prevInResult=this.prev.prevInResult():this._prevInResult=null,this._prevInResult)}beforeState(){if(this._beforeState!==void 0)return this._beforeState;if(!this.prev)this._beforeState={rings:[],windings:[],multiPolys:[]};else{const t=this.prev.consumedBy||this.prev;this._beforeState=t.afterState()}return this._beforeState}afterState(){if(this._afterState!==void 0)return this._afterState;const t=this.beforeState();this._afterState={rings:t.rings.slice(0),windings:t.windings.slice(0),multiPolys:[]};const n=this._afterState.rings,r=this._afterState.windings,i=this._afterState.multiPolys;for(let a=0,l=this.rings.length;a<l;a++){const u=this.rings[a],f=this.windings[a],c=n.indexOf(u);c===-1?(n.push(u),r.push(f)):r[c]+=f}const o=[],s=[];for(let a=0,l=n.length;a<l;a++){if(r[a]===0)continue;const u=n[a],f=u.poly;if(s.indexOf(f)===-1)if(u.isExterior)o.push(f);else{s.indexOf(f)===-1&&s.push(f);const c=o.indexOf(u.poly);c!==-1&&o.splice(c,1)}}for(let a=0,l=o.length;a<l;a++){const u=o[a].multiPoly;i.indexOf(u)===-1&&i.push(u)}return this._afterState}isInResult(){if(this.consumedBy)return!1;if(this._isInResult!==void 0)return this._isInResult;const t=this.beforeState().multiPolys,n=this.afterState().multiPolys;switch(Xe.type){case"union":{const r=t.length===0,i=n.length===0;this._isInResult=r!==i;break}case"intersection":{let r,i;t.length<n.length?(r=t.length,i=n.length):(r=n.length,i=t.length),this._isInResult=i===Xe.numMultiPolys&&r<i;break}case"xor":{const r=Math.abs(t.length-n.length);this._isInResult=r%2===1;break}case"difference":{const r=i=>i.length===1&&i[0].isSubject;this._isInResult=r(t)!==r(n);break}default:throw new Error(`Unrecognized operation type found ${Xe.type}`)}return this._isInResult}}class Wn{constructor(t,n,r){if(!Array.isArray(t)||t.length===0)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=n,this.isExterior=r,this.segments=[],typeof t[0][0]!="number"||typeof t[0][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const i=ht.round(t[0][0],t[0][1]);this.bbox={ll:{x:i.x,y:i.y},ur:{x:i.x,y:i.y}};let o=i;for(let s=1,a=t.length;s<a;s++){if(typeof t[s][0]!="number"||typeof t[s][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");let l=ht.round(t[s][0],t[s][1]);l.x===o.x&&l.y===o.y||(this.segments.push(Qe.fromRing(o,l,this)),l.x<this.bbox.ll.x&&(this.bbox.ll.x=l.x),l.y<this.bbox.ll.y&&(this.bbox.ll.y=l.y),l.x>this.bbox.ur.x&&(this.bbox.ur.x=l.x),l.y>this.bbox.ur.y&&(this.bbox.ur.y=l.y),o=l)}(i.x!==o.x||i.y!==o.y)&&this.segments.push(Qe.fromRing(o,i,this))}getSweepEvents(){const t=[];for(let n=0,r=this.segments.length;n<r;n++){const i=this.segments[n];t.push(i.leftSE),t.push(i.rightSE)}return t}}class Yi{constructor(t,n){if(!Array.isArray(t))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");this.exteriorRing=new Wn(t[0],this,!0),this.bbox={ll:{x:this.exteriorRing.bbox.ll.x,y:this.exteriorRing.bbox.ll.y},ur:{x:this.exteriorRing.bbox.ur.x,y:this.exteriorRing.bbox.ur.y}},this.interiorRings=[];for(let r=1,i=t.length;r<i;r++){const o=new Wn(t[r],this,!1);o.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=o.bbox.ll.x),o.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=o.bbox.ll.y),o.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=o.bbox.ur.x),o.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=o.bbox.ur.y),this.interiorRings.push(o)}this.multiPoly=n}getSweepEvents(){const t=this.exteriorRing.getSweepEvents();for(let n=0,r=this.interiorRings.length;n<r;n++){const i=this.interiorRings[n].getSweepEvents();for(let o=0,s=i.length;o<s;o++)t.push(i[o])}return t}}class Xn{constructor(t,n){if(!Array.isArray(t))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");try{typeof t[0][0][0]=="number"&&(t=[t])}catch{}this.polys=[],this.bbox={ll:{x:Number.POSITIVE_INFINITY,y:Number.POSITIVE_INFINITY},ur:{x:Number.NEGATIVE_INFINITY,y:Number.NEGATIVE_INFINITY}};for(let r=0,i=t.length;r<i;r++){const o=new Yi(t[r],this);o.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=o.bbox.ll.x),o.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=o.bbox.ll.y),o.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=o.bbox.ur.x),o.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=o.bbox.ur.y),this.polys.push(o)}this.isSubject=n}getSweepEvents(){const t=[];for(let n=0,r=this.polys.length;n<r;n++){const i=this.polys[n].getSweepEvents();for(let o=0,s=i.length;o<s;o++)t.push(i[o])}return t}}class zt{static factory(t){const n=[];for(let r=0,i=t.length;r<i;r++){const o=t[r];if(!o.isInResult()||o.ringOut)continue;let s=null,a=o.leftSE,l=o.rightSE;const u=[a],f=a.point,c=[];for(;s=a,a=l,u.push(a),a.point!==f;)for(;;){const h=a.getAvailableLinkedEvents();if(h.length===0){const p=u[0].point,y=u[u.length-1].point;throw new Error(`Unable to complete output ring starting at [${p.x}, ${p.y}]. Last matching segment found ends at [${y.x}, ${y.y}].`)}if(h.length===1){l=h[0].otherSE;break}let d=null;for(let p=0,y=c.length;p<y;p++)if(c[p].point===a.point){d=p;break}if(d!==null){const p=c.splice(d)[0],y=u.splice(p.index);y.unshift(y[0].otherSE),n.push(new zt(y.reverse()));continue}c.push({index:u.length,point:a.point});const m=a.getLeftmostComparator(s);l=h.sort(m)[0].otherSE;break}n.push(new zt(u))}return n}constructor(t){this.events=t;for(let n=0,r=t.length;n<r;n++)t[n].segment.ringOut=this;this.poly=null}getGeom(){let t=this.events[0].point;const n=[t];for(let u=1,f=this.events.length-1;u<f;u++){const c=this.events[u].point,h=this.events[u+1].point;Un(c,t,h)!==0&&(n.push(c),t=c)}if(n.length===1)return null;const r=n[0],i=n[1];Un(r,t,i)===0&&n.shift(),n.push(n[0]);const o=this.isExteriorRing()?1:-1,s=this.isExteriorRing()?0:n.length-1,a=this.isExteriorRing()?n.length:-1,l=[];for(let u=s;u!=a;u+=o)l.push([n[u].x,n[u].y]);return l}isExteriorRing(){if(this._isExteriorRing===void 0){const t=this.enclosingRing();this._isExteriorRing=t?!t.isExteriorRing():!0}return this._isExteriorRing}enclosingRing(){return this._enclosingRing===void 0&&(this._enclosingRing=this._calcEnclosingRing()),this._enclosingRing}_calcEnclosingRing(){let t=this.events[0];for(let i=1,o=this.events.length;i<o;i++){const s=this.events[i];De.compare(t,s)>0&&(t=s)}let n=t.segment.prevInResult(),r=n?n.prevInResult():null;for(;;){if(!n)return null;if(!r)return n.ringOut;if(r.ringOut!==n.ringOut)return r.ringOut.enclosingRing()!==n.ringOut?n.ringOut:n.ringOut.enclosingRing();n=r.prevInResult(),r=n?n.prevInResult():null}}}class Vn{constructor(t){this.exteriorRing=t,t.poly=this,this.interiorRings=[]}addInterior(t){this.interiorRings.push(t),t.poly=this}getGeom(){const t=[this.exteriorRing.getGeom()];if(t[0]===null)return null;for(let n=0,r=this.interiorRings.length;n<r;n++){const i=this.interiorRings[n].getGeom();i!==null&&t.push(i)}return t}}class Wi{constructor(t){this.rings=t,this.polys=this._composePolys(t)}getGeom(){const t=[];for(let n=0,r=this.polys.length;n<r;n++){const i=this.polys[n].getGeom();i!==null&&t.push(i)}return t}_composePolys(t){const n=[];for(let r=0,i=t.length;r<i;r++){const o=t[r];if(!o.poly)if(o.isExteriorRing())n.push(new Vn(o));else{const s=o.enclosingRing();s.poly||n.push(new Vn(s)),s.poly.addInterior(o)}}return n}}class Xi{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Qe.compare;this.queue=t,this.tree=new xn(n),this.segments=[]}process(t){const n=t.segment,r=[];if(t.consumedBy)return t.isLeft?this.queue.remove(t.otherSE):this.tree.remove(n),r;const i=t.isLeft?this.tree.add(n):this.tree.find(n);if(!i)throw new Error(`Unable to find segment #${n.id} [${n.leftSE.point.x}, ${n.leftSE.point.y}] -> [${n.rightSE.point.x}, ${n.rightSE.point.y}] in SweepLine tree.`);let o=i,s=i,a,l;for(;a===void 0;)o=this.tree.prev(o),o===null?a=null:o.key.consumedBy===void 0&&(a=o.key);for(;l===void 0;)s=this.tree.next(s),s===null?l=null:s.key.consumedBy===void 0&&(l=s.key);if(t.isLeft){let u=null;if(a){const c=a.getIntersection(n);if(c!==null&&(n.isAnEndpoint(c)||(u=c),!a.isAnEndpoint(c))){const h=this._splitSafely(a,c);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}}let f=null;if(l){const c=l.getIntersection(n);if(c!==null&&(n.isAnEndpoint(c)||(f=c),!l.isAnEndpoint(c))){const h=this._splitSafely(l,c);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}}if(u!==null||f!==null){let c=null;u===null?c=f:f===null?c=u:c=De.comparePoints(u,f)<=0?u:f,this.queue.remove(n.rightSE),r.push(n.rightSE);const h=n.split(c);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}r.length>0?(this.tree.remove(n),r.push(t)):(this.segments.push(n),n.prev=a)}else{if(a&&l){const u=a.getIntersection(l);if(u!==null){if(!a.isAnEndpoint(u)){const f=this._splitSafely(a,u);for(let c=0,h=f.length;c<h;c++)r.push(f[c])}if(!l.isAnEndpoint(u)){const f=this._splitSafely(l,u);for(let c=0,h=f.length;c<h;c++)r.push(f[c])}}}this.tree.remove(n)}return r}_splitSafely(t,n){this.tree.remove(t);const r=t.rightSE;this.queue.remove(r);const i=t.split(n);return i.push(r),t.consumedBy===void 0&&this.tree.add(t),i}}const Gn=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_QUEUE_SIZE||1e6,Vi=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS||1e6;class Gi{run(t,n,r){Xe.type=t,ht.reset();const i=[new Xn(n,!0)];for(let c=0,h=r.length;c<h;c++)i.push(new Xn(r[c],!1));if(Xe.numMultiPolys=i.length,Xe.type==="difference"){const c=i[0];let h=1;for(;h<i.length;)cn(i[h].bbox,c.bbox)!==null?h++:i.splice(h,1)}if(Xe.type==="intersection")for(let c=0,h=i.length;c<h;c++){const d=i[c];for(let m=c+1,p=i.length;m<p;m++)if(cn(d.bbox,i[m].bbox)===null)return[]}const o=new xn(De.compare);for(let c=0,h=i.length;c<h;c++){const d=i[c].getSweepEvents();for(let m=0,p=d.length;m<p;m++)if(o.insert(d[m]),o.size>Gn)throw new Error("Infinite loop when putting segment endpoints in a priority queue (queue size too big).")}const s=new Xi(o);let a=o.size,l=o.pop();for(;l;){const c=l.key;if(o.size===a){const d=c.segment;throw new Error(`Unable to pop() ${c.isLeft?"left":"right"} SweepEvent [${c.point.x}, ${c.point.y}] from segment #${d.id} [${d.leftSE.point.x}, ${d.leftSE.point.y}] -> [${d.rightSE.point.x}, ${d.rightSE.point.y}] from queue.`)}if(o.size>Gn)throw new Error("Infinite loop when passing sweep line over endpoints (queue size too big).");if(s.segments.length>Vi)throw new Error("Infinite loop when passing sweep line over endpoints (too many sweep line segments).");const h=s.process(c);for(let d=0,m=h.length;d<m;d++){const p=h[d];p.consumedBy===void 0&&o.insert(p)}a=o.size,l=o.pop()}ht.reset();const u=zt.factory(s.segments);return new Wi(u).getGeom()}}const Xe=new Gi,qi=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return Xe.run("union",e,n)},Hi=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return Xe.run("intersection",e,n)},Zi=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return Xe.run("xor",e,n)},$i=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return Xe.run("difference",e,n)};var Ki={union:qi,intersection:Hi,xor:Zi,difference:$i};function yt(e){return e==null?null:zr(e)||Dr(e)||ji(e)?e:null}function qn(e){return typeof e=="number"&&Number.isFinite(e)}function Lt(e){return Array.isArray(e)&&e.length>=2&&qn(e[0])&&qn(e[1])}function zr(e){return Array.isArray(e)&&e.length>0&&e.every(t=>Lt(t))}function Dr(e){return Array.isArray(e)&&e.length>0&&e.every(t=>zr(t))}function ji(e){return Array.isArray(e)&&e.length>0&&e.every(t=>Dr(t))}function Be(e){if(!Array.isArray(e)||e.length<3)return[];const t=[];for(const i of e){if(!Array.isArray(i)||i.length<2)continue;const o=Number(i[0]),s=Number(i[1]);if(!Number.isFinite(o)||!Number.isFinite(s))continue;const a=t[t.length-1];a&&a[0]===o&&a[1]===s||t.push([o,s])}if(t.length<3)return[];const n=t[0],r=t[t.length-1];return(n[0]!==r[0]||n[1]!==r[1])&&t.push([n[0],n[1]]),t.length>=4?t:[]}function dt(e){if(!Array.isArray(e)||e.length<4)return 0;let t=0;for(let n=0;n<e.length-1;n+=1){const r=e[n],i=e[n+1];t+=r[0]*i[1]-i[0]*r[1]}return t*.5}function Qt(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const o of e){const s=Be(o);s.length>=4&&t.push(s)}if(t.length===0)return[];if(t.length===1)return[t[0]];let n=0,r=0;for(let o=0;o<t.length;o+=1){const s=Math.abs(dt(t[o]));s<=r||(r=s,n=o)}const i=[t[n]];for(let o=0;o<t.length;o+=1)o!==n&&i.push(t[o]);return i}function Ur(e){if(!Array.isArray(e)||e.length===0)return[];const t=e[0];if(Lt(t)){const i=Qt([e]);return i.length>0?[i]:[]}if(!Array.isArray(t)||t.length===0)return[];const n=t[0];if(Lt(n)){const i=Qt(e);return i.length>0?[i]:[]}if(!Array.isArray(n)||n.length===0||!Lt(n[0]))return[];const r=[];for(const i of e){const o=Qt(i);o.length>0&&r.push(o)}return r}function Hn(e,t,n){let r=!1;for(let i=0,o=n.length-1;i<n.length;o=i,i+=1){const s=n[i][0],a=n[i][1],l=n[o][0],u=n[o][1];if(a===u||a>t==u>t)continue;e<(l-s)*(t-a)/(u-a)+s&&(r=!r)}return r}function bt(e){const t=[];for(const n of e??[]){const r=Ur(n);for(const i of r){const o=i[0];if(!o||o.length<4)continue;let s=1/0,a=1/0,l=-1/0,u=-1/0;for(const[c,h]of o)c<s&&(s=c),c>l&&(l=c),h<a&&(a=h),h>u&&(u=h);if(!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(l)||!Number.isFinite(u))continue;let f=Math.abs(dt(o));for(let c=1;c<i.length;c+=1)f-=Math.abs(dt(i[c]));t.push({outer:o,holes:i.slice(1),minX:s,minY:a,maxX:l,maxY:u,area:Math.max(1e-6,f)})}}return t}function Or(e,t,n){if(e<n.minX||e>n.maxX||t<n.minY||t>n.maxY||!Hn(e,t,n.outer))return!1;for(const r of n.holes)if(Hn(e,t,r))return!1;return!0}function Dt(e,t,n){for(const r of n)if(Or(e,t,r))return!0;return!1}const Sn=[160,160,160,255];function O(e,t,n){return Math.max(t,Math.min(n,e))}function En(e,t,n){const r=Number(e),i=Number(t),o=Number(n);return!Number.isFinite(r)||r<=0?1:!Number.isFinite(i)||!Number.isFinite(o)?r:Math.pow(2,i-o)*r}function Qi(e,t,n){let i=100*En(e,t,n);if(Number(e)){let o="μm";return i>1e3&&(i/=1e3,o="mm"),`${i.toPrecision(3)} ${o}`}return`${Math.round(i*1e3)/1e3} pixels`}function ye(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function tt(e){const t=e.fillModes instanceof Uint8Array?e.fillModes.length:Number.MAX_SAFE_INTEGER;return Math.max(0,Math.min(Math.floor(e.count??0),Math.floor((e.positions?.length??0)/2),e.paletteIndices?.length??0,t))}function un(e,t){return!e&&!t?!0:!e||!t?!1:Math.abs((e.zoom??0)-(t.zoom??0))<1e-6&&Math.abs((e.offsetX??0)-(t.offsetX??0))<1e-6&&Math.abs((e.offsetY??0)-(t.offsetY??0))<1e-6&&Math.abs((e.rotationDeg??0)-(t.rotationDeg??0))<1e-6}function Ji(e){const t=String(e??"").trim();if(!t)return"";if(/^bearer\s+/i.test(t)){const n=t.replace(/^bearer\s+/i,"").trim();return n?`Bearer ${n}`:""}return`Bearer ${t}`}function Yr(e){const n=String(e??"").trim().match(/^#?([0-9a-fA-F]{6})$/);if(!n)return[...Sn];const r=Number.parseInt(n[1],16);return[r>>16&255,r>>8&255,r&255,255]}function eo(e){const t=[[...Sn]],n=new Map;for(const i of e??[]){const o=String(i?.termId??"");!o||n.has(o)||(n.set(o,t.length),t.push(Yr(i?.termColor)))}const r=new Uint8Array(t.length*4);for(let i=0;i<t.length;i+=1)r[i*4]=t[i][0],r[i*4+1]=t[i][1],r[i*4+2]=t[i][2],r[i*4+3]=t[i][3];return{colors:r,termToPaletteIndex:n}}const to=[6,4,2],no=64,ro=.04,io=1,oo=4,Ut=1e-6,so=.1;function ao(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const n of e){if(!Array.isArray(n)||n.length<2)continue;const r=Number(n[0]),i=Number(n[1]);if(!Number.isFinite(r)||!Number.isFinite(i))continue;const o=t[t.length-1];o&&Math.abs(o[0]-r)<1e-9&&Math.abs(o[1]-i)<1e-9||t.push([r,i])}return t}function Zn(e,t,n){if(t<=Ut||n<8)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([e[0]+Math.cos(o)*t,e[1]+Math.sin(o)*t])}return Be(r)}function lo(e,t,n,r){const i=t[0]-e[0],o=t[1]-e[1],s=Math.sqrt(i*i+o*o);if(!Number.isFinite(s)||s<=r)return[];const a=i/s,u=-(o/s),f=a,c=Math.max(Ut,n);return Be([[e[0]+u*c,e[1]+f*c],[t[0]+u*c,t[1]+f*c],[t[0]-u*c,t[1]-f*c],[e[0]-u*c,e[1]-f*c]])}function $n(e,t){if(!e.length)return[];let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,l]of e)a<n&&(n=a),a>i&&(i=a),l<r&&(r=l),l>o&&(o=l);if(!Number.isFinite(n)||!Number.isFinite(r))return[];const s=Math.max(t,1);return Be([[n-s,r-s],[i+s,r-s],[i+s,o+s],[n-s,o+s]])}function St(e,t){return Be(t?e.map(([n,r])=>[O(n,t[0],t[2]),O(r,t[1],t[3])]):e)}function Kn(e,t){return Number.isFinite(e)?Number(e.toFixed(t)):e}function co(e,t){if(!Array.isArray(e)||e.length===0)return[];const n=[];for(const r of e){if(!Array.isArray(r)||r.length<2)continue;const i=Kn(Number(r[0]),t),o=Kn(Number(r[1]),t);if(!Number.isFinite(i)||!Number.isFinite(o))continue;const s=n[n.length-1];(!s||s[0]!==i||s[1]!==o)&&n.push([i,o])}if(n.length>=2){const r=n[0],i=n[n.length-1];if(!r||!i)return[];(r[0]!==i[0]||r[1]!==i[1])&&n.push([r[0],r[1]])}return n.length>=4?n:[]}function uo(e,t){if(!Array.isArray(e)||e.length===0)return[];const n=e.map(r=>co(r,t)).filter(r=>r.length>=4);return n.length>0?n:[]}function fo(e,t){const n=e.map(i=>uo(i,t)).filter(i=>i.length>0);if(n.length===0)return null;let r=[n[0]];try{for(let i=1;i<n.length;i+=1)if(r=Ki.union(r,[n[i]]),!Array.isArray(r)||r.length===0)return null}catch(i){return console.error("buildBrushStrokePolygon union failed",t,i),null}return r.length>0?r:null}function ho(e){if(e.length===0)return null;for(const t of to){const n=fo(e,t);if(n)return n}return null}function mo(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const n of e){if(!Array.isArray(n)||n.length<2)continue;const r=Number(n[0]),i=Number(n[1]);!Number.isFinite(r)||!Number.isFinite(i)||t.push([r,i])}return Be(t)}function go(e){let t=[],n=0;for(const r of e){if(!Array.isArray(r)||r.length===0)continue;const i=mo(r[0]??[]);if(i.length<4)continue;const o=Math.abs(dt(i));o<=n||(n=o,t=i)}return t}function po(e,t=1e-9){const n=Be(e);if(n.length<5)return n;const r=[n[0]];for(let i=1;i<n.length-1;i+=1){const o=r[r.length-1],s=n[i],a=n[i+1],l=(s[0]-o[0])*(a[1]-s[1])-(s[1]-o[1])*(a[0]-s[0]);Math.abs(l)<=t||r.push(s)}return r.push(r[0]),Be(r)}function yo(e,t,n){const r=n[0]-t[0],i=n[1]-t[1],o=r*r+i*i;if(o<=1e-12){const c=e[0]-t[0],h=e[1]-t[1];return c*c+h*h}const s=O(((e[0]-t[0])*r+(e[1]-t[1])*i)/o,0,1),a=t[0]+r*s,l=t[1]+i*s,u=e[0]-a,f=e[1]-l;return u*u+f*f}function bo(e,t){if(e.length<=2||t<=0)return e.slice();const n=new Uint8Array(e.length);n[0]=1,n[e.length-1]=1;const r=t*t,i=[[0,e.length-1]];for(;i.length>0;){const s=i.pop();if(!s)break;const[a,l]=s;if(l-a<=1)continue;let u=0,f=-1;for(let c=a+1;c<l;c+=1){const h=yo(e[c],e[a],e[l]);h>u&&(u=h,f=c)}f>=0&&u>r&&(n[f]=1,i.push([a,f],[f,l]))}const o=[];for(let s=0;s<e.length;s+=1)n[s]&&o.push(e[s]);return o}function wo(e,t){const n=Be(e);if(n.length<5||t<=0)return n;const r=n.slice(0,-1),i=bo(r,t);return i.length<3?n:Be(i)}function xo(e,t){let n=Be(e);if(t<=0||n.length<5)return n;for(let r=0;r<t;r+=1){const i=n.slice(0,-1);if(i.length<3)break;const o=[];for(let s=0;s<i.length;s+=1){const a=i[s],l=i[(s+1)%i.length];o.push([a[0]*.75+l[0]*.25,a[1]*.75+l[1]*.25],[a[0]*.25+l[0]*.75,a[1]*.25+l[1]*.75])}n=Be(o)}return n}function So(e,t){const n=ao(e),r=Math.max(Ut,Number(t.radius)||0);if(n.length===0||!Number.isFinite(r))return[];const i=Math.max(12,Math.floor(t.circleSides||no));if(n.length===1)return St(Zn(n[0],r,i),t.clipBounds);const o=[],s=Math.max(Ut,r*so);for(let h=0;h<n.length;h+=1){const d=n[h],m=Zn(d,r,i);if(m.length>=4&&o.push([m]),h===0)continue;const p=lo(n[h-1],d,r,s);p.length>=4&&o.push([p])}const a=ho(o),l=a?go(a):[];if(!l.length)return St($n(n,r),t.clipBounds);const u=typeof t.simplifyTolerance=="number"&&Number.isFinite(t.simplifyTolerance)?Math.max(0,t.simplifyTolerance):Math.max(.25,r*ro),f=typeof t.smoothingPasses=="number"&&Number.isFinite(t.smoothingPasses)?Math.round(O(t.smoothingPasses,0,oo)):io,c=wo(xo(po(l,1e-9),f),u);return c.length<4?St($n(n,r),t.clipBounds):St(c,t.clipBounds)}const et=[],jn=[],Ge={color:"#ff4d4f",width:2,lineDash:et,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},Wr={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},Xr="rgba(23, 23, 25, 0.1)",Vr=6,Oe={fontFamily:"Pretendard, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:11,fontWeight:600,textColor:"#171719",backgroundColor:"#FFCC00",borderColor:"rgba(0, 0, 0, 0)",borderWidth:0,paddingX:8,paddingY:4,offsetY:10,borderRadius:4},$e={fontFamily:"Pretendard, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:13,fontWeight:500,textColor:"#FFFFFF",backgroundColor:"rgba(23, 23, 25, 0.5)",borderRadius:4,paddingX:6,paddingY:3},Qn={x:16,y:-24},Eo=20,Jn=1e-6,er="transparent",Ro=3,Mo=2,Gr=96,Ao=1,tr=1e3,qr=2,Hr=2,vo=4096,Co=.2,Io=1.12,Po=.89,To=32,_o="#000000",Lo=.1,Fo="#FFCF00",ko="#FF0000",No=1.5,nr=[2,2],Bo=1,zo=.25,Do=4,Uo=1,Oo=0,Yo=4,Wo=1.5;function Ot(e,t,n){return[O(e[0],0,t),O(e[1],0,n)]}function Rn(e){if(!Array.isArray(e)||e.length<2)return null;const t=Number(e[0]),n=Number(e[1]);return!Number.isFinite(t)||!Number.isFinite(n)?null:[t,n]}const Ye=Rn;function Fe(e){return Be(e)}function Ft(e){return Math.abs(dt(Fe(e)))}function rr(e){if(!Array.isArray(e)||e.length===0)return[0,0,0,0];let t=1/0,n=1/0,r=-1/0,i=-1/0;for(const[o,s]of e)o<t&&(t=o),o>r&&(r=o),s<n&&(n=s),s>i&&(i=s);return[t,n,r,i]}function fn(e,t,n=!1){if(t.length!==0){e.moveTo(t[0][0],t[0][1]);for(let r=1;r<t.length;r+=1)e.lineTo(t[r][0],t[r][1]);n&&e.closePath()}}function Te(e,t,n,r=!1,i=!1,o="rgba(255, 77, 79, 0.16)"){t.length!==0&&(e.beginPath(),fn(e,t,r),i&&r&&(e.fillStyle=o,e.fill()),e.strokeStyle=n.color,e.lineWidth=n.width,e.lineJoin=n.lineJoin,e.lineCap=n.lineCap,e.shadowColor=n.shadowColor,e.shadowBlur=n.shadowBlur,e.shadowOffsetX=n.shadowOffsetX,e.shadowOffsetY=n.shadowOffsetY,e.setLineDash(n.lineDash),e.stroke(),e.setLineDash(et),e.shadowColor="rgba(0, 0, 0, 0)",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0)}function Mn(e){const t=Array.isArray(e?.lineDash)?e.lineDash.filter(s=>Number.isFinite(s)&&s>=0):et,n=typeof e?.width=="number"&&Number.isFinite(e.width)?Math.max(0,e.width):Ge.width,r=typeof e?.shadowBlur=="number"&&Number.isFinite(e.shadowBlur)?Math.max(0,e.shadowBlur):Ge.shadowBlur,i=typeof e?.shadowOffsetX=="number"&&Number.isFinite(e.shadowOffsetX)?e.shadowOffsetX:Ge.shadowOffsetX,o=typeof e?.shadowOffsetY=="number"&&Number.isFinite(e.shadowOffsetY)?e.shadowOffsetY:Ge.shadowOffsetY;return{color:e?.color||Ge.color,width:n,lineDash:t.length?t:et,lineJoin:e?.lineJoin||Ge.lineJoin,lineCap:e?.lineCap||Ge.lineCap,shadowColor:e?.shadowColor||Ge.shadowColor,shadowBlur:r,shadowOffsetX:i,shadowOffsetY:o}}function qe(e,t){return t?Mn({color:t.color??e.color,width:t.width??e.width,lineDash:t.lineDash??e.lineDash,lineJoin:t.lineJoin??e.lineJoin,lineCap:t.lineCap??e.lineCap,shadowColor:t.shadowColor??e.shadowColor,shadowBlur:t.shadowBlur??e.shadowBlur,shadowOffsetX:t.shadowOffsetX??e.shadowOffsetX,shadowOffsetY:t.shadowOffsetY??e.shadowOffsetY}):e}function Yt(e,t){return e==null||t===null||t===void 0?!1:String(e)===String(t)}function ir(e){return typeof e=="number"&&Number.isFinite(e)}function Xo(e){return Array.isArray(e)&&e.length>=2&&ir(e[0])&&ir(e[1])}function Vo(e){return Array.isArray(e)&&e.length>=2&&e.every(t=>Xo(t))}function Zr(e,t){if(!(!Array.isArray(e)||e.length===0)){if(Vo(e)){t.push(e.map(([n,r])=>[n,r]));return}for(const n of e)Zr(n,t)}}function or(e,t){const n=[];Zr(e,n);const r=[];for(const i of n){if(i.length<2)continue;const o=t?Fe(i):i;o.length>=(t?4:2)&&r.push(o)}return r}function ft(e,t){return typeof e!="number"||!Number.isFinite(e)||e<=0?t:e}function Go(e,t){return typeof e!="number"||!Number.isFinite(e)?t:O(e,0,1)}function $r(e,t,n,r,i,o){const s=Math.max(0,Math.min(o,r*.5,i*.5));e.beginPath(),e.moveTo(t+s,n),e.lineTo(t+r-s,n),e.quadraticCurveTo(t+r,n,t+r,n+s),e.lineTo(t+r,n+i-s),e.quadraticCurveTo(t+r,n+i,t+r-s,n+i),e.lineTo(t+s,n+i),e.quadraticCurveTo(t,n+i,t,n+i-s),e.lineTo(t,n+s),e.quadraticCurveTo(t,n,t+s,n),e.closePath()}function qo(e){const t=e[0];return Array.isArray(t)&&Array.isArray(t[0])}function Wt(e,t,n){if(!e||!t)return[];if(n){const r=n.worldToScreen(e[0],e[1]),i=n.worldToScreen(t[0],t[1]);if(r&&i){const o=[[r[0],r[1]],[i[0],r[1]],[i[0],i[1]],[r[0],i[1]]],s=[];for(const a of o){const l=n.screenToWorld(a);if(!l)return Wt(e,t);s.push(l)}return Fe(s)}}return Fe([[e[0],e[1]],[t[0],e[1]],[t[0],t[1]],[e[0],t[1]]])}function hn(e,t,n=Gr){if(!e||!t)return[];const r=(e[0]+t[0])*.5,i=(e[1]+t[1])*.5,o=Math.hypot(t[0]-e[0],t[1]-e[1])*.5;if(o<1)return[];const s=[];for(let a=0;a<=n;a+=1){const l=a/n*Math.PI*2;s.push([r+Math.cos(l)*o,i+Math.sin(l)*o])}return Fe(s)}function Xt(e){const t=Ur(yt(e));if(t.length===0)return[];const n=[];for(const r of t){const i=r[0];if(!i||i.length<4)continue;const o=i.map(([a,l])=>[a,l]),s=[];for(let a=1;a<r.length;a+=1){const l=r[a];!l||l.length<4||s.push(l.map(([u,f])=>[u,f]))}n.push({outer:o,holes:s})}return n}function Ho(e){if(!Array.isArray(e))return nr;const t=e.filter(n=>Number.isFinite(n)&&n>=0);return t.length>0?t:nr}function Zo(e){return typeof e!="number"||!Number.isFinite(e)?Bo:O(e,zo,Do)}function $o(e){return typeof e!="number"||!Number.isFinite(e)?Uo:Math.round(O(e,Oo,Yo))}function Ko(e){const t=ft(e?.radius,To),n=ft(e?.cursorLineWidth,No),r=Zo(e?.edgeDetail),i=$o(e?.edgeSmoothing);return{radius:t,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:e?.clickSelectRoi===!0,fillColor:e?.fillColor||_o,fillOpacity:Go(e?.fillOpacity,Lo),cursorColor:e?.cursorColor||Fo,cursorActiveColor:e?.cursorActiveColor||ko,cursorLineWidth:n,cursorLineDash:Ho(e?.cursorLineDash)}}function jo(e,t,n){if(!t.isDrawing||t.screenPoints.length===0)return;const r=t.screenPoints;if(r.length===0)return;const i=n.radius;if(!(!Number.isFinite(i)||i<=0)){if(e.save(),e.globalAlpha=n.fillOpacity,e.fillStyle=n.fillColor,e.strokeStyle=n.fillColor,e.lineCap="round",e.lineJoin="round",e.lineWidth=i*2,r.length===1)e.beginPath(),e.arc(r[0][0],r[0][1],i,0,Math.PI*2),e.fill();else{e.beginPath(),e.moveTo(r[0][0],r[0][1]);for(let o=1;o<r.length;o+=1)e.lineTo(r[o][0],r[o][1]);e.stroke()}e.restore()}}function Qo(e,t,n,r){const i=t.cursor;if(!i)return;const o=t.cursorScreen??Ye(n?.worldToScreen(i[0],i[1])??[]);if(!o)return;const s=r.radius;!Number.isFinite(s)||s<=0||(e.save(),e.beginPath(),e.arc(o[0],o[1],s,0,Math.PI*2),e.strokeStyle=t.isDrawing?r.cursorActiveColor:r.cursorColor,e.lineWidth=r.cursorLineWidth,e.setLineDash(r.cursorLineDash),e.stroke(),e.setLineDash(et),e.restore())}const Jo=.58,es=4096,ts=.5;let Et=null;const Rt=new Map;function ns(){if(Et)return Et;if(typeof document>"u")return null;const t=document.createElement("canvas").getContext("2d");return t?(Et=t,Et):null}function An(e,t){const n=`${t.fontWeight}|${t.fontSize}|${t.fontFamily}|${e}`,r=Rt.get(n);if(r!==void 0)return r;const i=e.length*t.fontSize*Jo,o=ns();let s=i;if(o){o.font=`${t.fontWeight} ${t.fontSize}px ${t.fontFamily}`;const a=o.measureText(e).width;Number.isFinite(a)&&a>=0&&(s=a)}return Rt.size>es&&Rt.clear(),Rt.set(n,s),s}function rs(e,t="top-center"){if(!e.length)return null;let n=1/0;for(const o of e)o[1]<n&&(n=o[1]);if(!Number.isFinite(n))return null;let r=1/0,i=-1/0;for(const o of e)Math.abs(o[1]-n)>ts||(o[0]<r&&(r=o[0]),o[0]>i&&(i=o[0]));return!Number.isFinite(r)||!Number.isFinite(i)?null:t==="top-center"?[(r+i)*.5,n]:[r,n]}function vn(e,t="top-center"){let n=null;for(const r of e){const i=rs(r.outer,t);i&&(!n||i[1]<n[1]||i[1]===n[1]&&i[0]<n[0])&&(n=i)}return n}function Cn(e){const t=typeof e?.paddingX=="number"&&Number.isFinite(e.paddingX)?Math.max(0,e.paddingX):Oe.paddingX,n=typeof e?.paddingY=="number"&&Number.isFinite(e.paddingY)?Math.max(0,e.paddingY):Oe.paddingY,r=typeof e?.fontSize=="number"&&Number.isFinite(e.fontSize)?Math.max(8,e.fontSize):Oe.fontSize,i=typeof e?.borderWidth=="number"&&Number.isFinite(e.borderWidth)?Math.max(0,e.borderWidth):Oe.borderWidth,o=typeof e?.offsetY=="number"&&Number.isFinite(e.offsetY)?e.offsetY:Oe.offsetY,s=typeof e?.borderRadius=="number"&&Number.isFinite(e.borderRadius)?Math.max(0,e.borderRadius):Oe.borderRadius;return{fontFamily:e?.fontFamily||Oe.fontFamily,fontSize:r,fontWeight:e?.fontWeight||Oe.fontWeight,textColor:e?.textColor||Oe.textColor,backgroundColor:e?.backgroundColor||Oe.backgroundColor,borderColor:e?.borderColor||Oe.borderColor,borderWidth:i,paddingX:t,paddingY:n,offsetY:o,borderRadius:s}}function In(e,t){return t?Cn({fontFamily:t.fontFamily??e.fontFamily,fontSize:t.fontSize??e.fontSize,fontWeight:t.fontWeight??e.fontWeight,textColor:t.textColor??e.textColor,backgroundColor:t.backgroundColor??e.backgroundColor,borderColor:t.borderColor??e.borderColor,borderWidth:t.borderWidth??e.borderWidth,paddingX:t.paddingX??e.paddingX,paddingY:t.paddingY??e.paddingY,offsetY:t.offsetY??e.offsetY,borderRadius:t.borderRadius??e.borderRadius}):e}function Pn(e,t,n,r){if(!e||!n)return 0;const i=Number(n.minZoom),o=Number(n.maxZoom);if(!Number.isFinite(i)||!Number.isFinite(o)||o-i<=Jn||!Number.isFinite(t))return 0;let s=o;r!=null&&Number.isFinite(r)&&(s=O(r,i,o));const a=Math.max(Jn,Math.abs(s)*1e-9);return t>=s-a?Eo:0}function is(e){const t=typeof e?.fontSize=="number"&&Number.isFinite(e.fontSize)?Math.max(8,e.fontSize):$e.fontSize,n=typeof e?.borderRadius=="number"&&Number.isFinite(e.borderRadius)?Math.max(0,e.borderRadius):$e.borderRadius,r=typeof e?.paddingX=="number"&&Number.isFinite(e.paddingX)?Math.max(0,e.paddingX):$e.paddingX,i=typeof e?.paddingY=="number"&&Number.isFinite(e.paddingY)?Math.max(0,e.paddingY):$e.paddingY;return{fontFamily:e?.fontFamily||$e.fontFamily,fontSize:t,fontWeight:e?.fontWeight||$e.fontWeight,textColor:e?.textColor||$e.textColor,backgroundColor:e?.backgroundColor||$e.backgroundColor,borderRadius:n,paddingX:r,paddingY:i}}function os(e){const t=typeof e?.x=="number"&&Number.isFinite(e.x)?e.x:Qn.x,n=typeof e?.y=="number"&&Number.isFinite(e.y)?e.y:Qn.y;return{x:t,y:n}}function ss(e){return Number.isFinite(e)?`${Math.max(0,e).toFixed(3)} mm²`:"0.000 mm²"}function as(e){const t=typeof e?.format=="function"?e.format:ss,n=os(e?.cursorOffset);return{enabled:e?.enabled===!0,format:t,style:is(e?.style),cursorOffsetX:n.x,cursorOffsetY:n.y}}function Kr(e,t,n,r,i,o,s=!0){const a=t.trim();if(!a)return;e.save(),e.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,e.textAlign="center",e.textBaseline="middle";const u=An(a,o)+o.paddingX*2,f=o.fontSize+o.paddingY*2,c=n[0],h=n[1]-o.offsetY,d=s?O(c,u*.5+1,r-u*.5-1):c,m=s?O(h,f*.5+1,i-f*.5-1):h,p=d-u*.5,y=m-f*.5;e.fillStyle=o.backgroundColor,e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,$r(e,p,y,u,f,o.borderRadius),e.fill(),o.borderWidth>0&&e.stroke(),e.fillStyle=o.textColor,e.fillText(a,d,m+.5),e.restore()}function ls(e,t,n,r,i,o,s,a){const l=t.trim();if(!l)return;e.save(),e.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,e.textAlign="center",e.textBaseline="middle";const f=An(l,o)+o.paddingX*2,c=o.fontSize+o.paddingY*2,h=O(n[0]+s,f*.5+1,r-f*.5-1),d=O(n[1]+a,c*.5+1,i-c*.5-1),m=h-f*.5,p=d-c*.5;e.fillStyle=o.backgroundColor,$r(e,m,p,f,c,o.borderRadius),e.fill(),e.fillStyle=o.textColor,e.fillText(l,h,d+.5),e.restore()}function cs(e,t,n,r){if(!(t.length<4||n.length===0)){e.save(),e.beginPath(),fn(e,t,!0);for(const i of n)i.length<4||fn(e,i,!0);e.fillStyle=r,e.fill("evenodd"),e.restore()}}function jr(e){const{ctx:t,overlayShapes:n,imageOuterRing:r,worldToScreenPoints:i,baseStrokeStyle:o,onInvertedFillDebug:s}=e,a=!!globalThis.__OPEN_PLANT_DEBUG_OVERLAY__;for(let l=0;l<n.length;l+=1){const u=n[l];if(!u?.coordinates?.length||u.visible===!1)continue;const f=u.closed??qo(u.coordinates),c=or(u.coordinates,f);if(u.invertedFill?.fillColor){const d=[],m=or(u.coordinates,!0);for(const p of m){const y=i(p);y.length>=4&&d.push(y)}a&&s&&s({id:u.id??l,outerRingPoints:r.length,sourceRingCount:m.length,holeRingCount:d.length,fillColor:u.invertedFill.fillColor}),cs(t,r,d,u.invertedFill.fillColor)}if(c.length===0)continue;const h=qe(o,u.stroke??u.strokeStyle);for(const d of c){const m=i(d);m.length<2||Te(t,m,h,f,u.fill??!1)}}}function Mt(e){return typeof e=="string"&&(e==="stamp-rectangle"||e==="stamp-circle"||e==="stamp-rectangle-4096px"||e==="stamp-rectangle-2mm2"||e==="stamp-circle-2mm2"||e==="stamp-circle-hpf-0.2mm2")}function us(e){return{rectangleAreaMm2:ft(e?.rectangleAreaMm2,qr),circleAreaMm2:ft(e?.circleAreaMm2,Hr),rectanglePixelSize:ft(e?.rectanglePixelSize,vo)}}const sr=1e3;function fs(e){return e*sr*sr}function ar(e,t,n){if(!e||!Number.isFinite(t)||t<=0)return[];if(n){const r=n.worldToScreen(e[0],e[1]),i=n.worldToScreen(e[0]+t,e[1]);if(r&&i){const o=Math.hypot(i[0]-r[0],i[1]-r[1]),s=[[r[0]-o,r[1]-o],[r[0]+o,r[1]-o],[r[0]+o,r[1]+o],[r[0]-o,r[1]+o]],a=[];for(const l of s){const u=n.screenToWorld(l);if(!u)throw new Error("Failed to create rectangle");a.push(u)}return Fe(a)}}return Fe([[e[0]-t,e[1]-t],[e[0]+t,e[1]-t],[e[0]+t,e[1]+t],[e[0]-t,e[1]+t]])}function hs(e,t,n=Gr){if(!e||!Number.isFinite(t)||t<=0)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([e[0]+Math.cos(o)*t,e[1]+Math.sin(o)*t])}return Fe(r)}function ds(e){const{stampTool:t,center:n,resolvedStampOptions:r,imageWidth:i,imageHeight:o,micronsToWorldPixels:s,getRectangleProjection:a}=e;if(!n)return[];if(t==="stamp-rectangle-4096px"){const c=r.rectanglePixelSize*.5;return ar(n,c,a()).map(h=>Ot(h,i,o))}let l=0;if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"?l=t==="stamp-rectangle-2mm2"?qr:r.rectangleAreaMm2:(t==="stamp-circle"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2")&&(l=t==="stamp-circle-hpf-0.2mm2"?Co:t==="stamp-circle-2mm2"?Hr:r.circleAreaMm2),!Number.isFinite(l)||l<=0)return[];const u=fs(l);let f=[];if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"){const c=s(Math.sqrt(u)*.5);f=ar(n,c,a())}else if(t==="stamp-circle"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2"){const c=s(Math.sqrt(u/Math.PI));f=hs(n,c)}return f.length?f.map(c=>Ot(c,i,o)):[]}function ms(e){return{color:Xr,width:Vr,lineDash:et,lineJoin:e.lineJoin,lineCap:e.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function gs(e){if(typeof e!="string")return er;const t=e.trim();return t.length>0?t:er}function lr(e){return Array.isArray(e)&&e.length>=4&&Ft(e)>Ao}function Qr({tool:e,imageWidth:t,imageHeight:n,imageMpp:r,imageZoom:i,stampOptions:o,brushOptions:s,projectorRef:a,onBrushTap:l,onDrawComplete:u,onPatchComplete:f,enabled:c,viewStateSignal:h,persistedRegions:d,patchRegions:m,persistedPolygons:p,drawFillColor:y,regionStrokeStyle:b,regionStrokeHoverStyle:x,regionStrokeActiveStyle:C,patchStrokeStyle:S,resolveRegionStrokeStyle:A,resolveRegionLabelStyle:_,overlayShapes:Y,hoveredRegionId:B=null,activeRegionId:G=null,regionLabelStyle:z,drawAreaTooltip:$,autoLiftRegionLabelAtMaxZoom:Q=!1,regionLabelAnchor:P="top-center",clampRegionLabelToViewport:W=!0,regionLabelAutoLiftOffsetPx:N,invalidateRef:k,className:K,style:me}){const ie=g.useRef(null),ve=g.useRef(!1),Se=g.useRef(new Map),Ce=g.useRef(e),v=g.useRef({isDrawing:!1,pointerId:null,start:null,current:null,cursor:null,cursorScreen:null,points:[],screenPoints:[],stampCenter:null}),M=c??e!=="cursor",X=g.useMemo(()=>d&&d.length>0?d:!p||p.length===0?jn:p.map((w,E)=>({id:E,coordinates:w})),[d,p]),fe=g.useMemo(()=>m??jn,[m]),J=g.useMemo(()=>{const w=[];for(let E=0;E<X.length;E+=1){const T=X[E],L=Xt(T.coordinates);L.length!==0&&w.push({region:T,regionIndex:E,regionKey:T.id??E,polygons:L})}return w},[X]),ae=g.useMemo(()=>{const w=[];for(let E=0;E<fe.length;E+=1){const T=fe[E],L=Xt(T.coordinates);L.length!==0&&w.push({region:T,regionIndex:E,regionKey:T.id??E,polygons:L})}return w},[fe]),le=g.useMemo(()=>Mn(b),[b]),ge=g.useMemo(()=>qe(le,x),[le,x]),oe=g.useMemo(()=>qe(le,C),[le,C]),ne=g.useMemo(()=>qe(Wr,S),[S]),be=g.useMemo(()=>gs(y),[y]),he=g.useMemo(()=>Cn(z),[z]),D=g.useMemo(()=>as($),[$]),H=g.useMemo(()=>us(o),[o]),q=g.useMemo(()=>Ko(s),[s]),ee=g.useMemo(()=>({position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",touchAction:"none",pointerEvents:M?"auto":"none",cursor:M?e==="brush"?"none":"crosshair":"default",...me}),[M,e,me]),te=g.useCallback(()=>{const w=ie.current;if(!w)return;const E=w.getBoundingClientRect(),T=Math.max(1,window.devicePixelRatio||1),L=Math.max(1,Math.round(E.width*T)),j=Math.max(1,Math.round(E.height*T));(w.width!==L||w.height!==j)&&(w.width=L,w.height=j)},[]),ce=g.useCallback(w=>{const E=a.current;if(!E||w.length===0)return[];const T=new Array(w.length);for(let L=0;L<w.length;L+=1){const j=Ye(E.worldToScreen(w[L][0],w[L][1]));if(!j)return[];T[L]=j}return T},[a]),Ee=g.useCallback(w=>{const E=a.current,T=ie.current;if(!E||!T)return null;const L=T.getBoundingClientRect(),j=Ye(E.screenToWorld(L.left+w[0],L.top+w[1]));return j?Ot(j,t,n):null},[a,t,n]),we=g.useCallback(()=>{const w=a.current,E=w?.getViewState?.().rotationDeg??0;if(!(Math.abs(E%360)<.01||!w))return{worldToScreen:(T,L)=>Ye(w.worldToScreen(T,L)),screenToWorld:Ee}},[a,Ee]),xe=g.useCallback(w=>{if(!Number.isFinite(w)||w<=0)return 0;const E=typeof r=="number"&&Number.isFinite(r)&&r>0?r:1,T=typeof i=="number"&&Number.isFinite(i)?i:0,L=a.current?.getViewState?.().zoom,j=typeof L=="number"&&Number.isFinite(L)&&L>0?L:1,Me=T+Math.log2(j),ue=Math.max(1e-9,En(E,T,Me));return w/ue/j},[r,i,a]),pe=g.useCallback((w,E)=>ds({stampTool:w,center:E,resolvedStampOptions:H,imageWidth:t,imageHeight:n,micronsToWorldPixels:xe,getRectangleProjection:we}),[xe,t,n,H,we]),F=g.useCallback(()=>{const w=v.current;return Mt(e)?pe(e,w.stampCenter):e==="brush"?[]:w.isDrawing?e==="freehand"?w.points:e==="rectangle"?Wt(w.start,w.current,we()):e==="circular"?hn(w.start,w.current):[]:[]},[e,pe,we]),V=g.useCallback(()=>{te();const w=ie.current;if(!w)return;const E=w.getContext("2d");if(!E)return;const T=Math.max(1,window.devicePixelRatio||1),L=w.width/T,j=w.height/T;if(E.setTransform(1,0,0,1,0,0),E.clearRect(0,0,w.width,w.height),E.setTransform(T,0,0,T,0,0),J.length>0)for(const ue of J){const{region:de,polygons:Re,regionIndex:Ae,regionKey:ke}=ue,Ue=Yt(G,ke)?"active":Yt(B,ke)?"hover":"default";let Ze=Ue==="active"?oe:Ue==="hover"?ge:le;if(A){const xt=A({region:de,regionId:ke,regionIndex:Ae,state:Ue});Ze=qe(Ze,xt||void 0)}const wt=Ue==="default"?null:ms(Ze);for(const xt of Re){const Ht=ce(xt.outer);Ht.length>=4&&(wt&&Te(E,Ht,wt,!0,!1),Te(E,Ht,Ze,!0,!1));for(const yi of xt.holes){const Zt=ce(yi);Zt.length>=4&&(wt&&Te(E,Zt,wt,!0,!1),Te(E,Zt,Ze,!0,!1))}}}if(ae.length>0)for(const ue of ae)for(const de of ue.polygons){const Re=ce(de.outer);Re.length>=4&&Te(E,Re,ne,!0,!1);for(const Ae of de.holes){const ke=ce(Ae);ke.length>=4&&Te(E,ke,ne,!0,!1)}}if(Array.isArray(Y)&&Y.length>0){const ue=ce(Fe([[0,0],[t,0],[t,n],[0,n]]));jr({ctx:E,overlayShapes:Y,imageOuterRing:ue,worldToScreenPoints:ce,baseStrokeStyle:le,onInvertedFillDebug:globalThis.__OPEN_PLANT_DEBUG_OVERLAY__?de=>{const Re=String(de.id),Ae=`${de.outerRingPoints}|${de.sourceRingCount}|${de.holeRingCount}|${de.fillColor}`;Se.current.get(Re)!==Ae&&(Se.current.set(Re,Ae),console.debug("[open-plant] invertedFill",de))}:void 0})}const Me=F();if(M){if(e==="brush")jo(E,v.current,q),Qo(E,v.current,a.current,q);else if(Me.length>0)if(e==="freehand"){const ue=ce(Me);ue.length>=2&&Te(E,ue,le,!1,!1),ue.length>=3&&Te(E,ce(Fe(Me)),le,!0,!0,be)}else{const ue=ce(Me);ue.length>=4&&Te(E,ue,le,!0,!0,be)}}if(J.length>0){const ue=Math.max(1e-6,a.current?.getViewState?.().zoom??1),de=typeof N=="number"&&Number.isFinite(N)?Math.max(0,N):Pn(Q,ue,a.current?.getZoomRange?.(),a.current?.getRegionLabelAutoLiftCapZoom?.());for(const Re of J){if(!Re.region.label)continue;const Ae=vn(Re.polygons,P);if(!Ae)continue;const ke=Ye(a.current?.worldToScreen(Ae[0],Ae[1])??[]);if(!ke)continue;let Ue=In(he,_?.({region:Re.region,regionId:Re.regionKey,regionIndex:Re.regionIndex,zoom:ue}));de>0&&(Ue={...Ue,offsetY:Ue.offsetY+de}),Kr(E,Re.region.label,ke,L,j,Ue,W)}}if(D.enabled&&M&&(e==="freehand"||e==="rectangle"||e==="circular")){const ue=v.current;if(ue.isDrawing){const de=e==="freehand"?Fe(Me):Me;if(de.length>=4){const Re=Ft(de),Ae=typeof r=="number"&&Number.isFinite(r)&&r>0?r:0,ke=Ae>0?Re*Ae*Ae/(tr*tr):0,Ue=D.format(ke),Ze=ue.cursorScreen??(ue.current?Ye(a.current?.worldToScreen(ue.current[0],ue.current[1])??[]):null);Ze&&ls(E,Ue,Ze,L,j,D.style,D.cursorOffsetX,D.cursorOffsetY)}}}},[M,e,F,te,ce,t,n,a,J,Y,B,G,le,ge,oe,be,ae,ne,A,_,he,D,Q,P,W,N,r,q]),I=g.useCallback(()=>{ve.current||(ve.current=!0,requestAnimationFrame(()=>{ve.current=!1,V()}))},[V]),U=g.useCallback((w=!1)=>{const E=v.current,T=ie.current;T&&E.pointerId!==null&&T.hasPointerCapture(E.pointerId)&&T.releasePointerCapture(E.pointerId),E.isDrawing=!1,E.pointerId=null,E.start=null,E.current=null,E.points=[],E.screenPoints=[],E.stampCenter=null,w||(E.cursor=null,E.cursorScreen=null)},[]),Z=g.useCallback(w=>{const E=a.current;if(!E||t<=0||n<=0)return null;const T=Ye(E.screenToWorld(w.clientX,w.clientY));return T?Ot(T,t,n):null},[a,t,n]),re=g.useCallback(w=>{const E=ie.current;if(!E)return null;const T=E.getBoundingClientRect(),L=O(w.clientX-T.left,0,T.width),j=O(w.clientY-T.top,0,T.height);return!Number.isFinite(L)||!Number.isFinite(j)?null:[L,j]},[]),se=g.useCallback(()=>{const w=v.current;if(!w.isDrawing){U(!0),I();return}let E=[];if(e==="freehand")w.points.length>=Ro&&(E=Fe(w.points));else if(e==="rectangle")E=Wt(w.start,w.current,we());else if(e==="circular")E=hn(w.start,w.current);else if(e==="brush"){const T=w.points[w.points.length-1]??w.current??w.start;if(q.clickSelectRoi&&T&&w.points.length<=1&&l?.(T)){U(!0),I();return}const L=Math.max(.25,q.edgeDetail),j=w.screenPoints.length>0?w.screenPoints:ce(w.points),Me=Math.max(.5,q.radius*.04/L),ue=So(j,{radius:q.radius,circleSides:Math.max(16,Math.round(32*L)),simplifyTolerance:Me,smoothingPasses:q.edgeSmoothing}),de=[];for(const Re of ue){const Ae=Ee(Re);Ae&&de.push(Ae)}E=Fe(de)}(e==="freehand"||e==="rectangle"||e==="circular"||e==="brush")&&lr(E)&&u&&u({tool:e,intent:e==="brush"?"brush":"roi",coordinates:E,bbox:rr(E),areaPx:Ft(E)}),U(!0),I()},[e,u,U,I,ce,Ee,we,q.radius,q.edgeDetail,q.edgeSmoothing,q.clickSelectRoi,l]),Ie=g.useCallback((w,E)=>{const T=pe(w,E);if(!lr(T))return;const L=w==="stamp-rectangle-4096px"?"patch":"roi",j={tool:w,intent:L,coordinates:T,bbox:rr(T),areaPx:Ft(T)};u?.(j),L==="patch"&&f&&f(j)},[pe,u,f]),ze=g.useCallback((w,E,T)=>{const L=Math.max(Wo,q.radius*.1),j=L*L,Me=w.screenPoints[w.screenPoints.length-1];if(!Me){w.points.push(E),w.screenPoints.push(T),w.current=E;return}const ue=T[0]-Me[0],de=T[1]-Me[1];ue*ue+de*de>=j?(w.points.push(E),w.screenPoints.push(T)):(w.points[w.points.length-1]=E,w.screenPoints[w.screenPoints.length-1]=T),w.current=E},[q.radius]),Ve=g.useCallback(w=>{if(!M||e==="cursor"||w.button!==0)return;const E=Z(w);if(!E)return;const T=re(w);if(!T)return;if(w.preventDefault(),w.stopPropagation(),Mt(e)){const Me=v.current;Me.stampCenter=E,Ie(e,E),I();return}const L=ie.current;L&&L.setPointerCapture(w.pointerId);const j=v.current;j.isDrawing=!0,j.pointerId=w.pointerId,j.start=E,j.current=E,j.cursor=E,j.cursorScreen=T,j.points=e==="freehand"||e==="brush"?[E]:[],j.screenPoints=e==="brush"?[T]:[],I()},[M,e,Z,re,Ie,I]),qt=g.useCallback(w=>{if(!M||e==="cursor")return;const E=Z(w);if(!E)return;const T=re(w);if(!T)return;const L=v.current;if(L.cursor=E,L.cursorScreen=T,Mt(e)){L.stampCenter=E,w.preventDefault(),w.stopPropagation(),I();return}if(e==="brush"){if(!L.isDrawing||L.pointerId!==w.pointerId){I();return}w.preventDefault(),w.stopPropagation(),ze(L,E,T),I();return}if(!(!L.isDrawing||L.pointerId!==w.pointerId)){if(w.preventDefault(),w.stopPropagation(),e==="freehand"){const j=a.current,Me=Math.max(1e-6,j?.getViewState?.().zoom??1),ue=Mo/Me,de=ue*ue,Re=L.points[L.points.length-1];if(!Re)L.points.push(E);else{const Ae=E[0]-Re[0],ke=E[1]-Re[1];Ae*Ae+ke*ke>=de&&L.points.push(E)}}else L.current=E;I()}},[M,e,Z,re,I,a,ze]),nt=g.useCallback(w=>{const E=v.current;if(!E.isDrawing||E.pointerId!==w.pointerId)return;w.preventDefault(),w.stopPropagation();const T=Z(w),L=re(w);T&&(E.cursor=T,L&&(E.cursorScreen=L),e==="brush"?L&&ze(E,T,L):E.current=T);const j=ie.current;j&&j.hasPointerCapture(w.pointerId)&&j.releasePointerCapture(w.pointerId),se()},[se,Z,re,e,ze]),pi=g.useCallback(()=>{const w=v.current;let E=!1;e==="brush"&&!w.isDrawing&&w.cursor&&(w.cursor=null,w.cursorScreen=null,E=!0),Mt(e)&&w.stampCenter&&(w.stampCenter=null,E=!0),E&&I()},[e,I]);return g.useEffect(()=>{te(),I();const w=ie.current;if(!w)return;const E=new ResizeObserver(()=>{te(),I()});return E.observe(w),()=>{E.disconnect()}},[te,I]),g.useEffect(()=>{M||U(),I()},[M,I,U]),g.useEffect(()=>{Ce.current!==e&&(Ce.current=e,U(),I())},[e,U,I]),g.useEffect(()=>{I()},[h,X,Y,I]),g.useEffect(()=>{if(k)return k.current=I,()=>{k.current===I&&(k.current=null)}},[k,I]),g.useEffect(()=>{if(!M)return;const w=E=>{E.key==="Escape"&&(U(),I())};return window.addEventListener("keydown",w),()=>{window.removeEventListener("keydown",w)}},[M,U,I]),We.jsx("canvas",{ref:ie,className:K,style:ee,onPointerDown:Ve,onPointerMove:qt,onPointerUp:nt,onPointerCancel:nt,onPointerLeave:pi,onContextMenu:w=>{M&&w.preventDefault()},onWheel:w=>{if(!M)return;const E=ie.current,T=a.current;if(!E||typeof T?.zoomBy!="function")return;w.preventDefault(),w.stopPropagation();const L=E.getBoundingClientRect(),j=w.clientX-L.left,Me=w.clientY-L.top;T.zoomBy(w.deltaY<0?Io:Po,j,Me),I()}})}const Jr=g.createContext(null),ps=Jr.Provider;function at(){const e=g.useContext(Jr);if(!e)throw new Error("useViewerContext must be used within a <WsiViewer>");return e}function ys({tool:e="cursor",stampOptions:t,brushOptions:n,fillColor:r,areaTooltip:i,onComplete:o,onPatchComplete:s,onBrushTap:a}){const{source:l,rendererRef:u,rendererSerial:f,setInteractionLock:c}=at(),h=e!=="cursor";g.useEffect(()=>(c("drawing-layer",h),()=>c("drawing-layer",!1)),[h,c]);const d=g.useMemo(()=>u.current?.getViewState(),[f]);return l?We.jsx(Qr,{tool:e,enabled:h,imageWidth:l.width,imageHeight:l.height,imageMpp:l.mpp,imageZoom:l.maxTierZoom,stampOptions:t,brushOptions:n,drawFillColor:r,projectorRef:u,onBrushTap:a,viewStateSignal:d,drawAreaTooltip:i,onDrawComplete:o,onPatchComplete:s}):null}const cr="__overlay_layer__";function bs({shapes:e}){const{rendererRef:t,source:n,registerDrawCallback:r,unregisterDrawCallback:i,requestOverlayRedraw:o}=at(),s=g.useCallback(l=>{const u=t.current;if(!u||l.length===0)return[];const f=new Array(l.length);for(let c=0;c<l.length;c+=1){const h=Ye(u.worldToScreen(l[c][0],l[c][1]));if(!h)return[];f[c]=h}return f},[]),a=g.useRef({shapes:e,worldToScreenPoints:s,source:n});return a.current={shapes:e,worldToScreenPoints:s,source:n},g.useEffect(()=>(r(cr,30,u=>{const{shapes:f,worldToScreenPoints:c,source:h}=a.current;if(!Array.isArray(f)||f.length===0||!h)return;const d=c(Fe([[0,0],[h.width,0],[h.width,h.height],[0,h.height]]));jr({ctx:u,overlayShapes:f,imageOuterRing:d,worldToScreenPoints:c,baseStrokeStyle:Ge})}),()=>i(cr)),[r,i]),g.useEffect(()=>{o()},[e,o]),null}function ur(e){return String(e??"").replace(/\/+$/,"")}function ei(e){const t=String(e??"");return t.startsWith("/")?t:`/${t}`}function ws(e){const t=ur(e);if(!t)return"";if(/\/TileGroup\d+$/i.test(t))return t;let n=null;try{n=new URL(t)}catch{n=null}if(n){const r=`${n.protocol}//${n.host}`,i=ur(n.pathname||"");return/\/ims$/i.test(i)?`${r}${i}`:/\/tiles$/i.test(i)?`${r}${i}`:`${r}${i}/tiles`}return/\/ims$/i.test(t)?"/ims":/\/tiles$/i.test(t)?`${t}`:`${t}/tiles`}function xs(e,t){const n=e?.imsInfo??{},r=!!e?.imsInfo,i=Number(n.width??e?.width??0),o=Number(n.height??e?.height??0),s=Number(n.tileSize??e?.tileSize??0),a=Number(n.zoom??e?.zoom??0),l=String(n.path??e?.path??""),u=Number(n.mpp??e?.mpp??0);if(!i||!o||!s||!l)throw new Error("Incomplete image metadata: width/height/tileSize/path required");const f=Array.isArray(e?.terms)?e.terms.map(m=>({termId:String(m?.termId??""),termName:String(m?.termName??""),termColor:String(m?.termColor??"")})):[],c=ei(l),h=ws(t),d=e?.tileUrlBuilder??(r?(m,p,y)=>`${h}${c}/${m}/${y}_${p}.webp`:void 0);return{id:e?._id||e?.id||"unknown",name:e?.name||"unknown",width:i,height:o,mpp:Number.isFinite(u)&&u>0?u:void 0,tileSize:s,maxTierZoom:Number.isFinite(a)?Math.max(0,Math.floor(a)):0,tilePath:l,tileBaseUrl:t,terms:f,tileUrlBuilder:d}}function Tn(e,t,n,r){if(e.tileUrlBuilder)return e.tileUrlBuilder(t,n,r,e.tilePath,e.tileBaseUrl);const i=ei(e.tilePath);return`${e.tileBaseUrl}${i}/${t}/${r}_${n}.webp`}function Ss(e,t){if(!t)return!1;const n=new URL(e,typeof window<"u"?window.location.href:void 0).hostname.toLowerCase();return!(n.includes("amazonaws.com")||n.startsWith("s3.")||n.includes(".s3."))}const Ne={width:200,height:125,margin:16,position:"bottom-right",borderRadius:6,borderWidth:0,backgroundColor:"rgba(4, 10, 18, 0.88)",borderColor:"rgba(230, 244, 255, 0.35)",viewportBorderColor:"rgba(255, 106, 61, 0.95)",viewportBorderStyle:"dash",viewportFillColor:"transparent",interactive:!0,showThumbnail:!0,maxThumbnailTiles:16};function fr(e,t,n,r){const i=t.length;if(!(i<3)){for(let o=0;o<i;o+=1){const s=t[o],a=t[(o+1)%i],l=Math.hypot(a[0]-s[0],a[1]-s[1]);if(l<1e-6)continue;const u=Math.max(1,Math.round((l+r)/(n+r))),f=u*n+(u-1)*r,c=l/Math.max(1e-6,f),h=n*c,d=r*c;e.beginPath(),e.moveTo(s[0],s[1]),e.lineTo(a[0],a[1]),e.setLineDash([h,d]),e.lineDashOffset=0,e.stroke()}e.setLineDash([]),e.lineDashOffset=0}}function hr(e,t,n=1e-4){return Math.abs(e[0]-t[0])<=n&&Math.abs(e[1]-t[1])<=n}function dr(e){const t=[];for(const n of e){const r=t[t.length-1];(!r||!hr(r,n))&&t.push(n)}return t.length>1&&hr(t[0],t[t.length-1])&&t.pop(),t}function mr(e,t,n){const r=t[0]-e[0];if(Math.abs(r)<1e-6)return[n,e[1]];const i=(n-e[0])/r;return[n,e[1]+(t[1]-e[1])*i]}function gr(e,t,n){const r=t[1]-e[1];if(Math.abs(r)<1e-6)return[e[0],n];const i=(n-e[1])/r;return[e[0]+(t[0]-e[0])*i,n]}function Es(e,t,n,r,i){let o=dr(e);if(o.length<3)return[];const s=[{inside:a=>a[0]>=t,intersect:(a,l)=>mr(a,l,t)},{inside:a=>a[0]<=r,intersect:(a,l)=>mr(a,l,r)},{inside:a=>a[1]>=n,intersect:(a,l)=>gr(a,l,n)},{inside:a=>a[1]<=i,intersect:(a,l)=>gr(a,l,i)}];for(const a of s){if(o.length===0)return[];const l=o;o=[];let u=l[l.length-1],f=a.inside(u);for(const c of l){const h=a.inside(c);h?(f||o.push(a.intersect(u,c)),o.push(c)):f&&o.push(a.intersect(u,c)),u=c,f=h}o=dr(o)}return o.length>=3?o:[]}function it(e,t,n=1){return typeof e!="number"||!Number.isFinite(e)?t:Math.max(n,e)}function ct(e){return Array.isArray(e)&&e.length===4&&Number.isFinite(e[0])&&Number.isFinite(e[1])&&Number.isFinite(e[2])&&Number.isFinite(e[3])}const Rs={position:"absolute",top:4,right:4,zIndex:1,width:18,height:18,borderRadius:999,border:"1px solid rgba(255,255,255,0.4)",background:"rgba(16, 17, 19, 0.85)",color:"#fff",fontSize:12,lineHeight:1,cursor:"pointer",padding:0,display:"flex",alignItems:"center",justifyContent:"center"};function Ms({source:e,projectorRef:t,authToken:n="",options:r,invalidateRef:i,className:o,style:s}){const a=g.useRef(null),l=g.useRef(null),u=g.useRef(null),f=g.useRef({active:!1,pointerId:null}),c=g.useRef(null),h=g.useRef(!1),d=it(r?.width,Ne.width,64),m=it(r?.height,Ne.height,48),p=g.useMemo(()=>{const v=Math.max(1,e.width),M=Math.max(1,e.height),X=v/M,fe=d/m;let J,ae;return X>fe?(J=d,ae=d/X):(ae=m,J=m*X),{x:(d-J)/2,y:(m-ae)/2,w:J,h:ae}},[e.width,e.height,d,m]),y=it(r?.margin,Ne.margin,0),b=it(r?.borderRadius,Ne.borderRadius,0),x=it(r?.borderWidth,Ne.borderWidth,0),C=Math.max(1,Math.round(it(r?.maxThumbnailTiles,Ne.maxThumbnailTiles,1))),S=r?.backgroundColor||Ne.backgroundColor,A=r?.borderColor||Ne.borderColor,_=r?.viewportBorderColor||Ne.viewportBorderColor,Y=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:Ne.viewportBorderStyle,B=r?.viewportFillColor??Ne.viewportFillColor,G=r?.interactive??Ne.interactive,z=r?.showThumbnail??Ne.showThumbnail,$=r?.position||Ne.position,Q=r?.onClose,P=r?.closeIcon,W=r?.closeButtonStyle,N=g.useMemo(()=>{const v={};return $==="top-left"||$==="bottom-left"?v.left=y:v.right=y,$==="top-left"||$==="top-right"?v.top=y:v.bottom=y,{position:"absolute",...v,width:d,height:m,borderRadius:b,overflow:"hidden",zIndex:4,pointerEvents:G?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[y,$,d,m,b,G,s]),k=g.useCallback(()=>{const v=a.current;if(!v)return;const M=v.getContext("2d");if(!M)return;const X=d,fe=m,J=Math.max(1,window.devicePixelRatio||1),ae=Math.max(1,Math.round(X*J)),le=Math.max(1,Math.round(fe*J));(v.width!==ae||v.height!==le)&&(v.width=ae,v.height=le),M.setTransform(1,0,0,1,0,0),M.clearRect(0,0,v.width,v.height),M.setTransform(J,0,0,J,0,0),M.fillStyle=S,M.fillRect(0,0,X,fe);const{x:ge,y:oe,w:ne,h:be}=p,he=l.current;he&&M.drawImage(he,ge,oe,ne,be),M.strokeStyle=A,M.lineWidth=x,M.strokeRect(x*.5,x*.5,X-x,fe-x);const D=t.current,H=D?.getViewBounds?.(),q=D?.getViewCorners?.(),ee=Array.isArray(q)&&q.length>=4&&q.every(Z=>Array.isArray(Z)&&Z.length>=2&&Number.isFinite(Z[0])&&Number.isFinite(Z[1]))?q:null,te=ct(H)?H:ct(u.current)?u.current:null;ct(H)&&(u.current=H);const ce=ne/Math.max(1,e.width),Ee=be/Math.max(1,e.height),we=Y==="dash";if(ee){const Z=ee.map(se=>[ge+se[0]*ce,oe+se[1]*Ee]),re=Es(Z,ge,oe,ge+ne,oe+be);if(re.length>=3){M.beginPath();for(let se=0;se<re.length;se+=1)se===0?M.moveTo(re[se][0],re[se][1]):M.lineTo(re[se][0],re[se][1]);M.closePath(),M.fillStyle=B,M.fill(),M.strokeStyle=_,M.lineWidth=2.25,we?fr(M,re,4,3):M.stroke();return}}if(!te)return;const xe=O(ge+te[0]*ce,ge,ge+ne),pe=O(oe+te[1]*Ee,oe,oe+be),F=O(ge+te[2]*ce,ge,ge+ne),V=O(oe+te[3]*Ee,oe,oe+be),I=Math.max(1,F-xe),U=Math.max(1,V-pe);if(M.fillStyle=B,M.fillRect(xe,pe,I,U),M.strokeStyle=_,M.lineWidth=2.25,we){const Z=[[xe+.5,pe+.5],[xe+.5+Math.max(1,I-1),pe+.5],[xe+.5+Math.max(1,I-1),pe+.5+Math.max(1,U-1)],[xe+.5,pe+.5+Math.max(1,U-1)]];fr(M,Z,4,3)}else M.strokeRect(xe+.5,pe+.5,Math.max(1,I-1),Math.max(1,U-1))},[d,m,p,S,A,x,t,e.width,e.height,B,_,Y]),K=g.useCallback(()=>{h.current||(h.current=!0,c.current=requestAnimationFrame(()=>{h.current=!1,c.current=null,k()}))},[k]),me=g.useCallback((v,M)=>{const X=a.current;if(!X)return null;const fe=X.getBoundingClientRect();if(!fe.width||!fe.height)return null;const J=fe.width/d,ae=fe.height/m,le=p.x*J,ge=p.y*ae,oe=p.w*J,ne=p.h*ae,be=O((v-fe.left-le)/oe,0,1),he=O((M-fe.top-ge)/ne,0,1);return[be*e.width,he*e.height]},[e.width,e.height,d,m,p]),ie=g.useCallback((v,M)=>{const X=t.current;if(!X)return;if(X.setViewCenter){X.setViewCenter(v,M),K();return}const fe=X.getViewBounds?.(),J=ct(fe)?fe:ct(u.current)?u.current:null;if(!J)return;const ae=Math.max(1e-6,J[2]-J[0]),le=Math.max(1e-6,J[3]-J[1]);X.setViewState({offsetX:v-ae*.5,offsetY:M-le*.5}),K()},[t,K]),ve=g.useCallback(v=>{if(!G||v.button!==0)return;const M=a.current;if(!M)return;const X=me(v.clientX,v.clientY);X&&(v.preventDefault(),v.stopPropagation(),M.setPointerCapture(v.pointerId),f.current={active:!0,pointerId:v.pointerId},ie(X[0],X[1]))},[G,me,ie]),Se=g.useCallback(v=>{const M=f.current;if(!M.active||M.pointerId!==v.pointerId)return;const X=me(v.clientX,v.clientY);X&&(v.preventDefault(),v.stopPropagation(),ie(X[0],X[1]))},[me,ie]),Ce=g.useCallback(v=>{const M=f.current;if(!M.active||M.pointerId!==v.pointerId)return;const X=a.current;if(X&&X.hasPointerCapture(v.pointerId))try{X.releasePointerCapture(v.pointerId)}catch{}f.current={active:!1,pointerId:null},K()},[K]);return g.useEffect(()=>{let v=!1;l.current=null,K();const M=0,X=2**(e.maxTierZoom-M),fe=Math.ceil(e.width/X),J=Math.ceil(e.height/X),ae=Math.max(1,Math.ceil(fe/e.tileSize)),le=Math.max(1,Math.ceil(J/e.tileSize)),ge=ae*le;if(!z||ge>C)return;const oe=document.createElement("canvas");oe.width=Math.max(1,Math.round(p.w)),oe.height=Math.max(1,Math.round(p.h));const ne=oe.getContext("2d");if(!ne)return;ne.fillStyle=S,ne.fillRect(0,0,oe.width,oe.height);const be=[];for(let he=0;he<le;he+=1)for(let D=0;D<ae;D+=1){const H=D*e.tileSize*X,q=he*e.tileSize*X,ee=Math.min((D+1)*e.tileSize,fe)*X,te=Math.min((he+1)*e.tileSize,J)*X;be.push({url:Tn(e,M,D,he),bounds:[H,q,ee,te]})}return Promise.allSettled(be.map(async he=>{const D=Ss(he.url,n),H=await fetch(he.url,{headers:D?{Authorization:n}:void 0});if(!H.ok)throw new Error(`HTTP ${H.status}`);const q=await createImageBitmap(await H.blob());return{tile:he,bitmap:q}})).then(he=>{if(v){for(const q of he)q.status==="fulfilled"&&q.value.bitmap.close();return}const D=oe.width/Math.max(1,e.width),H=oe.height/Math.max(1,e.height);for(const q of he){if(q.status!=="fulfilled")continue;const{tile:{bounds:ee},bitmap:te}=q.value,ce=ee[0]*D,Ee=ee[1]*H,we=Math.max(1,(ee[2]-ee[0])*D),xe=Math.max(1,(ee[3]-ee[1])*H);ne.drawImage(te,ce,Ee,we,xe),te.close()}l.current=oe,K()}),()=>{v=!0}},[e,n,p,S,z,C,K]),g.useEffect(()=>{K()},[K]),g.useEffect(()=>{if(i)return i.current=K,()=>{i.current===K&&(i.current=null)}},[i,K]),g.useEffect(()=>()=>{f.current={active:!1,pointerId:null},c.current!==null&&(cancelAnimationFrame(c.current),c.current=null),h.current=!1},[]),We.jsxs("div",{className:o,style:N,children:[We.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:ve,onPointerMove:Se,onPointerUp:Ce,onPointerCancel:Ce,onContextMenu:v=>{v.preventDefault()},onWheel:v=>{v.preventDefault(),v.stopPropagation()}}),Q&&We.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:v=>{v.stopPropagation(),Q()},style:W?{...W}:{...Rs},children:P??"×"})]})}const pr="__patch_layer__",As=[];function vs({regions:e,strokeStyle:t}){const{rendererRef:n,registerDrawCallback:r,unregisterDrawCallback:i,requestOverlayRedraw:o}=at(),s=e??As,a=g.useMemo(()=>qe(Wr,t),[t]),l=g.useMemo(()=>{const c=[];for(let h=0;h<s.length;h+=1){const d=s[h],m=Xt(d.coordinates);m.length!==0&&c.push({region:d,regionIndex:h,regionKey:d.id??h,polygons:m})}return c},[s]),u=g.useCallback(c=>{const h=n.current;if(!h||c.length===0)return[];const d=new Array(c.length);for(let m=0;m<c.length;m+=1){const p=Ye(h.worldToScreen(c[m][0],c[m][1]));if(!p)return[];d[m]=p}return d},[]),f=g.useRef({prepared:l,resolvedStrokeStyle:a,worldToScreenPoints:u});return f.current={prepared:l,resolvedStrokeStyle:a,worldToScreenPoints:u},g.useEffect(()=>(r(pr,20,h=>{const{prepared:d,resolvedStrokeStyle:m,worldToScreenPoints:p}=f.current;for(const y of d)for(const b of y.polygons){const x=p(b.outer);x.length>=4&&Te(h,x,m,!0,!1);for(const C of b.holes){const S=p(C);S.length>=4&&Te(h,S,m,!0,!1)}}}),()=>i(pr)),[r,i]),g.useEffect(()=>{o()},[l,a,o]),null}function mt(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return null;const n=bt(t??[]);if(n.length===0){const m={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return e.fillModes instanceof Uint8Array&&(m.fillModes=new Uint8Array(0)),e.ids instanceof Uint32Array&&(m.ids=new Uint32Array(0)),m}const r=tt(e),i=e.positions,o=e.paletteIndices,s=e.fillModes instanceof Uint8Array&&e.fillModes.length>=r?e.fillModes:null,a=e.ids instanceof Uint32Array&&e.ids.length>=r?e.ids:null,l=new Float32Array(r*2),u=new Uint16Array(r),f=s?new Uint8Array(r):null,c=a?new Uint32Array(r):null;let h=0;for(let m=0;m<r;m+=1){const p=i[m*2],y=i[m*2+1];Dt(p,y,n)&&(l[h*2]=p,l[h*2+1]=y,u[h]=o[m],f&&(f[h]=s[m]),c&&(c[h]=a[m]),h+=1)}const d={count:h,positions:l.subarray(0,h*2),paletteIndices:u.subarray(0,h)};return f&&(d.fillModes=f.subarray(0,h)),c&&(d.ids=c.subarray(0,h)),d}function ti(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return new Uint32Array(0);const n=bt(t??[]);if(n.length===0)return new Uint32Array(0);const r=tt(e);if(r===0)return new Uint32Array(0);const i=e.positions,o=new Uint32Array(r);let s=0;for(let a=0;a<r;a+=1){const l=i[a*2],u=i[a*2+1];Dt(l,u,n)&&(o[s]=a,s+=1)}return o.subarray(0,s)}let At=null;const Cs=`
|
|
34
34
|
struct Params {
|
|
35
35
|
pointCount: u32,
|
|
36
36
|
boundsCount: u32,
|
|
@@ -61,7 +61,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
61
61
|
}
|
|
62
62
|
outputMask[i] = inside;
|
|
63
63
|
}
|
|
64
|
-
`;function Is(){if(typeof navigator>"u")return!1;const e=navigator;return typeof e.gpu=="object"&&e.gpu!==null}function ni(){if(!Is())return null;const t=navigator.gpu;if(!t||typeof t!="object")return null;const n=t;return typeof n.requestAdapter!="function"?null:n}const At=globalThis.GPUShaderStage?.COMPUTE??4,Qt=globalThis.GPUBufferUsage?.STORAGE??128,vt=globalThis.GPUBufferUsage?.COPY_DST??8,Ps=globalThis.GPUBufferUsage?.COPY_SRC??4,Ts=globalThis.GPUBufferUsage?.UNIFORM??64,_s=globalThis.GPUBufferUsage?.MAP_READ??1,Fs=globalThis.GPUMapMode?.READ??1;async function Ls(){const e=ni();if(!e)return{supported:!1,features:[]};const t=await e.requestAdapter();return t?{supported:!0,adapterName:t.info?.description??t.info?.vendor??"unknown",features:Array.from(t.features),limits:{maxStorageBufferBindingSize:Number(t.limits.maxStorageBufferBindingSize),maxComputeInvocationsPerWorkgroup:Number(t.limits.maxComputeInvocationsPerWorkgroup),maxComputeWorkgroupSizeX:Number(t.limits.maxComputeWorkgroupSizeX)}}:{supported:!1,features:[]}}async function ks(){return Mt||(Mt=(async()=>{const e=ni();if(!e)return null;const t=await e.requestAdapter();if(!t)return null;const n=await t.requestDevice(),r=n.createBindGroupLayout({entries:[{binding:0,visibility:At,buffer:{type:"read-only-storage"}},{binding:1,visibility:At,buffer:{type:"read-only-storage"}},{binding:2,visibility:At,buffer:{type:"storage"}},{binding:3,visibility:At,buffer:{type:"uniform"}}]}),i=n.createComputePipeline({layout:n.createPipelineLayout({bindGroupLayouts:[r]}),compute:{module:n.createShaderModule({code:Cs}),entryPoint:"main"}});return{device:n,pipeline:i,bindGroupLayout:r}})(),Mt)}function Ct(e,t){return Math.ceil(e/t)*t}async function ri(e,t,n){const r=await ks();if(!r)return null;const i=Math.max(0,Math.floor(t)),o=Math.max(0,Math.floor(n.length/4));if(i===0||o===0)return new Uint32Array(0);const s=Math.min(i,Math.floor(e.length/2));if(s===0)return new Uint32Array(0);const a=s*2*Float32Array.BYTES_PER_ELEMENT,l=o*4*Float32Array.BYTES_PER_ELEMENT,u=s*Uint32Array.BYTES_PER_ELEMENT,f=Number(r.device.limits.maxStorageBufferBindingSize);if(a>f||l>f||u>f)return null;const c=r.device.createBuffer({size:Ct(a,4),usage:Qt|vt}),h=r.device.createBuffer({size:Ct(l,4),usage:Qt|vt}),d=r.device.createBuffer({size:Ct(u,4),usage:Qt|Ps}),m=r.device.createBuffer({size:16,usage:Ts|vt}),p=r.device.createBuffer({size:Ct(u,4),usage:vt|_s});let y=!1;try{r.device.queue.writeBuffer(c,0,e.buffer,e.byteOffset,a),r.device.queue.writeBuffer(h,0,n.buffer,n.byteOffset,l),r.device.queue.writeBuffer(m,0,new Uint32Array([s,o,0,0]));const b=r.device.createBindGroup({layout:r.bindGroupLayout,entries:[{binding:0,resource:{buffer:c}},{binding:1,resource:{buffer:h}},{binding:2,resource:{buffer:d}},{binding:3,resource:{buffer:m}}]}),x=r.device.createCommandEncoder(),C=x.beginComputePass();C.setPipeline(r.pipeline),C.setBindGroup(0,b),C.dispatchWorkgroups(Math.ceil(s/256)),C.end(),x.copyBufferToBuffer(d,0,p,0,u),r.device.queue.submit([x.finish()]),await p.mapAsync(Fs),y=!0;const S=p.getMappedRange();return new Uint32Array(S.slice(0))}finally{if(y)try{p.unmap()}catch{}c.destroy(),h.destroy(),d.destroy(),m.destroy(),p.destroy()}}async function ii(e,t,n={}){const r=be(),i=n.bridgeToDraw===!0;if(!e||!e.count||!e.positions||!e.paletteIndices)return{data:null,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}};const o=yt(t??[]);if(o.length===0){const S={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return e.fillModes instanceof Uint8Array&&(S.fillModes=new Uint8Array(0)),e.ids instanceof Uint32Array&&(S.ids=new Uint32Array(0)),{data:S,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const s=et(e),a=e.fillModes instanceof Uint8Array&&e.fillModes.length>=s?e.fillModes:null,l=e.ids instanceof Uint32Array&&e.ids.length>=s?e.ids:null;if(s===0){const S={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(S.fillModes=new Uint8Array(0)),l&&(S.ids=new Uint32Array(0)),{data:S,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const u=new Float32Array(o.length*4);for(let S=0;S<o.length;S+=1){const A=S*4,T=o[S];u[A]=T.minX,u[A+1]=T.minY,u[A+2]=T.maxX,u[A+3]=T.maxY}let f=null,c=!1;try{f=await ri(e.positions,s,u),c=!!f}catch{f=null,c=!1}if(!f)return{data:dt(e,t),meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!1,candidateCount:s,bridgedToDraw:!1}};let h=0;for(let S=0;S<s;S+=1)f[S]===1&&(h+=1);const d=new Uint32Array(h);if(h>0){let S=0;for(let A=0;A<s;A+=1)f[A]===1&&(d[S]=A,S+=1)}if(h===0){if(i){const A={count:s,positions:e.positions.subarray(0,s*2),paletteIndices:e.paletteIndices.subarray(0,s),drawIndices:new Uint32Array(0)};return a&&(A.fillModes=a.subarray(0,s)),l&&(A.ids=l.subarray(0,s)),{data:A,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!0}}}const S={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(S.fillModes=new Uint8Array(0)),l&&(S.ids=new Uint32Array(0)),{data:S,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const S=new Uint32Array(h);let A=0;for(let O=0;O<h;O+=1){const D=d[O]??0,G=e.positions[D*2],z=e.positions[D*2+1];Dt(G,z,o)&&(S[A]=D,A+=1)}const T={count:s,positions:e.positions.subarray(0,s*2),paletteIndices:e.paletteIndices.subarray(0,s),drawIndices:S.subarray(0,A)};return a&&(T.fillModes=a.subarray(0,s)),l&&(T.ids=l.subarray(0,s)),{data:T,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!0,candidateCount:h,bridgedToDraw:!0}}}const m=new Float32Array(h*2),p=new Uint16Array(h),y=a?new Uint8Array(h):null,b=l?new Uint32Array(h):null;let x=0;for(let S=0;S<h;S+=1){const A=d[S]??0,T=e.positions[A*2],O=e.positions[A*2+1];Dt(T,O,o)&&(m[x*2]=T,m[x*2+1]=O,p[x]=e.paletteIndices[A],y&&(y[x]=a[A]),b&&(b[x]=l[A]),x+=1)}const C={count:x,positions:m.subarray(0,x*2),paletteIndices:p.subarray(0,x)};return y&&(C.fillModes=y.subarray(0,x)),b&&(C.ids=b.subarray(0,x)),{data:C,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!0,candidateCount:h,bridgedToDraw:!1}}}class oi{constructor(t,n){R(this,"worker",null);R(this,"supported",!0);R(this,"requestId",1);R(this,"pendingById",new Map);R(this,"handleMessage",t=>{const n=t.data;if(!n)return;const r=this.pendingById.get(n.id);r&&(this.pendingById.delete(n.id),this.handlers.onResponse(n,r))});R(this,"handleError",()=>{this.supported=!1,this.teardownWorker("worker crashed")});this.createWorker=t,this.handlers=n}beginRequest(t){const n=this.getOrCreateWorker();if(!n)return null;const r=this.requestId++;return this.pendingById.set(r,t),{id:r,worker:n}}cancelRequest(t){const n=this.pendingById.get(t);if(n)return this.pendingById.delete(t),n}terminate(t="worker terminated"){this.teardownWorker(t)}getOrCreateWorker(){if(!this.supported)return null;if(this.worker)return this.worker;try{const t=this.createWorker();return t.addEventListener("message",this.handleMessage),t.addEventListener("error",this.handleError),this.worker=t,t}catch{return this.supported=!1,null}}teardownWorker(t){this.worker&&(this.worker.removeEventListener("message",this.handleMessage),this.worker.removeEventListener("error",this.handleError),this.worker.terminate(),this.worker=null);const n=new Error(t);for(const[,r]of this.pendingById)this.handlers.rejectPending(r,n);this.pendingById.clear()}}const mt=new oi(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/roi-clip-worker-BuNuUQQg.js").href:new URL("assets/roi-clip-worker-BuNuUQQg.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:it&&it.tagName.toUpperCase()==="SCRIPT"&&it.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(e,t)=>{if(e.type==="roi-clip-failure"){t.reject(new Error(e.error||"worker clip failed"));return}if(e.type==="roi-clip-index-success"){if(t.kind!=="index"){t.reject(new Error("worker response mismatch: expected point data result"));return}const l=Math.max(0,Math.floor(e.count)),u=new Uint32Array(e.indices).subarray(0,l);t.resolve({indices:u,meta:{mode:"worker",durationMs:Number.isFinite(e.durationMs)?e.durationMs:be()-t.startMs}});return}if(t.kind!=="data"){t.reject(new Error("worker response mismatch: expected index result"));return}const n=Math.max(0,Math.floor(e.count)),r=new Float32Array(e.positions),i=new Uint16Array(e.paletteIndices),o=e.fillModes?new Uint8Array(e.fillModes):null,s=e.ids?new Uint32Array(e.ids):null,a={count:n,positions:r.subarray(0,n*2),paletteIndices:i.subarray(0,n)};o&&(a.fillModes=o.subarray(0,n)),s&&(a.ids=s.subarray(0,n)),t.resolve({data:a,meta:{mode:"worker",durationMs:Number.isFinite(e.durationMs)?e.durationMs:be()-t.startMs}})},rejectPending:(e,t)=>{e.reject(t)}});function Ns(){mt.terminate("worker terminated")}async function si(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return{data:null,meta:{mode:"worker",durationMs:0}};const n=et(e),r=e.positions.slice(0,n*2),i=e.paletteIndices.slice(0,n),o=e.fillModes instanceof Uint8Array&&e.fillModes.length>=n?e.fillModes.slice(0,n):null,s=e.ids instanceof Uint32Array&&e.ids.length>=n?e.ids.slice(0,n):null;return new Promise((a,l)=>{const u=be(),f=mt.beginRequest({kind:"data",resolve:a,reject:l,startMs:u});if(!f){a({data:dt(e,t),meta:{mode:"sync",durationMs:be()-u}});return}const c={type:"roi-clip-request",id:f.id,count:n,positions:r.buffer,paletteIndices:i.buffer,fillModes:o?.buffer,ids:s?.buffer,polygons:t??[]},h=[r.buffer,i.buffer];o&&h.push(o.buffer),s&&h.push(s.buffer);try{f.worker.postMessage(c,h)}catch(d){const m=mt.cancelRequest(f.id);m?m.reject(d):l(d)}})}async function Bs(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return{indices:new Uint32Array(0),meta:{mode:"worker",durationMs:0}};const n=et(e),r=e.positions.slice(0,n*2);return new Promise((i,o)=>{const s=be(),a=mt.beginRequest({kind:"index",resolve:i,reject:o,startMs:s});if(!a){i({indices:ti(e,t),meta:{mode:"sync",durationMs:be()-s}});return}const l={type:"roi-clip-index-request",id:a.id,count:n,positions:r.buffer,polygons:t??[]};try{a.worker.postMessage(l,[r.buffer])}catch(u){const f=mt.cancelRequest(a.id);f?f.reject(u):o(u)}})}const Ds={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};function zs(e,t,n,r,i){const o=g.useRef(0),[s,a]=g.useState(n),l=g.useMemo(()=>r.map(u=>pt(u.coordinates)).filter(u=>u!=null),[r]);return g.useEffect(()=>{const u=++o.current;let f=!1;if(!e)return a(n),()=>{f=!0};if(!n||!n.count||!n.positions||!n.paletteIndices)return a(null),()=>{f=!0};if(l.length===0)return a(Ds),i?.({mode:t,durationMs:0,inputCount:n.count,outputCount:0,polygonCount:0}),()=>{f=!0};const c=(d,m)=>{if(f||u!==o.current)return;const p=n.count,y=d?.drawIndices?d.drawIndices.length:d?.count??0;a(d),i?.({mode:m.mode,durationMs:m.durationMs,inputCount:p,outputCount:y,polygonCount:l.length,usedWebGpu:m.usedWebGpu,candidateCount:m.candidateCount,bridgedToDraw:m.bridgedToDraw})};return(async()=>{if(t==="sync"){const d=performance.now(),m=dt(n,l);c(m,{mode:"sync",durationMs:performance.now()-d});return}if(t==="hybrid-webgpu"){const d=await ii(n,l,{bridgeToDraw:!0});c(d.data,{mode:d.meta.mode,durationMs:d.meta.durationMs,usedWebGpu:d.meta.usedWebGpu,candidateCount:d.meta.candidateCount,bridgedToDraw:d.meta.bridgedToDraw});return}try{const d=await si(n,l);c(d.data,{mode:d.meta.mode,durationMs:d.meta.durationMs})}catch{const d=performance.now(),m=dt(n,l);c(m,{mode:"sync",durationMs:performance.now()-d})}})(),()=>{f=!0}},[e,t,n,l,i]),s}const Us=24,Os=1024,Ys=4,Lt=-1;function ct(e,t,n){return(e*73856093^t*19349663)>>>0&n}function Ws(e,t,n){if(e<=0||t<=0||n<=0)return 256;const r=Math.max(1,e*t),o=Math.sqrt(r/Math.max(1,n))*Ys;return Math.max(Us,Math.min(Os,o))}function Xs(e,t){if(!(e instanceof Uint32Array)||e.length===0)return null;let n=!0;for(let o=0;o<e.length;o+=1)if(!(e[o]<t)){n=!1;break}if(n)return e;const r=new Uint32Array(e.length);let i=0;for(let o=0;o<e.length;o+=1)e[o]>=t||(r[i]=e[o],i+=1);return i>0?r.subarray(0,i):null}function Vs(e){const t=Math.max(0,Math.floor(e.count)),n=Math.floor(e.positions.length/2),r=Math.max(0,Math.min(t,n));if(r<=0)return null;const i=Xs(e.drawIndices??null,r),o=i?i.length:r;if(o===0)return null;const s=Ws(e.sourceWidth,e.sourceHeight,o),a=1/s,l=new Int32Array(o),u=new Int32Array(o);let f=0;if(i)for(let I=0;I<o;I+=1){const H=i[I],N=e.positions[H*2],k=e.positions[H*2+1];!Number.isFinite(N)||!Number.isFinite(k)||(l[f]=Math.floor(N*a),u[f]=Math.floor(k*a),f+=1)}else for(let I=0;I<r;I+=1){const H=e.positions[I*2],N=e.positions[I*2+1];!Number.isFinite(H)||!Number.isFinite(N)||(l[f]=Math.floor(H*a),u[f]=Math.floor(N*a),f+=1)}if(f===0)return null;let c=Math.min(f,Math.max(64,f>>>3));(!Number.isFinite(c)||c<=0)&&(c=f);let h=1;for(;h<c*2;)h<<=1;let d=h-1,m=new Int32Array(h*2),p=new Int32Array(h);m.fill(2147483647);let y=0;const b=new Int32Array(f);for(let I=0;I<f;I+=1){const H=l[I],N=u[I];let k=ct(H,N,d);for(;;){const Z=m[k*2];if(Z===2147483647){if(m[k*2]=H,m[k*2+1]=N,p[k]=1,b[I]=k,y+=1,y*4>h*3){const we=h;h<<=1,d=h-1;const se=new Int32Array(h*2),Re=new Int32Array(h);se.fill(2147483647);for(let Ce=0;Ce<we;Ce+=1){if(m[Ce*2]===2147483647)continue;const xe=m[Ce*2],M=m[Ce*2+1];let v=ct(xe,M,d);for(;se[v*2]!==2147483647;)v=v+1&d;se[v*2]=xe,se[v*2+1]=M,Re[v]=p[Ce]}for(m=se,p=Re,k=ct(H,N,d);m[k*2]!==H||m[k*2+1]!==N;)k=k+1&d;b[I]=k}break}if(Z===H&&m[k*2+1]===N){p[k]+=1,b[I]=k;break}k=k+1&d}}const x=new Int32Array(y*2),C=new Uint32Array(y),S=new Uint32Array(y),A=new Int32Array(h);A.fill(Lt);let T=0,O=0;for(let I=0;I<h;I+=1)m[I*2]!==2147483647&&(x[T*2]=m[I*2],x[T*2+1]=m[I*2+1],C[T]=O,S[T]=p[I],A[I]=T,O+=p[I],T+=1);const D=new Uint32Array(f),G=new Uint32Array(y);if(G.set(C),i)for(let I=0;I<f;I+=1){const H=A[b[I]];D[G[H]]=i[I],G[H]+=1}else{let I=0;for(let H=0;H<r;H+=1){const N=e.positions[H*2],k=e.positions[H*2+1];if(!Number.isFinite(N)||!Number.isFinite(k))continue;const Z=A[b[I]];D[G[Z]]=H,G[Z]+=1,I+=1}}let z=1;for(;z<y*2;)z<<=1;const q=z-1,re=new Int32Array(z);re.fill(Lt);for(let I=0;I<y;I+=1){const H=x[I*2],N=x[I*2+1];let k=ct(H,N,q);for(;re[k]!==Lt;)k=k+1&q;re[k]=I}return{cellSize:s,safeCount:r,cellCount:y,hashCapacity:z,hashTable:re,cellKeys:x,cellOffsets:C,cellLengths:S,pointIndices:D}}function ai(e,t,n){const{hashTable:r,cellKeys:i,hashMask:o}=e;let s=ct(t,n,o);for(;;){const a=r[s];if(a===Lt)return-1;if(i[a*2]===t&&i[a*2+1]===n)return a;s=s+1&o}}function Gs(e,t){if(e.safeCount<=0||e.cellCount<=0)return null;const n=e.safeCount;return{cellSize:e.cellSize,safeCount:n,positions:t.positions.subarray(0,n*2),ids:t.ids instanceof Uint32Array&&t.ids.length>=n?t.ids.subarray(0,n):null,hashCapacity:e.hashCapacity,hashMask:e.hashCapacity-1,hashTable:new Int32Array(e.hashTable),cellKeys:new Int32Array(e.cellKeys),cellOffsets:new Uint32Array(e.cellOffsets),cellLengths:new Uint32Array(e.cellLengths),pointIndices:new Uint32Array(e.pointIndices)}}const hn=new oi(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/point-hit-index-worker-CNFA6pZm.js").href:new URL("assets/point-hit-index-worker-CNFA6pZm.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:it&&it.tagName.toUpperCase()==="SCRIPT"&&it.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(e,t)=>{if(e.type==="point-hit-index-failure"){t.reject(new Error(e.error||"worker index build failed"));return}t.resolve(Gs(e,t.pointData))},rejectPending:(e,t)=>{e.reject(t)}});function qs(){hn.terminate("worker terminated")}function Hs(e,t){const n=et(e);if(n<=0)return null;const r=e.positions.subarray(0,n*2),i=Vs({count:n,positions:r,drawIndices:e.drawIndices instanceof Uint32Array?e.drawIndices:null,sourceWidth:t?.width??0,sourceHeight:t?.height??0});return i?{cellSize:i.cellSize,safeCount:n,positions:r,ids:e.ids instanceof Uint32Array&&e.ids.length>=n?e.ids.subarray(0,n):null,hashCapacity:i.hashCapacity,hashMask:i.hashCapacity-1,hashTable:i.hashTable,cellKeys:i.cellKeys,cellOffsets:i.cellOffsets,cellLengths:i.cellLengths,pointIndices:i.pointIndices}:null}async function li(e,t){if(!e||!e.positions||!e.paletteIndices)return null;const n=et(e);return n<=0?null:new Promise((r,i)=>{const o={resolve:r,reject:i,pointData:e},s=hn.beginRequest(o);if(!s||!s.worker){r(Hs(e,t));return}const a=e.positions.slice(0,n*2),l=e.drawIndices instanceof Uint32Array&&e.drawIndices.length>0?e.drawIndices.slice():void 0,u={type:"point-hit-index-request",id:s.id,count:n,positions:a.buffer,drawIndices:l?.buffer,sourceWidth:t?.width??0,sourceHeight:t?.height??0},f=[a.buffer];l&&f.push(l.buffer);try{s.worker.postMessage(u,f)}catch(c){const h=hn.cancelRequest(s.id);h?h.reject(c):i(c)}})}const Zs=.65,$s=4;function Ks(e,t,n,r,i,o,s){const a=!!(n||r||i),[l,u]=g.useState(null),f=g.useRef(null),c=g.useRef(null);g.useEffect(()=>{if(!a||!e){u(null);return}let p=!1;return li(e,t).then(y=>{p||u(y)}),()=>{p=!0}},[a,e,t]);const h=g.useCallback(p=>{const y=s.current;if(!y||!l)return null;const b=Number(p[0]),x=Number(p[1]);if(!Number.isFinite(b)||!Number.isFinite(x))return null;const C=Math.max(1e-6,y.getViewState().zoom),S=y.getPointSizeByZoom(),T=Math.max($s,S*Zs)/C;if(!Number.isFinite(T)||T<=0)return null;const{cellSize:O,cellOffsets:D,cellLengths:G,pointIndices:z,positions:q,safeCount:re}=l,I=Math.floor(b/O),H=Math.floor(x/O),N=Math.max(1,Math.ceil(T/O)),k=T*T;let Z=-1,we=k,se=0,Re=0;for(let xe=I-N;xe<=I+N;xe+=1)for(let M=H-N;M<=H+N;M+=1){const v=ai(l,xe,M);if(v<0)continue;const X=D[v],le=X+G[v];for(let Q=X;Q<le;Q+=1){const ie=z[Q];if(ie>=re)continue;const he=q[ie*2],me=q[ie*2+1],$=he-b,pe=me-x,ye=$*$+pe*pe;ye>we||(we=ye,Z=ie,se=he,Re=me)}}if(Z<0)return null;const Ce=l.ids?Number(l.ids[Z]):null;return{index:Z,id:Ce,coordinate:[b,x],pointCoordinate:[se,Re]}},[l]),d=g.useCallback((p,y)=>{if(!n)return;const b=p?.index??null,x=p?.id??null;f.current===b&&c.current===x||(f.current=b,c.current=x,n({index:b,id:x,coordinate:y,pointCoordinate:p?.pointCoordinate??null}))},[n]),m=g.useCallback((p,y)=>{if(!r)return;const b=h(p);b&&r({...b,button:y})},[r,h]);return g.useEffect(()=>{if(i)return i.current=h,()=>{i.current===h&&(i.current=null)}},[i,h]),g.useEffect(()=>{const p=f.current;p!==null&&(l&&p<l.safeCount||(f.current=null,c.current=null,n?.({index:null,id:null,coordinate:null,pointCoordinate:null})))},[l,n]),g.useEffect(()=>{},[o,n]),{getCellByCoordinates:h,emitPointHover:d,emitPointClick:m}}const js=g.forwardRef(function({data:t=null,palette:n=null,sizeByZoom:r,strokeScale:i,innerFillOpacity:o,clipEnabled:s=!1,clipToRegions:a,clipMode:l="worker",onClipStats:u,onHover:f,onClick:c},h){const{rendererRef:d,rendererSerial:m,source:p}=ot(),y=g.useRef(null),x=zs(s,l,t,a??Qs,u),{getCellByCoordinates:C}=Ks(x,p,f,c,y,"cursor",d);return g.useImperativeHandle(h,()=>({queryAt:C}),[C]),g.useEffect(()=>{const S=d.current;!S||!n||S.setPointPalette(n)},[m,n]),g.useEffect(()=>{const S=d.current;!S||r===void 0||S.setPointSizeByZoom(r)},[m,r]),g.useEffect(()=>{const S=d.current;!S||i===void 0||S.setPointStrokeScale(i)},[m,i]),g.useEffect(()=>{const S=d.current;!S||o===void 0||S.setPointInnerFillOpacity(o)},[m,o]),g.useEffect(()=>{const S=d.current;S&&S.setPointData(x)},[m,x]),null}),Qs=[],Js=180,yr=20;function ea(e){const t=W(e,0,1);return t*t*(3-2*t)}function ta(e,t,n){const[r,i]=g.useState(0),o=g.useRef(0),s=g.useRef({rafId:null,startMs:0,from:0,to:0}),a=g.useCallback(c=>{const h=W(c,0,yr);Math.abs(o.current-h)<1e-4||(o.current=h,i(h))},[]),l=g.useCallback(()=>{const c=s.current;c.rafId!==null&&(cancelAnimationFrame(c.rafId),c.rafId=null)},[]),u=g.useCallback(c=>{const h=W(c,0,yr),d=s.current,m=o.current;if(Math.abs(m-h)<1e-4){l(),d.to=h,a(h);return}l(),d.startMs=performance.now(),d.from=m,d.to=h;const p=y=>{const b=s.current,x=Math.max(0,y-b.startMs),C=W(x/Js,0,1),S=ea(C),A=b.from+(b.to-b.from)*S;if(a(A),n.current?.(),C>=1){b.rafId=null,a(b.to);return}b.rafId=requestAnimationFrame(p)};d.rafId=requestAnimationFrame(p)},[a,l]),f=g.useCallback(c=>{const h=t.current;if(!h||typeof c!="number"||!Number.isFinite(c)){u(0);return}const d=In(e,c,h.getZoomRange());u(d)},[e,u]);return g.useEffect(()=>()=>{l()},[l]),{regionLabelAutoLiftOffsetPx:r,syncRegionLabelAutoLiftTarget:f,cancelRegionLabelAutoLiftAnimation:l,applyRegionLabelAutoLiftOffset:a}}const na=6;function dn(e,t){return e.id??t}function ra(e,t,n,r,i,o){const s=i-n,a=o-r,l=s*s+a*a;if(l<=1e-12){const m=e-n,p=t-r;return m*m+p*p}const u=W(((e-n)*s+(t-r)*a)/l,0,1),f=n+s*u,c=r+a*u,h=e-f,d=t-c;return h*h+d*d}function br(e,t,n,r){for(let i=1;i<n.length;i+=1){const o=n[i-1],s=n[i];if(ra(e,t,o[0],o[1],s[0],s[1])<=r)return!0}return!1}function ia(e,t,n,r){if(e<n.minX-r||e>n.maxX+r||t<n.minY-r||t>n.maxY+r)return!1;const i=r*r;if(br(e,t,n.outer,i))return!0;for(const o of n.holes)if(br(e,t,o,i))return!0;return!1}function oa(e,t,n,r,i,o,s){if(!e.label||!e.labelAnchor)return!1;const a=En(n.worldToScreen(e.labelAnchor[0],e.labelAnchor[1]));if(!a)return!1;const u=Mn(e.label,r)+r.paddingX*2,f=r.fontSize+r.paddingY*2,c=a[0],h=a[1]-r.offsetY,d=s?W(c,u*.5+1,i-u*.5-1):c,m=s?W(h,f*.5+1,o-f*.5-1):h,p=d-u*.5,y=d+u*.5,b=m-f*.5,x=m+f*.5;return t[0]>=p&&t[0]<=y&&t[1]>=b&&t[1]<=x}function sa(e,t="top-center"){const n=[];for(let r=0;r<e.length;r+=1){const i=e[r],o=yt([pt(i?.coordinates)]);if(o.length===0)continue;const s=typeof i?.label=="string"?i.label.trim():"";n.push({region:i,regionIndex:r,regionId:dn(i,r),polygons:o,label:s,labelAnchor:s?An(o,t):null})}return n}function wr(e,t,n,r,i,o,s,a,l,u=!0){const f=e[0],c=e[1],h=Math.max(1e-6,r.getViewState().zoom),d=Math.max(0,s),m=na/h;for(let p=n.length-1;p>=0;p-=1){const y=n[p];for(const x of y.polygons)if(ia(f,c,x,m))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId};let b=Cn(i,o?.({region:y.region,regionId:y.regionId,regionIndex:y.regionIndex,zoom:h}));if(d>0&&(b={...b,offsetY:b.offsetY+d}),!!oa(y,t,r,b,a,l,u))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId}}return null}const xr=[],aa=[],Sr="__region_layer__",Er="__region_label__";function la(e){return{color:Xr,width:Vr,lineDash:Je,lineJoin:e.lineJoin,lineCap:e.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function ca({regions:e,polygons:t,strokeStyle:n,hoverStrokeStyle:r,activeStrokeStyle:i,resolveStrokeStyle:o,labelStyle:s,labelAnchor:a="top-center",autoLiftLabelAtMaxZoom:l=!1,clampLabelToViewport:u=!0,activeRegionId:f,onActiveChange:c,onHover:h,onClick:d}){const{rendererRef:m,rendererSerial:p,canvasRef:y,containerRef:b,registerDrawCallback:x,unregisterDrawCallback:C,requestOverlayRedraw:S,drawInvalidateRef:A,screenToWorld:T,worldToScreen:O,isInteractionLocked:D}=ot(),G=e??xr,z=t??aa,q=g.useMemo(()=>G.length>0?G:z.length===0?xr:z.map((U,V)=>({id:V,coordinates:U})),[G,z]),[re,I]=g.useState(null),[H,N]=g.useState(()=>f??null),k=f!==void 0,Z=k?f??null:H,we=g.useRef(null);g.useEffect(()=>{k&&N(f??null)},[k,f]);const se=g.useCallback(U=>{String(Z)!==String(U)&&(k||N(U),c?.(U))},[Z,k,c]),{regionLabelAutoLiftOffsetPx:Re,syncRegionLabelAutoLiftTarget:Ce}=ta(l,m,A),xe=g.useMemo(()=>Rn(n),[n]),M=g.useMemo(()=>Ve(xe,r),[xe,r]),v=g.useMemo(()=>Ve(xe,i),[xe,i]),{staticLabelStyle:X,labelStyleResolver:le}=g.useMemo(()=>typeof s=="function"?{staticLabelStyle:void 0,labelStyleResolver:s}:{staticLabelStyle:s,labelStyleResolver:void 0},[s]),Q=g.useMemo(()=>vn(X),[X]),ie=g.useMemo(()=>{const U=[];for(let V=0;V<q.length;V+=1){const ee=q[V],B=Wt(ee.coordinates);B.length!==0&&U.push({region:ee,regionIndex:V,regionKey:ee.id??V,polygons:B})}return U},[q]),he=g.useMemo(()=>sa(q,a),[q,a]);g.useEffect(()=>{const U=m.current;U&&Ce(U.getViewState().zoom)},[p,Ce]),g.useEffect(()=>{!(Z===null?!0:q.some((B,te)=>String(dn(B,te))===String(Z)))&&Z!==null&&se(null);const V=we.current;!(V===null?!0:q.some((B,te)=>String(dn(B,te))===String(V)))&&V!==null&&(we.current=null,I(null),h?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[q,Z,h,se]);const me=g.useCallback(U=>{const V=m.current;if(!V||U.length===0)return[];const ee=new Array(U.length);for(let B=0;B<U.length;B+=1){const te=Oe(V.worldToScreen(U[B][0],U[B][1]));if(!te)return[];ee[B]=te}return ee},[]),$=g.useRef({preparedRegions:ie,hoveredRegionId:re,activeRegionId:Z,resolvedStrokeStyle:xe,resolvedHoverStrokeStyle:M,resolvedActiveStrokeStyle:v,resolveStrokeStyleProp:o,worldToScreenPoints:me});$.current={preparedRegions:ie,hoveredRegionId:re,activeRegionId:Z,resolvedStrokeStyle:xe,resolvedHoverStrokeStyle:M,resolvedActiveStrokeStyle:v,resolveStrokeStyleProp:o,worldToScreenPoints:me},g.useEffect(()=>(x(Sr,10,V=>{const{preparedRegions:ee,hoveredRegionId:B,activeRegionId:te,resolvedStrokeStyle:de,resolvedHoverStrokeStyle:ae,resolvedActiveStrokeStyle:Me,resolveStrokeStyleProp:Se,worldToScreenPoints:_}=$.current;for(const Y of ee){const{region:J,polygons:oe,regionIndex:L,regionKey:K}=Y,ce=Ot(te,K)?"active":Ot(B,K)?"hover":"default";let ne=ce==="active"?Me:ce==="hover"?ae:de;if(Se){const De=Se({region:J,regionId:K,regionIndex:L,state:ce});ne=Ve(ne,De||void 0)}const ue=ce==="default"?null:la(ne);for(const De of oe){const qe=_(De.outer);qe.length>=4&&(ue&&Pe(V,qe,ue,!0,!1),Pe(V,qe,ne,!0,!1));for(const Gt of De.holes){const st=_(Gt);st.length>=4&&(ue&&Pe(V,st,ue,!0,!1),Pe(V,st,ne,!0,!1))}}}}),()=>C(Sr)),[x,C]);const pe=g.useRef({preparedRegions:ie,resolvedLabelStyle:Q,labelStyleResolver:le,labelAnchor:a,autoLiftLabelAtMaxZoom:l,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:Re,rendererRef:m});pe.current={preparedRegions:ie,resolvedLabelStyle:Q,labelStyleResolver:le,labelAnchor:a,autoLiftLabelAtMaxZoom:l,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:Re,rendererRef:m},g.useEffect(()=>(x(Er,50,(V,ee,B)=>{const{preparedRegions:te,resolvedLabelStyle:de,labelStyleResolver:ae,labelAnchor:Me,autoLiftLabelAtMaxZoom:Se,clampLabelToViewport:_,regionLabelAutoLiftOffsetPx:Y,rendererRef:J}=pe.current;if(te.length===0)return;const oe=Math.max(1e-6,J.current?.getViewState?.().zoom??1),L=typeof Y=="number"&&Number.isFinite(Y)?Math.max(0,Y):In(Se,oe,J.current?.getZoomRange?.());for(const K of te){if(!K.region.label)continue;const ce=An(K.polygons,Me);if(!ce)continue;const ne=Oe(J.current?.worldToScreen(ce[0],ce[1])??[]);if(!ne)continue;let ue=Cn(de,ae?.({region:K.region,regionId:K.regionKey,regionIndex:K.regionIndex,zoom:oe}));L>0&&(ue={...ue,offsetY:ue.offsetY+L}),Kr(V,K.region.label,ne,ee,B,ue,_)}}),()=>C(Er)),[x,C]),g.useEffect(()=>{S()},[ie,re,Z,xe,Q,Re,S]);const ye=g.useRef({preparedRegionHits:he,resolvedLabelStyle:Q,labelStyleResolver:le,regionLabelAutoLiftOffsetPx:Re,clampLabelToViewport:u,onHover:h,onClick:d,commitActive:se});return ye.current={preparedRegionHits:he,resolvedLabelStyle:Q,labelStyleResolver:le,regionLabelAutoLiftOffsetPx:Re,clampLabelToViewport:u,onHover:h,onClick:d,commitActive:se},g.useEffect(()=>{const U=b.current;if(!U)return;const V=te=>{if(D())return;const de=m.current;if(!de)return;const{preparedRegionHits:ae,resolvedLabelStyle:Me,labelStyleResolver:Se,regionLabelAutoLiftOffsetPx:_,clampLabelToViewport:Y,onHover:J}=ye.current,oe=T(te.clientX,te.clientY);if(!oe)return;let L=null,K=null;if(ae.length>0){const ne=O(oe[0],oe[1]);if(ne){const ue=y.current?.getBoundingClientRect();K=wr(oe,ne,ae,de,Me,Se,typeof _=="number"?_:0,ue?.width??0,ue?.height??0,Y),L=K?.regionId??null}}const ce=we.current;String(ce)!==String(L)&&(we.current=L,I(L),J?.({region:K?.region??null,regionId:L,regionIndex:K?.regionIndex??-1,coordinate:oe}),S())},ee=te=>{if(D())return;const de=m.current;if(!de)return;const{preparedRegionHits:ae,resolvedLabelStyle:Me,labelStyleResolver:Se,regionLabelAutoLiftOffsetPx:_,clampLabelToViewport:Y,onClick:J,commitActive:oe}=ye.current;if(ae.length===0)return;const L=T(te.clientX,te.clientY);if(!L)return;const K=O(L[0],L[1]);if(!K)return;const ce=y.current?.getBoundingClientRect(),ne=wr(L,K,ae,de,Me,Se,typeof _=="number"?_:0,ce?.width??0,ce?.height??0,Y),ue=ne?.regionId??null;oe(ue),ne&&J&&J({region:ne.region,regionId:ne.regionId,regionIndex:ne.regionIndex,coordinate:L})},B=()=>{we.current!==null&&(we.current=null,I(null),ye.current.onHover?.({region:null,regionId:null,regionIndex:-1,coordinate:null}),S())};return U.addEventListener("pointermove",V),U.addEventListener("click",ee),U.addEventListener("pointerleave",B),()=>{U.removeEventListener("pointermove",V),U.removeEventListener("click",ee),U.removeEventListener("pointerleave",B)}},[b,m,y,T,O,D,S]),null}function ua({imageWidth:e,imageHeight:t,tiles:n,viewState:r,className:i,style:o}){const s=g.useRef(null),a=g.useRef(null),l=g.useMemo(()=>({width:"100%",height:"100%",display:"block",...o}),[o]);return g.useEffect(()=>{const u=s.current;if(!u)return;const f=new Nr({canvas:u,imageWidth:e,imageHeight:t,initialViewState:r});return a.current=f,f.setTiles(n),()=>{f.destroy(),a.current=null}},[e,t]),g.useEffect(()=>{const u=a.current;u&&u.setTiles(n)},[n]),g.useEffect(()=>{const u=a.current;!u||!r||u.setViewState(r)},[r]),Ye.jsx("canvas",{ref:s,className:i,style:l})}function fa(e,t){if(!t)return!1;try{const r=new URL(e,typeof window<"u"?window.location.href:void 0).hostname.toLowerCase();if(r.includes("amazonaws.com")||r.startsWith("s3.")||r.includes(".s3."))return!1}catch{}return!0}class ci{constructor(t){R(this,"maxConcurrency");R(this,"maxRetries");R(this,"retryBaseDelayMs");R(this,"retryMaxDelayMs");R(this,"onTileLoad");R(this,"onTileError");R(this,"onStateChange");R(this,"authToken");R(this,"destroyed",!1);R(this,"queue",[]);R(this,"queuedByKey",new Map);R(this,"inflight",new Map);R(this,"visibleKeys",new Set);R(this,"timerId",null);R(this,"abortedCount",0);R(this,"retryCount",0);R(this,"failedCount",0);this.maxConcurrency=Math.max(1,Math.floor(t.maxConcurrency??12)),this.maxRetries=Math.max(0,Math.floor(t.maxRetries??2)),this.retryBaseDelayMs=Math.max(10,Math.floor(t.retryBaseDelayMs??120)),this.retryMaxDelayMs=Math.max(this.retryBaseDelayMs,Math.floor(t.retryMaxDelayMs??1200)),this.authToken=t.authToken??"",this.onTileLoad=t.onTileLoad,this.onTileError=t.onTileError,this.onStateChange=t.onStateChange}setAuthToken(t){this.authToken=String(t??"")}schedule(t){if(this.destroyed)return;const n=new Set;for(const r of t)n.add(r.key);this.visibleKeys=n,this.dropInvisibleQueued(n),this.abortInvisibleInflight(n);for(const r of t){if(this.inflight.has(r.key)){const s=this.inflight.get(r.key);s&&(s.tile=r);continue}const i=this.queuedByKey.get(r.key);if(i){i.tile=r;continue}const o={tile:r,attempt:0,readyAt:be()};this.queue.push(o),this.queuedByKey.set(r.key,o)}this.sortQueue(),this.pump(),this.emitStateChange()}clear(){this.clearPumpTimer(),this.visibleKeys.clear(),this.queue=[],this.queuedByKey.clear();for(const[,t]of this.inflight)t.controller.abort();this.inflight.clear(),this.emitStateChange()}destroy(){this.destroyed||(this.destroyed=!0,this.clear())}getInflightCount(){return this.inflight.size}getSnapshot(){return{inflight:this.inflight.size,queued:this.queue.length,aborted:this.abortedCount,retries:this.retryCount,failed:this.failedCount}}dropInvisibleQueued(t){if(this.queue.length===0)return;const n=[];for(const r of this.queue){if(!t.has(r.tile.key)){this.queuedByKey.delete(r.tile.key);continue}n.push(r)}this.queue=n}abortInvisibleInflight(t){for(const[n,r]of this.inflight)t.has(n)||(this.inflight.delete(n),this.abortedCount+=1,r.controller.abort())}sortQueue(){this.queue.sort((t,n)=>t.readyAt!==n.readyAt?t.readyAt-n.readyAt:t.tile.distance2!==n.tile.distance2?t.tile.distance2-n.tile.distance2:t.tile.tier!==n.tile.tier?n.tile.tier-t.tile.tier:t.tile.key.localeCompare(n.tile.key))}pump(){if(this.destroyed)return;for(this.clearPumpTimer();this.inflight.size<this.maxConcurrency;){const r=this.takeNextReadyQueueItem();if(!r)break;this.startFetch(r)}if(this.inflight.size>=this.maxConcurrency||this.queue.length===0)return;const t=this.queue[0]?.readyAt;if(typeof t!="number")return;const n=Math.max(0,t-be());this.timerId=globalThis.setTimeout(()=>{this.timerId=null,this.pump()},n)}takeNextReadyQueueItem(){if(this.queue.length===0)return null;const t=be(),n=this.queue[0];return!n||n.readyAt>t?null:(this.queue.shift(),this.queuedByKey.delete(n.tile.key),n)}startFetch(t){const n=new AbortController,r={tile:t.tile,attempt:t.attempt,controller:n};this.inflight.set(t.tile.key,r),this.emitStateChange();const i=fa(t.tile.url,this.authToken);fetch(t.tile.url,{signal:n.signal,headers:i?{Authorization:this.authToken}:void 0}).then(o=>{if(!o.ok)throw new Error(`HTTP ${o.status}`);return o.blob()}).then(o=>createImageBitmap(o)).then(o=>{if(this.destroyed||n.signal.aborted){o.close();return}if(!this.visibleKeys.has(t.tile.key)){o.close();return}this.onTileLoad(t.tile,o)}).catch(o=>{if(n.signal.aborted||this.destroyed)return;if(t.attempt<this.maxRetries&&this.visibleKeys.has(t.tile.key)){this.retryCount+=1;const a=t.attempt+1,l=this.getRetryDelay(a),u={tile:t.tile,attempt:a,readyAt:be()+l},f=this.queuedByKey.get(t.tile.key);f?(f.tile=u.tile,f.readyAt=Math.min(f.readyAt,u.readyAt),f.attempt=Math.max(f.attempt,u.attempt)):(this.queue.push(u),this.queuedByKey.set(u.tile.key,u)),this.sortQueue();return}this.failedCount+=1,this.onTileError?.(t.tile,o,t.attempt+1)}).finally(()=>{this.inflight.delete(t.tile.key),this.pump(),this.emitStateChange()})}getRetryDelay(t){const n=Math.max(0,t-1),r=Math.min(this.retryMaxDelayMs,this.retryBaseDelayMs*2**n),i=.85+Math.random()*.3;return Math.round(r*i)}clearPumpTimer(){this.timerId!==null&&(globalThis.clearTimeout(this.timerId),this.timerId=null)}emitStateChange(){this.onStateChange?.(this.getSnapshot())}}function ha(e,t){e.addEventListener("pointerdown",t.pointerDown),e.addEventListener("pointermove",t.pointerMove),e.addEventListener("pointerup",t.pointerUp),e.addEventListener("pointercancel",t.pointerUp),e.addEventListener("wheel",t.wheel,{passive:!1}),e.addEventListener("dblclick",t.doubleClick),e.addEventListener("contextmenu",t.contextMenu),e.addEventListener("webglcontextlost",t.contextLost),e.addEventListener("webglcontextrestored",t.contextRestored)}function da(e,t){e.removeEventListener("pointerdown",t.pointerDown),e.removeEventListener("pointermove",t.pointerMove),e.removeEventListener("pointerup",t.pointerUp),e.removeEventListener("pointercancel",t.pointerUp),e.removeEventListener("wheel",t.wheel),e.removeEventListener("dblclick",t.doubleClick),e.removeEventListener("contextmenu",t.contextMenu),e.removeEventListener("webglcontextlost",t.contextLost),e.removeEventListener("webglcontextrestored",t.contextRestored)}function ma(e,t,n){const r=e.getBoundingClientRect(),i=Math.max(1,r.width||e.clientWidth||1),o=Math.max(1,r.height||e.clientHeight||1),s=Math.max(1,window.devicePixelRatio||1),a=Math.max(1,Math.round(i*s)),l=Math.max(1,Math.round(o*s));(e.width!==a||e.height!==l)&&(e.width=a,e.height=l),n.setViewport(i,o),t.viewport(0,0,a,l)}const mn=.35,gn=.5,ga=256,pn=[{zoom:1,size:2.8},{zoom:2,size:3.4},{zoom:3,size:4.2},{zoom:4,size:5.3},{zoom:5,size:6.8},{zoom:6,size:8.4},{zoom:7,size:9.8},{zoom:8,size:11.2},{zoom:9,size:14},{zoom:10,size:17.5},{zoom:11,size:22},{zoom:12,size:28}],pa=.1,ya=5,ba=0,wa=1,xa=-100,Sa=100,Ea=2e3;function Vt(e){return e*Math.PI/180}function It(e,t){return!e||!t?e===t:e.buffer===t.buffer&&e.byteOffset===t.byteOffset&&e.byteLength===t.byteLength}function yn(e){return e.map(t=>({zoom:t.zoom,size:t.size}))}function Rr(e){if(!e)return yn(pn);const t=new Map;for(const[n,r]of Object.entries(e)){const i=Number(n),o=Number(r);!Number.isFinite(i)||!Number.isFinite(o)||o<=0||t.set(i,o)}return t.size===0?yn(pn):Array.from(t.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function Ra(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n].zoom!==t[n].zoom||e[n].size!==t[n].size)return!1;return!0}function Ma(e,t){if(!Number.isFinite(e))return t[0]?.size??gn;if(t.length===0)return gn;if(t.length===1||e<=t[0].zoom)return t[0].size;for(let s=1;s<t.length;s+=1){const a=t[s-1],l=t[s];if(e>l.zoom)continue;const u=Math.max(1e-6,l.zoom-a.zoom),f=W((e-a.zoom)/u,0,1);return a.size+(l.size-a.size)*f}const n=t[t.length-1],r=t[t.length-2],i=Math.max(1e-6,n.zoom-r.zoom),o=(n.size-r.size)/i;return n.size+(e-n.zoom)*o}function Mr(e){return typeof e!="number"||!Number.isFinite(e)?1:W(e,pa,ya)}function Ar(e){return typeof e!="number"||!Number.isFinite(e)?0:W(e,ba,wa)}function Jt(e){return typeof e!="number"||!Number.isFinite(e)?0:W(e,xa,Sa)}function vr(e){const t=Jt(e?.brightness),n=Jt(e?.contrast),r=Jt(e?.saturation);return{brightness:t/200,contrast:n/100,saturation:r/100}}function Tn(e){return e}function en(e){return typeof e!="number"||!Number.isFinite(e)?0:W(e,0,Ea)}function Pt(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:Math.max(1e-6,e)}function tn(e){return typeof e=="function"?e:Tn}function ui(e,t,n){const r=e.getBoundingClientRect(),i=t-r.left-r.width*.5,o=n-r.top-r.height*.5;return Math.atan2(o,i)}function fi(e,t){if(t.pointerId!==null&&e.hasPointerCapture(t.pointerId))try{e.releasePointerCapture(t.pointerId)}catch{}t.dragging=!1,t.mode="none",t.rotateLastAngleRad=null,t.pointerId=null,e.classList.remove("dragging")}function Aa(e){const{event:t,canvas:n,state:r,config:i,cancelViewAnimation:o}=e,s=i.ctrlDragRotate&&(t.ctrlKey||t.metaKey);(t.button===0||s&&t.button===2)&&(o(),s&&t.preventDefault(),r.dragging=!0,r.mode=s?"rotate":"pan",r.pointerId=t.pointerId,r.lastPointerX=t.clientX,r.lastPointerY=t.clientY,r.rotateLastAngleRad=r.mode==="rotate"?ui(n,t.clientX,t.clientY):null,n.classList.add("dragging"),n.setPointerCapture(t.pointerId))}function va(e){const{event:t,canvas:n,state:r,config:i,camera:o,clampViewState:s,emitViewState:a,requestRender:l}=e;if(!r.dragging||t.pointerId!==r.pointerId)return;const u=t.clientX-r.lastPointerX,f=t.clientY-r.lastPointerY;if(r.lastPointerX=t.clientX,r.lastPointerY=t.clientY,r.mode==="rotate"){const c=ui(n,t.clientX,t.clientY),h=r.rotateLastAngleRad;if(r.rotateLastAngleRad=c,h!==null){const d=c-h,m=Math.atan2(Math.sin(d),Math.cos(d)),p=i.rotationDragSensitivityDegPerPixel/mn,y=o.getViewState();o.setViewState({rotationDeg:y.rotationDeg-m*180/Math.PI*p})}}else{const c=o.getViewState(),h=Math.max(1e-6,c.zoom),d=Vt(c.rotationDeg),m=Math.cos(d),p=Math.sin(d),y=(u*m-f*p)/h,b=(u*p+f*m)/h;o.setViewState({offsetX:c.offsetX-y,offsetY:c.offsetY-b})}s(),a(),l()}function Ca(e,t,n){e.pointerId===n.pointerId&&fi(t,n)}function Ia(e){const{event:t,canvas:n,onZoomBy:r}=e;t.preventDefault();const i=n.getBoundingClientRect(),o=t.clientX-i.left,s=t.clientY-i.top,a=t.deltaY<0?1.12:.89;r(a,o,s)}const Pa=4;function Ta(e){const{event:t,canvas:n,snapState:r,onSnapZoom:i}=e;t.preventDefault();const o=t.deltaY<0?"in":t.deltaY>0?"out":null;if(o&&r.blockedDirection)if(o!==r.blockedDirection)r.blockedDirection=null,r.accumulatedDelta=0;else return;if(r.accumulatedDelta!==0&&t.deltaY!==0&&Math.sign(r.accumulatedDelta)!==Math.sign(t.deltaY)&&(r.accumulatedDelta=0),r.accumulatedDelta+=t.deltaY,Math.abs(r.accumulatedDelta)<Pa)return;const s=n.getBoundingClientRect(),a=t.clientX-s.left,l=t.clientY-s.top,u=r.accumulatedDelta>0?"out":"in";if(r.accumulatedDelta=0,!i(u,a,l)){r.blockedDirection=u;return}r.blockedDirection=null}function _a(e){const{event:t,canvas:n,onZoomBy:r}=e,i=n.getBoundingClientRect(),o=t.clientX-i.left,s=t.clientY-i.top;r(t.shiftKey?.8:1.25,o,s)}function Fa(e,t){(t||e.ctrlKey||e.metaKey)&&e.preventDefault()}function Xt(e){const t=e.getViewCorners();let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[s,a]of t)s<n&&(n=s),s>i&&(i=s),a<r&&(r=a),a>o&&(o=a);return[n,r,i,o]}function kt(e,t){const n=Xt(e),r=Math.max(1e-6,n[2]-n[0]),i=Math.max(1e-6,n[3]-n[1]),o=r*.2,s=i*.2,[a,l]=e.getCenter(),u=r*.5,f=i*.5,c=u-o,h=t.width-u+o,d=f-s,m=t.height-f+s,p=c<=h?W(a,c,h):t.width*.5,y=d<=m?W(l,d,m):t.height*.5;e.setCenter(p,y)}function La(e,t){const n=Math.max(1e-6,e.getViewState().zoom),r=t.maxTierZoom+Math.log2(n);return W(Math.floor(r),0,t.maxTierZoom)}function ka(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function hi(e,t,n){const r=Xt(e),i=Math.pow(2,t.maxTierZoom-n),o=Math.ceil(t.width/i),s=Math.ceil(t.height/i),a=Math.max(1,Math.ceil(o/t.tileSize)),l=Math.max(1,Math.ceil(s/t.tileSize)),u=r[0],f=r[1],c=r[2],h=r[3],d=W(Math.floor(u/i/t.tileSize),0,a-1),m=W(Math.floor((c-1)/i/t.tileSize),0,a-1),p=W(Math.floor(f/i/t.tileSize),0,l-1),y=W(Math.floor((h-1)/i/t.tileSize),0,l-1);if(d>m||p>y)return[];const b=(u+c)*.5/i/t.tileSize,x=(f+h)*.5/i/t.tileSize,C=[];for(let S=p;S<=y;S+=1)for(let A=d;A<=m;A+=1){const T=A*t.tileSize*i,O=S*t.tileSize*i,D=Math.min((A+1)*t.tileSize,o)*i,G=Math.min((S+1)*t.tileSize,s)*i,z=A-b,q=S-x;C.push({key:`${n}/${A}/${S}`,tier:n,x:A,y:S,bounds:[T,O,D,G],distance2:z*z+q*q,url:Pn(t,n,A,S)})}return C.sort((S,A)=>S.distance2-A.distance2),C}function Na(e,t){const n=La(e,t);return{tier:n,visible:hi(e,t,n)}}function Ba(e){e.interactionLocked||Aa({event:e.event,canvas:e.canvas,state:e.state,config:{ctrlDragRotate:e.ctrlDragRotate,rotationDragSensitivityDegPerPixel:e.rotationDragSensitivityDegPerPixel},cancelViewAnimation:e.cancelViewAnimation})}function Da(e){e.interactionLocked||va({event:e.event,canvas:e.canvas,state:e.state,config:{ctrlDragRotate:e.ctrlDragRotate,rotationDragSensitivityDegPerPixel:e.rotationDragSensitivityDegPerPixel},camera:e.camera,clampViewState:()=>kt(e.camera,e.source),emitViewState:e.emitViewState,requestRender:e.requestRender})}function za(e){e.interactionLocked||Ca(e.event,e.canvas,e.state)}function Ua(e){e.interactionLocked||_a({event:e.event,canvas:e.canvas,onZoomBy:e.onZoomBy})}function Oa(e){Fa(e.event,e.state.dragging)}function Ya(e,t){fi(e,t)}function Wa(e){return{pointerDown:t=>Ba({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state,ctrlDragRotate:e.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:e.getRotationDragSensitivityDegPerPixel(),cancelViewAnimation:e.cancelViewAnimation}),pointerMove:t=>Da({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state,ctrlDragRotate:e.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:e.getRotationDragSensitivityDegPerPixel(),camera:e.camera,source:e.source,emitViewState:e.emitViewState,requestRender:e.requestRender}),pointerUp:t=>za({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state}),wheel:t=>{if(e.getInteractionLocked()){t.preventDefault();return}if(e.getUseZoomSnaps?.()&&e.onSnapZoom&&e.zoomSnapState){Ta({event:t,canvas:e.canvas,snapState:e.zoomSnapState,onSnapZoom:e.onSnapZoom});return}Ia({event:t,canvas:e.canvas,onZoomBy:e.zoomBy})},doubleClick:t=>Ua({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,onZoomBy:e.zoomBy}),contextMenu:t=>Oa({event:t,canvas:e.canvas,state:e.state})}}function Xa(e){const{gl:t,cache:n,maxCacheTiles:r}=e;if(n.size<=r)return;const i=Math.max(0,Math.floor(r));for(;n.size>i;){let o=null,s=null;for(const[a,l]of n)(!s||l.lastUsed<s.lastUsed)&&(o=a,s=l);if(!o||!s)break;t.deleteTexture(s.texture),n.delete(o)}}function Va(e,t){if(e.isContextLost())return null;const n=e.createTexture();return n?(e.bindTexture(e.TEXTURE_2D,n),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,1),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.bindTexture(e.TEXTURE_2D,null),n):null}function Ga(e){const{gl:t,cache:n,tile:r,bitmap:i,frameSerial:o,maxCacheTiles:s,destroyed:a,contextLost:l,requestRender:u}=e;if(a||l||t.isContextLost()){i.close();return}if(n.has(r.key)){i.close();return}const f=Va(t,i);i.close(),f&&(n.set(r.key,{key:r.key,texture:f,bounds:r.bounds,tier:r.tier,lastUsed:o}),Xa({gl:t,cache:n,maxCacheTiles:s}),u())}function qa(e,t){for(const[,n]of t)e.deleteTexture(n.texture)}function Ha(e){const{event:t,destroyed:n,contextLost:r,cancelViewAnimation:i,cancelDrag:o,tileScheduler:s,cache:a,onContextLost:l}=e;if(t.preventDefault(),n||r)return{handled:!1,frame:e.frame};let u=e.frame;return u!==null&&(cancelAnimationFrame(u),u=null),i(),o(),s.clear(),a.clear(),l?.(),{handled:!0,frame:u}}function Za(e){if(e.destroyed)return{didDestroy:!1,frame:e.frame};let t=e.frame;return t!==null&&(cancelAnimationFrame(t),t=null),e.cancelViewAnimation(),e.resizeObserver.disconnect(),e.removeCanvasEventListeners(),e.cancelDrag(),e.tileScheduler.destroy(),!e.contextLost&&!e.gl.isContextLost()&&(qa(e.gl,e.cache),e.gl.deleteBuffer(e.tileProgram.vbo),e.gl.deleteVertexArray(e.tileProgram.vao),e.gl.deleteProgram(e.tileProgram.program),e.gl.deleteBuffer(e.pointProgram.posBuffer),e.gl.deleteBuffer(e.pointProgram.termBuffer),e.gl.deleteBuffer(e.pointProgram.fillModeBuffer),e.gl.deleteBuffer(e.pointProgram.indexBuffer),e.gl.deleteTexture(e.pointProgram.paletteTexture),e.gl.deleteVertexArray(e.pointProgram.vao),e.gl.deleteProgram(e.pointProgram.program)),e.cache.clear(),{didDestroy:!0,frame:t}}function $a(e,t){if(t<=0||e.length===0)return new Uint32Array(0);let n=e.length;for(let o=0;o<e.length;o+=1)e[o]<t||(n-=1);if(n===e.length)return e;if(n<=0)return new Uint32Array(0);const r=new Uint32Array(n);let i=0;for(let o=0;o<e.length;o+=1){const s=e[o];s>=t||(r[i]=s,i+=1)}return r}function Ka(e,t){return t<=0?new Uint8Array(0):e.length<t?new Uint8Array(t):e.subarray(0,t)}function ja(e,t,n,r,i){if(!i||i.length===0)return{...e,lastPointPalette:null};const o=new Uint8Array(i);if(r||t.isContextLost())return{...e,lastPointPalette:o};const s=Math.max(1,Math.floor(o.length/4));return t.bindTexture(t.TEXTURE_2D,n.paletteTexture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,s,1,0,t.RGBA,t.UNSIGNED_BYTE,o),t.bindTexture(t.TEXTURE_2D,null),{...e,lastPointPalette:o,pointPaletteSize:s}}function Qa(e,t,n,r,i){if(!i||!i.count||!i.positions||!i.paletteIndices)return{...e,lastPointData:null,pointCount:0,usePointIndices:!1};const o=i.fillModes instanceof Uint8Array?i.fillModes:null,s=o!==null,a=Math.max(0,Math.min(i.count,Math.floor(i.positions.length/2),i.paletteIndices.length,s?o.length:Number.MAX_SAFE_INTEGER)),l=i.positions.subarray(0,a*2),u=i.paletteIndices.subarray(0,a),f=s?o.subarray(0,a):void 0,c=i.drawIndices instanceof Uint32Array,h=c?$a(i.drawIndices,a):null,d=e.lastPointData,m=d?.fillModes instanceof Uint8Array,p=e.pointBuffersDirty||!d||d.count!==a||!It(d.positions,l)||!It(d.paletteIndices,u)||m!==s||s&&(!d?.fillModes||!It(d.fillModes,f)),y=e.pointBuffersDirty||c&&(!d?.drawIndices||!It(d.drawIndices,h))||!c&&!!d?.drawIndices,b={...e,lastPointData:{count:a,positions:l,paletteIndices:u,fillModes:f,drawIndices:c?h??void 0:void 0}};if(r||t.isContextLost())return b;const x=b.lastPointData;if(!x)return b;if(p){t.bindBuffer(t.ARRAY_BUFFER,n.posBuffer),t.bufferData(t.ARRAY_BUFFER,x.positions,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,n.termBuffer),t.bufferData(t.ARRAY_BUFFER,x.paletteIndices,t.STATIC_DRAW);const C=Ka(b.zeroFillModes,a);t.bindBuffer(t.ARRAY_BUFFER,n.fillModeBuffer),t.bufferData(t.ARRAY_BUFFER,x.fillModes??C,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,null),b.zeroFillModes=C}return c&&y&&(t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,n.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,h??new Uint32Array(0),t.DYNAMIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null)),b.usePointIndices=c,b.pointCount=c?h?.length??0:x.count,(p||y)&&(b.pointBuffersDirty=!1),b}function Ja(e){const{gl:t,camera:n,source:r,cache:i,frameSerial:o,tileProgram:s,pointProgram:a,imageColorSettings:l,pointCount:u,usePointIndices:f,pointPaletteSize:c,pointStrokeScale:h,pointInnerFillOpacity:d,pointSizePx:m,tileScheduler:p,getVisibleTiles:y,getVisibleTilesForTier:b,getViewBounds:x,intersectsBounds:C}=e;t.clearColor(.03,.06,.1,1),t.clear(t.COLOR_BUFFER_BIT);const{tier:S,visible:A}=y(),T=x(),O=new Set(A.map(N=>N.key));t.useProgram(s.program),t.bindVertexArray(s.vao),t.uniformMatrix3fv(s.uCamera,!1,n.getMatrix()),t.uniform1i(s.uTexture,0),t.uniform1f(s.uBrightness,l.brightness),t.uniform1f(s.uContrast,l.contrast),t.uniform1f(s.uSaturation,l.saturation);const D=[];for(const[,N]of i)O.has(N.key)||C(N.bounds,T)&&D.push(N);D.sort((N,k)=>N.tier-k.tier);for(const N of D)N.lastUsed=o,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,N.texture),t.uniform4f(s.uBounds,N.bounds[0],N.bounds[1],N.bounds[2],N.bounds[3]),t.drawArrays(t.TRIANGLE_STRIP,0,4);let G=0;const z=[];for(const N of A){const k=i.get(N.key);if(!k){z.push(N);continue}k.lastUsed=o,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,k.texture),t.uniform4f(s.uBounds,k.bounds[0],k.bounds[1],k.bounds[2],k.bounds[3]),t.drawArrays(t.TRIANGLE_STRIP,0,4),G+=1}const q=z.slice(),re=1e6,I=[];S>0&&I.push(S-1),S<r.maxTierZoom&&I.push(S+1);for(const N of I){const k=b(N);for(const Z of k)i.has(Z.key)||(Z.distance2+=re,q.push(Z))}p.schedule(q),t.bindTexture(t.TEXTURE_2D,null),t.bindVertexArray(null);let H=0;return u>0&&(t.enable(t.BLEND),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA),t.useProgram(a.program),t.bindVertexArray(a.vao),t.uniformMatrix3fv(a.uCamera,!1,n.getMatrix()),t.uniform1f(a.uPointSize,m),t.uniform1f(a.uPointStrokeScale,h),t.uniform1f(a.uPointInnerFillAlpha,d),t.uniform1f(a.uPaletteSize,c),t.uniform1i(a.uPalette,1),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,a.paletteTexture),f?t.drawElements(t.POINTS,u,t.UNSIGNED_INT,0):t.drawArrays(t.POINTS,0,u),t.bindTexture(t.TEXTURE_2D,null),t.bindVertexArray(null),H=u),{tier:S,visible:A.length,rendered:G,points:H,fallback:D.length,cacheHits:G,cacheMisses:z.length,drawCalls:D.length+G+(H>0?1:0)}}function Cr(e){const r=bn(e,`#version 300 es
|
|
64
|
+
`;function Is(){if(typeof navigator>"u")return!1;const e=navigator;return typeof e.gpu=="object"&&e.gpu!==null}function ni(){if(!Is())return null;const t=navigator.gpu;if(!t||typeof t!="object")return null;const n=t;return typeof n.requestAdapter!="function"?null:n}const vt=globalThis.GPUShaderStage?.COMPUTE??4,Jt=globalThis.GPUBufferUsage?.STORAGE??128,Ct=globalThis.GPUBufferUsage?.COPY_DST??8,Ps=globalThis.GPUBufferUsage?.COPY_SRC??4,Ts=globalThis.GPUBufferUsage?.UNIFORM??64,_s=globalThis.GPUBufferUsage?.MAP_READ??1,Ls=globalThis.GPUMapMode?.READ??1;async function Fs(){const e=ni();if(!e)return{supported:!1,features:[]};const t=await e.requestAdapter();return t?{supported:!0,adapterName:t.info?.description??t.info?.vendor??"unknown",features:Array.from(t.features),limits:{maxStorageBufferBindingSize:Number(t.limits.maxStorageBufferBindingSize),maxComputeInvocationsPerWorkgroup:Number(t.limits.maxComputeInvocationsPerWorkgroup),maxComputeWorkgroupSizeX:Number(t.limits.maxComputeWorkgroupSizeX)}}:{supported:!1,features:[]}}async function ks(){return At||(At=(async()=>{const e=ni();if(!e)return null;const t=await e.requestAdapter();if(!t)return null;const n=await t.requestDevice(),r=n.createBindGroupLayout({entries:[{binding:0,visibility:vt,buffer:{type:"read-only-storage"}},{binding:1,visibility:vt,buffer:{type:"read-only-storage"}},{binding:2,visibility:vt,buffer:{type:"storage"}},{binding:3,visibility:vt,buffer:{type:"uniform"}}]}),i=n.createComputePipeline({layout:n.createPipelineLayout({bindGroupLayouts:[r]}),compute:{module:n.createShaderModule({code:Cs}),entryPoint:"main"}});return{device:n,pipeline:i,bindGroupLayout:r}})(),At)}function It(e,t){return Math.ceil(e/t)*t}async function ri(e,t,n){const r=await ks();if(!r)return null;const i=Math.max(0,Math.floor(t)),o=Math.max(0,Math.floor(n.length/4));if(i===0||o===0)return new Uint32Array(0);const s=Math.min(i,Math.floor(e.length/2));if(s===0)return new Uint32Array(0);const a=s*2*Float32Array.BYTES_PER_ELEMENT,l=o*4*Float32Array.BYTES_PER_ELEMENT,u=s*Uint32Array.BYTES_PER_ELEMENT,f=Number(r.device.limits.maxStorageBufferBindingSize);if(a>f||l>f||u>f)return null;const c=r.device.createBuffer({size:It(a,4),usage:Jt|Ct}),h=r.device.createBuffer({size:It(l,4),usage:Jt|Ct}),d=r.device.createBuffer({size:It(u,4),usage:Jt|Ps}),m=r.device.createBuffer({size:16,usage:Ts|Ct}),p=r.device.createBuffer({size:It(u,4),usage:Ct|_s});let y=!1;try{r.device.queue.writeBuffer(c,0,e.buffer,e.byteOffset,a),r.device.queue.writeBuffer(h,0,n.buffer,n.byteOffset,l),r.device.queue.writeBuffer(m,0,new Uint32Array([s,o,0,0]));const b=r.device.createBindGroup({layout:r.bindGroupLayout,entries:[{binding:0,resource:{buffer:c}},{binding:1,resource:{buffer:h}},{binding:2,resource:{buffer:d}},{binding:3,resource:{buffer:m}}]}),x=r.device.createCommandEncoder(),C=x.beginComputePass();C.setPipeline(r.pipeline),C.setBindGroup(0,b),C.dispatchWorkgroups(Math.ceil(s/256)),C.end(),x.copyBufferToBuffer(d,0,p,0,u),r.device.queue.submit([x.finish()]),await p.mapAsync(Ls),y=!0;const S=p.getMappedRange();return new Uint32Array(S.slice(0))}finally{if(y)try{p.unmap()}catch{}c.destroy(),h.destroy(),d.destroy(),m.destroy(),p.destroy()}}async function ii(e,t,n={}){const r=ye(),i=n.bridgeToDraw===!0;if(!e||!e.count||!e.positions||!e.paletteIndices)return{data:null,meta:{mode:"hybrid-webgpu",durationMs:ye()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}};const o=bt(t??[]);if(o.length===0){const S={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return e.fillModes instanceof Uint8Array&&(S.fillModes=new Uint8Array(0)),e.ids instanceof Uint32Array&&(S.ids=new Uint32Array(0)),{data:S,meta:{mode:"hybrid-webgpu",durationMs:ye()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const s=tt(e),a=e.fillModes instanceof Uint8Array&&e.fillModes.length>=s?e.fillModes:null,l=e.ids instanceof Uint32Array&&e.ids.length>=s?e.ids:null;if(s===0){const S={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(S.fillModes=new Uint8Array(0)),l&&(S.ids=new Uint32Array(0)),{data:S,meta:{mode:"hybrid-webgpu",durationMs:ye()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const u=new Float32Array(o.length*4);for(let S=0;S<o.length;S+=1){const A=S*4,_=o[S];u[A]=_.minX,u[A+1]=_.minY,u[A+2]=_.maxX,u[A+3]=_.maxY}let f=null,c=!1;try{f=await ri(e.positions,s,u),c=!!f}catch{f=null,c=!1}if(!f)return{data:mt(e,t),meta:{mode:"hybrid-webgpu",durationMs:ye()-r,usedWebGpu:!1,candidateCount:s,bridgedToDraw:!1}};let h=0;for(let S=0;S<s;S+=1)f[S]===1&&(h+=1);const d=new Uint32Array(h);if(h>0){let S=0;for(let A=0;A<s;A+=1)f[A]===1&&(d[S]=A,S+=1)}if(h===0){if(i){const A={count:s,positions:e.positions.subarray(0,s*2),paletteIndices:e.paletteIndices.subarray(0,s),drawIndices:new Uint32Array(0)};return a&&(A.fillModes=a.subarray(0,s)),l&&(A.ids=l.subarray(0,s)),{data:A,meta:{mode:"hybrid-webgpu",durationMs:ye()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!0}}}const S={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(S.fillModes=new Uint8Array(0)),l&&(S.ids=new Uint32Array(0)),{data:S,meta:{mode:"hybrid-webgpu",durationMs:ye()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const S=new Uint32Array(h);let A=0;for(let Y=0;Y<h;Y+=1){const B=d[Y]??0,G=e.positions[B*2],z=e.positions[B*2+1];Dt(G,z,o)&&(S[A]=B,A+=1)}const _={count:s,positions:e.positions.subarray(0,s*2),paletteIndices:e.paletteIndices.subarray(0,s),drawIndices:S.subarray(0,A)};return a&&(_.fillModes=a.subarray(0,s)),l&&(_.ids=l.subarray(0,s)),{data:_,meta:{mode:"hybrid-webgpu",durationMs:ye()-r,usedWebGpu:!0,candidateCount:h,bridgedToDraw:!0}}}const m=new Float32Array(h*2),p=new Uint16Array(h),y=a?new Uint8Array(h):null,b=l?new Uint32Array(h):null;let x=0;for(let S=0;S<h;S+=1){const A=d[S]??0,_=e.positions[A*2],Y=e.positions[A*2+1];Dt(_,Y,o)&&(m[x*2]=_,m[x*2+1]=Y,p[x]=e.paletteIndices[A],y&&(y[x]=a[A]),b&&(b[x]=l[A]),x+=1)}const C={count:x,positions:m.subarray(0,x*2),paletteIndices:p.subarray(0,x)};return y&&(C.fillModes=y.subarray(0,x)),b&&(C.ids=b.subarray(0,x)),{data:C,meta:{mode:"hybrid-webgpu",durationMs:ye()-r,usedWebGpu:!0,candidateCount:h,bridgedToDraw:!1}}}class oi{constructor(t,n){R(this,"worker",null);R(this,"supported",!0);R(this,"requestId",1);R(this,"pendingById",new Map);R(this,"handleMessage",t=>{const n=t.data;if(!n)return;const r=this.pendingById.get(n.id);r&&(this.pendingById.delete(n.id),this.handlers.onResponse(n,r))});R(this,"handleError",()=>{this.supported=!1,this.teardownWorker("worker crashed")});this.createWorker=t,this.handlers=n}beginRequest(t){const n=this.getOrCreateWorker();if(!n)return null;const r=this.requestId++;return this.pendingById.set(r,t),{id:r,worker:n}}cancelRequest(t){const n=this.pendingById.get(t);if(n)return this.pendingById.delete(t),n}terminate(t="worker terminated"){this.teardownWorker(t)}getOrCreateWorker(){if(!this.supported)return null;if(this.worker)return this.worker;try{const t=this.createWorker();return t.addEventListener("message",this.handleMessage),t.addEventListener("error",this.handleError),this.worker=t,t}catch{return this.supported=!1,null}}teardownWorker(t){this.worker&&(this.worker.removeEventListener("message",this.handleMessage),this.worker.removeEventListener("error",this.handleError),this.worker.terminate(),this.worker=null);const n=new Error(t);for(const[,r]of this.pendingById)this.handlers.rejectPending(r,n);this.pendingById.clear()}}const gt=new oi(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/roi-clip-worker-BuNuUQQg.js").href:new URL("assets/roi-clip-worker-BuNuUQQg.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:st&&st.tagName.toUpperCase()==="SCRIPT"&&st.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(e,t)=>{if(e.type==="roi-clip-failure"){t.reject(new Error(e.error||"worker clip failed"));return}if(e.type==="roi-clip-index-success"){if(t.kind!=="index"){t.reject(new Error("worker response mismatch: expected point data result"));return}const l=Math.max(0,Math.floor(e.count)),u=new Uint32Array(e.indices).subarray(0,l);t.resolve({indices:u,meta:{mode:"worker",durationMs:Number.isFinite(e.durationMs)?e.durationMs:ye()-t.startMs}});return}if(t.kind!=="data"){t.reject(new Error("worker response mismatch: expected index result"));return}const n=Math.max(0,Math.floor(e.count)),r=new Float32Array(e.positions),i=new Uint16Array(e.paletteIndices),o=e.fillModes?new Uint8Array(e.fillModes):null,s=e.ids?new Uint32Array(e.ids):null,a={count:n,positions:r.subarray(0,n*2),paletteIndices:i.subarray(0,n)};o&&(a.fillModes=o.subarray(0,n)),s&&(a.ids=s.subarray(0,n)),t.resolve({data:a,meta:{mode:"worker",durationMs:Number.isFinite(e.durationMs)?e.durationMs:ye()-t.startMs}})},rejectPending:(e,t)=>{e.reject(t)}});function Ns(){gt.terminate("worker terminated")}async function si(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return{data:null,meta:{mode:"worker",durationMs:0}};const n=tt(e),r=e.positions.slice(0,n*2),i=e.paletteIndices.slice(0,n),o=e.fillModes instanceof Uint8Array&&e.fillModes.length>=n?e.fillModes.slice(0,n):null,s=e.ids instanceof Uint32Array&&e.ids.length>=n?e.ids.slice(0,n):null;return new Promise((a,l)=>{const u=ye(),f=gt.beginRequest({kind:"data",resolve:a,reject:l,startMs:u});if(!f){a({data:mt(e,t),meta:{mode:"sync",durationMs:ye()-u}});return}const c={type:"roi-clip-request",id:f.id,count:n,positions:r.buffer,paletteIndices:i.buffer,fillModes:o?.buffer,ids:s?.buffer,polygons:t??[]},h=[r.buffer,i.buffer];o&&h.push(o.buffer),s&&h.push(s.buffer);try{f.worker.postMessage(c,h)}catch(d){const m=gt.cancelRequest(f.id);m?m.reject(d):l(d)}})}async function Bs(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return{indices:new Uint32Array(0),meta:{mode:"worker",durationMs:0}};const n=tt(e),r=e.positions.slice(0,n*2);return new Promise((i,o)=>{const s=ye(),a=gt.beginRequest({kind:"index",resolve:i,reject:o,startMs:s});if(!a){i({indices:ti(e,t),meta:{mode:"sync",durationMs:ye()-s}});return}const l={type:"roi-clip-index-request",id:a.id,count:n,positions:r.buffer,polygons:t??[]};try{a.worker.postMessage(l,[r.buffer])}catch(u){const f=gt.cancelRequest(a.id);f?f.reject(u):o(u)}})}const zs={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};function Ds(e,t,n,r,i){const o=g.useRef(0),[s,a]=g.useState(n),l=g.useMemo(()=>r.map(u=>yt(u.coordinates)).filter(u=>u!=null),[r]);return g.useEffect(()=>{const u=++o.current;let f=!1;if(!e)return a(n),()=>{f=!0};if(!n||!n.count||!n.positions||!n.paletteIndices)return a(null),()=>{f=!0};if(l.length===0)return a(zs),i?.({mode:t,durationMs:0,inputCount:n.count,outputCount:0,polygonCount:0}),()=>{f=!0};const c=(d,m)=>{if(f||u!==o.current)return;const p=n.count,y=d?.drawIndices?d.drawIndices.length:d?.count??0;a(d),i?.({mode:m.mode,durationMs:m.durationMs,inputCount:p,outputCount:y,polygonCount:l.length,usedWebGpu:m.usedWebGpu,candidateCount:m.candidateCount,bridgedToDraw:m.bridgedToDraw})};return(async()=>{if(t==="sync"){const d=performance.now(),m=mt(n,l);c(m,{mode:"sync",durationMs:performance.now()-d});return}if(t==="hybrid-webgpu"){const d=await ii(n,l,{bridgeToDraw:!0});c(d.data,{mode:d.meta.mode,durationMs:d.meta.durationMs,usedWebGpu:d.meta.usedWebGpu,candidateCount:d.meta.candidateCount,bridgedToDraw:d.meta.bridgedToDraw});return}try{const d=await si(n,l);c(d.data,{mode:d.meta.mode,durationMs:d.meta.durationMs})}catch{const d=performance.now(),m=mt(n,l);c(m,{mode:"sync",durationMs:performance.now()-d})}})(),()=>{f=!0}},[e,t,n,l,i]),s}const Us=24,Os=1024,Ys=4,kt=-1;function ut(e,t,n){return(e*73856093^t*19349663)>>>0&n}function Ws(e,t,n){if(e<=0||t<=0||n<=0)return 256;const r=Math.max(1,e*t),o=Math.sqrt(r/Math.max(1,n))*Ys;return Math.max(Us,Math.min(Os,o))}function Xs(e,t){if(!(e instanceof Uint32Array)||e.length===0)return null;let n=!0;for(let o=0;o<e.length;o+=1)if(!(e[o]<t)){n=!1;break}if(n)return e;const r=new Uint32Array(e.length);let i=0;for(let o=0;o<e.length;o+=1)e[o]>=t||(r[i]=e[o],i+=1);return i>0?r.subarray(0,i):null}function Vs(e){const t=Math.max(0,Math.floor(e.count)),n=Math.floor(e.positions.length/2),r=Math.max(0,Math.min(t,n));if(r<=0)return null;const i=Xs(e.drawIndices??null,r),o=i?i.length:r;if(o===0)return null;const s=Ws(e.sourceWidth,e.sourceHeight,o),a=1/s,l=new Int32Array(o),u=new Int32Array(o);let f=0;if(i)for(let P=0;P<o;P+=1){const W=i[P],N=e.positions[W*2],k=e.positions[W*2+1];!Number.isFinite(N)||!Number.isFinite(k)||(l[f]=Math.floor(N*a),u[f]=Math.floor(k*a),f+=1)}else for(let P=0;P<r;P+=1){const W=e.positions[P*2],N=e.positions[P*2+1];!Number.isFinite(W)||!Number.isFinite(N)||(l[f]=Math.floor(W*a),u[f]=Math.floor(N*a),f+=1)}if(f===0)return null;let c=Math.min(f,Math.max(64,f>>>3));(!Number.isFinite(c)||c<=0)&&(c=f);let h=1;for(;h<c*2;)h<<=1;let d=h-1,m=new Int32Array(h*2),p=new Int32Array(h);m.fill(2147483647);let y=0;const b=new Int32Array(f);for(let P=0;P<f;P+=1){const W=l[P],N=u[P];let k=ut(W,N,d);for(;;){const K=m[k*2];if(K===2147483647){if(m[k*2]=W,m[k*2+1]=N,p[k]=1,b[P]=k,y+=1,y*4>h*3){const me=h;h<<=1,d=h-1;const ie=new Int32Array(h*2),ve=new Int32Array(h);ie.fill(2147483647);for(let Se=0;Se<me;Se+=1){if(m[Se*2]===2147483647)continue;const Ce=m[Se*2],v=m[Se*2+1];let M=ut(Ce,v,d);for(;ie[M*2]!==2147483647;)M=M+1&d;ie[M*2]=Ce,ie[M*2+1]=v,ve[M]=p[Se]}for(m=ie,p=ve,k=ut(W,N,d);m[k*2]!==W||m[k*2+1]!==N;)k=k+1&d;b[P]=k}break}if(K===W&&m[k*2+1]===N){p[k]+=1,b[P]=k;break}k=k+1&d}}const x=new Int32Array(y*2),C=new Uint32Array(y),S=new Uint32Array(y),A=new Int32Array(h);A.fill(kt);let _=0,Y=0;for(let P=0;P<h;P+=1)m[P*2]!==2147483647&&(x[_*2]=m[P*2],x[_*2+1]=m[P*2+1],C[_]=Y,S[_]=p[P],A[P]=_,Y+=p[P],_+=1);const B=new Uint32Array(f),G=new Uint32Array(y);if(G.set(C),i)for(let P=0;P<f;P+=1){const W=A[b[P]];B[G[W]]=i[P],G[W]+=1}else{let P=0;for(let W=0;W<r;W+=1){const N=e.positions[W*2],k=e.positions[W*2+1];if(!Number.isFinite(N)||!Number.isFinite(k))continue;const K=A[b[P]];B[G[K]]=W,G[K]+=1,P+=1}}let z=1;for(;z<y*2;)z<<=1;const $=z-1,Q=new Int32Array(z);Q.fill(kt);for(let P=0;P<y;P+=1){const W=x[P*2],N=x[P*2+1];let k=ut(W,N,$);for(;Q[k]!==kt;)k=k+1&$;Q[k]=P}return{cellSize:s,safeCount:r,cellCount:y,hashCapacity:z,hashTable:Q,cellKeys:x,cellOffsets:C,cellLengths:S,pointIndices:B}}function ai(e,t,n){const{hashTable:r,cellKeys:i,hashMask:o}=e;let s=ut(t,n,o);for(;;){const a=r[s];if(a===kt)return-1;if(i[a*2]===t&&i[a*2+1]===n)return a;s=s+1&o}}function Gs(e,t){if(e.safeCount<=0||e.cellCount<=0)return null;const n=e.safeCount;return{cellSize:e.cellSize,safeCount:n,positions:t.positions.subarray(0,n*2),ids:t.ids instanceof Uint32Array&&t.ids.length>=n?t.ids.subarray(0,n):null,hashCapacity:e.hashCapacity,hashMask:e.hashCapacity-1,hashTable:new Int32Array(e.hashTable),cellKeys:new Int32Array(e.cellKeys),cellOffsets:new Uint32Array(e.cellOffsets),cellLengths:new Uint32Array(e.cellLengths),pointIndices:new Uint32Array(e.pointIndices)}}const dn=new oi(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/point-hit-index-worker-CNFA6pZm.js").href:new URL("assets/point-hit-index-worker-CNFA6pZm.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:st&&st.tagName.toUpperCase()==="SCRIPT"&&st.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(e,t)=>{if(e.type==="point-hit-index-failure"){t.reject(new Error(e.error||"worker index build failed"));return}t.resolve(Gs(e,t.pointData))},rejectPending:(e,t)=>{e.reject(t)}});function qs(){dn.terminate("worker terminated")}function Hs(e,t){const n=tt(e);if(n<=0)return null;const r=e.positions.subarray(0,n*2),i=Vs({count:n,positions:r,drawIndices:e.drawIndices instanceof Uint32Array?e.drawIndices:null,sourceWidth:t?.width??0,sourceHeight:t?.height??0});return i?{cellSize:i.cellSize,safeCount:n,positions:r,ids:e.ids instanceof Uint32Array&&e.ids.length>=n?e.ids.subarray(0,n):null,hashCapacity:i.hashCapacity,hashMask:i.hashCapacity-1,hashTable:i.hashTable,cellKeys:i.cellKeys,cellOffsets:i.cellOffsets,cellLengths:i.cellLengths,pointIndices:i.pointIndices}:null}async function li(e,t){if(!e||!e.positions||!e.paletteIndices)return null;const n=tt(e);return n<=0?null:new Promise((r,i)=>{const o={resolve:r,reject:i,pointData:e},s=dn.beginRequest(o);if(!s||!s.worker){r(Hs(e,t));return}const a=e.positions.slice(0,n*2),l=e.drawIndices instanceof Uint32Array&&e.drawIndices.length>0?e.drawIndices.slice():void 0,u={type:"point-hit-index-request",id:s.id,count:n,positions:a.buffer,drawIndices:l?.buffer,sourceWidth:t?.width??0,sourceHeight:t?.height??0},f=[a.buffer];l&&f.push(l.buffer);try{s.worker.postMessage(u,f)}catch(c){const h=dn.cancelRequest(s.id);h?h.reject(c):i(c)}})}const Zs=.65,$s=4;function Ks(e,t,n,r,i,o,s){const a=!!(n||r||i),[l,u]=g.useState(null),f=g.useRef(null),c=g.useRef(null);g.useEffect(()=>{if(!a||!e){u(null);return}let p=!1;return li(e,t).then(y=>{p||u(y)}),()=>{p=!0}},[a,e,t]);const h=g.useCallback(p=>{const y=s.current;if(!y||!l)return null;const b=Number(p[0]),x=Number(p[1]);if(!Number.isFinite(b)||!Number.isFinite(x))return null;const C=Math.max(1e-6,y.getViewState().zoom),S=y.getPointSizeByZoom(),_=Math.max($s,S*Zs)/C;if(!Number.isFinite(_)||_<=0)return null;const{cellSize:Y,cellOffsets:B,cellLengths:G,pointIndices:z,positions:$,safeCount:Q}=l,P=Math.floor(b/Y),W=Math.floor(x/Y),N=Math.max(1,Math.ceil(_/Y)),k=_*_;let K=-1,me=k,ie=0,ve=0;for(let Ce=P-N;Ce<=P+N;Ce+=1)for(let v=W-N;v<=W+N;v+=1){const M=ai(l,Ce,v);if(M<0)continue;const X=B[M],fe=X+G[M];for(let J=X;J<fe;J+=1){const ae=z[J];if(ae>=Q)continue;const le=$[ae*2],ge=$[ae*2+1],oe=le-b,ne=ge-x,be=oe*oe+ne*ne;be>me||(me=be,K=ae,ie=le,ve=ge)}}if(K<0)return null;const Se=l.ids?Number(l.ids[K]):null;return{index:K,id:Se,coordinate:[b,x],pointCoordinate:[ie,ve]}},[l]),d=g.useCallback((p,y)=>{if(!n)return;const b=p?.index??null,x=p?.id??null;f.current===b&&c.current===x||(f.current=b,c.current=x,n({index:b,id:x,coordinate:y,pointCoordinate:p?.pointCoordinate??null}))},[n]),m=g.useCallback((p,y)=>{if(!r)return;const b=h(p);b&&r({...b,button:y})},[r,h]);return g.useEffect(()=>{if(i)return i.current=h,()=>{i.current===h&&(i.current=null)}},[i,h]),g.useEffect(()=>{const p=f.current;p!==null&&(l&&p<l.safeCount||(f.current=null,c.current=null,n?.({index:null,id:null,coordinate:null,pointCoordinate:null})))},[l,n]),g.useEffect(()=>{},[o,n]),{getCellByCoordinates:h,emitPointHover:d,emitPointClick:m}}const js=g.forwardRef(function({data:t=null,palette:n=null,sizeByZoom:r,strokeScale:i,innerFillOpacity:o,clipEnabled:s=!1,clipToRegions:a,clipMode:l="worker",onClipStats:u,onHover:f,onClick:c},h){const{rendererRef:d,rendererSerial:m,source:p}=at(),y=g.useRef(null),x=Ds(s,l,t,a??Qs,u),{getCellByCoordinates:C}=Ks(x,p,f,c,y,"cursor",d);return g.useImperativeHandle(h,()=>({queryAt:C}),[C]),g.useEffect(()=>{const S=d.current;!S||!n||S.setPointPalette(n)},[m,n]),g.useEffect(()=>{const S=d.current;!S||r===void 0||S.setPointSizeByZoom(r)},[m,r]),g.useEffect(()=>{const S=d.current;!S||i===void 0||S.setPointStrokeScale(i)},[m,i]),g.useEffect(()=>{const S=d.current;!S||o===void 0||S.setPointInnerFillOpacity(o)},[m,o]),g.useEffect(()=>{const S=d.current;S&&S.setPointData(x)},[m,x]),null}),Qs=[],Js=180,yr=20;function ea(e){const t=O(e,0,1);return t*t*(3-2*t)}function ta(e,t,n){const[r,i]=g.useState(0),o=g.useRef(0),s=g.useRef({rafId:null,startMs:0,from:0,to:0}),a=g.useCallback(c=>{const h=O(c,0,yr);Math.abs(o.current-h)<1e-4||(o.current=h,i(h))},[]),l=g.useCallback(()=>{const c=s.current;c.rafId!==null&&(cancelAnimationFrame(c.rafId),c.rafId=null)},[]),u=g.useCallback(c=>{const h=O(c,0,yr),d=s.current,m=o.current;if(Math.abs(m-h)<1e-4){l(),d.to=h,a(h);return}l(),d.startMs=performance.now(),d.from=m,d.to=h;const p=y=>{const b=s.current,x=Math.max(0,y-b.startMs),C=O(x/Js,0,1),S=ea(C),A=b.from+(b.to-b.from)*S;if(a(A),n.current?.(),C>=1){b.rafId=null,a(b.to);return}b.rafId=requestAnimationFrame(p)};d.rafId=requestAnimationFrame(p)},[a,l]),f=g.useCallback(c=>{const h=t.current;if(!h||typeof c!="number"||!Number.isFinite(c)){u(0);return}const d=Pn(e,c,h.getZoomRange(),h.getRegionLabelAutoLiftCapZoom());u(d)},[e,u]);return g.useEffect(()=>()=>{l()},[l]),{regionLabelAutoLiftOffsetPx:r,syncRegionLabelAutoLiftTarget:f,cancelRegionLabelAutoLiftAnimation:l,applyRegionLabelAutoLiftOffset:a}}const na=6;function mn(e,t){return e.id??t}function ra(e,t,n,r,i,o){const s=i-n,a=o-r,l=s*s+a*a;if(l<=1e-12){const m=e-n,p=t-r;return m*m+p*p}const u=O(((e-n)*s+(t-r)*a)/l,0,1),f=n+s*u,c=r+a*u,h=e-f,d=t-c;return h*h+d*d}function br(e,t,n,r){for(let i=1;i<n.length;i+=1){const o=n[i-1],s=n[i];if(ra(e,t,o[0],o[1],s[0],s[1])<=r)return!0}return!1}function ia(e,t,n,r){if(e<n.minX-r||e>n.maxX+r||t<n.minY-r||t>n.maxY+r)return!1;const i=r*r;if(br(e,t,n.outer,i))return!0;for(const o of n.holes)if(br(e,t,o,i))return!0;return!1}function oa(e,t,n,r,i,o,s){if(!e.label||!e.labelAnchor)return!1;const a=Rn(n.worldToScreen(e.labelAnchor[0],e.labelAnchor[1]));if(!a)return!1;const u=An(e.label,r)+r.paddingX*2,f=r.fontSize+r.paddingY*2,c=a[0],h=a[1]-r.offsetY,d=s?O(c,u*.5+1,i-u*.5-1):c,m=s?O(h,f*.5+1,o-f*.5-1):h,p=d-u*.5,y=d+u*.5,b=m-f*.5,x=m+f*.5;return t[0]>=p&&t[0]<=y&&t[1]>=b&&t[1]<=x}function sa(e,t="top-center"){const n=[];for(let r=0;r<e.length;r+=1){const i=e[r],o=bt([yt(i?.coordinates)]);if(o.length===0)continue;const s=typeof i?.label=="string"?i.label.trim():"";n.push({region:i,regionIndex:r,regionId:mn(i,r),polygons:o,label:s,labelAnchor:s?vn(o,t):null})}return n}function wr(e,t,n,r,i,o,s,a,l,u=!0){const f=e[0],c=e[1],h=Math.max(1e-6,r.getViewState().zoom),d=Math.max(0,s),m=na/h;for(let p=n.length-1;p>=0;p-=1){const y=n[p];for(const x of y.polygons)if(ia(f,c,x,m))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId};let b=In(i,o?.({region:y.region,regionId:y.regionId,regionIndex:y.regionIndex,zoom:h}));if(d>0&&(b={...b,offsetY:b.offsetY+d}),!!oa(y,t,r,b,a,l,u))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId}}return null}const xr=[],aa=[],Sr="__region_layer__",Er="__region_label__";function la(e){return{color:Xr,width:Vr,lineDash:et,lineJoin:e.lineJoin,lineCap:e.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function ca({regions:e,polygons:t,strokeStyle:n,hoverStrokeStyle:r,activeStrokeStyle:i,resolveStrokeStyle:o,labelStyle:s,labelAnchor:a="top-center",autoLiftLabelAtMaxZoom:l=!1,clampLabelToViewport:u=!0,activeRegionId:f,onActiveChange:c,onHover:h,onClick:d}){const{rendererRef:m,rendererSerial:p,canvasRef:y,containerRef:b,registerDrawCallback:x,unregisterDrawCallback:C,requestOverlayRedraw:S,drawInvalidateRef:A,registerViewStateListener:_,screenToWorld:Y,worldToScreen:B,isInteractionLocked:G}=at(),z=e??xr,$=t??aa,Q=g.useMemo(()=>z.length>0?z:$.length===0?xr:$.map((D,H)=>({id:H,coordinates:D})),[z,$]),[P,W]=g.useState(null),[N,k]=g.useState(()=>f??null),K=f!==void 0,me=K?f??null:N,ie=g.useRef(null);g.useEffect(()=>{K&&k(f??null)},[K,f]);const ve=g.useCallback(D=>{String(me)!==String(D)&&(K||k(D),c?.(D))},[me,K,c]),{regionLabelAutoLiftOffsetPx:Se,syncRegionLabelAutoLiftTarget:Ce}=ta(l,m,A),v=g.useMemo(()=>Mn(n),[n]),M=g.useMemo(()=>qe(v,r),[v,r]),X=g.useMemo(()=>qe(v,i),[v,i]),{staticLabelStyle:fe,labelStyleResolver:J}=g.useMemo(()=>typeof s=="function"?{staticLabelStyle:void 0,labelStyleResolver:s}:{staticLabelStyle:s,labelStyleResolver:void 0},[s]),ae=g.useMemo(()=>Cn(fe),[fe]),le=g.useMemo(()=>{const D=[];for(let H=0;H<Q.length;H+=1){const q=Q[H],ee=Xt(q.coordinates);ee.length!==0&&D.push({region:q,regionIndex:H,regionKey:q.id??H,polygons:ee})}return D},[Q]),ge=g.useMemo(()=>sa(Q,a),[Q,a]);g.useEffect(()=>{const D=m.current;if(D)return Ce(D.getViewState().zoom),_(H=>{Ce(H.zoom)})},[p,_,Ce]),g.useEffect(()=>{!(me===null?!0:Q.some((ee,te)=>String(mn(ee,te))===String(me)))&&me!==null&&ve(null);const H=ie.current;!(H===null?!0:Q.some((ee,te)=>String(mn(ee,te))===String(H)))&&H!==null&&(ie.current=null,W(null),h?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[Q,me,h,ve]);const oe=g.useCallback(D=>{const H=m.current;if(!H||D.length===0)return[];const q=new Array(D.length);for(let ee=0;ee<D.length;ee+=1){const te=Ye(H.worldToScreen(D[ee][0],D[ee][1]));if(!te)return[];q[ee]=te}return q},[]),ne=g.useRef({preparedRegions:le,hoveredRegionId:P,activeRegionId:me,resolvedStrokeStyle:v,resolvedHoverStrokeStyle:M,resolvedActiveStrokeStyle:X,resolveStrokeStyleProp:o,worldToScreenPoints:oe});ne.current={preparedRegions:le,hoveredRegionId:P,activeRegionId:me,resolvedStrokeStyle:v,resolvedHoverStrokeStyle:M,resolvedActiveStrokeStyle:X,resolveStrokeStyleProp:o,worldToScreenPoints:oe},g.useEffect(()=>(x(Sr,10,H=>{const{preparedRegions:q,hoveredRegionId:ee,activeRegionId:te,resolvedStrokeStyle:ce,resolvedHoverStrokeStyle:Ee,resolvedActiveStrokeStyle:we,resolveStrokeStyleProp:xe,worldToScreenPoints:pe}=ne.current;for(const F of q){const{region:V,polygons:I,regionIndex:U,regionKey:Z}=F,re=Yt(te,Z)?"active":Yt(ee,Z)?"hover":"default";let se=re==="active"?we:re==="hover"?Ee:ce;if(xe){const ze=xe({region:V,regionId:Z,regionIndex:U,state:re});se=qe(se,ze||void 0)}const Ie=re==="default"?null:la(se);for(const ze of I){const Ve=pe(ze.outer);Ve.length>=4&&(Ie&&Te(H,Ve,Ie,!0,!1),Te(H,Ve,se,!0,!1));for(const qt of ze.holes){const nt=pe(qt);nt.length>=4&&(Ie&&Te(H,nt,Ie,!0,!1),Te(H,nt,se,!0,!1))}}}}),()=>C(Sr)),[x,C]);const be=g.useRef({preparedRegions:le,resolvedLabelStyle:ae,labelStyleResolver:J,labelAnchor:a,autoLiftLabelAtMaxZoom:l,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:Se,rendererRef:m});be.current={preparedRegions:le,resolvedLabelStyle:ae,labelStyleResolver:J,labelAnchor:a,autoLiftLabelAtMaxZoom:l,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:Se,rendererRef:m},g.useEffect(()=>(x(Er,50,(H,q,ee)=>{const{preparedRegions:te,resolvedLabelStyle:ce,labelStyleResolver:Ee,labelAnchor:we,autoLiftLabelAtMaxZoom:xe,clampLabelToViewport:pe,regionLabelAutoLiftOffsetPx:F,rendererRef:V}=be.current;if(te.length===0)return;const I=Math.max(1e-6,V.current?.getViewState?.().zoom??1),U=typeof F=="number"&&Number.isFinite(F)?Math.max(0,F):Pn(xe,I,V.current?.getZoomRange?.(),V.current?.getRegionLabelAutoLiftCapZoom?.());for(const Z of te){if(!Z.region.label)continue;const re=vn(Z.polygons,we);if(!re)continue;const se=Ye(V.current?.worldToScreen(re[0],re[1])??[]);if(!se)continue;let Ie=In(ce,Ee?.({region:Z.region,regionId:Z.regionKey,regionIndex:Z.regionIndex,zoom:I}));U>0&&(Ie={...Ie,offsetY:Ie.offsetY+U}),Kr(H,Z.region.label,se,q,ee,Ie,pe)}}),()=>C(Er)),[x,C]),g.useEffect(()=>{S()},[le,P,me,v,ae,Se,S]);const he=g.useRef({preparedRegionHits:ge,resolvedLabelStyle:ae,labelStyleResolver:J,regionLabelAutoLiftOffsetPx:Se,clampLabelToViewport:u,onHover:h,onClick:d,commitActive:ve});return he.current={preparedRegionHits:ge,resolvedLabelStyle:ae,labelStyleResolver:J,regionLabelAutoLiftOffsetPx:Se,clampLabelToViewport:u,onHover:h,onClick:d,commitActive:ve},g.useEffect(()=>{const D=b.current;if(!D)return;const H=te=>{if(G())return;const ce=m.current;if(!ce)return;const{preparedRegionHits:Ee,resolvedLabelStyle:we,labelStyleResolver:xe,regionLabelAutoLiftOffsetPx:pe,clampLabelToViewport:F,onHover:V}=he.current,I=Y(te.clientX,te.clientY);if(!I)return;let U=null,Z=null;if(Ee.length>0){const se=B(I[0],I[1]);if(se){const Ie=y.current?.getBoundingClientRect();Z=wr(I,se,Ee,ce,we,xe,typeof pe=="number"?pe:0,Ie?.width??0,Ie?.height??0,F),U=Z?.regionId??null}}const re=ie.current;String(re)!==String(U)&&(ie.current=U,W(U),V?.({region:Z?.region??null,regionId:U,regionIndex:Z?.regionIndex??-1,coordinate:I}),S())},q=te=>{if(G())return;const ce=m.current;if(!ce)return;const{preparedRegionHits:Ee,resolvedLabelStyle:we,labelStyleResolver:xe,regionLabelAutoLiftOffsetPx:pe,clampLabelToViewport:F,onClick:V,commitActive:I}=he.current;if(Ee.length===0)return;const U=Y(te.clientX,te.clientY);if(!U)return;const Z=B(U[0],U[1]);if(!Z)return;const re=y.current?.getBoundingClientRect(),se=wr(U,Z,Ee,ce,we,xe,typeof pe=="number"?pe:0,re?.width??0,re?.height??0,F),Ie=se?.regionId??null;I(Ie),se&&V&&V({region:se.region,regionId:se.regionId,regionIndex:se.regionIndex,coordinate:U})},ee=()=>{ie.current!==null&&(ie.current=null,W(null),he.current.onHover?.({region:null,regionId:null,regionIndex:-1,coordinate:null}),S())};return D.addEventListener("pointermove",H),D.addEventListener("click",q),D.addEventListener("pointerleave",ee),()=>{D.removeEventListener("pointermove",H),D.removeEventListener("click",q),D.removeEventListener("pointerleave",ee)}},[b,m,y,Y,B,G,S]),null}function ua({imageWidth:e,imageHeight:t,tiles:n,viewState:r,className:i,style:o}){const s=g.useRef(null),a=g.useRef(null),l=g.useMemo(()=>({width:"100%",height:"100%",display:"block",...o}),[o]);return g.useEffect(()=>{const u=s.current;if(!u)return;const f=new Nr({canvas:u,imageWidth:e,imageHeight:t,initialViewState:r});return a.current=f,f.setTiles(n),()=>{f.destroy(),a.current=null}},[e,t]),g.useEffect(()=>{const u=a.current;u&&u.setTiles(n)},[n]),g.useEffect(()=>{const u=a.current;!u||!r||u.setViewState(r)},[r]),We.jsx("canvas",{ref:s,className:i,style:l})}function fa(e,t){if(!t)return!1;try{const r=new URL(e,typeof window<"u"?window.location.href:void 0).hostname.toLowerCase();if(r.includes("amazonaws.com")||r.startsWith("s3.")||r.includes(".s3."))return!1}catch{}return!0}class ci{constructor(t){R(this,"maxConcurrency");R(this,"maxRetries");R(this,"retryBaseDelayMs");R(this,"retryMaxDelayMs");R(this,"onTileLoad");R(this,"onTileError");R(this,"onStateChange");R(this,"authToken");R(this,"destroyed",!1);R(this,"queue",[]);R(this,"queuedByKey",new Map);R(this,"inflight",new Map);R(this,"visibleKeys",new Set);R(this,"timerId",null);R(this,"abortedCount",0);R(this,"retryCount",0);R(this,"failedCount",0);this.maxConcurrency=Math.max(1,Math.floor(t.maxConcurrency??12)),this.maxRetries=Math.max(0,Math.floor(t.maxRetries??2)),this.retryBaseDelayMs=Math.max(10,Math.floor(t.retryBaseDelayMs??120)),this.retryMaxDelayMs=Math.max(this.retryBaseDelayMs,Math.floor(t.retryMaxDelayMs??1200)),this.authToken=t.authToken??"",this.onTileLoad=t.onTileLoad,this.onTileError=t.onTileError,this.onStateChange=t.onStateChange}setAuthToken(t){this.authToken=String(t??"")}schedule(t){if(this.destroyed)return;const n=new Set;for(const r of t)n.add(r.key);this.visibleKeys=n,this.dropInvisibleQueued(n),this.abortInvisibleInflight(n);for(const r of t){if(this.inflight.has(r.key)){const s=this.inflight.get(r.key);s&&(s.tile=r);continue}const i=this.queuedByKey.get(r.key);if(i){i.tile=r;continue}const o={tile:r,attempt:0,readyAt:ye()};this.queue.push(o),this.queuedByKey.set(r.key,o)}this.sortQueue(),this.pump(),this.emitStateChange()}clear(){this.clearPumpTimer(),this.visibleKeys.clear(),this.queue=[],this.queuedByKey.clear();for(const[,t]of this.inflight)t.controller.abort();this.inflight.clear(),this.emitStateChange()}destroy(){this.destroyed||(this.destroyed=!0,this.clear())}getInflightCount(){return this.inflight.size}getSnapshot(){return{inflight:this.inflight.size,queued:this.queue.length,aborted:this.abortedCount,retries:this.retryCount,failed:this.failedCount}}dropInvisibleQueued(t){if(this.queue.length===0)return;const n=[];for(const r of this.queue){if(!t.has(r.tile.key)){this.queuedByKey.delete(r.tile.key);continue}n.push(r)}this.queue=n}abortInvisibleInflight(t){for(const[n,r]of this.inflight)t.has(n)||(this.inflight.delete(n),this.abortedCount+=1,r.controller.abort())}sortQueue(){this.queue.sort((t,n)=>t.readyAt!==n.readyAt?t.readyAt-n.readyAt:t.tile.distance2!==n.tile.distance2?t.tile.distance2-n.tile.distance2:t.tile.tier!==n.tile.tier?n.tile.tier-t.tile.tier:t.tile.key.localeCompare(n.tile.key))}pump(){if(this.destroyed)return;for(this.clearPumpTimer();this.inflight.size<this.maxConcurrency;){const r=this.takeNextReadyQueueItem();if(!r)break;this.startFetch(r)}if(this.inflight.size>=this.maxConcurrency||this.queue.length===0)return;const t=this.queue[0]?.readyAt;if(typeof t!="number")return;const n=Math.max(0,t-ye());this.timerId=globalThis.setTimeout(()=>{this.timerId=null,this.pump()},n)}takeNextReadyQueueItem(){if(this.queue.length===0)return null;const t=ye(),n=this.queue[0];return!n||n.readyAt>t?null:(this.queue.shift(),this.queuedByKey.delete(n.tile.key),n)}startFetch(t){const n=new AbortController,r={tile:t.tile,attempt:t.attempt,controller:n};this.inflight.set(t.tile.key,r),this.emitStateChange();const i=fa(t.tile.url,this.authToken);fetch(t.tile.url,{signal:n.signal,headers:i?{Authorization:this.authToken}:void 0}).then(o=>{if(!o.ok)throw new Error(`HTTP ${o.status}`);return o.blob()}).then(o=>createImageBitmap(o)).then(o=>{if(this.destroyed||n.signal.aborted){o.close();return}if(!this.visibleKeys.has(t.tile.key)){o.close();return}this.onTileLoad(t.tile,o)}).catch(o=>{if(n.signal.aborted||this.destroyed)return;if(t.attempt<this.maxRetries&&this.visibleKeys.has(t.tile.key)){this.retryCount+=1;const a=t.attempt+1,l=this.getRetryDelay(a),u={tile:t.tile,attempt:a,readyAt:ye()+l},f=this.queuedByKey.get(t.tile.key);f?(f.tile=u.tile,f.readyAt=Math.min(f.readyAt,u.readyAt),f.attempt=Math.max(f.attempt,u.attempt)):(this.queue.push(u),this.queuedByKey.set(u.tile.key,u)),this.sortQueue();return}this.failedCount+=1,this.onTileError?.(t.tile,o,t.attempt+1)}).finally(()=>{this.inflight.delete(t.tile.key),this.pump(),this.emitStateChange()})}getRetryDelay(t){const n=Math.max(0,t-1),r=Math.min(this.retryMaxDelayMs,this.retryBaseDelayMs*2**n),i=.85+Math.random()*.3;return Math.round(r*i)}clearPumpTimer(){this.timerId!==null&&(globalThis.clearTimeout(this.timerId),this.timerId=null)}emitStateChange(){this.onStateChange?.(this.getSnapshot())}}function ha(e,t){e.addEventListener("pointerdown",t.pointerDown),e.addEventListener("pointermove",t.pointerMove),e.addEventListener("pointerup",t.pointerUp),e.addEventListener("pointercancel",t.pointerUp),e.addEventListener("wheel",t.wheel,{passive:!1}),e.addEventListener("dblclick",t.doubleClick),e.addEventListener("contextmenu",t.contextMenu),e.addEventListener("webglcontextlost",t.contextLost),e.addEventListener("webglcontextrestored",t.contextRestored)}function da(e,t){e.removeEventListener("pointerdown",t.pointerDown),e.removeEventListener("pointermove",t.pointerMove),e.removeEventListener("pointerup",t.pointerUp),e.removeEventListener("pointercancel",t.pointerUp),e.removeEventListener("wheel",t.wheel),e.removeEventListener("dblclick",t.doubleClick),e.removeEventListener("contextmenu",t.contextMenu),e.removeEventListener("webglcontextlost",t.contextLost),e.removeEventListener("webglcontextrestored",t.contextRestored)}function ma(e,t,n){const r=e.getBoundingClientRect(),i=Math.max(1,r.width||e.clientWidth||1),o=Math.max(1,r.height||e.clientHeight||1),s=Math.max(1,window.devicePixelRatio||1),a=Math.max(1,Math.round(i*s)),l=Math.max(1,Math.round(o*s));(e.width!==a||e.height!==l)&&(e.width=a,e.height=l),n.setViewport(i,o),t.viewport(0,0,a,l)}const gn=.35,pn=.5,ga=256,yn=[{zoom:1,size:2.8},{zoom:2,size:3.4},{zoom:3,size:4.2},{zoom:4,size:5.3},{zoom:5,size:6.8},{zoom:6,size:8.4},{zoom:7,size:9.8},{zoom:8,size:11.2},{zoom:9,size:14},{zoom:10,size:17.5},{zoom:11,size:22},{zoom:12,size:28}],pa=.1,ya=5,ba=0,wa=1,xa=-100,Sa=100,Ea=2e3;function Gt(e){return e*Math.PI/180}function Pt(e,t){return!e||!t?e===t:e.buffer===t.buffer&&e.byteOffset===t.byteOffset&&e.byteLength===t.byteLength}function bn(e){return e.map(t=>({zoom:t.zoom,size:t.size}))}function Rr(e){if(!e)return bn(yn);const t=new Map;for(const[n,r]of Object.entries(e)){const i=Number(n),o=Number(r);!Number.isFinite(i)||!Number.isFinite(o)||o<=0||t.set(i,o)}return t.size===0?bn(yn):Array.from(t.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function Ra(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n].zoom!==t[n].zoom||e[n].size!==t[n].size)return!1;return!0}function Ma(e,t){if(!Number.isFinite(e))return t[0]?.size??pn;if(t.length===0)return pn;if(t.length===1||e<=t[0].zoom)return t[0].size;for(let s=1;s<t.length;s+=1){const a=t[s-1],l=t[s];if(e>l.zoom)continue;const u=Math.max(1e-6,l.zoom-a.zoom),f=O((e-a.zoom)/u,0,1);return a.size+(l.size-a.size)*f}const n=t[t.length-1],r=t[t.length-2],i=Math.max(1e-6,n.zoom-r.zoom),o=(n.size-r.size)/i;return n.size+(e-n.zoom)*o}function Mr(e){return typeof e!="number"||!Number.isFinite(e)?1:O(e,pa,ya)}function Ar(e){return typeof e!="number"||!Number.isFinite(e)?0:O(e,ba,wa)}function en(e){return typeof e!="number"||!Number.isFinite(e)?0:O(e,xa,Sa)}function vr(e){const t=en(e?.brightness),n=en(e?.contrast),r=en(e?.saturation);return{brightness:t/200,contrast:n/100,saturation:r/100}}function _n(e){return e}function tn(e){return typeof e!="number"||!Number.isFinite(e)?0:O(e,0,Ea)}function Tt(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:Math.max(1e-6,e)}function nn(e){return typeof e=="function"?e:_n}function ui(e,t,n){const r=e.getBoundingClientRect(),i=t-r.left-r.width*.5,o=n-r.top-r.height*.5;return Math.atan2(o,i)}function fi(e,t){if(t.pointerId!==null&&e.hasPointerCapture(t.pointerId))try{e.releasePointerCapture(t.pointerId)}catch{}t.dragging=!1,t.mode="none",t.rotateLastAngleRad=null,t.pointerId=null,e.classList.remove("dragging")}function Aa(e){const{event:t,canvas:n,state:r,config:i,cancelViewAnimation:o}=e,s=i.ctrlDragRotate&&(t.ctrlKey||t.metaKey);(t.button===0||s&&t.button===2)&&(o(),s&&t.preventDefault(),r.dragging=!0,r.mode=s?"rotate":"pan",r.pointerId=t.pointerId,r.lastPointerX=t.clientX,r.lastPointerY=t.clientY,r.rotateLastAngleRad=r.mode==="rotate"?ui(n,t.clientX,t.clientY):null,n.classList.add("dragging"),n.setPointerCapture(t.pointerId))}function va(e){const{event:t,canvas:n,state:r,config:i,camera:o,clampViewState:s,emitViewState:a,requestRender:l}=e;if(!r.dragging||t.pointerId!==r.pointerId)return;const u=t.clientX-r.lastPointerX,f=t.clientY-r.lastPointerY;if(r.lastPointerX=t.clientX,r.lastPointerY=t.clientY,r.mode==="rotate"){const c=ui(n,t.clientX,t.clientY),h=r.rotateLastAngleRad;if(r.rotateLastAngleRad=c,h!==null){const d=c-h,m=Math.atan2(Math.sin(d),Math.cos(d)),p=i.rotationDragSensitivityDegPerPixel/gn,y=o.getViewState();o.setViewState({rotationDeg:y.rotationDeg-m*180/Math.PI*p})}}else{const c=o.getViewState(),h=Math.max(1e-6,c.zoom),d=Gt(c.rotationDeg),m=Math.cos(d),p=Math.sin(d),y=(u*m-f*p)/h,b=(u*p+f*m)/h;o.setViewState({offsetX:c.offsetX-y,offsetY:c.offsetY-b})}s(),a(),l()}function Ca(e,t,n){e.pointerId===n.pointerId&&fi(t,n)}function Ia(e){const{event:t,canvas:n,onZoomBy:r}=e;t.preventDefault();const i=n.getBoundingClientRect(),o=t.clientX-i.left,s=t.clientY-i.top,a=t.deltaY<0?1.12:.89;r(a,o,s)}const Pa=4;function Ta(e){const{event:t,canvas:n,snapState:r,onSnapZoom:i}=e;t.preventDefault();const o=t.deltaY<0?"in":t.deltaY>0?"out":null;if(o&&r.blockedDirection)if(o!==r.blockedDirection)r.blockedDirection=null,r.accumulatedDelta=0;else return;if(r.accumulatedDelta!==0&&t.deltaY!==0&&Math.sign(r.accumulatedDelta)!==Math.sign(t.deltaY)&&(r.accumulatedDelta=0),r.accumulatedDelta+=t.deltaY,Math.abs(r.accumulatedDelta)<Pa)return;const s=n.getBoundingClientRect(),a=t.clientX-s.left,l=t.clientY-s.top,u=r.accumulatedDelta>0?"out":"in";if(r.accumulatedDelta=0,!i(u,a,l)){r.blockedDirection=u;return}r.blockedDirection=null}function _a(e){const{event:t,canvas:n,onZoomBy:r}=e,i=n.getBoundingClientRect(),o=t.clientX-i.left,s=t.clientY-i.top;r(t.shiftKey?.8:1.25,o,s)}function La(e,t){(t||e.ctrlKey||e.metaKey)&&e.preventDefault()}function Vt(e){const t=e.getViewCorners();let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[s,a]of t)s<n&&(n=s),s>i&&(i=s),a<r&&(r=a),a>o&&(o=a);return[n,r,i,o]}function Nt(e,t){const n=Vt(e),r=Math.max(1e-6,n[2]-n[0]),i=Math.max(1e-6,n[3]-n[1]),o=r*.2,s=i*.2,[a,l]=e.getCenter(),u=r*.5,f=i*.5,c=u-o,h=t.width-u+o,d=f-s,m=t.height-f+s,p=c<=h?O(a,c,h):t.width*.5,y=d<=m?O(l,d,m):t.height*.5;e.setCenter(p,y)}function Fa(e,t){const n=Math.max(1e-6,e.getViewState().zoom),r=t.maxTierZoom+Math.log2(n);return O(Math.floor(r),0,t.maxTierZoom)}function ka(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function hi(e,t,n){const r=Vt(e),i=Math.pow(2,t.maxTierZoom-n),o=Math.ceil(t.width/i),s=Math.ceil(t.height/i),a=Math.max(1,Math.ceil(o/t.tileSize)),l=Math.max(1,Math.ceil(s/t.tileSize)),u=r[0],f=r[1],c=r[2],h=r[3],d=O(Math.floor(u/i/t.tileSize),0,a-1),m=O(Math.floor((c-1)/i/t.tileSize),0,a-1),p=O(Math.floor(f/i/t.tileSize),0,l-1),y=O(Math.floor((h-1)/i/t.tileSize),0,l-1);if(d>m||p>y)return[];const b=(u+c)*.5/i/t.tileSize,x=(f+h)*.5/i/t.tileSize,C=[];for(let S=p;S<=y;S+=1)for(let A=d;A<=m;A+=1){const _=A*t.tileSize*i,Y=S*t.tileSize*i,B=Math.min((A+1)*t.tileSize,o)*i,G=Math.min((S+1)*t.tileSize,s)*i,z=A-b,$=S-x;C.push({key:`${n}/${A}/${S}`,tier:n,x:A,y:S,bounds:[_,Y,B,G],distance2:z*z+$*$,url:Tn(t,n,A,S)})}return C.sort((S,A)=>S.distance2-A.distance2),C}function Na(e,t){const n=Fa(e,t);return{tier:n,visible:hi(e,t,n)}}function Ba(e){e.interactionLocked||Aa({event:e.event,canvas:e.canvas,state:e.state,config:{ctrlDragRotate:e.ctrlDragRotate,rotationDragSensitivityDegPerPixel:e.rotationDragSensitivityDegPerPixel},cancelViewAnimation:e.cancelViewAnimation})}function za(e){e.interactionLocked||va({event:e.event,canvas:e.canvas,state:e.state,config:{ctrlDragRotate:e.ctrlDragRotate,rotationDragSensitivityDegPerPixel:e.rotationDragSensitivityDegPerPixel},camera:e.camera,clampViewState:()=>Nt(e.camera,e.source),emitViewState:e.emitViewState,requestRender:e.requestRender})}function Da(e){e.interactionLocked||Ca(e.event,e.canvas,e.state)}function Ua(e){e.interactionLocked||_a({event:e.event,canvas:e.canvas,onZoomBy:e.onZoomBy})}function Oa(e){La(e.event,e.state.dragging)}function Ya(e,t){fi(e,t)}function Wa(e){return{pointerDown:t=>Ba({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state,ctrlDragRotate:e.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:e.getRotationDragSensitivityDegPerPixel(),cancelViewAnimation:e.cancelViewAnimation}),pointerMove:t=>za({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state,ctrlDragRotate:e.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:e.getRotationDragSensitivityDegPerPixel(),camera:e.camera,source:e.source,emitViewState:e.emitViewState,requestRender:e.requestRender}),pointerUp:t=>Da({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state}),wheel:t=>{if(e.getInteractionLocked()){t.preventDefault();return}if(e.getUseZoomSnaps?.()&&e.onSnapZoom&&e.zoomSnapState){Ta({event:t,canvas:e.canvas,snapState:e.zoomSnapState,onSnapZoom:e.onSnapZoom});return}Ia({event:t,canvas:e.canvas,onZoomBy:e.zoomBy})},doubleClick:t=>Ua({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,onZoomBy:e.zoomBy}),contextMenu:t=>Oa({event:t,canvas:e.canvas,state:e.state})}}function Xa(e){const{gl:t,cache:n,maxCacheTiles:r}=e;if(n.size<=r)return;const i=Math.max(0,Math.floor(r));for(;n.size>i;){let o=null,s=null;for(const[a,l]of n)(!s||l.lastUsed<s.lastUsed)&&(o=a,s=l);if(!o||!s)break;t.deleteTexture(s.texture),n.delete(o)}}function Va(e,t){if(e.isContextLost())return null;const n=e.createTexture();return n?(e.bindTexture(e.TEXTURE_2D,n),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,1),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.bindTexture(e.TEXTURE_2D,null),n):null}function Ga(e){const{gl:t,cache:n,tile:r,bitmap:i,frameSerial:o,maxCacheTiles:s,destroyed:a,contextLost:l,requestRender:u}=e;if(a||l||t.isContextLost()){i.close();return}if(n.has(r.key)){i.close();return}const f=Va(t,i);i.close(),f&&(n.set(r.key,{key:r.key,texture:f,bounds:r.bounds,tier:r.tier,lastUsed:o}),Xa({gl:t,cache:n,maxCacheTiles:s}),u())}function qa(e,t){for(const[,n]of t)e.deleteTexture(n.texture)}function Ha(e){const{event:t,destroyed:n,contextLost:r,cancelViewAnimation:i,cancelDrag:o,tileScheduler:s,cache:a,onContextLost:l}=e;if(t.preventDefault(),n||r)return{handled:!1,frame:e.frame};let u=e.frame;return u!==null&&(cancelAnimationFrame(u),u=null),i(),o(),s.clear(),a.clear(),l?.(),{handled:!0,frame:u}}function Za(e){if(e.destroyed)return{didDestroy:!1,frame:e.frame};let t=e.frame;return t!==null&&(cancelAnimationFrame(t),t=null),e.cancelViewAnimation(),e.resizeObserver.disconnect(),e.removeCanvasEventListeners(),e.cancelDrag(),e.tileScheduler.destroy(),!e.contextLost&&!e.gl.isContextLost()&&(qa(e.gl,e.cache),e.gl.deleteBuffer(e.tileProgram.vbo),e.gl.deleteVertexArray(e.tileProgram.vao),e.gl.deleteProgram(e.tileProgram.program),e.gl.deleteBuffer(e.pointProgram.posBuffer),e.gl.deleteBuffer(e.pointProgram.termBuffer),e.gl.deleteBuffer(e.pointProgram.fillModeBuffer),e.gl.deleteBuffer(e.pointProgram.indexBuffer),e.gl.deleteTexture(e.pointProgram.paletteTexture),e.gl.deleteVertexArray(e.pointProgram.vao),e.gl.deleteProgram(e.pointProgram.program)),e.cache.clear(),{didDestroy:!0,frame:t}}function $a(e,t){if(t<=0||e.length===0)return new Uint32Array(0);let n=e.length;for(let o=0;o<e.length;o+=1)e[o]<t||(n-=1);if(n===e.length)return e;if(n<=0)return new Uint32Array(0);const r=new Uint32Array(n);let i=0;for(let o=0;o<e.length;o+=1){const s=e[o];s>=t||(r[i]=s,i+=1)}return r}function Ka(e,t){return t<=0?new Uint8Array(0):e.length<t?new Uint8Array(t):e.subarray(0,t)}function ja(e,t,n,r,i){if(!i||i.length===0)return{...e,lastPointPalette:null};const o=new Uint8Array(i);if(r||t.isContextLost())return{...e,lastPointPalette:o};const s=Math.max(1,Math.floor(o.length/4));return t.bindTexture(t.TEXTURE_2D,n.paletteTexture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,s,1,0,t.RGBA,t.UNSIGNED_BYTE,o),t.bindTexture(t.TEXTURE_2D,null),{...e,lastPointPalette:o,pointPaletteSize:s}}function Qa(e,t,n,r,i){if(!i||!i.count||!i.positions||!i.paletteIndices)return{...e,lastPointData:null,pointCount:0,usePointIndices:!1};const o=i.fillModes instanceof Uint8Array?i.fillModes:null,s=o!==null,a=Math.max(0,Math.min(i.count,Math.floor(i.positions.length/2),i.paletteIndices.length,s?o.length:Number.MAX_SAFE_INTEGER)),l=i.positions.subarray(0,a*2),u=i.paletteIndices.subarray(0,a),f=s?o.subarray(0,a):void 0,c=i.drawIndices instanceof Uint32Array,h=c?$a(i.drawIndices,a):null,d=e.lastPointData,m=d?.fillModes instanceof Uint8Array,p=e.pointBuffersDirty||!d||d.count!==a||!Pt(d.positions,l)||!Pt(d.paletteIndices,u)||m!==s||s&&(!d?.fillModes||!Pt(d.fillModes,f)),y=e.pointBuffersDirty||c&&(!d?.drawIndices||!Pt(d.drawIndices,h))||!c&&!!d?.drawIndices,b={...e,lastPointData:{count:a,positions:l,paletteIndices:u,fillModes:f,drawIndices:c?h??void 0:void 0}};if(r||t.isContextLost())return b;const x=b.lastPointData;if(!x)return b;if(p){t.bindBuffer(t.ARRAY_BUFFER,n.posBuffer),t.bufferData(t.ARRAY_BUFFER,x.positions,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,n.termBuffer),t.bufferData(t.ARRAY_BUFFER,x.paletteIndices,t.STATIC_DRAW);const C=Ka(b.zeroFillModes,a);t.bindBuffer(t.ARRAY_BUFFER,n.fillModeBuffer),t.bufferData(t.ARRAY_BUFFER,x.fillModes??C,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,null),b.zeroFillModes=C}return c&&y&&(t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,n.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,h??new Uint32Array(0),t.DYNAMIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null)),b.usePointIndices=c,b.pointCount=c?h?.length??0:x.count,(p||y)&&(b.pointBuffersDirty=!1),b}function Ja(e){const{gl:t,camera:n,source:r,cache:i,frameSerial:o,tileProgram:s,pointProgram:a,imageColorSettings:l,pointCount:u,usePointIndices:f,pointPaletteSize:c,pointStrokeScale:h,pointInnerFillOpacity:d,pointSizePx:m,tileScheduler:p,getVisibleTiles:y,getVisibleTilesForTier:b,getViewBounds:x,intersectsBounds:C}=e;t.clearColor(.03,.06,.1,1),t.clear(t.COLOR_BUFFER_BIT);const{tier:S,visible:A}=y(),_=x(),Y=new Set(A.map(N=>N.key));t.useProgram(s.program),t.bindVertexArray(s.vao),t.uniformMatrix3fv(s.uCamera,!1,n.getMatrix()),t.uniform1i(s.uTexture,0),t.uniform1f(s.uBrightness,l.brightness),t.uniform1f(s.uContrast,l.contrast),t.uniform1f(s.uSaturation,l.saturation);const B=[];for(const[,N]of i)Y.has(N.key)||C(N.bounds,_)&&B.push(N);B.sort((N,k)=>N.tier-k.tier);for(const N of B)N.lastUsed=o,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,N.texture),t.uniform4f(s.uBounds,N.bounds[0],N.bounds[1],N.bounds[2],N.bounds[3]),t.drawArrays(t.TRIANGLE_STRIP,0,4);let G=0;const z=[];for(const N of A){const k=i.get(N.key);if(!k){z.push(N);continue}k.lastUsed=o,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,k.texture),t.uniform4f(s.uBounds,k.bounds[0],k.bounds[1],k.bounds[2],k.bounds[3]),t.drawArrays(t.TRIANGLE_STRIP,0,4),G+=1}const $=z.slice(),Q=1e6,P=[];S>0&&P.push(S-1),S<r.maxTierZoom&&P.push(S+1);for(const N of P){const k=b(N);for(const K of k)i.has(K.key)||(K.distance2+=Q,$.push(K))}p.schedule($),t.bindTexture(t.TEXTURE_2D,null),t.bindVertexArray(null);let W=0;return u>0&&(t.enable(t.BLEND),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA),t.useProgram(a.program),t.bindVertexArray(a.vao),t.uniformMatrix3fv(a.uCamera,!1,n.getMatrix()),t.uniform1f(a.uPointSize,m),t.uniform1f(a.uPointStrokeScale,h),t.uniform1f(a.uPointInnerFillAlpha,d),t.uniform1f(a.uPaletteSize,c),t.uniform1i(a.uPalette,1),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,a.paletteTexture),f?t.drawElements(t.POINTS,u,t.UNSIGNED_INT,0):t.drawArrays(t.POINTS,0,u),t.bindTexture(t.TEXTURE_2D,null),t.bindVertexArray(null),W=u),{tier:S,visible:A.length,rendered:G,points:W,fallback:B.length,cacheHits:G,cacheMisses:z.length,drawCalls:B.length+G+(W>0?1:0)}}function Cr(e){const r=wn(e,`#version 300 es
|
|
65
65
|
precision highp float;
|
|
66
66
|
in vec2 aUnit;
|
|
67
67
|
in vec2 aUv;
|
|
@@ -106,7 +106,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
106
106
|
|
|
107
107
|
color.rgb = clamp(color.rgb + uBrightness, vec3(0.0), vec3(1.0));
|
|
108
108
|
outColor = color;
|
|
109
|
-
}`),i=
|
|
109
|
+
}`),i=Le(e,r,"uCamera"),o=Le(e,r,"uBounds"),s=Le(e,r,"uTexture"),a=Le(e,r,"uBrightness"),l=Le(e,r,"uContrast"),u=Le(e,r,"uSaturation"),f=e.createVertexArray(),c=e.createBuffer();if(!f||!c)throw new Error("buffer allocation failed");e.bindVertexArray(f),e.bindBuffer(e.ARRAY_BUFFER,c),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,0,0,1,0,1,0,0,1,0,1,1,1,1,1]),e.STATIC_DRAW);const h=e.getAttribLocation(r,"aUnit"),d=e.getAttribLocation(r,"aUv");if(h<0||d<0)throw new Error("tile attribute lookup failed");return e.enableVertexAttribArray(h),e.enableVertexAttribArray(d),e.vertexAttribPointer(h,2,e.FLOAT,!1,16,0),e.vertexAttribPointer(d,2,e.FLOAT,!1,16,8),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),{program:r,vao:f,vbo:c,uCamera:i,uBounds:o,uTexture:s,uBrightness:a,uContrast:l,uSaturation:u}}function Ir(e){const r=wn(e,`#version 300 es
|
|
110
110
|
precision highp float;
|
|
111
111
|
in vec2 aPosition;
|
|
112
112
|
in uint aTerm;
|
|
@@ -159,6 +159,6 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
159
159
|
// Premultiplied alpha output: inner fill is black, so it only contributes alpha.
|
|
160
160
|
outColor = vec4(color.rgb * ringAlpha, alpha);
|
|
161
161
|
}
|
|
162
|
-
}`),i=_e(e,r,"uCamera"),o=_e(e,r,"uPointSize"),s=_e(e,r,"uPointStrokeScale"),a=_e(e,r,"uPointInnerFillAlpha"),l=_e(e,r,"uPalette"),u=_e(e,r,"uPaletteSize"),f=e.createVertexArray(),c=e.createBuffer(),h=e.createBuffer(),d=e.createBuffer(),m=e.createBuffer(),p=e.createTexture();if(!f||!c||!h||!d||!m||!p)throw new Error("point buffer allocation failed");e.bindVertexArray(f),e.bindBuffer(e.ARRAY_BUFFER,c),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const y=e.getAttribLocation(r,"aPosition");if(y<0)throw new Error("point position attribute not found");e.enableVertexAttribArray(y),e.vertexAttribPointer(y,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,h),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const b=e.getAttribLocation(r,"aTerm");if(b<0)throw new Error("point term attribute not found");e.enableVertexAttribArray(b),e.vertexAttribIPointer(b,1,e.UNSIGNED_SHORT,0,0),e.bindBuffer(e.ARRAY_BUFFER,d),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const x=e.getAttribLocation(r,"aFillMode");if(x<0)throw new Error("point fill mode attribute not found");return e.enableVertexAttribArray(x),e.vertexAttribIPointer(x,1,e.UNSIGNED_BYTE,0,0),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,m),e.bufferData(e.ELEMENT_ARRAY_BUFFER,0,e.DYNAMIC_DRAW),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),e.bindTexture(e.TEXTURE_2D,p),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([160,160,160,255])),e.bindTexture(e.TEXTURE_2D,null),{program:r,vao:f,posBuffer:c,termBuffer:h,fillModeBuffer:d,indexBuffer:m,paletteTexture:p,uCamera:i,uPointSize:o,uPointStrokeScale:s,uPointInnerFillAlpha:a,uPalette:l,uPaletteSize:u}}function di(e){e.animation=null,e.frame!==null&&(cancelAnimationFrame(e.frame),e.frame=null)}function el(e){const{state:t,camera:n,target:r,durationMs:i,easing:o,onUpdate:s}=e,a=n.getViewState();di(t),t.animation={startMs:be(),durationMs:Math.max(0,i),from:a,to:r,easing:o};const l=()=>{const u=t.animation;if(!u)return;const f=Math.max(0,be()-u.startMs),c=u.durationMs<=0?1:W(f/u.durationMs,0,1);let h=c;try{h=u.easing(c)}catch{h=c}if(Number.isFinite(h)||(h=c),h=W(h,0,1),n.setViewState({zoom:u.from.zoom+(u.to.zoom-u.from.zoom)*h,offsetX:u.from.offsetX+(u.to.offsetX-u.from.offsetX)*h,offsetY:u.from.offsetY+(u.to.offsetY-u.from.offsetY)*h,rotationDeg:u.from.rotationDeg+(u.to.rotationDeg-u.from.rotationDeg)*h}),s(),c>=1){t.animation=null,t.frame=null;return}t.frame=requestAnimationFrame(l)};t.frame=requestAnimationFrame(l)}function tl(e){const t=Math.max(e*.5,1e-6),n=Math.max(1,e*8);return{minZoom:t,maxZoom:Math.max(t,n)}}function nl(e,t,n){const r=tl(e);let i=t??r.minZoom,o=n??r.maxZoom;return i=Math.max(1e-6,i),o=Math.max(1e-6,o),i>o&&(i=o),{minZoom:i,maxZoom:o}}function rl(e,t,n,r,i){const o=e.getViewState(),s={zoom:typeof r.zoom=="number"&&Number.isFinite(r.zoom)?W(r.zoom,t,n):o.zoom,offsetX:typeof r.offsetX=="number"&&Number.isFinite(r.offsetX)?r.offsetX:o.offsetX,offsetY:typeof r.offsetY=="number"&&Number.isFinite(r.offsetY)?r.offsetY:o.offsetY,rotationDeg:typeof r.rotationDeg=="number"&&Number.isFinite(r.rotationDeg)?r.rotationDeg:o.rotationDeg};e.setViewState(s),i();const a=e.getViewState();return e.setViewState(o),a}function Pr(e,t,n,r,i){const o=Math.min(t/e.width,n/e.height),s=Number.isFinite(o)&&o>0?o:1,a=W(s,r,i),l=t/a,u=n/a;return{fitZoom:s,target:{zoom:a,offsetX:(e.width-l)*.5,offsetY:(e.height-u)*.5,rotationDeg:0}}}function il(e,t,n,r,i,o){const s=e.getViewState(),a=W(s.zoom*r,t,n);if(a===s.zoom)return null;const[l,u]=e.screenToWorld(i,o),f=e.getViewportSize(),c=i-f.width*.5,h=o-f.height*.5,d=Vt(s.rotationDeg),m=Math.cos(d),p=Math.sin(d),y=c/a*m-h/a*p,b=c/a*p+h/a*m,x=l-y,C=u-b;return{zoom:a,offsetX:x-f.width/(2*a),offsetY:C-f.height/(2*a)}}function ol(e,t,n,r,i,o){const s=e.getViewState(),a=W(r,t,n);if(a===s.zoom)return null;const[l,u]=e.screenToWorld(i,o),f=e.getViewportSize(),c=i-f.width*.5,h=o-f.height*.5,d=Vt(s.rotationDeg),m=Math.cos(d),p=Math.sin(d),y=c/a*m-h/a*p,b=c/a*p+h/a*m,x=l-y,C=u-b;return{zoom:a,offsetX:x-f.width/(2*a),offsetY:C-f.height/(2*a)}}const sl=250;function Tr(e,t){if(!e||e.length===0)return[];if(!t||t<=0)return[];const n=10/t;return e.map(r=>r/n).filter(r=>Number.isFinite(r)&&r>0).sort((r,i)=>r-i)}function al(e,t,n,r){if(e.length===0)return null;const i=Math.max(t*.005,1e-8);if(n==="in"){for(const o of e)if(o>t+i)return{type:"snap",zoom:o};return null}for(let o=e.length-1;o>=0;o--)if(e[o]<t-i)return{type:"snap",zoom:e[o]};return r&&t<=e[0]+i?{type:"fit"}:null}function ll(e,t,n,r,i){const o=e.camera.getViewState(),[s,a]=e.camera.screenToWorld(n,r),l=e.camera.getViewportSize(),u=W(t,e.minZoom,e.maxZoom);if(u===o.zoom)return;const f=Vt(o.rotationDeg),c=Math.cos(f),h=Math.sin(f),d=n-l.width*.5,m=r-l.height*.5;e.cancelViewAnimation();const p=x=>{const C=d/x*c-m/x*h,S=d/x*h+m/x*c;return{offsetX:s-C-l.width/(2*x),offsetY:a-S-l.height/(2*x)}},y=p(u);e.viewAnimationState.animation={startMs:be(),durationMs:Math.max(0,i),from:o,to:{zoom:u,offsetX:y.offsetX,offsetY:y.offsetY,rotationDeg:o.rotationDeg},easing:Tn};const b=()=>{const x=e.viewAnimationState.animation;if(!x)return;const C=Math.max(0,be()-x.startMs),S=W(C/i,0,1),A=W(S*S*(3-2*S),0,1),T=o.zoom+(u-o.zoom)*A,{offsetX:O,offsetY:D}=p(T);e.camera.setViewState({zoom:T,offsetX:O,offsetY:D,rotationDeg:o.rotationDeg});const G=S>=1;G&&(e.clampViewState(),e.viewAnimationState.animation=null,e.viewAnimationState.frame=null),e.onViewStateChange(e.camera.getViewState()),e.requestRender(),G||(e.viewAnimationState.frame=requestAnimationFrame(b))};e.viewAnimationState.frame=requestAnimationFrame(b)}class mi{constructor(t,n,r={}){R(this,"canvas");R(this,"source");R(this,"gl");R(this,"camera",new kr);R(this,"onViewStateChange");R(this,"onStats");R(this,"onTileError");R(this,"onContextLost");R(this,"onContextRestored");R(this,"resizeObserver");R(this,"tileProgram");R(this,"pointProgram");R(this,"tileScheduler");R(this,"authToken");R(this,"destroyed",!1);R(this,"contextLost",!1);R(this,"frame",null);R(this,"frameSerial",0);R(this,"interactionState",{dragging:!1,mode:"none",rotateLastAngleRad:null,pointerId:null,lastPointerX:0,lastPointerY:0});R(this,"interactionLocked",!1);R(this,"ctrlDragRotate",!0);R(this,"rotationDragSensitivityDegPerPixel",mn);R(this,"maxCacheTiles");R(this,"fitZoom",1);R(this,"minZoom",1e-6);R(this,"maxZoom",1);R(this,"minZoomOverride",null);R(this,"maxZoomOverride",null);R(this,"viewTransitionDurationMs",0);R(this,"viewTransitionEasing",Tn);R(this,"viewAnimationState",{animation:null,frame:null});R(this,"pointCount",0);R(this,"usePointIndices",!1);R(this,"pointBuffersDirty",!0);R(this,"pointPaletteSize",1);R(this,"pointSizeStops",yn(pn));R(this,"pointStrokeScale",1);R(this,"pointInnerFillOpacity",0);R(this,"imageColorSettings",{brightness:0,contrast:0,saturation:0});R(this,"lastPointData",null);R(this,"lastPointPalette",null);R(this,"zeroFillModes",new Uint8Array(0));R(this,"cache",new Map);R(this,"zoomSnaps",[]);R(this,"zoomSnapFitAsMin",!1);R(this,"zoomSnapState",{accumulatedDelta:0,lastSnapTimeMs:0,blockedDirection:null});R(this,"boundPointerDown");R(this,"boundPointerMove");R(this,"boundPointerUp");R(this,"boundWheel");R(this,"boundDoubleClick");R(this,"boundContextMenu");R(this,"boundContextLost");R(this,"boundContextRestored");this.canvas=t,this.source=n,this.onViewStateChange=r.onViewStateChange,this.onStats=r.onStats,this.onTileError=r.onTileError,this.onContextLost=r.onContextLost,this.onContextRestored=r.onContextRestored,this.authToken=r.authToken??"",this.maxCacheTiles=Math.max(32,Math.floor(r.maxCacheTiles??320)),this.ctrlDragRotate=r.ctrlDragRotate??!0,this.rotationDragSensitivityDegPerPixel=typeof r.rotationDragSensitivityDegPerPixel=="number"&&Number.isFinite(r.rotationDragSensitivityDegPerPixel)?Math.max(0,r.rotationDragSensitivityDegPerPixel):mn,this.pointSizeStops=Rr(r.pointSizeByZoom),this.pointStrokeScale=Mr(r.pointStrokeScale),this.pointInnerFillOpacity=Ar(r.pointInnerFillOpacity),this.imageColorSettings=vr(r.imageColorSettings),this.minZoomOverride=Pt(r.minZoom),this.maxZoomOverride=Pt(r.maxZoom),this.viewTransitionDurationMs=en(r.viewTransition?.duration),this.viewTransitionEasing=tn(r.viewTransition?.easing),this.zoomSnaps=Tr(r.zoomSnaps,this.source.mpp),this.zoomSnapFitAsMin=!!r.zoomSnapFitAsMin;const i=t.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,stencil:!1,powerPreference:"high-performance"});if(!i)throw new Error("WebGL2 not supported");this.gl=i,this.tileProgram=Cr(this.gl),this.pointProgram=Ir(this.gl),this.tileScheduler=new ci({authToken:this.authToken,maxConcurrency:r.tileScheduler?.maxConcurrency??12,maxRetries:r.tileScheduler?.maxRetries??2,retryBaseDelayMs:r.tileScheduler?.retryBaseDelayMs??120,retryMaxDelayMs:r.tileScheduler?.retryMaxDelayMs??1200,onTileLoad:(s,a)=>Ga({gl:this.gl,cache:this.cache,tile:s,bitmap:a,frameSerial:this.frameSerial,maxCacheTiles:this.maxCacheTiles,destroyed:this.destroyed,contextLost:this.contextLost,requestRender:()=>this.requestRender()}),onTileError:(s,a,l)=>{this.onTileError?.({tile:s,error:a,attemptCount:l}),console.warn("tile load failed",s.url,a)}}),this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(t);const o=Wa({canvas:this.canvas,state:this.interactionState,getInteractionLocked:()=>this.interactionLocked,getCtrlDragRotate:()=>this.ctrlDragRotate,getRotationDragSensitivityDegPerPixel:()=>this.rotationDragSensitivityDegPerPixel,cancelViewAnimation:()=>this.cancelViewAnimation(),camera:this.camera,source:this.source,emitViewState:()=>this.onViewStateChange?.(this.camera.getViewState()),requestRender:()=>this.requestRender(),zoomBy:(s,a,l)=>this.zoomBy(s,a,l),getUseZoomSnaps:()=>this.zoomSnaps.length>0,onSnapZoom:(s,a,l)=>this.handleSnapZoom(s,a,l),zoomSnapState:this.zoomSnapState});this.boundPointerDown=o.pointerDown,this.boundPointerMove=o.pointerMove,this.boundPointerUp=o.pointerUp,this.boundWheel=o.wheel,this.boundDoubleClick=o.doubleClick,this.boundContextMenu=o.contextMenu,this.boundContextLost=s=>this.onWebGlContextLost(s),this.boundContextRestored=s=>this.onWebGlContextRestored(s),ha(t,this.getCanvasHandlers()),this.fitToImage({duration:0}),this.resize()}getCanvasHandlers(){return{pointerDown:this.boundPointerDown,pointerMove:this.boundPointerMove,pointerUp:this.boundPointerUp,wheel:this.boundWheel,doubleClick:this.boundDoubleClick,contextMenu:this.boundContextMenu,contextLost:this.boundContextLost,contextRestored:this.boundContextRestored}}applyZoomBounds(){const t=nl(this.fitZoom,this.minZoomOverride,this.maxZoomOverride);this.minZoom=t.minZoom,this.maxZoom=t.maxZoom}resolveTargetViewState(t){return rl(this.camera,this.minZoom,this.maxZoom,t,()=>kt(this.camera,this.source))}cancelViewAnimation(){di(this.viewAnimationState)}startViewAnimation(t,n,r){el({state:this.viewAnimationState,camera:this.camera,target:t,durationMs:n,easing:r,onUpdate:()=>{kt(this.camera,this.source),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}})}getPointBufferRuntime(){return{pointCount:this.pointCount,usePointIndices:this.usePointIndices,pointBuffersDirty:this.pointBuffersDirty,lastPointData:this.lastPointData,zeroFillModes:this.zeroFillModes,lastPointPalette:this.lastPointPalette,pointPaletteSize:this.pointPaletteSize}}applyPointBufferRuntime(t){this.pointCount=t.pointCount,this.usePointIndices=t.usePointIndices,this.pointBuffersDirty=t.pointBuffersDirty,this.lastPointData=t.lastPointData,this.zeroFillModes=t.zeroFillModes,this.lastPointPalette=t.lastPointPalette,this.pointPaletteSize=t.pointPaletteSize}applyViewStateAndRender(t,n=!0){n&&this.cancelViewAnimation(),this.camera.setViewState(t),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}setAuthToken(t){this.authToken=String(t??""),this.tileScheduler.setAuthToken(this.authToken)}setZoomRange(t,n){const r=Pt(t),i=Pt(n);if(this.minZoomOverride===r&&this.maxZoomOverride===i)return;this.minZoomOverride=r,this.maxZoomOverride=i,this.applyZoomBounds();const o=this.resolveTargetViewState({}),s=this.camera.getViewState();cn(s,o)||this.applyViewStateAndRender(o)}setViewTransition(t){this.viewTransitionDurationMs=en(t?.duration),this.viewTransitionEasing=tn(t?.easing)}setViewState(t,n){const r=this.resolveTargetViewState(t),i=this.camera.getViewState();if(cn(i,r))return;const o=en(n?.duration??this.viewTransitionDurationMs),s=tn(n?.easing??this.viewTransitionEasing);if(o<=0){this.applyViewStateAndRender(r);return}this.startViewAnimation(r,o,s)}getViewState(){return this.camera.getViewState()}getZoomRange(){return{minZoom:this.minZoom,maxZoom:this.maxZoom}}isViewAnimating(){return this.viewAnimationState.animation!==null}setPointPalette(t){const n=ja(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,t);this.applyPointBufferRuntime(n),!(!t||t.length===0)&&this.requestRender()}setPointData(t){const n=Qa(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,t);this.applyPointBufferRuntime(n),this.requestRender()}setInteractionLock(t){const n=!!t;this.interactionLocked!==n&&(this.interactionLocked=n,n&&this.cancelDrag())}setPointSizeByZoom(t){const n=Rr(t);Ra(this.pointSizeStops,n)||(this.pointSizeStops=n,this.requestRender())}setPointStrokeScale(t){const n=Mr(t);this.pointStrokeScale!==n&&(this.pointStrokeScale=n,this.requestRender())}setPointInnerFillOpacity(t){const n=Ar(t);this.pointInnerFillOpacity!==n&&(this.pointInnerFillOpacity=n,this.requestRender())}setImageColorSettings(t){const n=vr(t),r=this.imageColorSettings;r.brightness===n.brightness&&r.contrast===n.contrast&&r.saturation===n.saturation||(this.imageColorSettings=n,this.requestRender())}cancelDrag(){Ya(this.canvas,this.interactionState)}screenToWorld(t,n){const r=this.canvas.getBoundingClientRect(),i=t-r.left,o=n-r.top;return this.camera.screenToWorld(i,o)}worldToScreen(t,n){return this.camera.worldToScreen(t,n)}setViewCenter(t,n,r){if(!Number.isFinite(t)||!Number.isFinite(n))return;const i=this.camera.getViewState(),o=Math.max(1e-6,i.zoom),s=this.camera.getViewportSize();this.setViewState({offsetX:t-s.width/(2*o),offsetY:n-s.height/(2*o)},r)}getViewCorners(){return this.camera.getViewCorners()}getViewBounds(){return Xt(this.camera)}resetRotation(t){const n=this.camera.getViewState();Math.abs(n.rotationDeg)<1e-6||this.setViewState({rotationDeg:0},t)}getPointSizeByZoom(){const t=Math.max(1e-6,this.camera.getViewState().zoom),n=this.source.maxTierZoom+Math.log2(t),r=Ma(n,this.pointSizeStops);return W(r,gn,ga)}fitToImage(t){const n=this.canvas.getBoundingClientRect(),r=Math.max(1,n.width||1),i=Math.max(1,n.height||1),o=Pr(this.source,r,i,this.minZoom,this.maxZoom);this.fitZoom=o.fitZoom,this.applyZoomBounds(),this.setViewState(o.target,t)}zoomBy(t,n,r,i){const o=il(this.camera,this.minZoom,this.maxZoom,t,n,r);o&&this.setViewState(o,i)}zoomTo(t,n,r,i){const o=ol(this.camera,this.minZoom,this.maxZoom,t,n,r);o&&this.setViewState(o,i)}setZoomSnaps(t,n){this.zoomSnaps=Tr(t,this.source.mpp),this.zoomSnapFitAsMin=!!n}getZoomPivotAnimationContext(){return{camera:this.camera,viewAnimationState:this.viewAnimationState,minZoom:this.minZoom,maxZoom:this.maxZoom,cancelViewAnimation:()=>this.cancelViewAnimation(),clampViewState:()=>kt(this.camera,this.source),onViewStateChange:t=>this.onViewStateChange?.(t),requestRender:()=>this.requestRender()}}handleSnapZoom(t,n,r){const i=this.viewAnimationState.animation,o=i?i.to.zoom:this.camera.getViewState().zoom,s=this.zoomSnaps.filter(f=>f>=this.minZoom&&f<=this.maxZoom),a=al(s,o,t,this.zoomSnapFitAsMin);if(!a)return!1;let l;if(a.type==="fit"){const f=this.canvas.getBoundingClientRect(),c=Math.max(1,f.width||1),h=Math.max(1,f.height||1),d=Pr(this.source,c,h,this.minZoom,this.maxZoom);this.fitZoom=d.fitZoom,this.applyZoomBounds(),l=d.target.zoom}else l=a.zoom;const u=Math.max(Math.abs(l)*.005,1e-8);if(i){if((i.to.zoom>i.from.zoom+u?"in":i.to.zoom<i.from.zoom-u?"out":null)===t&&Math.abs(i.to.zoom-l)<=u)return!1}else if(Math.abs(o-l)<=u)return!1;return ll(this.getZoomPivotAnimationContext(),l,n,r,sl),!0}render(){if(this.destroyed||this.contextLost||this.gl.isContextLost())return;const t=this.onStats?be():0;this.frameSerial+=1;const n=Ja({gl:this.gl,camera:this.camera,source:this.source,cache:this.cache,frameSerial:this.frameSerial,tileProgram:this.tileProgram,pointProgram:this.pointProgram,imageColorSettings:this.imageColorSettings,pointCount:this.pointCount,usePointIndices:this.usePointIndices,pointPaletteSize:this.pointPaletteSize,pointStrokeScale:this.pointStrokeScale,pointInnerFillOpacity:this.pointInnerFillOpacity,pointSizePx:this.getPointSizeByZoom()*Math.max(1,window.devicePixelRatio||1),tileScheduler:this.tileScheduler,getVisibleTiles:()=>Na(this.camera,this.source),getVisibleTilesForTier:r=>hi(this.camera,this.source,r),getViewBounds:()=>Xt(this.camera),intersectsBounds:ka});if(this.onStats){const r=this.tileScheduler.getSnapshot();this.onStats({tier:n.tier,visible:n.visible,rendered:n.rendered,points:n.points,fallback:n.fallback,cache:this.cache.size,inflight:r.inflight,queued:r.queued,retries:r.retries,failed:r.failed,aborted:r.aborted,cacheHits:n.cacheHits,cacheMisses:n.cacheMisses,drawCalls:n.drawCalls,frameMs:be()-t})}}requestRender(){this.frame!==null||this.destroyed||this.contextLost||this.gl.isContextLost()||(this.frame=requestAnimationFrame(()=>{this.frame=null,this.render()}))}resize(){ma(this.canvas,this.gl,this.camera),this.requestRender()}onWebGlContextLost(t){const n=Ha({event:t,destroyed:this.destroyed,contextLost:this.contextLost,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,cache:this.cache,onContextLost:this.onContextLost});n.handled&&(this.frame=n.frame,this.contextLost=!0,this.pointBuffersDirty=!0)}onWebGlContextRestored(t){this.destroyed||(this.contextLost=!1,this.cache.clear(),this.tileProgram=Cr(this.gl),this.pointProgram=Ir(this.gl),this.pointBuffersDirty=!0,this.lastPointPalette&&this.lastPointPalette.length>0&&this.setPointPalette(this.lastPointPalette),this.lastPointData?this.setPointData(this.lastPointData):this.pointCount=0,this.resize(),this.onContextRestored?.())}destroy(){const t=Za({destroyed:this.destroyed,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),resizeObserver:this.resizeObserver,removeCanvasEventListeners:()=>da(this.canvas,this.getCanvasHandlers()),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,contextLost:this.contextLost,gl:this.gl,cache:this.cache,tileProgram:this.tileProgram,pointProgram:this.pointProgram});t.didDestroy&&(this.destroyed=!0,this.frame=t.frame)}}const cl=[];function ul({source:e,viewState:t,onViewStateChange:n,onStats:r,onTileError:i,onContextLost:o,onContextRestored:s,imageColorSettings:a=null,fitNonce:l=0,rotationResetNonce:u=0,authToken:f="",ctrlDragRotate:c=!0,minZoom:h,maxZoom:d,viewTransition:m,zoomSnaps:p,zoomSnapFitAsMin:y,onPointerWorldMove:b,debugOverlay:x=!1,debugOverlayStyle:C,className:S,style:A,children:T}){const O=g.useRef(null),D=g.useRef(null),G=g.useRef(null),z=g.useRef(null),q=g.useRef(null),re=g.useRef(null),I=g.useRef(cl),H=g.useRef(!1),N=g.useRef(new Set),k=g.useRef(n),Z=g.useRef(r),we=g.useRef(i),se=g.useRef(o),Re=g.useRef(s),[Ce,xe]=g.useState(0),[M,v]=g.useState(null),X=g.useRef(x);g.useEffect(()=>{k.current=n},[n]),g.useEffect(()=>{Z.current=r},[r]),g.useEffect(()=>{we.current=i},[i]),g.useEffect(()=>{se.current=o},[o]),g.useEffect(()=>{Re.current=s},[s]),g.useEffect(()=>{X.current=x,x||v(null)},[x]);const le=g.useMemo(()=>({position:"relative",width:"100%",height:"100%",...A}),[A]),Q=g.useMemo(()=>({position:"absolute",top:8,left:8,zIndex:7,margin:0,padding:"8px 10px",maxWidth:"min(420px, 80%)",pointerEvents:"none",whiteSpace:"pre-wrap",lineHeight:1.35,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:11,color:"#cde6ff",background:"rgba(6, 12, 20, 0.82)",border:"1px solid rgba(173, 216, 255, 0.28)",borderRadius:8,boxShadow:"0 8px 22px rgba(0,0,0,0.35)",...C}),[C]),ie=g.useCallback(_=>{Z.current?.(_),X.current&&v(_)},[]),he=g.useMemo(()=>M?[`tier ${M.tier} | frame ${M.frameMs?.toFixed(2)??"-"} ms | drawCalls ${M.drawCalls??"-"}`,`tiles visible ${M.visible} | rendered ${M.rendered} | fallback ${M.fallback}`,`cache size ${M.cache} | hit ${M.cacheHits??"-"} | miss ${M.cacheMisses??"-"}`,`queue inflight ${M.inflight} | queued ${M.queued??"-"} | retries ${M.retries??"-"} | failed ${M.failed??"-"} | aborted ${M.aborted??"-"}`,`points ${M.points}`].join(`
|
|
163
|
-
`):"stats: waiting for first frame...",[M]),me=g.useCallback(()=>{const _=G.current;if(!_)return;const Y=_.getContext("2d");if(!Y)return;const J=Math.max(1,window.devicePixelRatio||1),oe=_.getBoundingClientRect(),L=Math.max(1,Math.round(oe.width*J)),K=Math.max(1,Math.round(oe.height*J));(_.width!==L||_.height!==K)&&(_.width=L,_.height=K);const ce=oe.width,ne=oe.height;Y.setTransform(1,0,0,1,0,0),Y.clearRect(0,0,_.width,_.height),Y.setTransform(J,0,0,J,0,0);const ue=I.current;for(let De=0;De<ue.length;De+=1)Y.save(),ue[De].draw(Y,ce,ne),Y.restore()},[]),$=g.useCallback(()=>{H.current||(H.current=!0,requestAnimationFrame(()=>{H.current=!1,me()}))},[me]),pe=g.useCallback((_,Y,J)=>{const oe=I.current.filter(L=>L.id!==_);oe.push({id:_,priority:Y,draw:J}),oe.sort((L,K)=>L.priority-K.priority),I.current=oe,$()},[$]),ye=g.useCallback(_=>{I.current=I.current.filter(Y=>Y.id!==_),$()},[$]),U=g.useCallback((_,Y)=>{Y?N.current.add(_):N.current.delete(_),z.current?.setInteractionLock(N.current.size>0)},[]),V=g.useCallback(()=>N.current.size>0,[]),ee=g.useCallback((_,Y)=>{const J=z.current;return J?En(J.worldToScreen(_,Y)):null},[]),B=g.useCallback((_,Y)=>{const J=z.current;if(!J)return null;const oe=J.screenToWorld(_,Y);if(!Array.isArray(oe)||oe.length<2)return null;const L=Number(oe[0]),K=Number(oe[1]);return!Number.isFinite(L)||!Number.isFinite(K)?null:[L,K]},[]),te=g.useCallback(_=>{k.current?.(_),q.current?.(),re.current?.(),$()},[$]);g.useEffect(()=>{const _=D.current;if(!_||!e)return;const Y=new mi(_,e,{onViewStateChange:te,onStats:ie,onTileError:J=>{we.current?.(J)},onContextLost:()=>{se.current?.()},onContextRestored:()=>{Re.current?.()},authToken:f,imageColorSettings:a,ctrlDragRotate:c,minZoom:h,maxZoom:d,viewTransition:m,zoomSnaps:p,zoomSnapFitAsMin:y});return z.current=Y,xe(J=>J+1),t&&Y.setViewState(t),Y.setInteractionLock(N.current.size>0),()=>{Y.destroy(),z.current=null}},[e,ie,c,te]),g.useEffect(()=>{z.current?.setAuthToken(f)},[f]),g.useEffect(()=>{const _=z.current;!_||!t||_.isViewAnimating()||_.setViewState(t)},[t]),g.useEffect(()=>{z.current?.fitToImage()},[l]),g.useEffect(()=>{z.current?.resetRotation()},[u]),g.useEffect(()=>{z.current?.setZoomRange(h,d)},[h,d]),g.useEffect(()=>{z.current?.setViewTransition(m)},[m]),g.useEffect(()=>{z.current?.setZoomSnaps(p,y)},[p,y]),g.useEffect(()=>{z.current?.setImageColorSettings(a)},[a]),g.useEffect(()=>{const _=G.current;if(!_)return;q.current=$,$();const Y=new ResizeObserver(()=>$());return Y.observe(_),()=>{Y.disconnect(),q.current===$&&(q.current=null)}},[$]);const de=g.useMemo(()=>({source:e,rendererRef:z,rendererSerial:Ce,canvasRef:D,containerRef:O,drawInvalidateRef:q,overviewInvalidateRef:re,worldToScreen:ee,screenToWorld:B,registerDrawCallback:pe,unregisterDrawCallback:ye,requestOverlayRedraw:$,setInteractionLock:U,isInteractionLocked:V}),[e,Ce,ee,B,pe,ye,$,U,V]),ae=g.useRef(b);g.useEffect(()=>{ae.current=b},[b]);const Me=g.useCallback(_=>{const Y=ae.current;if(!Y)return;const J=B(_.clientX,_.clientY),oe=!!J&&J[0]>=0&&J[1]>=0&&!!e&&J[0]<=e.width&&J[1]<=e.height;Y({coordinate:J,clientX:_.clientX,clientY:_.clientY,insideImage:oe})},[B,e]),Se=g.useCallback(()=>{ae.current?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1})},[]);return Ye.jsx(ps,{value:de,children:Ye.jsxs("div",{ref:O,className:S,style:le,onPointerMove:b?Me:void 0,onPointerLeave:b?Se:void 0,children:[Ye.jsx("canvas",{ref:D,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none"}}),Ye.jsx("canvas",{ref:G,className:"wsi-overlay-canvas",style:{position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",pointerEvents:"none",touchAction:"none"}}),T,x&&Ye.jsx("pre",{"data-open-plant-debug-overlay":!0,style:Q,children:he})]})})}function fl(e){const t=[];for(let n=0;n<e.length;n+=1){const r=e[n],i=yt([pt(r?.coordinates)]);if(i.length===0)continue;let o=0,s=1/0,a=1/0,l=-1/0,u=-1/0;for(const f of i)o+=f.area,f.minX<s&&(s=f.minX),f.minY<a&&(a=f.minY),f.maxX>l&&(l=f.maxX),f.maxY>u&&(u=f.maxY);!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(l)||!Number.isFinite(u)||t.push({regionId:r.id??n,regionIndex:n,polygons:i,area:Math.max(1e-6,o),minX:s,minY:a,maxX:l,maxY:u})}return t}const hl=128,nn=[];function rt(e,t,n,r,i){if(i<=1||n<=t)return 0;const o=(e-t)/r;return!Number.isFinite(o)||o<=0?0:o>=i-1?i-1:Math.floor(o)}function dl(e){if(e.length===0)return null;let t=1/0,n=1/0,r=-1/0,i=-1/0;for(const f of e)f.minX<t&&(t=f.minX),f.minY<n&&(n=f.minY),f.maxX>r&&(r=f.maxX),f.maxY>i&&(i=f.maxY);if(!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i))return null;const o=Math.ceil(Math.sqrt(e.length*2)),s=Math.max(1,Math.min(hl,o)),a=r>t?(r-t)/s:1,l=i>n?(i-n)/s:1,u=Array.from({length:s*s},()=>[]);for(let f=0;f<e.length;f+=1){const c=e[f],h=rt(c.minX,t,r,a,s),d=rt(c.maxX,t,r,a,s),m=rt(c.minY,n,i,l,s),p=rt(c.maxY,n,i,l,s);for(let y=m;y<=p;y+=1)for(let b=h;b<=d;b+=1)u[y*s+b].push(f)}return{minX:t,minY:n,maxX:r,maxY:i,gridSize:s,cellWidth:a,cellHeight:l,buckets:u}}function ml(e,t,n){if(!e||t<e.minX||t>e.maxX||n<e.minY||n>e.maxY)return nn;const r=rt(t,e.minX,e.maxX,e.cellWidth,e.gridSize),i=rt(n,e.minY,e.maxY,e.cellHeight,e.gridSize);return e.buckets[i*e.gridSize+r]??nn}function gl(e,t){if(Array.isArray(t)){const n=t[e];if(typeof n=="string"&&n.length>0)return n}if(t instanceof Map){const n=t.get(e);if(typeof n=="string"&&n.length>0)return n}return String(e)}function pl(e,t,n={}){const r=Math.max(0,Math.min(Math.floor(e?.count??0),Math.floor((e?.positions?.length??0)/2),e?.paletteIndices?.length??0,e?.fillModes instanceof Uint8Array?e.fillModes.length:Number.MAX_SAFE_INTEGER));let i=null;if(e?.drawIndices instanceof Uint32Array){const d=e.drawIndices;let m=d.length;for(let p=0;p<d.length;p+=1)d[p]<r||(m-=1);if(m===d.length)i=d;else if(m>0){const p=new Uint32Array(m);let y=0;for(let b=0;b<d.length;b+=1){const x=d[b];x>=r||(p[y]=x,y+=1)}i=p}else i=new Uint32Array(0)}const o=i?i.length:r,s=fl(t??[]);if(!e||o===0||s.length===0)return{groups:[],inputPointCount:o,pointsInsideAnyRegion:0,unmatchedPointCount:o};const a=new Map,l=new Map,u=dl(s);let f=0;for(let d=0;d<o;d+=1){const m=i?i[d]:d,p=e.positions[m*2],y=e.positions[m*2+1];if(!Number.isFinite(p)||!Number.isFinite(y))continue;let b=null;const x=ml(u,p,y);if(x.length===0)continue;for(const A of x){const T=s[A];let O=!1;for(const D of T.polygons)if(Or(p,y,D)){O=!0;break}O&&(!b||T.area<b.area)&&(b=T)}if(!b)continue;f+=1;const C=e.paletteIndices[m]??0,S=a.get(b.regionIndex)??new Map;S.set(C,(S.get(C)??0)+1),a.set(b.regionIndex,S),l.set(b.regionIndex,(l.get(b.regionIndex)??0)+1)}const c=n.includeEmptyRegions??!1,h=[];for(const d of s){const m=l.get(d.regionIndex)??0;if(!c&&m<=0)continue;const p=a.get(d.regionIndex)??new Map,y=Array.from(p.entries()).map(([b,x])=>({termId:gl(b,n.paletteIndexToTermId),paletteIndex:b,count:x})).sort((b,x)=>x.count-b.count||b.paletteIndex-x.paletteIndex);h.push({regionId:d.regionId,regionIndex:d.regionIndex,totalCount:m,termCounts:y})}return{groups:h,inputPointCount:o,pointsInsideAnyRegion:f,unmatchedPointCount:Math.max(0,o-f)}}function _r(e,t,n,r){return[Math.min(e,n),Math.min(t,r),Math.max(e,n),Math.max(t,r)]}function Fr(e,t){return!(e[2]<t[0]||e[0]>t[2]||e[3]<t[1]||e[1]>t[3])}class yl{constructor(t=16){R(this,"targetNodeSize");R(this,"items",[]);R(this,"globalBounds",[0,0,0,0]);R(this,"gridSize",1);R(this,"cellWidth",1);R(this,"cellHeight",1);R(this,"buckets",[]);R(this,"visited",new Uint32Array(0));R(this,"querySerial",1);const n=Number.isFinite(t)?Math.floor(t):16;this.targetNodeSize=Math.max(1,n)}load(t){if(!Array.isArray(t)||t.length===0){this.items=[],this.globalBounds=[0,0,0,0],this.gridSize=1,this.cellWidth=1,this.cellHeight=1,this.buckets=[],this.visited=new Uint32Array(0),this.querySerial=1;return}const n=[];let r=1/0,i=1/0,o=-1/0,s=-1/0;for(const f of t){if(!f||!Number.isFinite(f.minX)||!Number.isFinite(f.minY)||!Number.isFinite(f.maxX)||!Number.isFinite(f.maxY))continue;const c=_r(f.minX,f.minY,f.maxX,f.maxY);r=Math.min(r,c[0]),i=Math.min(i,c[1]),o=Math.max(o,c[2]),s=Math.max(s,c[3]),n.push({minX:c[0],minY:c[1],maxX:c[2],maxY:c[3],value:f.value})}if(this.items=n,this.visited=new Uint32Array(n.length),this.querySerial=1,n.length===0||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(o)||!Number.isFinite(s)){this.globalBounds=[0,0,0,0],this.gridSize=1,this.cellWidth=1,this.cellHeight=1,this.buckets=[];return}this.globalBounds=[r,i,o,s],this.gridSize=Math.max(1,Math.ceil(Math.sqrt(n.length/this.targetNodeSize)));const a=Math.max(0,o-r),l=Math.max(0,s-i);this.cellWidth=a>0?a/this.gridSize:1,this.cellHeight=l>0?l/this.gridSize:1;const u=this.gridSize*this.gridSize;this.buckets=Array.from({length:u},()=>[]);for(let f=0;f<n.length;f+=1){const c=n[f],h=this.toCellX(c.minX),d=this.toCellX(c.maxX),m=this.toCellY(c.minY),p=this.toCellY(c.maxY);for(let y=m;y<=p;y+=1)for(let b=h;b<=d;b+=1)this.buckets[y*this.gridSize+b].push(f)}}search(t){if(this.items.length===0)return[];if(!Array.isArray(t)||t.length<4)return[];const n=_r(t[0],t[1],t[2],t[3]);if(!Fr(n,this.globalBounds))return[];const r=this.toCellX(n[0]),i=this.toCellX(n[2]),o=this.toCellY(n[1]),s=this.toCellY(n[3]),a=this.nextSerial(),l=[];for(let u=o;u<=s;u+=1)for(let f=r;f<=i;f+=1){const c=this.buckets[u*this.gridSize+f];if(!(!c||c.length===0))for(const h of c){if(this.visited[h]===a)continue;this.visited[h]=a;const d=this.items[h];Fr(n,[d.minX,d.minY,d.maxX,d.maxY])&&l.push(d)}}return l}nextSerial(){return this.querySerial+=1,this.querySerial===4294967295&&(this.visited.fill(0),this.querySerial=1),this.querySerial}toCellX(t){const n=this.globalBounds[0],r=this.globalBounds[2];if(this.gridSize<=1||r<=n)return 0;const i=(t-n)/this.cellWidth;return!Number.isFinite(i)||i<=0?0:i>=this.gridSize-1?this.gridSize-1:Math.max(0,Math.min(this.gridSize-1,Math.floor(i)))}toCellY(t){const n=this.globalBounds[1],r=this.globalBounds[3];if(this.gridSize<=1||r<=n)return 0;const i=(t-n)/this.cellHeight;return!Number.isFinite(i)||i<=0?0:i>=this.gridSize-1?this.gridSize-1:Math.max(0,Math.min(this.gridSize-1,Math.floor(i)))}}function bl(e){return new yl(e)}function wl(e){return e.replace(/^\s*SRID\s*=\s*\d+\s*;\s*/i,"")}function xl(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function Sl(e){return e>="0"&&e<="9"}function Lr(e){return e==="+"||e==="-"||e==="."||Sl(e)}class El{constructor(t){R(this,"text");R(this,"index",0);this.text=wl(t.trim())}parse(){if(!this.text)return null;const t=this.readWord();if(!t)return null;const n=t.toUpperCase();if(n!=="POLYGON"&&n!=="MULTIPOLYGON")return null;this.skipWhitespace();const r=this.peekWord();if(r){const s=r.toUpperCase();(s==="Z"||s==="M"||s==="ZM")&&(this.readWord(),this.skipWhitespace())}if(this.consumeWordIf("EMPTY"))return this.skipWhitespace(),this.isEof()?n==="POLYGON"?{type:"Polygon",coordinates:[]}:{type:"MultiPolygon",coordinates:[]}:null;let i;try{i=this.parseNestedList()}catch{return null}if(this.skipWhitespace(),!this.isEof())return null;if(n==="POLYGON"){const s=gi(i);return s?{type:"Polygon",coordinates:s}:null}const o=Ml(i);return o?{type:"MultiPolygon",coordinates:o}:null}isEof(){return this.index>=this.text.length}currentChar(){return this.text[this.index]??""}skipWhitespace(){for(;!this.isEof()&&/\s/.test(this.currentChar());)this.index+=1}readWord(){if(this.skipWhitespace(),this.isEof())return null;const t=this.index;for(;!this.isEof()&&xl(this.currentChar());)this.index+=1;return this.index===t?null:this.text.slice(t,this.index)}peekWord(){const t=this.index,n=this.readWord();return this.index=t,n}consumeWordIf(t){const n=this.index,r=this.readWord();return!r||r.toUpperCase()!==t.toUpperCase()?(this.index=n,!1):!0}parseNestedList(){if(this.skipWhitespace(),this.currentChar()!=="(")throw new Error("Expected '('");this.index+=1;const t=[];for(;;){this.skipWhitespace(),this.currentChar()==="("?t.push(this.parseNestedList()):t.push(this.parseCoordinateTuple()),this.skipWhitespace();const n=this.currentChar();if(n===","){this.index+=1;continue}if(n===")"){this.index+=1;break}throw new Error("Expected ',' or ')'")}return t}parseCoordinateTuple(){this.skipWhitespace();const t=[];for(;;){this.skipWhitespace();const n=this.currentChar();if(!n||!Lr(n))break;const r=this.readNumber();if(r===null)break;t.push(r),this.skipWhitespace();const i=this.currentChar();if(!i||i===","||i===")")break;if(!Lr(i))throw new Error("Invalid coordinate")}if(t.length<2)throw new Error("Coordinate requires at least x y");return[t[0],t[1]]}readNumber(){if(this.skipWhitespace(),this.isEof())return null;const n=this.text.slice(this.index).match(/^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/);if(!n)return null;const r=Number(n[0]);return Number.isFinite(r)?(this.index+=n[0].length,r):null}}function Rl(e){return Array.isArray(e)&&e.length>=2&&typeof e[0]=="number"&&Number.isFinite(e[0])&&typeof e[1]=="number"&&Number.isFinite(e[1])}function gi(e){if(!Array.isArray(e))return null;const t=[];for(const n of e){if(!Array.isArray(n))return null;const r=[];for(const i of n){if(!Rl(i))return null;r.push([i[0],i[1]])}t.push(r)}return t}function Ml(e){if(!Array.isArray(e))return null;const t=[];for(const n of e){const r=gi(n);if(!r)return null;t.push(r)}return t}function Al(e){return typeof e!="string"?null:new El(e).parse()}exports.DEFAULT_POINT_COLOR=xn;exports.DrawLayer=Qr;exports.DrawingLayer=ys;exports.M1TileRenderer=Nr;exports.OverlayLayer=bs;exports.OverviewMap=Ms;exports.PatchLayer=vs;exports.PointLayer=js;exports.RegionLayer=ca;exports.TileScheduler=ci;exports.TileViewerCanvas=ua;exports.WsiTileRenderer=mi;exports.WsiViewer=ul;exports.buildPointSpatialIndexAsync=li;exports.buildTermPalette=eo;exports.calcScaleLength=Qi;exports.calcScaleResolution=Sn;exports.clamp=W;exports.closeRing=Fe;exports.computeRoiPointGroups=pl;exports.createCircle=fn;exports.createRectangle=Yt;exports.createSpatialIndex=bl;exports.filterPointDataByPolygons=dt;exports.filterPointDataByPolygonsHybrid=ii;exports.filterPointDataByPolygonsInWorker=si;exports.filterPointIndicesByPolygons=ti;exports.filterPointIndicesByPolygonsInWorker=Bs;exports.getWebGpuCapabilities=Ls;exports.hexToRgba=Yr;exports.isSameViewState=cn;exports.lookupCellIndex=ai;exports.normalizeImageInfo=xs;exports.parseWkt=Al;exports.prefilterPointsByBoundsWebGpu=ri;exports.terminatePointHitIndexWorker=qs;exports.terminateRoiClipWorker=Ns;exports.toBearerToken=Ji;exports.toRoiGeometry=pt;exports.toTileUrl=Pn;exports.useViewerContext=ot;
|
|
162
|
+
}`),i=Le(e,r,"uCamera"),o=Le(e,r,"uPointSize"),s=Le(e,r,"uPointStrokeScale"),a=Le(e,r,"uPointInnerFillAlpha"),l=Le(e,r,"uPalette"),u=Le(e,r,"uPaletteSize"),f=e.createVertexArray(),c=e.createBuffer(),h=e.createBuffer(),d=e.createBuffer(),m=e.createBuffer(),p=e.createTexture();if(!f||!c||!h||!d||!m||!p)throw new Error("point buffer allocation failed");e.bindVertexArray(f),e.bindBuffer(e.ARRAY_BUFFER,c),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const y=e.getAttribLocation(r,"aPosition");if(y<0)throw new Error("point position attribute not found");e.enableVertexAttribArray(y),e.vertexAttribPointer(y,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,h),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const b=e.getAttribLocation(r,"aTerm");if(b<0)throw new Error("point term attribute not found");e.enableVertexAttribArray(b),e.vertexAttribIPointer(b,1,e.UNSIGNED_SHORT,0,0),e.bindBuffer(e.ARRAY_BUFFER,d),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const x=e.getAttribLocation(r,"aFillMode");if(x<0)throw new Error("point fill mode attribute not found");return e.enableVertexAttribArray(x),e.vertexAttribIPointer(x,1,e.UNSIGNED_BYTE,0,0),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,m),e.bufferData(e.ELEMENT_ARRAY_BUFFER,0,e.DYNAMIC_DRAW),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),e.bindTexture(e.TEXTURE_2D,p),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([160,160,160,255])),e.bindTexture(e.TEXTURE_2D,null),{program:r,vao:f,posBuffer:c,termBuffer:h,fillModeBuffer:d,indexBuffer:m,paletteTexture:p,uCamera:i,uPointSize:o,uPointStrokeScale:s,uPointInnerFillAlpha:a,uPalette:l,uPaletteSize:u}}function di(e){e.animation=null,e.frame!==null&&(cancelAnimationFrame(e.frame),e.frame=null)}function el(e){const{state:t,camera:n,target:r,durationMs:i,easing:o,onUpdate:s}=e,a=n.getViewState();di(t),t.animation={startMs:ye(),durationMs:Math.max(0,i),from:a,to:r,easing:o};const l=()=>{const u=t.animation;if(!u)return;const f=Math.max(0,ye()-u.startMs),c=u.durationMs<=0?1:O(f/u.durationMs,0,1);let h=c;try{h=u.easing(c)}catch{h=c}if(Number.isFinite(h)||(h=c),h=O(h,0,1),n.setViewState({zoom:u.from.zoom+(u.to.zoom-u.from.zoom)*h,offsetX:u.from.offsetX+(u.to.offsetX-u.from.offsetX)*h,offsetY:u.from.offsetY+(u.to.offsetY-u.from.offsetY)*h,rotationDeg:u.from.rotationDeg+(u.to.rotationDeg-u.from.rotationDeg)*h}),s(),c>=1){t.animation=null,t.frame=null;return}t.frame=requestAnimationFrame(l)};t.frame=requestAnimationFrame(l)}function tl(e){const t=Math.max(e*.5,1e-6),n=Math.max(1,e*8);return{minZoom:t,maxZoom:Math.max(t,n)}}function nl(e,t,n){const r=tl(e);let i=t??r.minZoom,o=n??r.maxZoom;return i=Math.max(1e-6,i),o=Math.max(1e-6,o),i>o&&(i=o),{minZoom:i,maxZoom:o}}function rl(e,t,n,r,i){const o=e.getViewState(),s={zoom:typeof r.zoom=="number"&&Number.isFinite(r.zoom)?O(r.zoom,t,n):o.zoom,offsetX:typeof r.offsetX=="number"&&Number.isFinite(r.offsetX)?r.offsetX:o.offsetX,offsetY:typeof r.offsetY=="number"&&Number.isFinite(r.offsetY)?r.offsetY:o.offsetY,rotationDeg:typeof r.rotationDeg=="number"&&Number.isFinite(r.rotationDeg)?r.rotationDeg:o.rotationDeg};e.setViewState(s),i();const a=e.getViewState();return e.setViewState(o),a}function Pr(e,t,n,r,i){const o=Math.min(t/e.width,n/e.height),s=Number.isFinite(o)&&o>0?o:1,a=O(s,r,i),l=t/a,u=n/a;return{fitZoom:s,target:{zoom:a,offsetX:(e.width-l)*.5,offsetY:(e.height-u)*.5,rotationDeg:0}}}function il(e,t,n,r,i,o){const s=e.getViewState(),a=O(s.zoom*r,t,n);if(a===s.zoom)return null;const[l,u]=e.screenToWorld(i,o),f=e.getViewportSize(),c=i-f.width*.5,h=o-f.height*.5,d=Gt(s.rotationDeg),m=Math.cos(d),p=Math.sin(d),y=c/a*m-h/a*p,b=c/a*p+h/a*m,x=l-y,C=u-b;return{zoom:a,offsetX:x-f.width/(2*a),offsetY:C-f.height/(2*a)}}function ol(e,t,n,r,i,o){const s=e.getViewState(),a=O(r,t,n);if(a===s.zoom)return null;const[l,u]=e.screenToWorld(i,o),f=e.getViewportSize(),c=i-f.width*.5,h=o-f.height*.5,d=Gt(s.rotationDeg),m=Math.cos(d),p=Math.sin(d),y=c/a*m-h/a*p,b=c/a*p+h/a*m,x=l-y,C=u-b;return{zoom:a,offsetX:x-f.width/(2*a),offsetY:C-f.height/(2*a)}}const sl=250;function Tr(e,t){if(!e||e.length===0)return[];if(!t||t<=0)return[];const n=10/t;return e.map(r=>r/n).filter(r=>Number.isFinite(r)&&r>0).sort((r,i)=>r-i)}function al(e,t,n,r){if(e.length===0)return null;const i=Math.max(t*.005,1e-8);if(n==="in"){for(const o of e)if(o>t+i)return{type:"snap",zoom:o};return null}for(let o=e.length-1;o>=0;o--)if(e[o]<t-i)return{type:"snap",zoom:e[o]};return r&&t<=e[0]+i?{type:"fit"}:null}function ll(e,t,n,r,i){const o=e.camera.getViewState(),[s,a]=e.camera.screenToWorld(n,r),l=e.camera.getViewportSize(),u=O(t,e.minZoom,e.maxZoom);if(u===o.zoom)return;const f=Gt(o.rotationDeg),c=Math.cos(f),h=Math.sin(f),d=n-l.width*.5,m=r-l.height*.5;e.cancelViewAnimation();const p=x=>{const C=d/x*c-m/x*h,S=d/x*h+m/x*c;return{offsetX:s-C-l.width/(2*x),offsetY:a-S-l.height/(2*x)}},y=p(u);e.viewAnimationState.animation={startMs:ye(),durationMs:Math.max(0,i),from:o,to:{zoom:u,offsetX:y.offsetX,offsetY:y.offsetY,rotationDeg:o.rotationDeg},easing:_n};const b=()=>{const x=e.viewAnimationState.animation;if(!x)return;const C=Math.max(0,ye()-x.startMs),S=O(C/i,0,1),A=O(S*S*(3-2*S),0,1),_=o.zoom+(u-o.zoom)*A,{offsetX:Y,offsetY:B}=p(_);e.camera.setViewState({zoom:_,offsetX:Y,offsetY:B,rotationDeg:o.rotationDeg});const G=S>=1;G&&(e.clampViewState(),e.viewAnimationState.animation=null,e.viewAnimationState.frame=null),e.onViewStateChange(e.camera.getViewState()),e.requestRender(),G||(e.viewAnimationState.frame=requestAnimationFrame(b))};e.viewAnimationState.frame=requestAnimationFrame(b)}class mi{constructor(t,n,r={}){R(this,"canvas");R(this,"source");R(this,"gl");R(this,"camera",new kr);R(this,"onViewStateChange");R(this,"onStats");R(this,"onTileError");R(this,"onContextLost");R(this,"onContextRestored");R(this,"resizeObserver");R(this,"tileProgram");R(this,"pointProgram");R(this,"tileScheduler");R(this,"authToken");R(this,"destroyed",!1);R(this,"contextLost",!1);R(this,"frame",null);R(this,"frameSerial",0);R(this,"interactionState",{dragging:!1,mode:"none",rotateLastAngleRad:null,pointerId:null,lastPointerX:0,lastPointerY:0});R(this,"interactionLocked",!1);R(this,"ctrlDragRotate",!0);R(this,"rotationDragSensitivityDegPerPixel",gn);R(this,"maxCacheTiles");R(this,"fitZoom",1);R(this,"minZoom",1e-6);R(this,"maxZoom",1);R(this,"minZoomOverride",null);R(this,"maxZoomOverride",null);R(this,"viewTransitionDurationMs",0);R(this,"viewTransitionEasing",_n);R(this,"viewAnimationState",{animation:null,frame:null});R(this,"pointCount",0);R(this,"usePointIndices",!1);R(this,"pointBuffersDirty",!0);R(this,"pointPaletteSize",1);R(this,"pointSizeStops",bn(yn));R(this,"pointStrokeScale",1);R(this,"pointInnerFillOpacity",0);R(this,"imageColorSettings",{brightness:0,contrast:0,saturation:0});R(this,"lastPointData",null);R(this,"lastPointPalette",null);R(this,"zeroFillModes",new Uint8Array(0));R(this,"cache",new Map);R(this,"zoomSnaps",[]);R(this,"zoomSnapFitAsMin",!1);R(this,"zoomSnapState",{accumulatedDelta:0,lastSnapTimeMs:0,blockedDirection:null});R(this,"boundPointerDown");R(this,"boundPointerMove");R(this,"boundPointerUp");R(this,"boundWheel");R(this,"boundDoubleClick");R(this,"boundContextMenu");R(this,"boundContextLost");R(this,"boundContextRestored");this.canvas=t,this.source=n,this.onViewStateChange=r.onViewStateChange,this.onStats=r.onStats,this.onTileError=r.onTileError,this.onContextLost=r.onContextLost,this.onContextRestored=r.onContextRestored,this.authToken=r.authToken??"",this.maxCacheTiles=Math.max(32,Math.floor(r.maxCacheTiles??320)),this.ctrlDragRotate=r.ctrlDragRotate??!0,this.rotationDragSensitivityDegPerPixel=typeof r.rotationDragSensitivityDegPerPixel=="number"&&Number.isFinite(r.rotationDragSensitivityDegPerPixel)?Math.max(0,r.rotationDragSensitivityDegPerPixel):gn,this.pointSizeStops=Rr(r.pointSizeByZoom),this.pointStrokeScale=Mr(r.pointStrokeScale),this.pointInnerFillOpacity=Ar(r.pointInnerFillOpacity),this.imageColorSettings=vr(r.imageColorSettings),this.minZoomOverride=Tt(r.minZoom),this.maxZoomOverride=Tt(r.maxZoom),this.viewTransitionDurationMs=tn(r.viewTransition?.duration),this.viewTransitionEasing=nn(r.viewTransition?.easing),this.zoomSnaps=Tr(r.zoomSnaps,this.source.mpp),this.zoomSnapFitAsMin=!!r.zoomSnapFitAsMin;const i=t.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,stencil:!1,powerPreference:"high-performance"});if(!i)throw new Error("WebGL2 not supported");this.gl=i,this.tileProgram=Cr(this.gl),this.pointProgram=Ir(this.gl),this.tileScheduler=new ci({authToken:this.authToken,maxConcurrency:r.tileScheduler?.maxConcurrency??12,maxRetries:r.tileScheduler?.maxRetries??2,retryBaseDelayMs:r.tileScheduler?.retryBaseDelayMs??120,retryMaxDelayMs:r.tileScheduler?.retryMaxDelayMs??1200,onTileLoad:(s,a)=>Ga({gl:this.gl,cache:this.cache,tile:s,bitmap:a,frameSerial:this.frameSerial,maxCacheTiles:this.maxCacheTiles,destroyed:this.destroyed,contextLost:this.contextLost,requestRender:()=>this.requestRender()}),onTileError:(s,a,l)=>{this.onTileError?.({tile:s,error:a,attemptCount:l}),console.warn("tile load failed",s.url,a)}}),this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(t);const o=Wa({canvas:this.canvas,state:this.interactionState,getInteractionLocked:()=>this.interactionLocked,getCtrlDragRotate:()=>this.ctrlDragRotate,getRotationDragSensitivityDegPerPixel:()=>this.rotationDragSensitivityDegPerPixel,cancelViewAnimation:()=>this.cancelViewAnimation(),camera:this.camera,source:this.source,emitViewState:()=>this.onViewStateChange?.(this.camera.getViewState()),requestRender:()=>this.requestRender(),zoomBy:(s,a,l)=>this.zoomBy(s,a,l),getUseZoomSnaps:()=>this.zoomSnaps.length>0,onSnapZoom:(s,a,l)=>this.handleSnapZoom(s,a,l),zoomSnapState:this.zoomSnapState});this.boundPointerDown=o.pointerDown,this.boundPointerMove=o.pointerMove,this.boundPointerUp=o.pointerUp,this.boundWheel=o.wheel,this.boundDoubleClick=o.doubleClick,this.boundContextMenu=o.contextMenu,this.boundContextLost=s=>this.onWebGlContextLost(s),this.boundContextRestored=s=>this.onWebGlContextRestored(s),ha(t,this.getCanvasHandlers()),this.fitToImage({duration:0}),this.resize()}getCanvasHandlers(){return{pointerDown:this.boundPointerDown,pointerMove:this.boundPointerMove,pointerUp:this.boundPointerUp,wheel:this.boundWheel,doubleClick:this.boundDoubleClick,contextMenu:this.boundContextMenu,contextLost:this.boundContextLost,contextRestored:this.boundContextRestored}}applyZoomBounds(){const t=nl(this.fitZoom,this.minZoomOverride,this.maxZoomOverride);this.minZoom=t.minZoom,this.maxZoom=t.maxZoom}resolveTargetViewState(t){return rl(this.camera,this.minZoom,this.maxZoom,t,()=>Nt(this.camera,this.source))}cancelViewAnimation(){di(this.viewAnimationState)}startViewAnimation(t,n,r){el({state:this.viewAnimationState,camera:this.camera,target:t,durationMs:n,easing:r,onUpdate:()=>{Nt(this.camera,this.source),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}})}getPointBufferRuntime(){return{pointCount:this.pointCount,usePointIndices:this.usePointIndices,pointBuffersDirty:this.pointBuffersDirty,lastPointData:this.lastPointData,zeroFillModes:this.zeroFillModes,lastPointPalette:this.lastPointPalette,pointPaletteSize:this.pointPaletteSize}}applyPointBufferRuntime(t){this.pointCount=t.pointCount,this.usePointIndices=t.usePointIndices,this.pointBuffersDirty=t.pointBuffersDirty,this.lastPointData=t.lastPointData,this.zeroFillModes=t.zeroFillModes,this.lastPointPalette=t.lastPointPalette,this.pointPaletteSize=t.pointPaletteSize}applyViewStateAndRender(t,n=!0){n&&this.cancelViewAnimation(),this.camera.setViewState(t),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}setAuthToken(t){this.authToken=String(t??""),this.tileScheduler.setAuthToken(this.authToken)}setZoomRange(t,n){const r=Tt(t),i=Tt(n);if(this.minZoomOverride===r&&this.maxZoomOverride===i)return;this.minZoomOverride=r,this.maxZoomOverride=i,this.applyZoomBounds();const o=this.resolveTargetViewState({}),s=this.camera.getViewState();un(s,o)||this.applyViewStateAndRender(o)}setViewTransition(t){this.viewTransitionDurationMs=tn(t?.duration),this.viewTransitionEasing=nn(t?.easing)}setViewState(t,n){const r=this.resolveTargetViewState(t),i=this.camera.getViewState();if(un(i,r))return;const o=tn(n?.duration??this.viewTransitionDurationMs),s=nn(n?.easing??this.viewTransitionEasing);if(o<=0){this.applyViewStateAndRender(r);return}this.startViewAnimation(r,o,s)}getViewState(){return this.camera.getViewState()}getZoomRange(){return{minZoom:this.minZoom,maxZoom:this.maxZoom}}getRegionLabelAutoLiftCapZoom(){const t=this.zoomSnaps.filter(n=>n>=this.minZoom&&n<=this.maxZoom);return t.length>0?t[t.length-1]:this.maxZoom}isViewAnimating(){return this.viewAnimationState.animation!==null}setPointPalette(t){const n=ja(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,t);this.applyPointBufferRuntime(n),!(!t||t.length===0)&&this.requestRender()}setPointData(t){const n=Qa(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,t);this.applyPointBufferRuntime(n),this.requestRender()}setInteractionLock(t){const n=!!t;this.interactionLocked!==n&&(this.interactionLocked=n,n&&this.cancelDrag())}setPointSizeByZoom(t){const n=Rr(t);Ra(this.pointSizeStops,n)||(this.pointSizeStops=n,this.requestRender())}setPointStrokeScale(t){const n=Mr(t);this.pointStrokeScale!==n&&(this.pointStrokeScale=n,this.requestRender())}setPointInnerFillOpacity(t){const n=Ar(t);this.pointInnerFillOpacity!==n&&(this.pointInnerFillOpacity=n,this.requestRender())}setImageColorSettings(t){const n=vr(t),r=this.imageColorSettings;r.brightness===n.brightness&&r.contrast===n.contrast&&r.saturation===n.saturation||(this.imageColorSettings=n,this.requestRender())}cancelDrag(){Ya(this.canvas,this.interactionState)}screenToWorld(t,n){const r=this.canvas.getBoundingClientRect(),i=t-r.left,o=n-r.top;return this.camera.screenToWorld(i,o)}worldToScreen(t,n){return this.camera.worldToScreen(t,n)}setViewCenter(t,n,r){if(!Number.isFinite(t)||!Number.isFinite(n))return;const i=this.camera.getViewState(),o=Math.max(1e-6,i.zoom),s=this.camera.getViewportSize();this.setViewState({offsetX:t-s.width/(2*o),offsetY:n-s.height/(2*o)},r)}getViewCorners(){return this.camera.getViewCorners()}getViewBounds(){return Vt(this.camera)}resetRotation(t){const n=this.camera.getViewState();Math.abs(n.rotationDeg)<1e-6||this.setViewState({rotationDeg:0},t)}getPointSizeByZoom(){const t=Math.max(1e-6,this.camera.getViewState().zoom),n=this.source.maxTierZoom+Math.log2(t),r=Ma(n,this.pointSizeStops);return O(r,pn,ga)}fitToImage(t){const n=this.canvas.getBoundingClientRect(),r=Math.max(1,n.width||1),i=Math.max(1,n.height||1),o=Pr(this.source,r,i,this.minZoom,this.maxZoom);this.fitZoom=o.fitZoom,this.applyZoomBounds(),this.setViewState(o.target,t)}zoomBy(t,n,r,i){const o=il(this.camera,this.minZoom,this.maxZoom,t,n,r);o&&this.setViewState(o,i)}zoomTo(t,n,r,i){const o=ol(this.camera,this.minZoom,this.maxZoom,t,n,r);o&&this.setViewState(o,i)}setZoomSnaps(t,n){this.zoomSnaps=Tr(t,this.source.mpp),this.zoomSnapFitAsMin=!!n}getZoomPivotAnimationContext(){return{camera:this.camera,viewAnimationState:this.viewAnimationState,minZoom:this.minZoom,maxZoom:this.maxZoom,cancelViewAnimation:()=>this.cancelViewAnimation(),clampViewState:()=>Nt(this.camera,this.source),onViewStateChange:t=>this.onViewStateChange?.(t),requestRender:()=>this.requestRender()}}handleSnapZoom(t,n,r){const i=this.viewAnimationState.animation,o=i?i.to.zoom:this.camera.getViewState().zoom,s=this.zoomSnaps.filter(f=>f>=this.minZoom&&f<=this.maxZoom),a=al(s,o,t,this.zoomSnapFitAsMin);if(!a)return!1;let l;if(a.type==="fit"){const f=this.canvas.getBoundingClientRect(),c=Math.max(1,f.width||1),h=Math.max(1,f.height||1),d=Pr(this.source,c,h,this.minZoom,this.maxZoom);this.fitZoom=d.fitZoom,this.applyZoomBounds(),l=d.target.zoom}else l=a.zoom;const u=Math.max(Math.abs(l)*.005,1e-8);if(i){if((i.to.zoom>i.from.zoom+u?"in":i.to.zoom<i.from.zoom-u?"out":null)===t&&Math.abs(i.to.zoom-l)<=u)return!1}else if(Math.abs(o-l)<=u)return!1;return ll(this.getZoomPivotAnimationContext(),l,n,r,sl),!0}render(){if(this.destroyed||this.contextLost||this.gl.isContextLost())return;const t=this.onStats?ye():0;this.frameSerial+=1;const n=Ja({gl:this.gl,camera:this.camera,source:this.source,cache:this.cache,frameSerial:this.frameSerial,tileProgram:this.tileProgram,pointProgram:this.pointProgram,imageColorSettings:this.imageColorSettings,pointCount:this.pointCount,usePointIndices:this.usePointIndices,pointPaletteSize:this.pointPaletteSize,pointStrokeScale:this.pointStrokeScale,pointInnerFillOpacity:this.pointInnerFillOpacity,pointSizePx:this.getPointSizeByZoom()*Math.max(1,window.devicePixelRatio||1),tileScheduler:this.tileScheduler,getVisibleTiles:()=>Na(this.camera,this.source),getVisibleTilesForTier:r=>hi(this.camera,this.source,r),getViewBounds:()=>Vt(this.camera),intersectsBounds:ka});if(this.onStats){const r=this.tileScheduler.getSnapshot();this.onStats({tier:n.tier,visible:n.visible,rendered:n.rendered,points:n.points,fallback:n.fallback,cache:this.cache.size,inflight:r.inflight,queued:r.queued,retries:r.retries,failed:r.failed,aborted:r.aborted,cacheHits:n.cacheHits,cacheMisses:n.cacheMisses,drawCalls:n.drawCalls,frameMs:ye()-t})}}requestRender(){this.frame!==null||this.destroyed||this.contextLost||this.gl.isContextLost()||(this.frame=requestAnimationFrame(()=>{this.frame=null,this.render()}))}resize(){ma(this.canvas,this.gl,this.camera),this.requestRender()}onWebGlContextLost(t){const n=Ha({event:t,destroyed:this.destroyed,contextLost:this.contextLost,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,cache:this.cache,onContextLost:this.onContextLost});n.handled&&(this.frame=n.frame,this.contextLost=!0,this.pointBuffersDirty=!0)}onWebGlContextRestored(t){this.destroyed||(this.contextLost=!1,this.cache.clear(),this.tileProgram=Cr(this.gl),this.pointProgram=Ir(this.gl),this.pointBuffersDirty=!0,this.lastPointPalette&&this.lastPointPalette.length>0&&this.setPointPalette(this.lastPointPalette),this.lastPointData?this.setPointData(this.lastPointData):this.pointCount=0,this.resize(),this.onContextRestored?.())}destroy(){const t=Za({destroyed:this.destroyed,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),resizeObserver:this.resizeObserver,removeCanvasEventListeners:()=>da(this.canvas,this.getCanvasHandlers()),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,contextLost:this.contextLost,gl:this.gl,cache:this.cache,tileProgram:this.tileProgram,pointProgram:this.pointProgram});t.didDestroy&&(this.destroyed=!0,this.frame=t.frame)}}const cl=[];function ul({source:e,viewState:t,onViewStateChange:n,onStats:r,onTileError:i,onContextLost:o,onContextRestored:s,imageColorSettings:a=null,fitNonce:l=0,rotationResetNonce:u=0,authToken:f="",ctrlDragRotate:c=!0,minZoom:h,maxZoom:d,viewTransition:m,zoomSnaps:p,zoomSnapFitAsMin:y,onPointerWorldMove:b,debugOverlay:x=!1,debugOverlayStyle:C,className:S,style:A,children:_}){const Y=g.useRef(null),B=g.useRef(null),G=g.useRef(null),z=g.useRef(null),$=g.useRef(null),Q=g.useRef(null),P=g.useRef(cl),W=g.useRef(!1),N=g.useRef(new Set),k=g.useRef(new Set),K=g.useRef(n),me=g.useRef(r),ie=g.useRef(i),ve=g.useRef(o),Se=g.useRef(s),[Ce,v]=g.useState(0),[M,X]=g.useState(null),fe=g.useRef(x);g.useEffect(()=>{K.current=n},[n]),g.useEffect(()=>{me.current=r},[r]),g.useEffect(()=>{ie.current=i},[i]),g.useEffect(()=>{ve.current=o},[o]),g.useEffect(()=>{Se.current=s},[s]),g.useEffect(()=>{fe.current=x,x||X(null)},[x]);const J=g.useMemo(()=>({position:"relative",width:"100%",height:"100%",...A}),[A]),ae=g.useMemo(()=>({position:"absolute",top:8,left:8,zIndex:7,margin:0,padding:"8px 10px",maxWidth:"min(420px, 80%)",pointerEvents:"none",whiteSpace:"pre-wrap",lineHeight:1.35,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:11,color:"#cde6ff",background:"rgba(6, 12, 20, 0.82)",border:"1px solid rgba(173, 216, 255, 0.28)",borderRadius:8,boxShadow:"0 8px 22px rgba(0,0,0,0.35)",...C}),[C]),le=g.useCallback(F=>{me.current?.(F),fe.current&&X(F)},[]),ge=g.useMemo(()=>M?[`tier ${M.tier} | frame ${M.frameMs?.toFixed(2)??"-"} ms | drawCalls ${M.drawCalls??"-"}`,`tiles visible ${M.visible} | rendered ${M.rendered} | fallback ${M.fallback}`,`cache size ${M.cache} | hit ${M.cacheHits??"-"} | miss ${M.cacheMisses??"-"}`,`queue inflight ${M.inflight} | queued ${M.queued??"-"} | retries ${M.retries??"-"} | failed ${M.failed??"-"} | aborted ${M.aborted??"-"}`,`points ${M.points}`].join(`
|
|
163
|
+
`):"stats: waiting for first frame...",[M]),oe=g.useCallback(()=>{const F=G.current;if(!F)return;const V=F.getContext("2d");if(!V)return;const I=Math.max(1,window.devicePixelRatio||1),U=F.getBoundingClientRect(),Z=Math.max(1,Math.round(U.width*I)),re=Math.max(1,Math.round(U.height*I));(F.width!==Z||F.height!==re)&&(F.width=Z,F.height=re);const se=U.width,Ie=U.height;V.setTransform(1,0,0,1,0,0),V.clearRect(0,0,F.width,F.height),V.setTransform(I,0,0,I,0,0);const ze=P.current;for(let Ve=0;Ve<ze.length;Ve+=1)V.save(),ze[Ve].draw(V,se,Ie),V.restore()},[]),ne=g.useCallback(()=>{W.current||(W.current=!0,requestAnimationFrame(()=>{W.current=!1,oe()}))},[oe]),be=g.useCallback((F,V,I)=>{const U=P.current.filter(Z=>Z.id!==F);U.push({id:F,priority:V,draw:I}),U.sort((Z,re)=>Z.priority-re.priority),P.current=U,ne()},[ne]),he=g.useCallback(F=>{P.current=P.current.filter(V=>V.id!==F),ne()},[ne]),D=g.useCallback((F,V)=>{V?N.current.add(F):N.current.delete(F),z.current?.setInteractionLock(N.current.size>0)},[]),H=g.useCallback(()=>N.current.size>0,[]),q=g.useCallback((F,V)=>{const I=z.current;return I?Rn(I.worldToScreen(F,V)):null},[]),ee=g.useCallback((F,V)=>{const I=z.current;if(!I)return null;const U=I.screenToWorld(F,V);if(!Array.isArray(U)||U.length<2)return null;const Z=Number(U[0]),re=Number(U[1]);return!Number.isFinite(Z)||!Number.isFinite(re)?null:[Z,re]},[]),te=g.useCallback(F=>(k.current.add(F),()=>{k.current.delete(F)}),[]),ce=g.useCallback(F=>{K.current?.(F);const V=k.current;if(V.size>0){const I=Array.from(V);for(let U=0;U<I.length;U+=1)I[U](F)}$.current?.(),Q.current?.(),ne()},[ne]);g.useEffect(()=>{const F=B.current;if(!F||!e)return;const V=new mi(F,e,{onViewStateChange:ce,onStats:le,onTileError:I=>{ie.current?.(I)},onContextLost:()=>{ve.current?.()},onContextRestored:()=>{Se.current?.()},authToken:f,imageColorSettings:a,ctrlDragRotate:c,minZoom:h,maxZoom:d,viewTransition:m,zoomSnaps:p,zoomSnapFitAsMin:y});return z.current=V,v(I=>I+1),t&&V.setViewState(t),V.setInteractionLock(N.current.size>0),()=>{V.destroy(),z.current=null}},[e,le,c,ce]),g.useEffect(()=>{z.current?.setAuthToken(f)},[f]),g.useEffect(()=>{const F=z.current;!F||!t||F.isViewAnimating()||F.setViewState(t)},[t]),g.useEffect(()=>{z.current?.fitToImage()},[l]),g.useEffect(()=>{z.current?.resetRotation()},[u]),g.useEffect(()=>{z.current?.setZoomRange(h,d)},[h,d]),g.useEffect(()=>{z.current?.setViewTransition(m)},[m]),g.useEffect(()=>{z.current?.setZoomSnaps(p,y)},[p,y]),g.useEffect(()=>{z.current?.setImageColorSettings(a)},[a]),g.useEffect(()=>{const F=G.current;if(!F)return;$.current=ne,ne();const V=new ResizeObserver(()=>ne());return V.observe(F),()=>{V.disconnect(),$.current===ne&&($.current=null)}},[ne]);const Ee=g.useMemo(()=>({source:e,rendererRef:z,rendererSerial:Ce,canvasRef:B,containerRef:Y,drawInvalidateRef:$,overviewInvalidateRef:Q,worldToScreen:q,screenToWorld:ee,registerDrawCallback:be,unregisterDrawCallback:he,requestOverlayRedraw:ne,registerViewStateListener:te,setInteractionLock:D,isInteractionLocked:H}),[e,Ce,q,ee,be,he,ne,te,D,H]),we=g.useRef(b);g.useEffect(()=>{we.current=b},[b]);const xe=g.useCallback(F=>{const V=we.current;if(!V)return;const I=ee(F.clientX,F.clientY),U=!!I&&I[0]>=0&&I[1]>=0&&!!e&&I[0]<=e.width&&I[1]<=e.height;V({coordinate:I,clientX:F.clientX,clientY:F.clientY,insideImage:U})},[ee,e]),pe=g.useCallback(()=>{we.current?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1})},[]);return We.jsx(ps,{value:Ee,children:We.jsxs("div",{ref:Y,className:S,style:J,onPointerMove:b?xe:void 0,onPointerLeave:b?pe:void 0,children:[We.jsx("canvas",{ref:B,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none"}}),We.jsx("canvas",{ref:G,className:"wsi-overlay-canvas",style:{position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",pointerEvents:"none",touchAction:"none"}}),_,x&&We.jsx("pre",{"data-open-plant-debug-overlay":!0,style:ae,children:ge})]})})}function fl(e){const t=[];for(let n=0;n<e.length;n+=1){const r=e[n],i=bt([yt(r?.coordinates)]);if(i.length===0)continue;let o=0,s=1/0,a=1/0,l=-1/0,u=-1/0;for(const f of i)o+=f.area,f.minX<s&&(s=f.minX),f.minY<a&&(a=f.minY),f.maxX>l&&(l=f.maxX),f.maxY>u&&(u=f.maxY);!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(l)||!Number.isFinite(u)||t.push({regionId:r.id??n,regionIndex:n,polygons:i,area:Math.max(1e-6,o),minX:s,minY:a,maxX:l,maxY:u})}return t}const hl=128,rn=[];function ot(e,t,n,r,i){if(i<=1||n<=t)return 0;const o=(e-t)/r;return!Number.isFinite(o)||o<=0?0:o>=i-1?i-1:Math.floor(o)}function dl(e){if(e.length===0)return null;let t=1/0,n=1/0,r=-1/0,i=-1/0;for(const f of e)f.minX<t&&(t=f.minX),f.minY<n&&(n=f.minY),f.maxX>r&&(r=f.maxX),f.maxY>i&&(i=f.maxY);if(!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i))return null;const o=Math.ceil(Math.sqrt(e.length*2)),s=Math.max(1,Math.min(hl,o)),a=r>t?(r-t)/s:1,l=i>n?(i-n)/s:1,u=Array.from({length:s*s},()=>[]);for(let f=0;f<e.length;f+=1){const c=e[f],h=ot(c.minX,t,r,a,s),d=ot(c.maxX,t,r,a,s),m=ot(c.minY,n,i,l,s),p=ot(c.maxY,n,i,l,s);for(let y=m;y<=p;y+=1)for(let b=h;b<=d;b+=1)u[y*s+b].push(f)}return{minX:t,minY:n,maxX:r,maxY:i,gridSize:s,cellWidth:a,cellHeight:l,buckets:u}}function ml(e,t,n){if(!e||t<e.minX||t>e.maxX||n<e.minY||n>e.maxY)return rn;const r=ot(t,e.minX,e.maxX,e.cellWidth,e.gridSize),i=ot(n,e.minY,e.maxY,e.cellHeight,e.gridSize);return e.buckets[i*e.gridSize+r]??rn}function gl(e,t){if(Array.isArray(t)){const n=t[e];if(typeof n=="string"&&n.length>0)return n}if(t instanceof Map){const n=t.get(e);if(typeof n=="string"&&n.length>0)return n}return String(e)}function pl(e,t,n={}){const r=Math.max(0,Math.min(Math.floor(e?.count??0),Math.floor((e?.positions?.length??0)/2),e?.paletteIndices?.length??0,e?.fillModes instanceof Uint8Array?e.fillModes.length:Number.MAX_SAFE_INTEGER));let i=null;if(e?.drawIndices instanceof Uint32Array){const d=e.drawIndices;let m=d.length;for(let p=0;p<d.length;p+=1)d[p]<r||(m-=1);if(m===d.length)i=d;else if(m>0){const p=new Uint32Array(m);let y=0;for(let b=0;b<d.length;b+=1){const x=d[b];x>=r||(p[y]=x,y+=1)}i=p}else i=new Uint32Array(0)}const o=i?i.length:r,s=fl(t??[]);if(!e||o===0||s.length===0)return{groups:[],inputPointCount:o,pointsInsideAnyRegion:0,unmatchedPointCount:o};const a=new Map,l=new Map,u=dl(s);let f=0;for(let d=0;d<o;d+=1){const m=i?i[d]:d,p=e.positions[m*2],y=e.positions[m*2+1];if(!Number.isFinite(p)||!Number.isFinite(y))continue;let b=null;const x=ml(u,p,y);if(x.length===0)continue;for(const A of x){const _=s[A];let Y=!1;for(const B of _.polygons)if(Or(p,y,B)){Y=!0;break}Y&&(!b||_.area<b.area)&&(b=_)}if(!b)continue;f+=1;const C=e.paletteIndices[m]??0,S=a.get(b.regionIndex)??new Map;S.set(C,(S.get(C)??0)+1),a.set(b.regionIndex,S),l.set(b.regionIndex,(l.get(b.regionIndex)??0)+1)}const c=n.includeEmptyRegions??!1,h=[];for(const d of s){const m=l.get(d.regionIndex)??0;if(!c&&m<=0)continue;const p=a.get(d.regionIndex)??new Map,y=Array.from(p.entries()).map(([b,x])=>({termId:gl(b,n.paletteIndexToTermId),paletteIndex:b,count:x})).sort((b,x)=>x.count-b.count||b.paletteIndex-x.paletteIndex);h.push({regionId:d.regionId,regionIndex:d.regionIndex,totalCount:m,termCounts:y})}return{groups:h,inputPointCount:o,pointsInsideAnyRegion:f,unmatchedPointCount:Math.max(0,o-f)}}function _r(e,t,n,r){return[Math.min(e,n),Math.min(t,r),Math.max(e,n),Math.max(t,r)]}function Lr(e,t){return!(e[2]<t[0]||e[0]>t[2]||e[3]<t[1]||e[1]>t[3])}class yl{constructor(t=16){R(this,"targetNodeSize");R(this,"items",[]);R(this,"globalBounds",[0,0,0,0]);R(this,"gridSize",1);R(this,"cellWidth",1);R(this,"cellHeight",1);R(this,"buckets",[]);R(this,"visited",new Uint32Array(0));R(this,"querySerial",1);const n=Number.isFinite(t)?Math.floor(t):16;this.targetNodeSize=Math.max(1,n)}load(t){if(!Array.isArray(t)||t.length===0){this.items=[],this.globalBounds=[0,0,0,0],this.gridSize=1,this.cellWidth=1,this.cellHeight=1,this.buckets=[],this.visited=new Uint32Array(0),this.querySerial=1;return}const n=[];let r=1/0,i=1/0,o=-1/0,s=-1/0;for(const f of t){if(!f||!Number.isFinite(f.minX)||!Number.isFinite(f.minY)||!Number.isFinite(f.maxX)||!Number.isFinite(f.maxY))continue;const c=_r(f.minX,f.minY,f.maxX,f.maxY);r=Math.min(r,c[0]),i=Math.min(i,c[1]),o=Math.max(o,c[2]),s=Math.max(s,c[3]),n.push({minX:c[0],minY:c[1],maxX:c[2],maxY:c[3],value:f.value})}if(this.items=n,this.visited=new Uint32Array(n.length),this.querySerial=1,n.length===0||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(o)||!Number.isFinite(s)){this.globalBounds=[0,0,0,0],this.gridSize=1,this.cellWidth=1,this.cellHeight=1,this.buckets=[];return}this.globalBounds=[r,i,o,s],this.gridSize=Math.max(1,Math.ceil(Math.sqrt(n.length/this.targetNodeSize)));const a=Math.max(0,o-r),l=Math.max(0,s-i);this.cellWidth=a>0?a/this.gridSize:1,this.cellHeight=l>0?l/this.gridSize:1;const u=this.gridSize*this.gridSize;this.buckets=Array.from({length:u},()=>[]);for(let f=0;f<n.length;f+=1){const c=n[f],h=this.toCellX(c.minX),d=this.toCellX(c.maxX),m=this.toCellY(c.minY),p=this.toCellY(c.maxY);for(let y=m;y<=p;y+=1)for(let b=h;b<=d;b+=1)this.buckets[y*this.gridSize+b].push(f)}}search(t){if(this.items.length===0)return[];if(!Array.isArray(t)||t.length<4)return[];const n=_r(t[0],t[1],t[2],t[3]);if(!Lr(n,this.globalBounds))return[];const r=this.toCellX(n[0]),i=this.toCellX(n[2]),o=this.toCellY(n[1]),s=this.toCellY(n[3]),a=this.nextSerial(),l=[];for(let u=o;u<=s;u+=1)for(let f=r;f<=i;f+=1){const c=this.buckets[u*this.gridSize+f];if(!(!c||c.length===0))for(const h of c){if(this.visited[h]===a)continue;this.visited[h]=a;const d=this.items[h];Lr(n,[d.minX,d.minY,d.maxX,d.maxY])&&l.push(d)}}return l}nextSerial(){return this.querySerial+=1,this.querySerial===4294967295&&(this.visited.fill(0),this.querySerial=1),this.querySerial}toCellX(t){const n=this.globalBounds[0],r=this.globalBounds[2];if(this.gridSize<=1||r<=n)return 0;const i=(t-n)/this.cellWidth;return!Number.isFinite(i)||i<=0?0:i>=this.gridSize-1?this.gridSize-1:Math.max(0,Math.min(this.gridSize-1,Math.floor(i)))}toCellY(t){const n=this.globalBounds[1],r=this.globalBounds[3];if(this.gridSize<=1||r<=n)return 0;const i=(t-n)/this.cellHeight;return!Number.isFinite(i)||i<=0?0:i>=this.gridSize-1?this.gridSize-1:Math.max(0,Math.min(this.gridSize-1,Math.floor(i)))}}function bl(e){return new yl(e)}function wl(e){return e.replace(/^\s*SRID\s*=\s*\d+\s*;\s*/i,"")}function xl(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function Sl(e){return e>="0"&&e<="9"}function Fr(e){return e==="+"||e==="-"||e==="."||Sl(e)}class El{constructor(t){R(this,"text");R(this,"index",0);this.text=wl(t.trim())}parse(){if(!this.text)return null;const t=this.readWord();if(!t)return null;const n=t.toUpperCase();if(n!=="POLYGON"&&n!=="MULTIPOLYGON")return null;this.skipWhitespace();const r=this.peekWord();if(r){const s=r.toUpperCase();(s==="Z"||s==="M"||s==="ZM")&&(this.readWord(),this.skipWhitespace())}if(this.consumeWordIf("EMPTY"))return this.skipWhitespace(),this.isEof()?n==="POLYGON"?{type:"Polygon",coordinates:[]}:{type:"MultiPolygon",coordinates:[]}:null;let i;try{i=this.parseNestedList()}catch{return null}if(this.skipWhitespace(),!this.isEof())return null;if(n==="POLYGON"){const s=gi(i);return s?{type:"Polygon",coordinates:s}:null}const o=Ml(i);return o?{type:"MultiPolygon",coordinates:o}:null}isEof(){return this.index>=this.text.length}currentChar(){return this.text[this.index]??""}skipWhitespace(){for(;!this.isEof()&&/\s/.test(this.currentChar());)this.index+=1}readWord(){if(this.skipWhitespace(),this.isEof())return null;const t=this.index;for(;!this.isEof()&&xl(this.currentChar());)this.index+=1;return this.index===t?null:this.text.slice(t,this.index)}peekWord(){const t=this.index,n=this.readWord();return this.index=t,n}consumeWordIf(t){const n=this.index,r=this.readWord();return!r||r.toUpperCase()!==t.toUpperCase()?(this.index=n,!1):!0}parseNestedList(){if(this.skipWhitespace(),this.currentChar()!=="(")throw new Error("Expected '('");this.index+=1;const t=[];for(;;){this.skipWhitespace(),this.currentChar()==="("?t.push(this.parseNestedList()):t.push(this.parseCoordinateTuple()),this.skipWhitespace();const n=this.currentChar();if(n===","){this.index+=1;continue}if(n===")"){this.index+=1;break}throw new Error("Expected ',' or ')'")}return t}parseCoordinateTuple(){this.skipWhitespace();const t=[];for(;;){this.skipWhitespace();const n=this.currentChar();if(!n||!Fr(n))break;const r=this.readNumber();if(r===null)break;t.push(r),this.skipWhitespace();const i=this.currentChar();if(!i||i===","||i===")")break;if(!Fr(i))throw new Error("Invalid coordinate")}if(t.length<2)throw new Error("Coordinate requires at least x y");return[t[0],t[1]]}readNumber(){if(this.skipWhitespace(),this.isEof())return null;const n=this.text.slice(this.index).match(/^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/);if(!n)return null;const r=Number(n[0]);return Number.isFinite(r)?(this.index+=n[0].length,r):null}}function Rl(e){return Array.isArray(e)&&e.length>=2&&typeof e[0]=="number"&&Number.isFinite(e[0])&&typeof e[1]=="number"&&Number.isFinite(e[1])}function gi(e){if(!Array.isArray(e))return null;const t=[];for(const n of e){if(!Array.isArray(n))return null;const r=[];for(const i of n){if(!Rl(i))return null;r.push([i[0],i[1]])}t.push(r)}return t}function Ml(e){if(!Array.isArray(e))return null;const t=[];for(const n of e){const r=gi(n);if(!r)return null;t.push(r)}return t}function Al(e){return typeof e!="string"?null:new El(e).parse()}exports.DEFAULT_POINT_COLOR=Sn;exports.DrawLayer=Qr;exports.DrawingLayer=ys;exports.M1TileRenderer=Nr;exports.OverlayLayer=bs;exports.OverviewMap=Ms;exports.PatchLayer=vs;exports.PointLayer=js;exports.RegionLayer=ca;exports.TileScheduler=ci;exports.TileViewerCanvas=ua;exports.WsiTileRenderer=mi;exports.WsiViewer=ul;exports.buildPointSpatialIndexAsync=li;exports.buildTermPalette=eo;exports.calcScaleLength=Qi;exports.calcScaleResolution=En;exports.clamp=O;exports.closeRing=Fe;exports.computeRoiPointGroups=pl;exports.createCircle=hn;exports.createRectangle=Wt;exports.createSpatialIndex=bl;exports.filterPointDataByPolygons=mt;exports.filterPointDataByPolygonsHybrid=ii;exports.filterPointDataByPolygonsInWorker=si;exports.filterPointIndicesByPolygons=ti;exports.filterPointIndicesByPolygonsInWorker=Bs;exports.getWebGpuCapabilities=Fs;exports.hexToRgba=Yr;exports.isSameViewState=un;exports.lookupCellIndex=ai;exports.normalizeImageInfo=xs;exports.parseWkt=Al;exports.prefilterPointsByBoundsWebGpu=ri;exports.terminatePointHitIndexWorker=qs;exports.terminateRoiClipWorker=Ns;exports.toBearerToken=Ji;exports.toRoiGeometry=yt;exports.toTileUrl=Tn;exports.useViewerContext=at;
|
|
164
164
|
//# sourceMappingURL=index.cjs.map
|