open-plant 1.4.1 → 1.4.2
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 +9 -10
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +2582 -3016
- package/dist/index.js.map +1 -1
- package/dist/types/index.d.ts +1 -3
- package/dist/types/index.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 -0
- package/dist/types/react/viewer-context.d.ts.map +1 -1
- package/dist/types/react/wsi-viewer-canvas-types.d.ts +2 -98
- package/dist/types/react/wsi-viewer-canvas-types.d.ts.map +1 -1
- package/dist/types/react/wsi-viewer.d.ts +2 -5
- package/dist/types/react/wsi-viewer.d.ts.map +1 -1
- package/dist/types/wsi/wsi-tile-renderer.d.ts.map +1 -1
- package/dist/types/wsi/wsi-view-animation.d.ts.map +1 -1
- package/package.json +1 -1
- package/dist/types/react/use-renderer-sync.d.ts +0 -23
- package/dist/types/react/use-renderer-sync.d.ts.map +0 -1
- package/dist/types/react/wsi-viewer-canvas.d.ts +0 -4
- package/dist/types/react/wsi-viewer-canvas.d.ts.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var xi=Object.defineProperty;var Si=(e,t,n)=>t in e?xi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var R=(e,t,n)=>Si(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ye=require("react/jsx-runtime"),g=require("react");var it=typeof document<"u"?document.currentScript:null;function Fn(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 bn(e,t,n){const r=Fn(e,e.VERTEX_SHADER,t),i=Fn(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 _e(e,t,n){const r=e.getUniformLocation(t,n);if(!r)throw new Error(`Failed to get uniform location: ${n}`);return r}function Ei(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 Zt(e){return e*Math.PI/180}class Br{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,c=(n-this.viewportHeight*.5)/r,u=Zt(s),h=Math.cos(u),l=Math.sin(u);return[i+a*h-c*l,o+a*l+c*h]}worldToScreen(t,n){const r=Math.max(1e-6,this.viewState.zoom),[i,o]=this.getCenter(),s=this.viewState.rotationDeg??0,a=t-i,c=n-o,u=Zt(s),h=Math.cos(u),l=Math.sin(u),f=a*h+c*l,d=-a*l+c*h;return[this.viewportWidth*.5+f*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=Zt(n),s=Math.cos(o),a=Math.sin(o),c=2*t*s/this.viewportWidth,u=2*t*a/this.viewportWidth,h=2*t*a/this.viewportHeight,l=-2*t*s/this.viewportHeight,f=-(c*r+u*i),d=-(h*r+l*i);return new Float32Array([c,h,0,u,l,0,f,d,1])}}const Ri=`#version 300 es
|
|
2
2
|
precision highp float;
|
|
3
3
|
|
|
4
4
|
in vec2 aUnit;
|
|
@@ -18,7 +18,7 @@ void main() {
|
|
|
18
18
|
gl_Position = vec4(clip.xy, 0.0, 1.0);
|
|
19
19
|
vUv = aUv;
|
|
20
20
|
}
|
|
21
|
-
`,
|
|
21
|
+
`,Mi=`#version 300 es
|
|
22
22
|
precision highp float;
|
|
23
23
|
|
|
24
24
|
in vec2 vUv;
|
|
@@ -29,8 +29,8 @@ out vec4 outColor;
|
|
|
29
29
|
void main() {
|
|
30
30
|
outColor = texture(uTexture, vUv);
|
|
31
31
|
}
|
|
32
|
-
`;class
|
|
33
|
-
`);const o=t+(n?" ":"│ ");e.left&&Pn(e.left,o,!1,r,i),e.right&&Pn(e.right,o,!0,r,i)}}class Xn{constructor(t=ho){this._root=null,this._size=0,this._comparator=t}insert(t,n){return this._size++,this._root=xn(t,n,this._root,this._comparator)}add(t,n){const r=new ut(t,n);this._root===null&&(r.left=r.right=null,this._size++,this._root=r);const i=this._comparator,o=at(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=at(t,n,r),r(t,n.key)===0?(n.left===null?i=n.right:(i=at(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=at(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=at(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 po(this._root)}load(t,n=[],r=!1){let i=t.length;const o=this._comparator;if(r&&Fn(t,n,0,i-1,o),this._root===null)this._root=Tn(t,n,0,i),this._size=i;else{const s=yo(this.toList(),go(t,n),o);i=this._size+i,this._root=_n({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 Pn(this._root,"",!0,r=>n.push(r),t),n.join("")}update(t,n,r){const i=this._comparator;let{left:o,right:s}=hr(t,this._root,i);i(t,n)<0?s=xn(n,r,s,i):o=xn(n,r,o,i),this._root=mo(o,s,i)}split(t){return hr(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 Tn(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 ut(s,a);return l.left=Tn(e,t,n,o),l.right=Tn(e,t,o+1,r),l}return null}function go(e,t){const n=new ut(null,null);let r=n;for(let i=0;i<e.length;i++)r=r.next=new ut(e[i],t[i]);return r.next=null,n.next}function po(e){let t=e;const n=[];let r=!1;const i=new ut(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 _n(e,t,n){const r=n-t;if(r>0){const i=t+Math.floor(r/2),o=_n(e,t,i),s=e.head;return s.left=o,e.head=e.head.next,s.right=_n(e,i+1,n),s}return null}function yo(e,t,n){const r=new ut(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 Fn(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}Fn(e,t,n,a,i),Fn(e,t,a+1,r,i)}const et=11102230246251565e-32,ze=134217729,bo=(3+8*et)*et;function Sn(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 wo(e,t){let n=t[0];for(let r=1;r<e;r++)n+=t[r];return n}function Lt(e){return new Float64Array(e)}const xo=(3+16*et)*et,So=(2+12*et)*et,Eo=(9+64*et)*et*et,pt=Lt(4),dr=Lt(8),mr=Lt(12),gr=Lt(16),Ue=Lt(4);function Ro(e,t,n,r,i,o,s){let a,l,u,f,c,h,d,g,y,b,p,x,C,E,A,T,W,U;const q=e-i,H=n-i,X=t-o,$=r-o;E=q*$,h=ze*q,d=h-(h-q),g=q-d,h=ze*$,y=h-(h-$),b=$-y,A=g*b-(E-d*y-g*y-d*b),T=X*H,h=ze*X,d=h-(h-X),g=X-d,h=ze*H,y=h-(h-H),b=H-y,W=g*b-(T-d*y-g*y-d*b),p=A-W,c=A-p,pt[0]=A-(p+c)+(c-W),x=E+p,c=x-E,C=E-(x-c)+(p-c),p=C-T,c=C-p,pt[1]=C-(p+c)+(c-T),U=x+p,c=U-x,pt[2]=x-(U-c)+(p-c),pt[3]=U;let I=wo(4,pt),k=So*s;if(I>=k||-I>=k||(c=e-q,a=e-(q+c)+(c-i),c=n-H,u=n-(H+c)+(c-i),c=t-X,l=t-(X+c)+(c-o),c=r-$,f=r-($+c)+(c-o),a===0&&l===0&&u===0&&f===0)||(k=Eo*s+bo*Math.abs(I),I+=q*f+$*a-(X*u+H*l),I>=k||-I>=k))return I;E=a*$,h=ze*a,d=h-(h-a),g=a-d,h=ze*$,y=h-(h-$),b=$-y,A=g*b-(E-d*y-g*y-d*b),T=l*H,h=ze*l,d=h-(h-l),g=l-d,h=ze*H,y=h-(h-H),b=H-y,W=g*b-(T-d*y-g*y-d*b),p=A-W,c=A-p,Ue[0]=A-(p+c)+(c-W),x=E+p,c=x-E,C=E-(x-c)+(p-c),p=C-T,c=C-p,Ue[1]=C-(p+c)+(c-T),U=x+p,c=U-x,Ue[2]=x-(U-c)+(p-c),Ue[3]=U;const B=Sn(4,pt,4,Ue,dr);E=q*f,h=ze*q,d=h-(h-q),g=q-d,h=ze*f,y=h-(h-f),b=f-y,A=g*b-(E-d*y-g*y-d*b),T=X*u,h=ze*X,d=h-(h-X),g=X-d,h=ze*u,y=h-(h-u),b=u-y,W=g*b-(T-d*y-g*y-d*b),p=A-W,c=A-p,Ue[0]=A-(p+c)+(c-W),x=E+p,c=x-E,C=E-(x-c)+(p-c),p=C-T,c=C-p,Ue[1]=C-(p+c)+(c-T),U=x+p,c=U-x,Ue[2]=x-(U-c)+(p-c),Ue[3]=U;const _=Sn(B,dr,4,Ue,mr);E=a*f,h=ze*a,d=h-(h-a),g=a-d,h=ze*f,y=h-(h-f),b=f-y,A=g*b-(E-d*y-g*y-d*b),T=l*u,h=ze*l,d=h-(h-l),g=l-d,h=ze*u,y=h-(h-u),b=u-y,W=g*b-(T-d*y-g*y-d*b),p=A-W,c=A-p,Ue[0]=A-(p+c)+(c-W),x=E+p,c=x-E,C=E-(x-c)+(p-c),p=C-T,c=C-p,Ue[1]=C-(p+c)+(c-T),U=x+p,c=U-x,Ue[2]=x-(U-c)+(p-c),Ue[3]=U;const J=Sn(_,mr,4,Ue,gr);return gr[J-1]}function Mo(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)>=xo*u?l:-Ro(e,t,n,r,i,o,u)}const Mt=(e,t)=>e.ll.x<=t.x&&t.x<=e.ur.x&&e.ll.y<=t.y&&t.y<=e.ur.y,kn=(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 lt=Number.EPSILON;lt===void 0&&(lt=Math.pow(2,-52));const Ao=lt*lt,pr=(e,t)=>{if(-lt<e&&e<lt&&-lt<t&&t<lt)return 0;const n=e-t;return n*n<Ao*e*t?0:e<t?-1:1};class Co{constructor(){this.reset()}reset(){this.xRounder=new yr,this.yRounder=new yr}round(t,n){return{x:this.xRounder.round(t),y:this.yRounder.round(n)}}}class yr{constructor(){this.tree=new Xn,this.round(0)}round(t){const n=this.tree.add(t),r=this.tree.prev(n);if(r!==null&&pr(n.key,r.key)===0)return this.tree.remove(t),r.key;const i=this.tree.next(n);return i!==null&&pr(n.key,i.key)===0?(this.tree.remove(t),i.key):t}}const It=new Co,Jt=(e,t)=>e.x*t.y-e.y*t.x,pi=(e,t)=>e.x*t.x+e.y*t.y,br=(e,t,n)=>{const r=Mo(e.x,e.y,t.x,t.y,n.x,n.y);return r>0?-1:r<0?1:0},on=e=>Math.sqrt(pi(e,e)),vo=(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 Jt(i,r)/on(i)/on(r)},Io=(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 pi(i,r)/on(i)/on(r)},wr=(e,t,n)=>t.y===0?null:{x:e.x+t.x/t.y*(n-e.y),y:n},xr=(e,t,n)=>t.x===0?null:{x:n,y:e.y+t.y/t.x*(n-e.x)},Po=(e,t,n,r)=>{if(t.x===0)return xr(n,r,e.x);if(r.x===0)return xr(e,t,n.x);if(t.y===0)return wr(n,r,e.y);if(r.y===0)return wr(e,t,n.y);const i=Jt(t,r);if(i==0)return null;const o={x:n.x-e.x,y:n.y-e.y},s=Jt(o,t)/i,a=Jt(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 Ge{static compare(t,n){const r=Ge.comparePoints(t.point,n.point);return r!==0?r:(t.point!==n.point&&t.link(n),t.isLeft!==n.isLeft?t.isLeft?1:-1:ct.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:vo(this.point,t.point,o.point),cosine:Io(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 To=0;class ct{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,g=s-i;if(c>h&&d<g)return 1;if(c<h&&d>g)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=++To,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=Ge.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 Ge(i,!0),u=new Ge(o,!1);return new ct(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=kn(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=Mt(n,a)&&this.comparePoint(a)===0,f=Mt(r,o)&&t.comparePoint(o)===0,c=Mt(n,l)&&this.comparePoint(l)===0,h=Mt(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=Po(o,this.vector(),a,t.vector());return d===null||!Mt(i,d)?null:It.round(d.x,d.y)}split(t){const n=[],r=t.events!==void 0,i=new Ge(t,!0),o=new Ge(t,!1),s=this.rightSE;this.replaceRightSE(o),n.push(o),n.push(i);const a=new ct(i,s,this.rings.slice(),this.windings.slice());return Ge.comparePoints(a.leftSE.point,a.rightSE.point)>0&&a.swapEvents(),Ge.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=ct.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(Ze.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===Ze.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 ${Ze.type}`)}return this._isInResult}}class Sr{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=It.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=It.round(t[s][0],t[s][1]);l.x===o.x&&l.y===o.y||(this.segments.push(ct.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(ct.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 _o{constructor(t,n){if(!Array.isArray(t))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");this.exteriorRing=new Sr(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 Sr(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 Er{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 _o(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 sn{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 y=u[0].point,b=u[u.length-1].point;throw new Error(`Unable to complete output ring starting at [${y.x}, ${y.y}]. Last matching segment found ends at [${b.x}, ${b.y}].`)}if(h.length===1){l=h[0].otherSE;break}let d=null;for(let y=0,b=c.length;y<b;y++)if(c[y].point===a.point){d=y;break}if(d!==null){const y=c.splice(d)[0],b=u.splice(y.index);b.unshift(b[0].otherSE),n.push(new sn(b.reverse()));continue}c.push({index:u.length,point:a.point});const g=a.getLeftmostComparator(s);l=h.sort(g)[0].otherSE;break}n.push(new sn(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;br(c,t,h)!==0&&(n.push(c),t=c)}if(n.length===1)return null;const r=n[0],i=n[1];br(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];Ge.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 Rr{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 Fo{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 Rr(o));else{const s=o.enclosingRing();s.poly||n.push(new Rr(s)),s.poly.addInterior(o)}}return n}}class ko{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:ct.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,g=h.length;d<g;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,g=h.length;d<g;d++)r.push(h[d])}}if(u!==null||f!==null){let c=null;u===null?c=f:f===null?c=u:c=Ge.comparePoints(u,f)<=0?u:f,this.queue.remove(n.rightSE),r.push(n.rightSE);const h=n.split(c);for(let d=0,g=h.length;d<g;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 Mr=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_QUEUE_SIZE||1e6,Lo=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS||1e6;class No{run(t,n,r){Ze.type=t,It.reset();const i=[new Er(n,!0)];for(let c=0,h=r.length;c<h;c++)i.push(new Er(r[c],!1));if(Ze.numMultiPolys=i.length,Ze.type==="difference"){const c=i[0];let h=1;for(;h<i.length;)kn(i[h].bbox,c.bbox)!==null?h++:i.splice(h,1)}if(Ze.type==="intersection")for(let c=0,h=i.length;c<h;c++){const d=i[c];for(let g=c+1,y=i.length;g<y;g++)if(kn(d.bbox,i[g].bbox)===null)return[]}const o=new Xn(Ge.compare);for(let c=0,h=i.length;c<h;c++){const d=i[c].getSweepEvents();for(let g=0,y=d.length;g<y;g++)if(o.insert(d[g]),o.size>Mr)throw new Error("Infinite loop when putting segment endpoints in a priority queue (queue size too big).")}const s=new ko(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>Mr)throw new Error("Infinite loop when passing sweep line over endpoints (queue size too big).");if(s.segments.length>Lo)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,g=h.length;d<g;d++){const y=h[d];y.consumedBy===void 0&&o.insert(y)}a=o.size,l=o.pop()}It.reset();const u=sn.factory(s.segments);return new Fo(u).getGeom()}}const Ze=new No,Bo=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 Ze.run("union",e,n)},zo=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 Ze.run("intersection",e,n)},Do=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 Ze.run("xor",e,n)},Uo=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 Ze.run("difference",e,n)};var Oo={union:Bo,intersection:zo,xor:Do,difference:Uo};function Nt(e){return e==null?null:yi(e)||bi(e)||Yo(e)?e:null}function Ar(e){return typeof e=="number"&&Number.isFinite(e)}function en(e){return Array.isArray(e)&&e.length>=2&&Ar(e[0])&&Ar(e[1])}function yi(e){return Array.isArray(e)&&e.length>0&&e.every(t=>en(t))}function bi(e){return Array.isArray(e)&&e.length>0&&e.every(t=>yi(t))}function Yo(e){return Array.isArray(e)&&e.length>0&&e.every(t=>bi(t))}function Xe(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 Pt(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 En(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const o of e){const s=Xe(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(Pt(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 wi(e){if(!Array.isArray(e)||e.length===0)return[];const t=e[0];if(en(t)){const i=En([e]);return i.length>0?[i]:[]}if(!Array.isArray(t)||t.length===0)return[];const n=t[0];if(en(n)){const i=En(e);return i.length>0?[i]:[]}if(!Array.isArray(n)||n.length===0||!en(n[0]))return[];const r=[];for(const i of e){const o=En(i);o.length>0&&r.push(o)}return r}function Cr(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=wi(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(Pt(o));for(let c=1;c<i.length;c+=1)f-=Math.abs(Pt(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 xi(e,t,n){if(e<n.minX||e>n.maxX||t<n.minY||t>n.maxY||!Cr(e,t,n.outer))return!1;for(const r of n.holes)if(Cr(e,t,r))return!1;return!0}function an(e,t,n){for(const r of n)if(xi(e,t,r))return!0;return!1}const Vn=[160,160,160,255];function Y(e,t,n){return Math.max(t,Math.min(n,e))}function Gn(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 Wo(e,t,n){let i=100*Gn(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 Me(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function ht(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 Ln(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 Xo(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 Si(e){const n=String(e??"").trim().match(/^#?([0-9a-fA-F]{6})$/);if(!n)return[...Vn];const r=Number.parseInt(n[1],16);return[r>>16&255,r>>8&255,r&255,255]}function Vo(e){const t=[[...Vn]],n=new Map;for(const i of e??[]){const o=String(i?.termId??"");!o||n.has(o)||(n.set(o,t.length),t.push(Si(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 Go=[6,4,2],qo=64,Ho=.04,$o=1,Zo=4,ln=1e-6,jo=.1;function Ko(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 vr(e,t,n){if(t<=ln||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 Xe(r)}function Qo(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(ln,n);return Xe([[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 Ir(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 Xe([[n-s,r-s],[i+s,r-s],[i+s,o+s],[n-s,o+s]])}function Xt(e,t){return Xe(t?e.map(([n,r])=>[Y(n,t[0],t[2]),Y(r,t[1],t[3])]):e)}function Pr(e,t){return Number.isFinite(e)?Number(e.toFixed(t)):e}function Jo(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=Pr(Number(r[0]),t),o=Pr(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 es(e,t){if(!Array.isArray(e)||e.length===0)return[];const n=e.map(r=>Jo(r,t)).filter(r=>r.length>=4);return n.length>0?n:[]}function ts(e,t){const n=e.map(i=>es(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=Oo.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 ns(e){if(e.length===0)return null;for(const t of Go){const n=ts(e,t);if(n)return n}return null}function rs(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 Xe(t)}function is(e){let t=[],n=0;for(const r of e){if(!Array.isArray(r)||r.length===0)continue;const i=rs(r[0]??[]);if(i.length<4)continue;const o=Math.abs(Pt(i));o<=n||(n=o,t=i)}return t}function os(e,t=1e-9){const n=Xe(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]),Xe(r)}function ss(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=Y(((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 as(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=ss(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 ls(e,t){const n=Xe(e);if(n.length<5||t<=0)return n;const r=n.slice(0,-1),i=as(r,t);return i.length<3?n:Xe(i)}function cs(e,t){let n=Xe(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=Xe(o)}return n}function us(e,t){const n=Ko(e),r=Math.max(ln,Number(t.radius)||0);if(n.length===0||!Number.isFinite(r))return[];const i=Math.max(12,Math.floor(t.circleSides||qo));if(n.length===1)return Xt(vr(n[0],r,i),t.clipBounds);const o=[],s=Math.max(ln,r*jo);for(let h=0;h<n.length;h+=1){const d=n[h],g=vr(d,r,i);if(g.length>=4&&o.push([g]),h===0)continue;const y=Qo(n[h-1],d,r,s);y.length>=4&&o.push([y])}const a=ns(o),l=a?is(a):[];if(!l.length)return Xt(Ir(n,r),t.clipBounds);const u=typeof t.simplifyTolerance=="number"&&Number.isFinite(t.simplifyTolerance)?Math.max(0,t.simplifyTolerance):Math.max(.25,r*Ho),f=typeof t.smoothingPasses=="number"&&Number.isFinite(t.smoothingPasses)?Math.round(Y(t.smoothingPasses,0,Zo)):$o,c=ls(cs(os(l,1e-9),f),u);return c.length<4?Xt(Ir(n,r),t.clipBounds):Xt(c,t.clipBounds)}const ft=[],Tr=[],Qe={color:"#ff4d4f",width:2,lineDash:ft,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},Ei={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},Ri="rgba(23, 23, 25, 0.1)",Mi=6,He={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},st={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},_r={x:16,y:-24},fs=20,Fr=1e-6,kr="transparent",hs=3,ds=2,Ai=96,ms=1,Lr=1e3,Ci=2,vi=2,gs=4096,ps=.2,ys=1.12,bs=.89,ws=32,xs="#000000",Ss=.1,Es="#FFCF00",Rs="#FF0000",Ms=1.5,Nr=[2,2],As=1,Cs=.25,vs=4,Is=1,Ps=0,Ts=4,_s=1.5;function cn(e,t,n){return[Y(e[0],0,t),Y(e[1],0,n)]}function Tt(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 $e=Tt;function Ye(e){return Xe(e)}function tn(e){return Math.abs(Pt(Ye(e)))}function Br(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 Nn(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 De(e,t,n,r=!1,i=!1,o="rgba(255, 77, 79, 0.16)"){t.length!==0&&(e.beginPath(),Nn(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(ft),e.shadowColor="rgba(0, 0, 0, 0)",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0)}function qn(e){const t=Array.isArray(e?.lineDash)?e.lineDash.filter(s=>Number.isFinite(s)&&s>=0):ft,n=typeof e?.width=="number"&&Number.isFinite(e.width)?Math.max(0,e.width):Qe.width,r=typeof e?.shadowBlur=="number"&&Number.isFinite(e.shadowBlur)?Math.max(0,e.shadowBlur):Qe.shadowBlur,i=typeof e?.shadowOffsetX=="number"&&Number.isFinite(e.shadowOffsetX)?e.shadowOffsetX:Qe.shadowOffsetX,o=typeof e?.shadowOffsetY=="number"&&Number.isFinite(e.shadowOffsetY)?e.shadowOffsetY:Qe.shadowOffsetY;return{color:e?.color||Qe.color,width:n,lineDash:t.length?t:ft,lineJoin:e?.lineJoin||Qe.lineJoin,lineCap:e?.lineCap||Qe.lineCap,shadowColor:e?.shadowColor||Qe.shadowColor,shadowBlur:r,shadowOffsetX:i,shadowOffsetY:o}}function Je(e,t){return t?qn({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 un(e,t){return e==null||t===null||t===void 0?!1:String(e)===String(t)}function zr(e){return typeof e=="number"&&Number.isFinite(e)}function Fs(e){return Array.isArray(e)&&e.length>=2&&zr(e[0])&&zr(e[1])}function ks(e){return Array.isArray(e)&&e.length>=2&&e.every(t=>Fs(t))}function Ii(e,t){if(!(!Array.isArray(e)||e.length===0)){if(ks(e)){t.push(e.map(([n,r])=>[n,r]));return}for(const n of e)Ii(n,t)}}function Dr(e,t){const n=[];Ii(e,n);const r=[];for(const i of n){if(i.length<2)continue;const o=t?Ye(i):i;o.length>=(t?4:2)&&r.push(o)}return r}function vt(e,t){return typeof e!="number"||!Number.isFinite(e)||e<=0?t:e}function Ls(e,t){return typeof e!="number"||!Number.isFinite(e)?t:Y(e,0,1)}function Pi(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 Ns(e){const t=e[0];return Array.isArray(t)&&Array.isArray(t[0])}function fn(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 fn(e,t);s.push(l)}return Ye(s)}}return Ye([[e[0],e[1]],[t[0],e[1]],[t[0],t[1]],[e[0],t[1]]])}function Bn(e,t,n=Ai){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 Ye(s)}function hn(e){const t=wi(Nt(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 Bs(e){if(!Array.isArray(e))return Nr;const t=e.filter(n=>Number.isFinite(n)&&n>=0);return t.length>0?t:Nr}function zs(e){return typeof e!="number"||!Number.isFinite(e)?As:Y(e,Cs,vs)}function Ds(e){return typeof e!="number"||!Number.isFinite(e)?Is:Math.round(Y(e,Ps,Ts))}function Us(e){const t=vt(e?.radius,ws),n=vt(e?.cursorLineWidth,Ms),r=zs(e?.edgeDetail),i=Ds(e?.edgeSmoothing);return{radius:t,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:e?.clickSelectRoi===!0,fillColor:e?.fillColor||xs,fillOpacity:Ls(e?.fillOpacity,Ss),cursorColor:e?.cursorColor||Es,cursorActiveColor:e?.cursorActiveColor||Rs,cursorLineWidth:n,cursorLineDash:Bs(e?.cursorLineDash)}}function Os(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 Ys(e,t,n,r){const i=t.cursor;if(!i)return;const o=t.cursorScreen??$e(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(ft),e.restore())}const Ws=.58,Xs=4096,Vs=.5;let Vt=null;const Gt=new Map;function Gs(){if(Vt)return Vt;if(typeof document>"u")return null;const t=document.createElement("canvas").getContext("2d");return t?(Vt=t,Vt):null}function Hn(e,t){const n=`${t.fontWeight}|${t.fontSize}|${t.fontFamily}|${e}`,r=Gt.get(n);if(r!==void 0)return r;const i=e.length*t.fontSize*Ws,o=Gs();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 Gt.size>Xs&&Gt.clear(),Gt.set(n,s),s}function qs(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)>Vs||(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 $n(e,t="top-center"){let n=null;for(const r of e){const i=qs(r.outer,t);i&&(!n||i[1]<n[1]||i[1]===n[1]&&i[0]<n[0])&&(n=i)}return n}function mn(e){const t=typeof e?.paddingX=="number"&&Number.isFinite(e.paddingX)?Math.max(0,e.paddingX):He.paddingX,n=typeof e?.paddingY=="number"&&Number.isFinite(e.paddingY)?Math.max(0,e.paddingY):He.paddingY,r=typeof e?.fontSize=="number"&&Number.isFinite(e.fontSize)?Math.max(8,e.fontSize):He.fontSize,i=typeof e?.borderWidth=="number"&&Number.isFinite(e.borderWidth)?Math.max(0,e.borderWidth):He.borderWidth,o=typeof e?.offsetY=="number"&&Number.isFinite(e.offsetY)?e.offsetY:He.offsetY,s=typeof e?.borderRadius=="number"&&Number.isFinite(e.borderRadius)?Math.max(0,e.borderRadius):He.borderRadius;return{fontFamily:e?.fontFamily||He.fontFamily,fontSize:r,fontWeight:e?.fontWeight||He.fontWeight,textColor:e?.textColor||He.textColor,backgroundColor:e?.backgroundColor||He.backgroundColor,borderColor:e?.borderColor||He.borderColor,borderWidth:i,paddingX:t,paddingY:n,offsetY:o,borderRadius:s}}function Zn(e,t){return t?mn({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 jn(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<=Fr||!Number.isFinite(t)?0:t>=i-Fr?fs:0}function Hs(e){const t=typeof e?.fontSize=="number"&&Number.isFinite(e.fontSize)?Math.max(8,e.fontSize):st.fontSize,n=typeof e?.borderRadius=="number"&&Number.isFinite(e.borderRadius)?Math.max(0,e.borderRadius):st.borderRadius,r=typeof e?.paddingX=="number"&&Number.isFinite(e.paddingX)?Math.max(0,e.paddingX):st.paddingX,i=typeof e?.paddingY=="number"&&Number.isFinite(e.paddingY)?Math.max(0,e.paddingY):st.paddingY;return{fontFamily:e?.fontFamily||st.fontFamily,fontSize:t,fontWeight:e?.fontWeight||st.fontWeight,textColor:e?.textColor||st.textColor,backgroundColor:e?.backgroundColor||st.backgroundColor,borderRadius:n,paddingX:r,paddingY:i}}function $s(e){const t=typeof e?.x=="number"&&Number.isFinite(e.x)?e.x:_r.x,n=typeof e?.y=="number"&&Number.isFinite(e.y)?e.y:_r.y;return{x:t,y:n}}function Zs(e){return Number.isFinite(e)?`${Math.max(0,e).toFixed(3)} mm²`:"0.000 mm²"}function js(e){const t=typeof e?.format=="function"?e.format:Zs,n=$s(e?.cursorOffset);return{enabled:e?.enabled===!0,format:t,style:Hs(e?.style),cursorOffsetX:n.x,cursorOffsetY:n.y}}function Ti(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=Hn(a,o)+o.paddingX*2,f=o.fontSize+o.paddingY*2,c=n[0],h=n[1]-o.offsetY,d=s?Y(c,u*.5+1,r-u*.5-1):c,g=s?Y(h,f*.5+1,i-f*.5-1):h,y=d-u*.5,b=g-f*.5;e.fillStyle=o.backgroundColor,e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,Pi(e,y,b,u,f,o.borderRadius),e.fill(),o.borderWidth>0&&e.stroke(),e.fillStyle=o.textColor,e.fillText(a,d,g+.5),e.restore()}function Ks(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=Hn(l,o)+o.paddingX*2,c=o.fontSize+o.paddingY*2,h=Y(n[0]+s,f*.5+1,r-f*.5-1),d=Y(n[1]+a,c*.5+1,i-c*.5-1),g=h-f*.5,y=d-c*.5;e.fillStyle=o.backgroundColor,Pi(e,g,y,f,c,o.borderRadius),e.fill(),e.fillStyle=o.textColor,e.fillText(l,h,d+.5),e.restore()}function Qs(e,t,n,r){if(!(t.length<4||n.length===0)){e.save(),e.beginPath(),Nn(e,t,!0);for(const i of n)i.length<4||Nn(e,i,!0);e.fillStyle=r,e.fill("evenodd"),e.restore()}}function _i(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??Ns(u.coordinates),c=Dr(u.coordinates,f);if(u.invertedFill?.fillColor){const d=[],g=Dr(u.coordinates,!0);for(const y of g){const b=i(y);b.length>=4&&d.push(b)}a&&s&&s({id:u.id??l,outerRingPoints:r.length,sourceRingCount:g.length,holeRingCount:d.length,fillColor:u.invertedFill.fillColor}),Qs(t,r,d,u.invertedFill.fillColor)}if(c.length===0)continue;const h=Je(o,u.stroke??u.strokeStyle);for(const d of c){const g=i(d);g.length<2||De(t,g,h,f,u.fill??!1)}}}function qt(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 Js(e){return{rectangleAreaMm2:vt(e?.rectangleAreaMm2,Ci),circleAreaMm2:vt(e?.circleAreaMm2,vi),rectanglePixelSize:vt(e?.rectanglePixelSize,gs)}}const Ur=1e3;function ea(e){return e*Ur*Ur}function Or(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 Ye(a)}}return Ye([[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 ta(e,t,n=Ai){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 Ye(r)}function na(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 Or(n,c,a()).map(h=>cn(h,i,o))}let l=0;if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"?l=t==="stamp-rectangle-2mm2"?Ci:r.rectangleAreaMm2:(t==="stamp-circle"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2")&&(l=t==="stamp-circle-hpf-0.2mm2"?ps:t==="stamp-circle-2mm2"?vi:r.circleAreaMm2),!Number.isFinite(l)||l<=0)return[];const u=ea(l);let f=[];if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"){const c=s(Math.sqrt(u)*.5);f=Or(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=ta(n,c)}return f.length?f.map(c=>cn(c,i,o)):[]}function ra(e){return{color:Ri,width:Mi,lineDash:ft,lineJoin:e.lineJoin,lineCap:e.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function ia(e){if(typeof e!="string")return kr;const t=e.trim();return t.length>0?t:kr}function Yr(e){return Array.isArray(e)&&e.length>=4&&tn(e)>ms}function Kn({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:g,persistedPolygons:y,drawFillColor:b,regionStrokeStyle:p,regionStrokeHoverStyle:x,regionStrokeActiveStyle:C,patchStrokeStyle:E,resolveRegionStrokeStyle:A,resolveRegionLabelStyle:T,overlayShapes:W,hoveredRegionId:U=null,activeRegionId:q=null,regionLabelStyle:H,drawAreaTooltip:X,autoLiftRegionLabelAtMaxZoom:$=!1,regionLabelAnchor:I="top-center",clampRegionLabelToViewport:k=!0,regionLabelAutoLiftOffsetPx:B,invalidateRef:_,className:J,style:_e}){const ce=m.useRef(null),ke=m.useRef(!1),Ie=m.useRef(new Map),Ce=m.useRef(e),M=m.useRef({isDrawing:!1,pointerId:null,start:null,current:null,cursor:null,cursorScreen:null,points:[],screenPoints:[],stampCenter:null}),v=c??e!=="cursor",O=m.useMemo(()=>d&&d.length>0?d:!y||y.length===0?Tr:y.map((w,S)=>({id:S,coordinates:w})),[d,y]),V=m.useMemo(()=>g??Tr,[g]),z=m.useMemo(()=>{const w=[];for(let S=0;S<O.length;S+=1){const P=O[S],F=hn(P.coordinates);F.length!==0&&w.push({region:P,regionIndex:S,regionKey:P.id??S,polygons:F})}return w},[O]),ee=m.useMemo(()=>{const w=[];for(let S=0;S<V.length;S+=1){const P=V[S],F=hn(P.coordinates);F.length!==0&&w.push({region:P,regionIndex:S,regionKey:P.id??S,polygons:F})}return w},[V]),K=m.useMemo(()=>qn(p),[p]),ie=m.useMemo(()=>Je(K,x),[K,x]),G=m.useMemo(()=>Je(K,C),[K,C]),ue=m.useMemo(()=>Je(Ei,E),[E]),ye=m.useMemo(()=>ia(b),[b]),fe=m.useMemo(()=>mn(H),[H]),ne=m.useMemo(()=>js(X),[X]),me=m.useMemo(()=>Js(o),[o]),Z=m.useMemo(()=>Us(s),[s]),Ae=m.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",..._e}),[v,e,_e]),Se=m.useCallback(()=>{const w=ce.current;if(!w)return;const S=w.getBoundingClientRect(),P=Math.max(1,window.devicePixelRatio||1),F=Math.max(1,Math.round(S.width*P)),Q=Math.max(1,Math.round(S.height*P));(w.width!==F||w.height!==Q)&&(w.width=F,w.height=Q)},[]),ae=m.useCallback(w=>{const S=a.current;if(!S||w.length===0)return[];const P=new Array(w.length);for(let F=0;F<w.length;F+=1){const Q=$e(S.worldToScreen(w[F][0],w[F][1]));if(!Q)return[];P[F]=Q}return P},[a]),ve=m.useCallback(w=>{const S=a.current,P=ce.current;if(!S||!P)return null;const F=P.getBoundingClientRect(),Q=$e(S.screenToWorld(F.left+w[0],F.top+w[1]));return Q?cn(Q,t,n):null},[a,t,n]),Ee=m.useCallback(()=>{const w=a.current,S=w?.getViewState?.().rotationDeg??0;if(!(Math.abs(S%360)<.01||!w))return{worldToScreen:(P,F)=>$e(w.worldToScreen(P,F)),screenToWorld:ve}},[a,ve]),be=m.useCallback(w=>{if(!Number.isFinite(w)||w<=0)return 0;const S=typeof r=="number"&&Number.isFinite(r)&&r>0?r:1,P=typeof i=="number"&&Number.isFinite(i)?i:0,F=a.current?.getViewState?.().zoom,Q=typeof F=="number"&&Number.isFinite(F)&&F>0?F:1,xe=P+Math.log2(Q),j=Math.max(1e-9,Gn(S,P,xe));return w/j/Q},[r,i,a]),L=m.useCallback((w,S)=>na({stampTool:w,center:S,resolvedStampOptions:me,imageWidth:t,imageHeight:n,micronsToWorldPixels:be,getRectangleProjection:Ee}),[be,t,n,me,Ee]),re=m.useCallback(()=>{const w=M.current;return qt(e)?L(e,w.stampCenter):e==="brush"?[]:w.isDrawing?e==="freehand"?w.points:e==="rectangle"?fn(w.start,w.current,Ee()):e==="circular"?Bn(w.start,w.current):[]:[]},[e,L,Ee]),he=m.useCallback(()=>{Se();const w=ce.current;if(!w)return;const S=w.getContext("2d");if(!S)return;const P=Math.max(1,window.devicePixelRatio||1),F=w.width/P,Q=w.height/P;if(S.setTransform(1,0,0,1,0,0),S.clearRect(0,0,w.width,w.height),S.setTransform(P,0,0,P,0,0),z.length>0)for(const j of z){const{region:pe,polygons:Re,regionIndex:oe,regionKey:Le}=j,Pe=un(q,Le)?"active":un(U,Le)?"hover":"default";let Ve=Pe==="active"?G:Pe==="hover"?ie:K;if(A){const tt=A({region:pe,regionId:Le,regionIndex:oe,state:Pe});Ve=Je(Ve,tt||void 0)}const dt=Pe==="default"?null:ra(Ve);for(const tt of Re){const nt=ae(tt.outer);nt.length>=4&&(dt&&De(S,nt,dt,!0,!1),De(S,nt,Ve,!0,!1));for(const pn of tt.holes){const Et=ae(pn);Et.length>=4&&(dt&&De(S,Et,dt,!0,!1),De(S,Et,Ve,!0,!1))}}}if(ee.length>0)for(const j of ee)for(const pe of j.polygons){const Re=ae(pe.outer);Re.length>=4&&De(S,Re,ue,!0,!1);for(const oe of pe.holes){const Le=ae(oe);Le.length>=4&&De(S,Le,ue,!0,!1)}}if(Array.isArray(W)&&W.length>0){const j=ae(Ye([[0,0],[t,0],[t,n],[0,n]]));_i({ctx:S,overlayShapes:W,imageOuterRing:j,worldToScreenPoints:ae,baseStrokeStyle:K,onInvertedFillDebug:globalThis.__OPEN_PLANT_DEBUG_OVERLAY__?pe=>{const Re=String(pe.id),oe=`${pe.outerRingPoints}|${pe.sourceRingCount}|${pe.holeRingCount}|${pe.fillColor}`;Ie.current.get(Re)!==oe&&(Ie.current.set(Re,oe),console.debug("[open-plant] invertedFill",pe))}:void 0})}const xe=re();if(v){if(e==="brush")Os(S,M.current,Z),Ys(S,M.current,a.current,Z);else if(xe.length>0)if(e==="freehand"){const j=ae(xe);j.length>=2&&De(S,j,K,!1,!1),j.length>=3&&De(S,ae(Ye(xe)),K,!0,!0,ye)}else{const j=ae(xe);j.length>=4&&De(S,j,K,!0,!0,ye)}}if(z.length>0){const j=Math.max(1e-6,a.current?.getViewState?.().zoom??1),pe=typeof B=="number"&&Number.isFinite(B)?Math.max(0,B):jn($,j,a.current?.getZoomRange?.());for(const Re of z){if(!Re.region.label)continue;const oe=$n(Re.polygons,I);if(!oe)continue;const Le=$e(a.current?.worldToScreen(oe[0],oe[1])??[]);if(!Le)continue;let Pe=Zn(fe,T?.({region:Re.region,regionId:Re.regionKey,regionIndex:Re.regionIndex,zoom:j}));pe>0&&(Pe={...Pe,offsetY:Pe.offsetY+pe}),Ti(S,Re.region.label,Le,F,Q,Pe,k)}}if(ne.enabled&&v&&(e==="freehand"||e==="rectangle"||e==="circular")){const j=M.current;if(j.isDrawing){const pe=e==="freehand"?Ye(xe):xe;if(pe.length>=4){const Re=tn(pe),oe=typeof r=="number"&&Number.isFinite(r)&&r>0?r:0,Le=oe>0?Re*oe*oe/(Lr*Lr):0,Pe=ne.format(Le),Ve=j.cursorScreen??(j.current?$e(a.current?.worldToScreen(j.current[0],j.current[1])??[]):null);Ve&&Ks(S,Pe,Ve,F,Q,ne.style,ne.cursorOffsetX,ne.cursorOffsetY)}}}},[v,e,re,Se,ae,t,n,a,z,W,U,q,K,ie,G,ye,ee,ue,A,T,fe,ne,$,I,k,B,r,Z]),D=m.useCallback(()=>{ke.current||(ke.current=!0,requestAnimationFrame(()=>{ke.current=!1,he()}))},[he]),we=m.useCallback((w=!1)=>{const S=M.current,P=ce.current;P&&S.pointerId!==null&&P.hasPointerCapture(S.pointerId)&&P.releasePointerCapture(S.pointerId),S.isDrawing=!1,S.pointerId=null,S.start=null,S.current=null,S.points=[],S.screenPoints=[],S.stampCenter=null,w||(S.cursor=null,S.cursorScreen=null)},[]),de=m.useCallback(w=>{const S=a.current;if(!S||t<=0||n<=0)return null;const P=$e(S.screenToWorld(w.clientX,w.clientY));return P?cn(P,t,n):null},[a,t,n]),ge=m.useCallback(w=>{const S=ce.current;if(!S)return null;const P=S.getBoundingClientRect(),F=Y(w.clientX-P.left,0,P.width),Q=Y(w.clientY-P.top,0,P.height);return!Number.isFinite(F)||!Number.isFinite(Q)?null:[F,Q]},[]),Fe=m.useCallback(()=>{const w=M.current;if(!w.isDrawing){we(!0),D();return}let S=[];if(e==="freehand")w.points.length>=hs&&(S=Ye(w.points));else if(e==="rectangle")S=fn(w.start,w.current,Ee());else if(e==="circular")S=Bn(w.start,w.current);else if(e==="brush"){const P=w.points[w.points.length-1]??w.current??w.start;if(Z.clickSelectRoi&&P&&w.points.length<=1&&l?.(P)){we(!0),D();return}const F=Math.max(.25,Z.edgeDetail),Q=w.screenPoints.length>0?w.screenPoints:ae(w.points),xe=Math.max(.5,Z.radius*.04/F),j=us(Q,{radius:Z.radius,circleSides:Math.max(16,Math.round(32*F)),simplifyTolerance:xe,smoothingPasses:Z.edgeSmoothing}),pe=[];for(const Re of j){const oe=ve(Re);oe&&pe.push(oe)}S=Ye(pe)}(e==="freehand"||e==="rectangle"||e==="circular"||e==="brush")&&Yr(S)&&u&&u({tool:e,intent:e==="brush"?"brush":"roi",coordinates:S,bbox:Br(S),areaPx:tn(S)}),we(!0),D()},[e,u,we,D,ae,ve,Ee,Z.radius,Z.edgeDetail,Z.edgeSmoothing,Z.clickSelectRoi,l]),je=m.useCallback((w,S)=>{const P=L(w,S);if(!Yr(P))return;const F=w==="stamp-rectangle-4096px"?"patch":"roi",Q={tool:w,intent:F,coordinates:P,bbox:Br(P),areaPx:tn(P)};u?.(Q),F==="patch"&&f&&f(Q)},[L,u,f]),qe=m.useCallback((w,S,P)=>{const F=Math.max(_s,Z.radius*.1),Q=F*F,xe=w.screenPoints[w.screenPoints.length-1];if(!xe){w.points.push(S),w.screenPoints.push(P),w.current=S;return}const j=P[0]-xe[0],pe=P[1]-xe[1];j*j+pe*pe>=Q?(w.points.push(S),w.screenPoints.push(P)):(w.points[w.points.length-1]=S,w.screenPoints[w.screenPoints.length-1]=P),w.current=S},[Z.radius]),zt=m.useCallback(w=>{if(!v||e==="cursor"||w.button!==0)return;const S=de(w);if(!S)return;const P=ge(w);if(!P)return;if(w.preventDefault(),w.stopPropagation(),qt(e)){const xe=M.current;xe.stampCenter=S,je(e,S),D();return}const F=ce.current;F&&F.setPointerCapture(w.pointerId);const Q=M.current;Q.isDrawing=!0,Q.pointerId=w.pointerId,Q.start=S,Q.current=S,Q.cursor=S,Q.cursorScreen=P,Q.points=e==="freehand"||e==="brush"?[S]:[],Q.screenPoints=e==="brush"?[P]:[],D()},[v,e,de,ge,je,D]),Dt=m.useCallback(w=>{if(!v||e==="cursor")return;const S=de(w);if(!S)return;const P=ge(w);if(!P)return;const F=M.current;if(F.cursor=S,F.cursorScreen=P,qt(e)){F.stampCenter=S,w.preventDefault(),w.stopPropagation(),D();return}if(e==="brush"){if(!F.isDrawing||F.pointerId!==w.pointerId){D();return}w.preventDefault(),w.stopPropagation(),qe(F,S,P),D();return}if(!(!F.isDrawing||F.pointerId!==w.pointerId)){if(w.preventDefault(),w.stopPropagation(),e==="freehand"){const Q=a.current,xe=Math.max(1e-6,Q?.getViewState?.().zoom??1),j=ds/xe,pe=j*j,Re=F.points[F.points.length-1];if(!Re)F.points.push(S);else{const oe=S[0]-Re[0],Le=S[1]-Re[1];oe*oe+Le*Le>=pe&&F.points.push(S)}}else F.current=S;D()}},[v,e,de,ge,D,a,qe]),St=m.useCallback(w=>{const S=M.current;if(!S.isDrawing||S.pointerId!==w.pointerId)return;w.preventDefault(),w.stopPropagation();const P=de(w),F=ge(w);P&&(S.cursor=P,F&&(S.cursorScreen=F),e==="brush"?F&&qe(S,P,F):S.current=P);const Q=ce.current;Q&&Q.hasPointerCapture(w.pointerId)&&Q.releasePointerCapture(w.pointerId),Fe()},[Fe,de,ge,e,qe]),Ut=m.useCallback(()=>{const w=M.current;let S=!1;e==="brush"&&!w.isDrawing&&w.cursor&&(w.cursor=null,w.cursorScreen=null,S=!0),qt(e)&&w.stampCenter&&(w.stampCenter=null,S=!0),S&&D()},[e,D]);return m.useEffect(()=>{Se(),D();const w=ce.current;if(!w)return;const S=new ResizeObserver(()=>{Se(),D()});return S.observe(w),()=>{S.disconnect()}},[Se,D]),m.useEffect(()=>{v||we(),D()},[v,D,we]),m.useEffect(()=>{Ce.current!==e&&(Ce.current=e,we(),D())},[e,we,D]),m.useEffect(()=>{D()},[h,O,W,D]),m.useEffect(()=>{if(_)return _.current=D,()=>{_.current===D&&(_.current=null)}},[_,D]),m.useEffect(()=>{if(!v)return;const w=S=>{S.key==="Escape"&&(we(),D())};return window.addEventListener("keydown",w),()=>{window.removeEventListener("keydown",w)}},[v,we,D]),Be.jsx("canvas",{ref:ce,className:J,style:Ae,onPointerDown:zt,onPointerMove:Dt,onPointerUp:St,onPointerCancel:St,onPointerLeave:Ut,onContextMenu:w=>{v&&w.preventDefault()},onWheel:w=>{if(!v)return;const S=ce.current,P=a.current;if(!S||typeof P?.zoomBy!="function")return;w.preventDefault(),w.stopPropagation();const F=S.getBoundingClientRect(),Q=w.clientX-F.left,xe=w.clientY-F.top;P.zoomBy(w.deltaY<0?ys:bs,Q,xe),D()}})}const Fi=m.createContext(null),oa=Fi.Provider;function xt(){const e=m.useContext(Fi);if(!e)throw new Error("useViewerContext must be used within a <WsiViewer>");return e}function sa({tool:e="cursor",stampOptions:t,brushOptions:n,fillColor:r,areaTooltip:i,onComplete:o,onPatchComplete:s,onBrushTap:a}){const{source:l,rendererRef:u,setInteractionLock:f}=xt(),c=e!=="cursor";m.useEffect(()=>(f("drawing-layer",c),()=>f("drawing-layer",!1)),[c,f]);const h=m.useMemo(()=>u.current?.getViewState(),[u]);return l?Be.jsx(Kn,{tool:e,enabled:c,imageWidth:l.width,imageHeight:l.height,imageMpp:l.mpp,imageZoom:l.maxTierZoom,stampOptions:t,brushOptions:n,drawFillColor:r,projectorRef:u,onBrushTap:a,viewStateSignal:h,drawAreaTooltip:i,onDrawComplete:o,onPatchComplete:s}):null}const Wr="__overlay_layer__";function aa({shapes:e}){const{rendererRef:t,source:n,registerDrawCallback:r,unregisterDrawCallback:i,requestOverlayRedraw:o}=xt(),s=m.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=$e(u.worldToScreen(l[c][0],l[c][1]));if(!h)return[];f[c]=h}return f},[t]),a=m.useRef({shapes:e,worldToScreenPoints:s,source:n});return a.current={shapes:e,worldToScreenPoints:s,source:n},m.useEffect(()=>(r(Wr,30,u=>{const{shapes:f,worldToScreenPoints:c,source:h}=a.current;if(!Array.isArray(f)||f.length===0||!h)return;const d=c(Ye([[0,0],[h.width,0],[h.width,h.height],[0,h.height]]));_i({ctx:u,overlayShapes:f,imageOuterRing:d,worldToScreenPoints:c,baseStrokeStyle:Qe})}),()=>i(Wr)),[r,i]),m.useEffect(()=>{o()},[e,o]),null}function Xr(e){return String(e??"").replace(/\/+$/,"")}function ki(e){const t=String(e??"");return t.startsWith("/")?t:`/${t}`}function la(e){const t=Xr(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=Xr(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 ca(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(g=>({termId:String(g?.termId??""),termName:String(g?.termName??""),termColor:String(g?.termColor??"")})):[],c=ki(l),h=la(t),d=r?(g,y,b)=>`${h}${c}/${g}/${b}_${y}.webp`:void 0;return{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 Qn(e,t,n,r){if(e.tileUrlBuilder)return e.tileUrlBuilder(t,n,r);const i=ki(e.tilePath);return`${e.tileBaseUrl}${i}/${t}/${r}_${n}.webp`}function ua(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 We={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 Vr(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 Gr(e,t,n=1e-4){return Math.abs(e[0]-t[0])<=n&&Math.abs(e[1]-t[1])<=n}function qr(e){const t=[];for(const n of e){const r=t[t.length-1];(!r||!Gr(r,n))&&t.push(n)}return t.length>1&&Gr(t[0],t[t.length-1])&&t.pop(),t}function Hr(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 $r(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 fa(e,t,n,r,i){let o=qr(e);if(o.length<3)return[];const s=[{inside:a=>a[0]>=t,intersect:(a,l)=>Hr(a,l,t)},{inside:a=>a[0]<=r,intersect:(a,l)=>Hr(a,l,r)},{inside:a=>a[1]>=n,intersect:(a,l)=>$r(a,l,n)},{inside:a=>a[1]<=i,intersect:(a,l)=>$r(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=qr(o)}return o.length>=3?o:[]}function yt(e,t,n=1){return typeof e!="number"||!Number.isFinite(e)?t:Math.max(n,e)}function At(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 ha={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 Li({source:e,projectorRef:t,authToken:n="",options:r,invalidateRef:i,className:o,style:s}){const a=m.useRef(null),l=m.useRef(null),u=m.useRef(null),f=m.useRef({active:!1,pointerId:null}),c=m.useRef(null),h=m.useRef(!1),d=yt(r?.width,We.width,64),g=yt(r?.height,We.height,48),y=m.useMemo(()=>{const M=Math.max(1,e.width),v=Math.max(1,e.height),O=M/v,V=d/g;let z,ee;return O>V?(z=d,ee=d/O):(ee=g,z=g*O),{x:(d-z)/2,y:(g-ee)/2,w:z,h:ee}},[e.width,e.height,d,g]),b=yt(r?.margin,We.margin,0),p=yt(r?.borderRadius,We.borderRadius,0),x=yt(r?.borderWidth,We.borderWidth,0),C=Math.max(1,Math.round(yt(r?.maxThumbnailTiles,We.maxThumbnailTiles,1))),E=r?.backgroundColor||We.backgroundColor,A=r?.borderColor||We.borderColor,T=r?.viewportBorderColor||We.viewportBorderColor,W=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:We.viewportBorderStyle,U=r?.viewportFillColor??We.viewportFillColor,q=r?.interactive??We.interactive,H=r?.showThumbnail??We.showThumbnail,X=r?.position||We.position,$=r?.onClose,I=r?.closeIcon,k=r?.closeButtonStyle,B=m.useMemo(()=>{const M={};return X==="top-left"||X==="bottom-left"?M.left=b:M.right=b,X==="top-left"||X==="top-right"?M.top=b:M.bottom=b,{position:"absolute",...M,width:d,height:g,borderRadius:p,overflow:"hidden",zIndex:4,pointerEvents:q?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[b,X,d,g,p,q,s]),_=m.useCallback(()=>{const M=a.current;if(!M)return;const v=M.getContext("2d");if(!v)return;const O=d,V=g,z=Math.max(1,window.devicePixelRatio||1),ee=Math.max(1,Math.round(O*z)),K=Math.max(1,Math.round(V*z));(M.width!==ee||M.height!==K)&&(M.width=ee,M.height=K),v.setTransform(1,0,0,1,0,0),v.clearRect(0,0,M.width,M.height),v.setTransform(z,0,0,z,0,0),v.fillStyle=E,v.fillRect(0,0,O,V);const{x:ie,y:G,w:ue,h:ye}=y,fe=l.current;fe&&v.drawImage(fe,ie,G,ue,ye),v.strokeStyle=A,v.lineWidth=x,v.strokeRect(x*.5,x*.5,O-x,V-x);const ne=t.current,me=ne?.getViewBounds?.(),Z=ne?.getViewCorners?.(),Ae=Array.isArray(Z)&&Z.length>=4&&Z.every(de=>Array.isArray(de)&&de.length>=2&&Number.isFinite(de[0])&&Number.isFinite(de[1]))?Z:null,Se=At(me)?me:At(u.current)?u.current:null;At(me)&&(u.current=me);const ae=ue/Math.max(1,e.width),ve=ye/Math.max(1,e.height),Ee=W==="dash";if(Ae){const de=Ae.map(Fe=>[ie+Fe[0]*ae,G+Fe[1]*ve]),ge=fa(de,ie,G,ie+ue,G+ye);if(ge.length>=3){v.beginPath();for(let Fe=0;Fe<ge.length;Fe+=1)Fe===0?v.moveTo(ge[Fe][0],ge[Fe][1]):v.lineTo(ge[Fe][0],ge[Fe][1]);v.closePath(),v.fillStyle=U,v.fill(),v.strokeStyle=T,v.lineWidth=2.25,Ee?Vr(v,ge,4,3):v.stroke();return}}if(!Se)return;const be=Y(ie+Se[0]*ae,ie,ie+ue),L=Y(G+Se[1]*ve,G,G+ye),re=Y(ie+Se[2]*ae,ie,ie+ue),he=Y(G+Se[3]*ve,G,G+ye),D=Math.max(1,re-be),we=Math.max(1,he-L);if(v.fillStyle=U,v.fillRect(be,L,D,we),v.strokeStyle=T,v.lineWidth=2.25,Ee){const de=[[be+.5,L+.5],[be+.5+Math.max(1,D-1),L+.5],[be+.5+Math.max(1,D-1),L+.5+Math.max(1,we-1)],[be+.5,L+.5+Math.max(1,we-1)]];Vr(v,de,4,3)}else v.strokeRect(be+.5,L+.5,Math.max(1,D-1),Math.max(1,we-1))},[d,g,y,E,A,x,t,e.width,e.height,U,T,W]),J=m.useCallback(()=>{h.current||(h.current=!0,c.current=requestAnimationFrame(()=>{h.current=!1,c.current=null,_()}))},[_]),_e=m.useCallback((M,v)=>{const O=a.current;if(!O)return null;const V=O.getBoundingClientRect();if(!V.width||!V.height)return null;const z=V.width/d,ee=V.height/g,K=y.x*z,ie=y.y*ee,G=y.w*z,ue=y.h*ee,ye=Y((M-V.left-K)/G,0,1),fe=Y((v-V.top-ie)/ue,0,1);return[ye*e.width,fe*e.height]},[e.width,e.height,d,g,y]),ce=m.useCallback((M,v)=>{const O=t.current;if(!O)return;if(O.setViewCenter){O.setViewCenter(M,v),J();return}const V=O.getViewBounds?.(),z=At(V)?V:At(u.current)?u.current:null;if(!z)return;const ee=Math.max(1e-6,z[2]-z[0]),K=Math.max(1e-6,z[3]-z[1]);O.setViewState({offsetX:M-ee*.5,offsetY:v-K*.5}),J()},[t,J]),ke=m.useCallback(M=>{if(!q||M.button!==0)return;const v=a.current;if(!v)return;const O=_e(M.clientX,M.clientY);O&&(M.preventDefault(),M.stopPropagation(),v.setPointerCapture(M.pointerId),f.current={active:!0,pointerId:M.pointerId},ce(O[0],O[1]))},[q,_e,ce]),Ie=m.useCallback(M=>{const v=f.current;if(!v.active||v.pointerId!==M.pointerId)return;const O=_e(M.clientX,M.clientY);O&&(M.preventDefault(),M.stopPropagation(),ce(O[0],O[1]))},[_e,ce]),Ce=m.useCallback(M=>{const v=f.current;if(!v.active||v.pointerId!==M.pointerId)return;const O=a.current;if(O&&O.hasPointerCapture(M.pointerId))try{O.releasePointerCapture(M.pointerId)}catch{}f.current={active:!1,pointerId:null},J()},[J]);return m.useEffect(()=>{let M=!1;l.current=null,J();const v=0,O=2**(e.maxTierZoom-v),V=Math.ceil(e.width/O),z=Math.ceil(e.height/O),ee=Math.max(1,Math.ceil(V/e.tileSize)),K=Math.max(1,Math.ceil(z/e.tileSize)),ie=ee*K;if(!H||ie>C)return;const G=document.createElement("canvas");G.width=Math.max(1,Math.round(y.w)),G.height=Math.max(1,Math.round(y.h));const ue=G.getContext("2d");if(!ue)return;ue.fillStyle=E,ue.fillRect(0,0,G.width,G.height);const ye=[];for(let fe=0;fe<K;fe+=1)for(let ne=0;ne<ee;ne+=1){const me=ne*e.tileSize*O,Z=fe*e.tileSize*O,Ae=Math.min((ne+1)*e.tileSize,V)*O,Se=Math.min((fe+1)*e.tileSize,z)*O;ye.push({url:Qn(e,v,ne,fe),bounds:[me,Z,Ae,Se]})}return Promise.allSettled(ye.map(async fe=>{const ne=ua(fe.url,n),me=await fetch(fe.url,{headers:ne?{Authorization:n}:void 0});if(!me.ok)throw new Error(`HTTP ${me.status}`);const Z=await createImageBitmap(await me.blob());return{tile:fe,bitmap:Z}})).then(fe=>{if(M){for(const Z of fe)Z.status==="fulfilled"&&Z.value.bitmap.close();return}const ne=G.width/Math.max(1,e.width),me=G.height/Math.max(1,e.height);for(const Z of fe){if(Z.status!=="fulfilled")continue;const{tile:{bounds:Ae},bitmap:Se}=Z.value,ae=Ae[0]*ne,ve=Ae[1]*me,Ee=Math.max(1,(Ae[2]-Ae[0])*ne),be=Math.max(1,(Ae[3]-Ae[1])*me);ue.drawImage(Se,ae,ve,Ee,be),Se.close()}l.current=G,J()}),()=>{M=!0}},[e,n,y,E,H,C,J]),m.useEffect(()=>{J()},[J]),m.useEffect(()=>{if(i)return i.current=J,()=>{i.current===J&&(i.current=null)}},[i,J]),m.useEffect(()=>()=>{f.current={active:!1,pointerId:null},c.current!==null&&(cancelAnimationFrame(c.current),c.current=null),h.current=!1},[]),Be.jsxs("div",{className:o,style:B,children:[Be.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:ke,onPointerMove:Ie,onPointerUp:Ce,onPointerCancel:Ce,onContextMenu:M=>{M.preventDefault()},onWheel:M=>{M.preventDefault(),M.stopPropagation()}}),$&&Be.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:M=>{M.stopPropagation(),$()},style:k?{...k}:{...ha},children:I??"×"})]})}const Zr="__patch_layer__",da=[];function ma({regions:e,strokeStyle:t}){const{rendererRef:n,registerDrawCallback:r,unregisterDrawCallback:i,requestOverlayRedraw:o}=xt(),s=e??da,a=m.useMemo(()=>Je(Ei,t),[t]),l=m.useMemo(()=>{const c=[];for(let h=0;h<s.length;h+=1){const d=s[h],g=hn(d.coordinates);g.length!==0&&c.push({region:d,regionIndex:h,regionKey:d.id??h,polygons:g})}return c},[s]),u=m.useCallback(c=>{const h=n.current;if(!h||c.length===0)return[];const d=new Array(c.length);for(let g=0;g<c.length;g+=1){const y=$e(h.worldToScreen(c[g][0],c[g][1]));if(!y)return[];d[g]=y}return d},[n]),f=m.useRef({prepared:l,resolvedStrokeStyle:a,worldToScreenPoints:u});return f.current={prepared:l,resolvedStrokeStyle:a,worldToScreenPoints:u},m.useEffect(()=>(r(Zr,20,h=>{const{prepared:d,resolvedStrokeStyle:g,worldToScreenPoints:y}=f.current;for(const b of d)for(const p of b.polygons){const x=y(p.outer);x.length>=4&&De(h,x,g,!0,!1);for(const C of p.holes){const E=y(C);E.length>=4&&De(h,E,g,!0,!1)}}}),()=>i(Zr)),[r,i]),m.useEffect(()=>{o()},[l,a,o]),null}function _t(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return null;const n=Bt(t??[]);if(n.length===0){const g={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return e.fillModes instanceof Uint8Array&&(g.fillModes=new Uint8Array(0)),e.ids instanceof Uint32Array&&(g.ids=new Uint32Array(0)),g}const r=ht(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 g=0;g<r;g+=1){const y=i[g*2],b=i[g*2+1];an(y,b,n)&&(l[h*2]=y,l[h*2+1]=b,u[h]=o[g],f&&(f[h]=s[g]),c&&(c[h]=a[g]),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 Ni(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=ht(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];an(l,u,n)&&(o[s]=a,s+=1)}return o.subarray(0,s)}let Ht=null;const ga=`
|
|
32
|
+
`;class zr{constructor(t){R(this,"canvas");R(this,"gl");R(this,"camera",new Br);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=Ei(this.canvas),this.program=bn(this.gl,Ri,Mi);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=_e(this.gl,this.program,"uCamera"),this.uBoundsLocation=_e(this.gl,this.program,"uBounds"),this.uTextureLocation=_e(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 Qe{constructor(t,n){this.next=null,this.key=t,this.data=n,this.left=null,this.right=null}}function Ai(e,t){return e>t?1:e<t?-1:0}function $e(e,t,n){const r=new Qe(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 $t(e,t,n,r){const i=new Qe(e,t);if(n===null)return i.left=i.right=null,i;n=$e(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 Ln(e,t,n){let r=null,i=null;if(t){t=$e(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 vi(e,t,n){return t===null?e:(e===null||(t=$e(e.key,t,n),t.left=e),t)}function rn(e,t,n,r,i){if(e){r(`${t}${n?"└── ":"├── "}${i(e)}
|
|
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=Ai){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,c;for(;o.length!==0||a;)if(a)o.push(a),a=a.left;else{if(a=o.pop(),c=s(a.key,n),c>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 Pi(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=Ti(this.toList(),Ci(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=vi(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],c=new Qe(s,a);return c.left=on(e,t,n,o),c.right=on(e,t,o+1,r),c}return null}function Ci(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 Pi(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 Ti(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 c=e[s];e[s]=e[a],e[a]=c,c=t[s],t[s]=t[a],t[a]=c}an(e,t,n,a,i),an(e,t,a+1,r,i)}const Ge=11102230246251565e-32,Pe=134217729,Ii=(3+8*Ge)*Ge;function Kt(e,t,n,r,i){let o,s,a,c,u=t[0],h=r[0],l=0,f=0;h>u==h>-u?(o=u,u=t[++l]):(o=h,h=r[++f]);let d=0;if(l<e&&f<n)for(h>u==h>-u?(s=u+o,a=o-(s-u),u=t[++l]):(s=h+o,a=o-(s-h),h=r[++f]),o=s,a!==0&&(i[d++]=a);l<e&&f<n;)h>u==h>-u?(s=o+u,c=s-o,a=o-(s-c)+(u-c),u=t[++l]):(s=o+h,c=s-o,a=o-(s-c)+(h-c),h=r[++f]),o=s,a!==0&&(i[d++]=a);for(;l<e;)s=o+u,c=s-o,a=o-(s-c)+(u-c),u=t[++l],o=s,a!==0&&(i[d++]=a);for(;f<n;)s=o+h,c=s-o,a=o-(s-c)+(h-c),h=r[++f],o=s,a!==0&&(i[d++]=a);return(o!==0||d===0)&&(i[d++]=o),d}function _i(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 Fi=(3+16*Ge)*Ge,Li=(2+12*Ge)*Ge,ki=(9+64*Ge)*Ge*Ge,tt=gt(4),kn=gt(8),Nn=gt(12),Bn=gt(16),Ie=gt(4);function Ni(e,t,n,r,i,o,s){let a,c,u,h,l,f,d,m,p,y,b,x,C,S,A,I,O,z;const G=e-i,D=n-i,q=t-o,re=r-o;S=G*re,f=Pe*G,d=f-(f-G),m=G-d,f=Pe*re,p=f-(f-re),y=re-p,A=m*y-(S-d*p-m*p-d*y),I=q*D,f=Pe*q,d=f-(f-q),m=q-d,f=Pe*D,p=f-(f-D),y=D-p,O=m*y-(I-d*p-m*p-d*y),b=A-O,l=A-b,tt[0]=A-(b+l)+(l-O),x=S+b,l=x-S,C=S-(x-l)+(b-l),b=C-I,l=C-b,tt[1]=C-(b+l)+(l-I),z=x+b,l=z-x,tt[2]=x-(z-l)+(b-l),tt[3]=z;let P=_i(4,tt),H=Li*s;if(P>=H||-P>=H||(l=e-G,a=e-(G+l)+(l-i),l=n-D,u=n-(D+l)+(l-i),l=t-q,c=t-(q+l)+(l-o),l=r-re,h=r-(re+l)+(l-o),a===0&&c===0&&u===0&&h===0)||(H=ki*s+Ii*Math.abs(P),P+=G*h+re*a-(q*u+D*c),P>=H||-P>=H))return P;S=a*re,f=Pe*a,d=f-(f-a),m=a-d,f=Pe*re,p=f-(f-re),y=re-p,A=m*y-(S-d*p-m*p-d*y),I=c*D,f=Pe*c,d=f-(f-c),m=c-d,f=Pe*D,p=f-(f-D),y=D-p,O=m*y-(I-d*p-m*p-d*y),b=A-O,l=A-b,Ie[0]=A-(b+l)+(l-O),x=S+b,l=x-S,C=S-(x-l)+(b-l),b=C-I,l=C-b,Ie[1]=C-(b+l)+(l-I),z=x+b,l=z-x,Ie[2]=x-(z-l)+(b-l),Ie[3]=z;const N=Kt(4,tt,4,Ie,kn);S=G*h,f=Pe*G,d=f-(f-G),m=G-d,f=Pe*h,p=f-(f-h),y=h-p,A=m*y-(S-d*p-m*p-d*y),I=q*u,f=Pe*q,d=f-(f-q),m=q-d,f=Pe*u,p=f-(f-u),y=u-p,O=m*y-(I-d*p-m*p-d*y),b=A-O,l=A-b,Ie[0]=A-(b+l)+(l-O),x=S+b,l=x-S,C=S-(x-l)+(b-l),b=C-I,l=C-b,Ie[1]=C-(b+l)+(l-I),z=x+b,l=z-x,Ie[2]=x-(z-l)+(b-l),Ie[3]=z;const k=Kt(N,kn,4,Ie,Nn);S=a*h,f=Pe*a,d=f-(f-a),m=a-d,f=Pe*h,p=f-(f-h),y=h-p,A=m*y-(S-d*p-m*p-d*y),I=c*u,f=Pe*c,d=f-(f-c),m=c-d,f=Pe*u,p=f-(f-u),y=u-p,O=m*y-(I-d*p-m*p-d*y),b=A-O,l=A-b,Ie[0]=A-(b+l)+(l-O),x=S+b,l=x-S,C=S-(x-l)+(b-l),b=C-I,l=C-b,Ie[1]=C-(b+l)+(l-I),z=x+b,l=z-x,Ie[2]=x-(z-l)+(b-l),Ie[3]=z;const Z=Kt(k,Nn,4,Ie,Bn);return Bn[Z-1]}function Bi(e,t,n,r,i,o){const s=(t-o)*(n-i),a=(e-i)*(r-o),c=s-a,u=Math.abs(s+a);return Math.abs(c)>=Fi*u?c:-Ni(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 zi=Ke*Ke,zn=(e,t)=>{if(-Ke<e&&e<Ke&&-Ke<t&&t<Ke)return 0;const n=e-t;return n*n<zi*e*t?0:e<t?-1:1};class Di{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 wn,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 ft=new Di,It=(e,t)=>e.x*t.y-e.y*t.x,Dr=(e,t)=>e.x*t.x+e.y*t.y,Un=(e,t,n)=>{const r=Bi(e.x,e.y,t.x,t.y,n.x,n.y);return r>0?-1:r<0?1:0},Nt=e=>Math.sqrt(Dr(e,e)),Ui=(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 It(i,r)/Nt(i)/Nt(r)},Oi=(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 Dr(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)},Yi=(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=It(t,r);if(i==0)return null;const o={x:n.x-e.x,y:n.y-e.y},s=It(o,t)/i,a=It(o,r)/i,c=e.x+a*t.x,u=n.x+s*r.x,h=e.y+a*t.y,l=n.y+s*r.y,f=(c+u)/2,d=(h+l)/2;return{x:f,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:Ui(this.point,t.point,o.point),cosine:Oi(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:c,cosine:u}=n.get(o);return s>=0&&c>=0?a<u?1:a>u?-1:0:s<0&&c<0?a<u?-1:a>u?1:0:c<s?-1:c>s?1:0}}}let Wi=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,c=n.leftSE.point.y,u=t.rightSE.point.y,h=n.rightSE.point.y;if(r<i){if(c<a&&c<u)return 1;if(c>a&&c>u)return-1;const l=t.comparePoint(n.leftSE.point);if(l<0)return 1;if(l>0)return-1;const f=n.comparePoint(t.rightSE.point);return f!==0?f:-1}if(r>i){if(a<c&&a<h)return-1;if(a>c&&a>h)return 1;const l=n.comparePoint(t.leftSE.point);if(l!==0)return l;const f=t.comparePoint(n.rightSE.point);return f<0?1:f>0?-1:1}if(a<c)return-1;if(a>c)return 1;if(o<s){const l=n.comparePoint(t.rightSE.point);if(l!==0)return l}if(o>s){const l=t.comparePoint(n.rightSE.point);if(l<0)return 1;if(l>0)return-1}if(o!==s){const l=u-a,f=o-r,d=h-c,m=s-i;if(l>f&&d<m)return 1;if(l<f&&d>m)return-1}return o>s?1:o<s||u<h?-1:u>h?1:t.id<n.id?-1:t.id>n.id?1:0}constructor(t,n,r,i){this.id=++Wi,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 c=new Be(i,!0),u=new Be(o,!1);return new je(c,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,c=n.y+a*i.y;return t.y===c?0:t.y<c?-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,c=t.rightSE.point,u=at(n,a)&&this.comparePoint(a)===0,h=at(r,o)&&t.comparePoint(o)===0,l=at(n,c)&&this.comparePoint(c)===0,f=at(r,s)&&t.comparePoint(s)===0;if(h&&u)return f&&!l?s:!f&&l?c:null;if(h)return l&&o.x===c.x&&o.y===c.y?null:o;if(u)return f&&s.x===a.x&&s.y===a.y?null:a;if(f&&l)return null;if(f)return s;if(l)return c;const d=Yi(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],c=r.windings[o],u=n.rings.indexOf(a);u===-1?(n.rings.push(a),n.windings.push(c)):n.windings[u]+=c}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,c=this.rings.length;a<c;a++){const u=this.rings[a],h=this.windings[a],l=n.indexOf(u);l===-1?(n.push(u),r.push(h)):r[l]+=h}const o=[],s=[];for(let a=0,c=n.length;a<c;a++){if(r[a]===0)continue;const u=n[a],h=u.poly;if(s.indexOf(h)===-1)if(u.isExterior)o.push(h);else{s.indexOf(h)===-1&&s.push(h);const l=o.indexOf(u.poly);l!==-1&&o.splice(l,1)}}for(let a=0,c=o.length;a<c;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 c=ft.round(t[s][0],t[s][1]);c.x===o.x&&c.y===o.y||(this.segments.push(je.fromRing(o,c,this)),c.x<this.bbox.ll.x&&(this.bbox.ll.x=c.x),c.y<this.bbox.ll.y&&(this.bbox.ll.y=c.y),c.x>this.bbox.ur.x&&(this.bbox.ur.x=c.x),c.y>this.bbox.ur.y&&(this.bbox.ur.y=c.y),o=c)}(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 Xi{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 Xi(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,c=o.rightSE;const u=[a],h=a.point,l=[];for(;s=a,a=c,u.push(a),a.point!==h;)for(;;){const f=a.getAvailableLinkedEvents();if(f.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(f.length===1){c=f[0].otherSE;break}let d=null;for(let p=0,y=l.length;p<y;p++)if(l[p].point===a.point){d=p;break}if(d!==null){const p=l.splice(d)[0],y=u.splice(p.index);y.unshift(y[0].otherSE),n.push(new Bt(y.reverse()));continue}l.push({index:u.length,point:a.point});const m=a.getLeftmostComparator(s);c=f.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,h=this.events.length-1;u<h;u++){const l=this.events[u].point,f=this.events[u+1].point;Un(l,t,f)!==0&&(n.push(l),t=l)}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,c=[];for(let u=s;u!=a;u+=o)c.push([n[u].x,n[u].y]);return c}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 Vi{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 Gi{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,c;for(;a===void 0;)o=this.tree.prev(o),o===null?a=null:o.key.consumedBy===void 0&&(a=o.key);for(;c===void 0;)s=this.tree.next(s),s===null?c=null:s.key.consumedBy===void 0&&(c=s.key);if(t.isLeft){let u=null;if(a){const l=a.getIntersection(n);if(l!==null&&(n.isAnEndpoint(l)||(u=l),!a.isAnEndpoint(l))){const f=this._splitSafely(a,l);for(let d=0,m=f.length;d<m;d++)r.push(f[d])}}let h=null;if(c){const l=c.getIntersection(n);if(l!==null&&(n.isAnEndpoint(l)||(h=l),!c.isAnEndpoint(l))){const f=this._splitSafely(c,l);for(let d=0,m=f.length;d<m;d++)r.push(f[d])}}if(u!==null||h!==null){let l=null;u===null?l=h:h===null?l=u:l=Be.comparePoints(u,h)<=0?u:h,this.queue.remove(n.rightSE),r.push(n.rightSE);const f=n.split(l);for(let d=0,m=f.length;d<m;d++)r.push(f[d])}r.length>0?(this.tree.remove(n),r.push(t)):(this.segments.push(n),n.prev=a)}else{if(a&&c){const u=a.getIntersection(c);if(u!==null){if(!a.isAnEndpoint(u)){const h=this._splitSafely(a,u);for(let l=0,f=h.length;l<f;l++)r.push(h[l])}if(!c.isAnEndpoint(u)){const h=this._splitSafely(c,u);for(let l=0,f=h.length;l<f;l++)r.push(h[l])}}}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,qi=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS||1e6;class Hi{run(t,n,r){We.type=t,ft.reset();const i=[new Xn(n,!0)];for(let l=0,f=r.length;l<f;l++)i.push(new Xn(r[l],!1));if(We.numMultiPolys=i.length,We.type==="difference"){const l=i[0];let f=1;for(;f<i.length;)ln(i[f].bbox,l.bbox)!==null?f++:i.splice(f,1)}if(We.type==="intersection")for(let l=0,f=i.length;l<f;l++){const d=i[l];for(let m=l+1,p=i.length;m<p;m++)if(ln(d.bbox,i[m].bbox)===null)return[]}const o=new wn(Be.compare);for(let l=0,f=i.length;l<f;l++){const d=i[l].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 Gi(o);let a=o.size,c=o.pop();for(;c;){const l=c.key;if(o.size===a){const d=l.segment;throw new Error(`Unable to pop() ${l.isLeft?"left":"right"} SweepEvent [${l.point.x}, ${l.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>qi)throw new Error("Infinite loop when passing sweep line over endpoints (too many sweep line segments).");const f=s.process(l);for(let d=0,m=f.length;d<m;d++){const p=f[d];p.consumedBy===void 0&&o.insert(p)}a=o.size,c=o.pop()}ft.reset();const u=Bt.factory(s.segments);return new Vi(u).getGeom()}}const We=new Hi,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("union",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("intersection",e,n)},Ki=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)},ji=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 Qi={union:Zi,intersection:$i,xor:Ki,difference:ji};function pt(e){return e==null?null:Ur(e)||Or(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 Ur(e){return Array.isArray(e)&&e.length>0&&e.every(t=>_t(t))}function Or(e){return Array.isArray(e)&&e.length>0&&e.every(t=>Ur(t))}function Ji(e){return Array.isArray(e)&&e.length>0&&e.every(t=>Or(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 Yr(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],c=n[o][0],u=n[o][1];if(a===u||a>t==u>t)continue;e<(c-s)*(t-a)/(u-a)+s&&(r=!r)}return r}function yt(e){const t=[];for(const n of e??[]){const r=Yr(n);for(const i of r){const o=i[0];if(!o||o.length<4)continue;let s=1/0,a=1/0,c=-1/0,u=-1/0;for(const[l,f]of o)l<s&&(s=l),l>c&&(c=l),f<a&&(a=f),f>u&&(u=f);if(!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(c)||!Number.isFinite(u))continue;let h=Math.abs(ht(o));for(let l=1;l<i.length;l+=1)h-=Math.abs(ht(i[l]));t.push({outer:o,holes:i.slice(1),minX:s,minY:a,maxX:c,maxY:u,area:Math.max(1e-6,h)})}}return t}function Wr(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 zt(e,t,n){for(const r of n)if(Wr(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 eo(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 to(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 Xr(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 no(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(Xr(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 ro=[6,4,2],io=64,oo=.04,so=1,ao=4,Dt=1e-6,lo=.1;function co(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<=Dt||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 uo(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),h=a,l=Math.max(Dt,n);return Ne([[e[0]+u*l,e[1]+h*l],[t[0]+u*l,t[1]+h*l],[t[0]-u*l,t[1]-h*l],[e[0]-u*l,e[1]-h*l]])}function $n(e,t){if(!e.length)return[];let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,c]of e)a<n&&(n=a),a>i&&(i=a),c<r&&(r=c),c>o&&(o=c);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 fo(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 ho(e,t){if(!Array.isArray(e)||e.length===0)return[];const n=e.map(r=>fo(r,t)).filter(r=>r.length>=4);return n.length>0?n:[]}function mo(e,t){const n=e.map(i=>ho(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=Qi.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 go(e){if(e.length===0)return null;for(const t of ro){const n=mo(e,t);if(n)return n}return null}function po(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 yo(e){let t=[],n=0;for(const r of e){if(!Array.isArray(r)||r.length===0)continue;const i=po(r[0]??[]);if(i.length<4)continue;const o=Math.abs(ht(i));o<=n||(n=o,t=i)}return t}function bo(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],c=(s[0]-o[0])*(a[1]-s[1])-(s[1]-o[1])*(a[0]-s[0]);Math.abs(c)<=t||r.push(s)}return r.push(r[0]),Ne(r)}function wo(e,t,n){const r=n[0]-t[0],i=n[1]-t[1],o=r*r+i*i;if(o<=1e-12){const l=e[0]-t[0],f=e[1]-t[1];return l*l+f*f}const s=W(((e[0]-t[0])*r+(e[1]-t[1])*i)/o,0,1),a=t[0]+r*s,c=t[1]+i*s,u=e[0]-a,h=e[1]-c;return u*u+h*h}function xo(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,c]=s;if(c-a<=1)continue;let u=0,h=-1;for(let l=a+1;l<c;l+=1){const f=wo(e[l],e[a],e[c]);f>u&&(u=f,h=l)}h>=0&&u>r&&(n[h]=1,i.push([a,h],[h,c]))}const o=[];for(let s=0;s<e.length;s+=1)n[s]&&o.push(e[s]);return o}function So(e,t){const n=Ne(e);if(n.length<5||t<=0)return n;const r=n.slice(0,-1),i=xo(r,t);return i.length<3?n:Ne(i)}function Eo(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],c=i[(s+1)%i.length];o.push([a[0]*.75+c[0]*.25,a[1]*.75+c[1]*.25],[a[0]*.25+c[0]*.75,a[1]*.25+c[1]*.75])}n=Ne(o)}return n}function Ro(e,t){const n=co(e),r=Math.max(Dt,Number(t.radius)||0);if(n.length===0||!Number.isFinite(r))return[];const i=Math.max(12,Math.floor(t.circleSides||io));if(n.length===1)return xt(Zn(n[0],r,i),t.clipBounds);const o=[],s=Math.max(Dt,r*lo);for(let f=0;f<n.length;f+=1){const d=n[f],m=Zn(d,r,i);if(m.length>=4&&o.push([m]),f===0)continue;const p=uo(n[f-1],d,r,s);p.length>=4&&o.push([p])}const a=go(o),c=a?yo(a):[];if(!c.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*oo),h=typeof t.smoothingPasses=="number"&&Number.isFinite(t.smoothingPasses)?Math.round(W(t.smoothingPasses,0,ao)):so,l=So(Eo(bo(c,1e-9),h),u);return l.length<4?xt($n(n,r),t.clipBounds):xt(l,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},Vr={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},Gr="rgba(23, 23, 25, 0.1)",qr=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},Mo=20,Jn=1e-6,er="transparent",Ao=3,vo=2,Hr=96,Co=1,tr=1e3,Zr=2,$r=2,Po=4096,To=.2,Io=1.12,_o=.89,Fo=32,Lo="#000000",ko=.1,No="#FFCF00",Bo="#FF0000",zo=1.5,nr=[2,2],Do=1,Uo=.25,Oo=4,Yo=1,Wo=0,Xo=4,Vo=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 Te(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 Go(e){return Array.isArray(e)&&e.length>=2&&ir(e[0])&&ir(e[1])}function qo(e){return Array.isArray(e)&&e.length>=2&&e.every(t=>Go(t))}function Kr(e,t){if(!(!Array.isArray(e)||e.length===0)){if(qo(e)){t.push(e.map(([n,r])=>[n,r]));return}for(const n of e)Kr(n,t)}}function or(e,t){const n=[];Kr(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 Ho(e,t){return typeof e!="number"||!Number.isFinite(e)?t:W(e,0,1)}function jr(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 Zo(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 c=n.screenToWorld(a);if(!c)return Yt(e,t);s.push(c)}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=Hr){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 c=a/n*Math.PI*2;s.push([r+Math.cos(c)*o,i+Math.sin(c)*o])}return Fe(s)}function Wt(e){const t=Yr(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,c])=>[a,c]),s=[];for(let a=1;a<r.length;a+=1){const c=r[a];!c||c.length<4||s.push(c.map(([u,h])=>[u,h]))}n.push({outer:o,holes:s})}return n}function $o(e){if(!Array.isArray(e))return nr;const t=e.filter(n=>Number.isFinite(n)&&n>=0);return t.length>0?t:nr}function Ko(e){return typeof e!="number"||!Number.isFinite(e)?Do:W(e,Uo,Oo)}function jo(e){return typeof e!="number"||!Number.isFinite(e)?Yo:Math.round(W(e,Wo,Xo))}function Qo(e){const t=ut(e?.radius,Fo),n=ut(e?.cursorLineWidth,zo),r=Ko(e?.edgeDetail),i=jo(e?.edgeSmoothing);return{radius:t,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:e?.clickSelectRoi===!0,fillColor:e?.fillColor||Lo,fillOpacity:Ho(e?.fillOpacity,ko),cursorColor:e?.cursorColor||No,cursorActiveColor:e?.cursorActiveColor||Bo,cursorLineWidth:n,cursorLineDash:$o(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 es(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 ts=.58,ns=4096,rs=.5;let St=null;const Et=new Map;function is(){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*ts,o=is();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>ns&&Et.clear(),Et.set(n,s),s}function os(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)>rs||(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=os(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 Pn(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?Mo:0}function ss(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 as(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 ls(e){return Number.isFinite(e)?`${Math.max(0,e).toFixed(3)} mm²`:"0.000 mm²"}function cs(e){const t=typeof e?.format=="function"?e.format:ls,n=as(e?.cursorOffset);return{enabled:e?.enabled===!0,format:t,style:ss(e?.style),cursorOffsetX:n.x,cursorOffsetY:n.y}}function Qr(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,h=o.fontSize+o.paddingY*2,l=n[0],f=n[1]-o.offsetY,d=s?W(l,u*.5+1,r-u*.5-1):l,m=s?W(f,h*.5+1,i-h*.5-1):f,p=d-u*.5,y=m-h*.5;e.fillStyle=o.backgroundColor,e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,jr(e,p,y,u,h,o.borderRadius),e.fill(),o.borderWidth>0&&e.stroke(),e.fillStyle=o.textColor,e.fillText(a,d,m+.5),e.restore()}function us(e,t,n,r,i,o,s,a){const c=t.trim();if(!c)return;e.save(),e.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,e.textAlign="center",e.textBaseline="middle";const h=Mn(c,o)+o.paddingX*2,l=o.fontSize+o.paddingY*2,f=W(n[0]+s,h*.5+1,r-h*.5-1),d=W(n[1]+a,l*.5+1,i-l*.5-1),m=f-h*.5,p=d-l*.5;e.fillStyle=o.backgroundColor,jr(e,m,p,h,l,o.borderRadius),e.fill(),e.fillStyle=o.textColor,e.fillText(c,f,d+.5),e.restore()}function fs(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 c=0;c<n.length;c+=1){const u=n[c];if(!u?.coordinates?.length||u.visible===!1)continue;const h=u.closed??Zo(u.coordinates),l=or(u.coordinates,h);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??c,outerRingPoints:r.length,sourceRingCount:m.length,holeRingCount:d.length,fillColor:u.invertedFill.fillColor}),fs(t,r,d,u.invertedFill.fillColor)}if(l.length===0)continue;const f=Ve(o,u.stroke??u.strokeStyle);for(const d of l){const m=i(d);m.length<2||Te(t,m,f,h,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 hs(e){return{rectangleAreaMm2:ut(e?.rectangleAreaMm2,Zr),circleAreaMm2:ut(e?.circleAreaMm2,$r),rectanglePixelSize:ut(e?.rectanglePixelSize,Po)}}const sr=1e3;function ds(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 c of s){const u=n.screenToWorld(c);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 ms(e,t,n=Hr){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 gs(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 l=r.rectanglePixelSize*.5;return ar(n,l,a()).map(f=>Ut(f,i,o))}let c=0;if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"?c=t==="stamp-rectangle-2mm2"?Zr:r.rectangleAreaMm2:(t==="stamp-circle"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2")&&(c=t==="stamp-circle-hpf-0.2mm2"?To:t==="stamp-circle-2mm2"?$r:r.circleAreaMm2),!Number.isFinite(c)||c<=0)return[];const u=ds(c);let h=[];if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"){const l=s(Math.sqrt(u)*.5);h=ar(n,l,a())}else if(t==="stamp-circle"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2"){const l=s(Math.sqrt(u/Math.PI));h=ms(n,l)}return h.length?h.map(l=>Ut(l,i,o)):[]}function ps(e){return{color:Gr,width:qr,lineDash:Je,lineJoin:e.lineJoin,lineCap:e.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function ys(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)>Co}function ei({tool:e,imageWidth:t,imageHeight:n,imageMpp:r,imageZoom:i,stampOptions:o,brushOptions:s,projectorRef:a,onBrushTap:c,onDrawComplete:u,onPatchComplete:h,enabled:l,viewStateSignal:f,persistedRegions:d,patchRegions:m,persistedPolygons:p,drawFillColor:y,regionStrokeStyle:b,regionStrokeHoverStyle:x,regionStrokeActiveStyle:C,patchStrokeStyle:S,resolveRegionStrokeStyle:A,resolveRegionLabelStyle:I,overlayShapes:O,hoveredRegionId:z=null,activeRegionId:G=null,regionLabelStyle:D,drawAreaTooltip:q,autoLiftRegionLabelAtMaxZoom:re=!1,regionLabelAnchor:P="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=l??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 T=X[E],F=Wt(T.coordinates);F.length!==0&&w.push({region:T,regionIndex:E,regionKey:T.id??E,polygons:F})}return w},[X]),ie=g.useMemo(()=>{const w=[];for(let E=0;E<le.length;E+=1){const T=le[E],F=Wt(T.coordinates);F.length!==0&&w.push({region:T,regionIndex:E,regionKey:T.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(Vr,S),[S]),ye=g.useMemo(()=>ys(y),[y]),U=g.useMemo(()=>vn(D),[D]),V=g.useMemo(()=>cs(q),[q]),ee=g.useMemo(()=>hs(o),[o]),B=g.useMemo(()=>Qo(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(),T=Math.max(1,window.devicePixelRatio||1),F=Math.max(1,Math.round(E.width*T)),j=Math.max(1,Math.round(E.height*T));(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 T=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[];T[F]=j}return T},[a]),Me=g.useCallback(w=>{const E=a.current,T=se.current;if(!E||!T)return null;const F=T.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:(T,F)=>Oe(w.worldToScreen(T,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,T=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=T+Math.log2(j),fe=Math.max(1e-9,Sn(E,T,Ae));return w/fe/j},[r,i,a]),Y=g.useCallback((w,E)=>gs({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 T=Math.max(1,window.devicePixelRatio||1),F=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),Q.length>0)for(const fe of Q){const{region:ge,polygons:Ee,regionIndex:ve,regionKey:Le}=fe,De=Ot(G,Le)?"active":Ot(z,Le)?"hover":"default";let He=De==="active"?$:De==="hover"?me:he;if(A){const wt=A({region:ge,regionId:Le,regionIndex:ve,state:De});He=Ve(He,wt||void 0)}const bt=De==="default"?null:ps(He);for(const wt of Ee){const qt=ae(wt.outer);qt.length>=4&&(bt&&Te(E,qt,bt,!0,!1),Te(E,qt,He,!0,!1));for(const wi of wt.holes){const Ht=ae(wi);Ht.length>=4&&(bt&&Te(E,Ht,bt,!0,!1),Te(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&&Te(E,Ee,pe,!0,!1);for(const ve of ge.holes){const Le=ae(ve);Le.length>=4&&Te(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),es(E,M.current,a.current,B);else if(Ae.length>0)if(e==="freehand"){const fe=ae(Ae);fe.length>=2&&Te(E,fe,he,!1,!1),fe.length>=3&&Te(E,ae(Fe(Ae)),he,!0,!0,ye)}else{const fe=ae(Ae);fe.length>=4&&Te(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):Pn(re,fe,a.current?.getZoomRange?.());for(const Ee of Q){if(!Ee.region.label)continue;const ve=An(Ee.polygons,P);if(!ve)continue;const Le=Oe(a.current?.worldToScreen(ve[0],ve[1])??[]);if(!Le)continue;let De=Cn(U,I?.({region:Ee.region,regionId:Ee.regionKey,regionIndex:Ee.regionIndex,zoom:fe}));ge>0&&(De={...De,offsetY:De.offsetY+ge}),Qr(E,Ee.region.label,Le,F,j,De,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,De=V.format(Le),He=fe.cursorScreen??(fe.current?Oe(a.current?.worldToScreen(fe.current[0],fe.current[1])??[]):null);He&&us(E,De,He,F,j,V.style,V.cursorOffsetX,V.cursorOffsetY)}}}},[v,e,J,de,ae,t,n,a,Q,O,z,G,he,me,$,ye,ie,pe,A,I,U,V,re,P,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,T=se.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)},[]),ce=g.useCallback(w=>{const E=a.current;if(!E||t<=0||n<=0)return null;const T=Oe(E.screenToWorld(w.clientX,w.clientY));return T?Ut(T,t,n):null},[a,t,n]),ne=g.useCallback(w=>{const E=se.current;if(!E)return null;const T=E.getBoundingClientRect(),F=W(w.clientX-T.left,0,T.width),j=W(w.clientY-T.top,0,T.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>=Ao&&(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 T=w.points[w.points.length-1]??w.current??w.start;if(B.clickSelectRoi&&T&&w.points.length<=1&&c?.(T)){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=Ro(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,c]),ze=g.useCallback((w,E)=>{const T=Y(w,E);if(!lr(T))return;const F=w==="stamp-rectangle-4096px"?"patch":"roi",j={tool:w,intent:F,coordinates:T,bbox:rr(T),areaPx:Ft(T)};u?.(j),F==="patch"&&h&&h(j)},[Y,u,h]),qe=g.useCallback((w,E,T)=>{const F=Math.max(Vo,B.radius*.1),j=F*F,Ae=w.screenPoints[w.screenPoints.length-1];if(!Ae){w.points.push(E),w.screenPoints.push(T),w.current=E;return}const fe=T[0]-Ae[0],ge=T[1]-Ae[1];fe*fe+ge*ge>=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},[B.radius]),Gt=g.useCallback(w=>{if(!v||e==="cursor"||w.button!==0)return;const E=ce(w);if(!E)return;const T=ne(w);if(!T)return;if(w.preventDefault(),w.stopPropagation(),Rt(e)){const Ae=M.current;Ae.stampCenter=E,ze(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=T,j.points=e==="freehand"||e==="brush"?[E]:[],j.screenPoints=e==="brush"?[T]:[],L()},[v,e,ce,ne,ze,L]),st=g.useCallback(w=>{if(!v||e==="cursor")return;const E=ce(w);if(!E)return;const T=ne(w);if(!T)return;const F=M.current;if(F.cursor=E,F.cursorScreen=T,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,T),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=vo/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 T=ce(w),F=ne(w);T&&(E.cursor=T,F&&(E.cursorScreen=F),e==="brush"?F&&qe(E,T,F):E.current=T);const j=se.current;j&&j.hasPointerCapture(w.pointerId)&&j.releasePointerCapture(w.pointerId),ue()},[ue,ce,ne,e,qe]),bi=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()},[f,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:bi,onContextMenu:w=>{v&&w.preventDefault()},onWheel:w=>{if(!v)return;const E=se.current,T=a.current;if(!E||typeof T?.zoomBy!="function")return;w.preventDefault(),w.stopPropagation();const F=E.getBoundingClientRect(),j=w.clientX-F.left,Ae=w.clientY-F.top;T.zoomBy(w.deltaY<0?Io:_o,j,Ae),L()}})}const ti=g.createContext(null),bs=ti.Provider;function ot(){const e=g.useContext(ti);if(!e)throw new Error("useViewerContext must be used within a <WsiViewer>");return e}function ws({tool:e="cursor",stampOptions:t,brushOptions:n,fillColor:r,areaTooltip:i,onComplete:o,onPatchComplete:s,onBrushTap:a}){const{source:c,rendererRef:u,rendererSerial:h,setInteractionLock:l}=ot(),f=e!=="cursor";g.useEffect(()=>(l("drawing-layer",f),()=>l("drawing-layer",!1)),[f,l]);const d=g.useMemo(()=>u.current?.getViewState(),[h]);return c?Ye.jsx(ei,{tool:e,enabled:f,imageWidth:c.width,imageHeight:c.height,imageMpp:c.mpp,imageZoom:c.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 xs({shapes:e}){const{rendererRef:t,source:n,registerDrawCallback:r,unregisterDrawCallback:i,requestOverlayRedraw:o}=ot(),s=g.useCallback(c=>{const u=t.current;if(!u||c.length===0)return[];const h=new Array(c.length);for(let l=0;l<c.length;l+=1){const f=Oe(u.worldToScreen(c[l][0],c[l][1]));if(!f)return[];h[l]=f}return h},[]),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:h,worldToScreenPoints:l,source:f}=a.current;if(!Array.isArray(h)||h.length===0||!f)return;const d=l(Fe([[0,0],[f.width,0],[f.width,f.height],[0,f.height]]));Jr({ctx:u,overlayShapes:h,imageOuterRing:d,worldToScreenPoints:l,baseStrokeStyle:Xe})}),()=>i(cr)),[r,i]),g.useEffect(()=>{o()},[e,o]),null}function ur(e){return String(e??"").replace(/\/+$/,"")}function ni(e){const t=String(e??"");return t.startsWith("/")?t:`/${t}`}function Ss(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 Es(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),c=String(n.path??e?.path??""),u=Number(n.mpp??e?.mpp??0);if(!i||!o||!s||!c)throw new Error("Incomplete image metadata: width/height/tileSize/path required");const h=Array.isArray(e?.terms)?e.terms.map(m=>({termId:String(m?.termId??""),termName:String(m?.termName??""),termColor:String(m?.termColor??"")})):[],l=ni(c),f=Ss(t),d=r?(m,p,y)=>`${f}${l}/${m}/${y}_${p}.webp`:void 0;return{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:c,tileBaseUrl:t,terms:h,tileUrlBuilder:d}}function Tn(e,t,n,r){if(e.tileUrlBuilder)return e.tileUrlBuilder(t,n,r);const i=ni(e.tilePath);return`${e.tileBaseUrl}${i}/${t}/${r}_${n}.webp`}function Rs(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],c=Math.hypot(a[0]-s[0],a[1]-s[1]);if(c<1e-6)continue;const u=Math.max(1,Math.round((c+r)/(n+r))),h=u*n+(u-1)*r,l=c/Math.max(1e-6,h),f=n*l,d=r*l;e.beginPath(),e.moveTo(s[0],s[1]),e.lineTo(a[0],a[1]),e.setLineDash([f,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 Ms(e,t,n,r,i){let o=dr(e);if(o.length<3)return[];const s=[{inside:a=>a[0]>=t,intersect:(a,c)=>mr(a,c,t)},{inside:a=>a[0]<=r,intersect:(a,c)=>mr(a,c,r)},{inside:a=>a[1]>=n,intersect:(a,c)=>gr(a,c,n)},{inside:a=>a[1]<=i,intersect:(a,c)=>gr(a,c,i)}];for(const a of s){if(o.length===0)return[];const c=o;o=[];let u=c[c.length-1],h=a.inside(u);for(const l of c){const f=a.inside(l);f?(h||o.push(a.intersect(u,l)),o.push(l)):h&&o.push(a.intersect(u,l)),u=l,h=f}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 As={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 vs({source:e,projectorRef:t,authToken:n="",options:r,invalidateRef:i,className:o,style:s}){const a=g.useRef(null),c=g.useRef(null),u=g.useRef(null),h=g.useRef({active:!1,pointerId:null}),l=g.useRef(null),f=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,I=r?.viewportBorderColor||ke.viewportBorderColor,O=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:ke.viewportBorderStyle,z=r?.viewportFillColor??ke.viewportFillColor,G=r?.interactive??ke.interactive,D=r?.showThumbnail??ke.showThumbnail,q=r?.position||ke.position,re=r?.onClose,P=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=c.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=Ms(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=z,v.fill(),v.strokeStyle=I,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=z,v.fillRect(_,Y,L,K),v.strokeStyle=I,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,z,I,O]),Z=g.useCallback(()=>{f.current||(f.current=!0,l.current=requestAnimationFrame(()=>{f.current=!1,l.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),h.current={active:!0,pointerId:M.pointerId},se(X[0],X[1]))},[G,we,se]),Ce=g.useCallback(M=>{const v=h.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=h.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{}h.current={active:!1,pointerId:null},Z()},[Z]);return g.useEffect(()=>{let M=!1;c.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(!D||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:Tn(e,v,V,U),bounds:[ee,B,te,de]})}return Promise.allSettled(ye.map(async U=>{const V=Rs(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()}c.current=$,Z()}),()=>{M=!0}},[e,n,p,S,D,C,Z]),g.useEffect(()=>{Z()},[Z]),g.useEffect(()=>{if(i)return i.current=Z,()=>{i.current===Z&&(i.current=null)}},[i,Z]),g.useEffect(()=>()=>{h.current={active:!1,pointerId:null},l.current!==null&&(cancelAnimationFrame(l.current),l.current=null),f.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}:{...As},children:P??"×"})]})}const pr="__patch_layer__",Cs=[];function Ps({regions:e,strokeStyle:t}){const{rendererRef:n,registerDrawCallback:r,unregisterDrawCallback:i,requestOverlayRedraw:o}=ot(),s=e??Cs,a=g.useMemo(()=>Ve(Vr,t),[t]),c=g.useMemo(()=>{const l=[];for(let f=0;f<s.length;f+=1){const d=s[f],m=Wt(d.coordinates);m.length!==0&&l.push({region:d,regionIndex:f,regionKey:d.id??f,polygons:m})}return l},[s]),u=g.useCallback(l=>{const f=n.current;if(!f||l.length===0)return[];const d=new Array(l.length);for(let m=0;m<l.length;m+=1){const p=Oe(f.worldToScreen(l[m][0],l[m][1]));if(!p)return[];d[m]=p}return d},[]),h=g.useRef({prepared:c,resolvedStrokeStyle:a,worldToScreenPoints:u});return h.current={prepared:c,resolvedStrokeStyle:a,worldToScreenPoints:u},g.useEffect(()=>(r(pr,20,f=>{const{prepared:d,resolvedStrokeStyle:m,worldToScreenPoints:p}=h.current;for(const y of d)for(const b of y.polygons){const x=p(b.outer);x.length>=4&&Te(f,x,m,!0,!1);for(const C of b.holes){const S=p(C);S.length>=4&&Te(f,S,m,!0,!1)}}}),()=>i(pr)),[r,i]),g.useEffect(()=>{o()},[c,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,c=new Float32Array(r*2),u=new Uint16Array(r),h=s?new Uint8Array(r):null,l=a?new Uint32Array(r):null;let f=0;for(let m=0;m<r;m+=1){const p=i[m*2],y=i[m*2+1];zt(p,y,n)&&(c[f*2]=p,c[f*2+1]=y,u[f]=o[m],h&&(h[f]=s[m]),l&&(l[f]=a[m]),f+=1)}const d={count:f,positions:c.subarray(0,f*2),paletteIndices:u.subarray(0,f)};return h&&(d.fillModes=h.subarray(0,f)),l&&(d.ids=l.subarray(0,f)),d}function ri(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 c=i[a*2],u=i[a*2+1];zt(c,u,n)&&(o[s]=a,s+=1)}return o.subarray(0,s)}let Mt=null;const Ts=`
|
|
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 pa(){if(typeof navigator>"u")return!1;const e=navigator;return typeof e.gpu=="object"&&e.gpu!==null}function Bi(){if(!pa())return null;const t=navigator.gpu;if(!t||typeof t!="object")return null;const n=t;return typeof n.requestAdapter!="function"?null:n}const $t=globalThis.GPUShaderStage?.COMPUTE??4,Rn=globalThis.GPUBufferUsage?.STORAGE??128,Zt=globalThis.GPUBufferUsage?.COPY_DST??8,ya=globalThis.GPUBufferUsage?.COPY_SRC??4,ba=globalThis.GPUBufferUsage?.UNIFORM??64,wa=globalThis.GPUBufferUsage?.MAP_READ??1,xa=globalThis.GPUMapMode?.READ??1;async function Sa(){const e=Bi();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 Ea(){return Ht||(Ht=(async()=>{const e=Bi();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:$t,buffer:{type:"read-only-storage"}},{binding:1,visibility:$t,buffer:{type:"read-only-storage"}},{binding:2,visibility:$t,buffer:{type:"storage"}},{binding:3,visibility:$t,buffer:{type:"uniform"}}]}),i=n.createComputePipeline({layout:n.createPipelineLayout({bindGroupLayouts:[r]}),compute:{module:n.createShaderModule({code:ga}),entryPoint:"main"}});return{device:n,pipeline:i,bindGroupLayout:r}})(),Ht)}function jt(e,t){return Math.ceil(e/t)*t}async function zi(e,t,n){const r=await Ea();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:jt(a,4),usage:Rn|Zt}),h=r.device.createBuffer({size:jt(l,4),usage:Rn|Zt}),d=r.device.createBuffer({size:jt(u,4),usage:Rn|ya}),g=r.device.createBuffer({size:16,usage:ba|Zt}),y=r.device.createBuffer({size:jt(u,4),usage:Zt|wa});let b=!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(g,0,new Uint32Array([s,o,0,0]));const p=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:g}}]}),x=r.device.createCommandEncoder(),C=x.beginComputePass();C.setPipeline(r.pipeline),C.setBindGroup(0,p),C.dispatchWorkgroups(Math.ceil(s/256)),C.end(),x.copyBufferToBuffer(d,0,y,0,u),r.device.queue.submit([x.finish()]),await y.mapAsync(xa),b=!0;const E=y.getMappedRange();return new Uint32Array(E.slice(0))}finally{if(b)try{y.unmap()}catch{}c.destroy(),h.destroy(),d.destroy(),g.destroy(),y.destroy()}}async function Di(e,t,n={}){const r=Me(),i=n.bridgeToDraw===!0;if(!e||!e.count||!e.positions||!e.paletteIndices)return{data:null,meta:{mode:"hybrid-webgpu",durationMs:Me()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}};const o=Bt(t??[]);if(o.length===0){const E={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return e.fillModes instanceof Uint8Array&&(E.fillModes=new Uint8Array(0)),e.ids instanceof Uint32Array&&(E.ids=new Uint32Array(0)),{data:E,meta:{mode:"hybrid-webgpu",durationMs:Me()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const s=ht(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 E={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(E.fillModes=new Uint8Array(0)),l&&(E.ids=new Uint32Array(0)),{data:E,meta:{mode:"hybrid-webgpu",durationMs:Me()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const u=new Float32Array(o.length*4);for(let E=0;E<o.length;E+=1){const A=E*4,T=o[E];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 zi(e.positions,s,u),c=!!f}catch{f=null,c=!1}if(!f)return{data:_t(e,t),meta:{mode:"hybrid-webgpu",durationMs:Me()-r,usedWebGpu:!1,candidateCount:s,bridgedToDraw:!1}};let h=0;for(let E=0;E<s;E+=1)f[E]===1&&(h+=1);const d=new Uint32Array(h);if(h>0){let E=0;for(let A=0;A<s;A+=1)f[A]===1&&(d[E]=A,E+=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:Me()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!0}}}const E={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(E.fillModes=new Uint8Array(0)),l&&(E.ids=new Uint32Array(0)),{data:E,meta:{mode:"hybrid-webgpu",durationMs:Me()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const E=new Uint32Array(h);let A=0;for(let W=0;W<h;W+=1){const U=d[W]??0,q=e.positions[U*2],H=e.positions[U*2+1];an(q,H,o)&&(E[A]=U,A+=1)}const T={count:s,positions:e.positions.subarray(0,s*2),paletteIndices:e.paletteIndices.subarray(0,s),drawIndices:E.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:Me()-r,usedWebGpu:!0,candidateCount:h,bridgedToDraw:!0}}}const g=new Float32Array(h*2),y=new Uint16Array(h),b=a?new Uint8Array(h):null,p=l?new Uint32Array(h):null;let x=0;for(let E=0;E<h;E+=1){const A=d[E]??0,T=e.positions[A*2],W=e.positions[A*2+1];an(T,W,o)&&(g[x*2]=T,g[x*2+1]=W,y[x]=e.paletteIndices[A],b&&(b[x]=a[A]),p&&(p[x]=l[A]),x+=1)}const C={count:x,positions:g.subarray(0,x*2),paletteIndices:y.subarray(0,x)};return b&&(C.fillModes=b.subarray(0,x)),p&&(C.ids=p.subarray(0,x)),{data:C,meta:{mode:"hybrid-webgpu",durationMs:Me()-r,usedWebGpu:!0,candidateCount:h,bridgedToDraw:!1}}}class Ui{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 Ft=new Ui(()=>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:wt&&wt.tagName.toUpperCase()==="SCRIPT"&&wt.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:Me()-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:Me()-t.startMs}})},rejectPending:(e,t)=>{e.reject(t)}});function Ra(){Ft.terminate("worker terminated")}async function Oi(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return{data:null,meta:{mode:"worker",durationMs:0}};const n=ht(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=Me(),f=Ft.beginRequest({kind:"data",resolve:a,reject:l,startMs:u});if(!f){a({data:_t(e,t),meta:{mode:"sync",durationMs:Me()-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 g=Ft.cancelRequest(f.id);g?g.reject(d):l(d)}})}async function Ma(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return{indices:new Uint32Array(0),meta:{mode:"worker",durationMs:0}};const n=ht(e),r=e.positions.slice(0,n*2);return new Promise((i,o)=>{const s=Me(),a=Ft.beginRequest({kind:"index",resolve:i,reject:o,startMs:s});if(!a){i({indices:Ni(e,t),meta:{mode:"sync",durationMs:Me()-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=Ft.cancelRequest(a.id);f?f.reject(u):o(u)}})}const Aa={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};function Yi(e,t,n,r,i){const o=m.useRef(0),[s,a]=m.useState(n),l=m.useMemo(()=>r.map(u=>Nt(u.coordinates)).filter(u=>u!=null),[r]);return m.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(Aa),i?.({mode:t,durationMs:0,inputCount:n.count,outputCount:0,polygonCount:0}),()=>{f=!0};const c=(d,g)=>{if(f||u!==o.current)return;const y=n.count,b=d?.drawIndices?d.drawIndices.length:d?.count??0;a(d),i?.({mode:g.mode,durationMs:g.durationMs,inputCount:y,outputCount:b,polygonCount:l.length,usedWebGpu:g.usedWebGpu,candidateCount:g.candidateCount,bridgedToDraw:g.bridgedToDraw})};return(async()=>{if(t==="sync"){const d=performance.now(),g=_t(n,l);c(g,{mode:"sync",durationMs:performance.now()-d});return}if(t==="hybrid-webgpu"){const d=await Di(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 Oi(n,l);c(d.data,{mode:d.meta.mode,durationMs:d.meta.durationMs})}catch{const d=performance.now(),g=_t(n,l);c(g,{mode:"sync",durationMs:performance.now()-d})}})(),()=>{f=!0}},[e,t,n,l,i]),s}const Ca=24,va=1024,Ia=4,nn=-1;function Ct(e,t,n){return(e*73856093^t*19349663)>>>0&n}function Pa(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))*Ia;return Math.max(Ca,Math.min(va,o))}function Ta(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 _a(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=Ta(e.drawIndices??null,r),o=i?i.length:r;if(o===0)return null;const s=Pa(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 k=i[I],B=e.positions[k*2],_=e.positions[k*2+1];!Number.isFinite(B)||!Number.isFinite(_)||(l[f]=Math.floor(B*a),u[f]=Math.floor(_*a),f+=1)}else for(let I=0;I<r;I+=1){const k=e.positions[I*2],B=e.positions[I*2+1];!Number.isFinite(k)||!Number.isFinite(B)||(l[f]=Math.floor(k*a),u[f]=Math.floor(B*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,g=new Int32Array(h*2),y=new Int32Array(h);g.fill(2147483647);let b=0;const p=new Int32Array(f);for(let I=0;I<f;I+=1){const k=l[I],B=u[I];let _=Ct(k,B,d);for(;;){const J=g[_*2];if(J===2147483647){if(g[_*2]=k,g[_*2+1]=B,y[_]=1,p[I]=_,b+=1,b*4>h*3){const _e=h;h<<=1,d=h-1;const ce=new Int32Array(h*2),ke=new Int32Array(h);ce.fill(2147483647);for(let Ie=0;Ie<_e;Ie+=1){if(g[Ie*2]===2147483647)continue;const Ce=g[Ie*2],M=g[Ie*2+1];let v=Ct(Ce,M,d);for(;ce[v*2]!==2147483647;)v=v+1&d;ce[v*2]=Ce,ce[v*2+1]=M,ke[v]=y[Ie]}for(g=ce,y=ke,_=Ct(k,B,d);g[_*2]!==k||g[_*2+1]!==B;)_=_+1&d;p[I]=_}break}if(J===k&&g[_*2+1]===B){y[_]+=1,p[I]=_;break}_=_+1&d}}const x=new Int32Array(b*2),C=new Uint32Array(b),E=new Uint32Array(b),A=new Int32Array(h);A.fill(nn);let T=0,W=0;for(let I=0;I<h;I+=1)g[I*2]!==2147483647&&(x[T*2]=g[I*2],x[T*2+1]=g[I*2+1],C[T]=W,E[T]=y[I],A[I]=T,W+=y[I],T+=1);const U=new Uint32Array(f),q=new Uint32Array(b);if(q.set(C),i)for(let I=0;I<f;I+=1){const k=A[p[I]];U[q[k]]=i[I],q[k]+=1}else{let I=0;for(let k=0;k<r;k+=1){const B=e.positions[k*2],_=e.positions[k*2+1];if(!Number.isFinite(B)||!Number.isFinite(_))continue;const J=A[p[I]];U[q[J]]=k,q[J]+=1,I+=1}}let H=1;for(;H<b*2;)H<<=1;const X=H-1,$=new Int32Array(H);$.fill(nn);for(let I=0;I<b;I+=1){const k=x[I*2],B=x[I*2+1];let _=Ct(k,B,X);for(;$[_]!==nn;)_=_+1&X;$[_]=I}return{cellSize:s,safeCount:r,cellCount:b,hashCapacity:H,hashTable:$,cellKeys:x,cellOffsets:C,cellLengths:E,pointIndices:U}}function Wi(e,t,n){const{hashTable:r,cellKeys:i,hashMask:o}=e;let s=Ct(t,n,o);for(;;){const a=r[s];if(a===nn)return-1;if(i[a*2]===t&&i[a*2+1]===n)return a;s=s+1&o}}function Fa(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 zn=new Ui(()=>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:wt&&wt.tagName.toUpperCase()==="SCRIPT"&&wt.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(Fa(e,t.pointData))},rejectPending:(e,t)=>{e.reject(t)}});function ka(){zn.terminate("worker terminated")}function La(e,t){const n=ht(e);if(n<=0)return null;const r=e.positions.subarray(0,n*2),i=_a({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 Xi(e,t){if(!e||!e.positions||!e.paletteIndices)return null;const n=ht(e);return n<=0?null:new Promise((r,i)=>{const o={resolve:r,reject:i,pointData:e},s=zn.beginRequest(o);if(!s||!s.worker){r(La(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=zn.cancelRequest(s.id);h?h.reject(c):i(c)}})}const Na=.65,Ba=4;function Vi(e,t,n,r,i,o,s){const a=!!(n||r||i),[l,u]=m.useState(null),f=m.useRef(null),c=m.useRef(null);m.useEffect(()=>{if(!a||!e){u(null);return}let y=!1;return Xi(e,t).then(b=>{y||u(b)}),()=>{y=!0}},[a,e,t]);const h=m.useCallback(y=>{const b=s.current;if(!b||!l)return null;const p=Number(y[0]),x=Number(y[1]);if(!Number.isFinite(p)||!Number.isFinite(x))return null;const C=Math.max(1e-6,b.getViewState().zoom),E=b.getPointSizeByZoom(),T=Math.max(Ba,E*Na)/C;if(!Number.isFinite(T)||T<=0)return null;const{cellSize:W,cellOffsets:U,cellLengths:q,pointIndices:H,positions:X,safeCount:$}=l,I=Math.floor(p/W),k=Math.floor(x/W),B=Math.max(1,Math.ceil(T/W)),_=T*T;let J=-1,_e=_,ce=0,ke=0;for(let Ce=I-B;Ce<=I+B;Ce+=1)for(let M=k-B;M<=k+B;M+=1){const v=Wi(l,Ce,M);if(v<0)continue;const O=U[v],V=O+q[v];for(let z=O;z<V;z+=1){const ee=H[z];if(ee>=$)continue;const K=X[ee*2],ie=X[ee*2+1],G=K-p,ue=ie-x,ye=G*G+ue*ue;ye>_e||(_e=ye,J=ee,ce=K,ke=ie)}}if(J<0)return null;const Ie=l.ids?Number(l.ids[J]):null;return{index:J,id:Ie,coordinate:[p,x],pointCoordinate:[ce,ke]}},[l]),d=m.useCallback((y,b)=>{if(!n)return;const p=y?.index??null,x=y?.id??null;f.current===p&&c.current===x||(f.current=p,c.current=x,n({index:p,id:x,coordinate:b,pointCoordinate:y?.pointCoordinate??null}))},[n]),g=m.useCallback((y,b)=>{if(!r)return;const p=h(y);p&&r({...p,button:b})},[r,h]);return m.useEffect(()=>{if(i)return i.current=h,()=>{i.current===h&&(i.current=null)}},[i,h]),m.useEffect(()=>{const y=f.current;y!==null&&(l&&y<l.safeCount||(f.current=null,c.current=null,n?.({index:null,id:null,coordinate:null,pointCoordinate:null})))},[l,n]),m.useEffect(()=>{o!=="cursor"&&f.current!==null&&(f.current=null,c.current=null,n?.({index:null,id:null,coordinate:null,pointCoordinate:null}))},[o,n]),{getCellByCoordinates:h,emitPointHover:d,emitPointClick:g}}const za=m.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,source:g}=xt(),y=m.useRef(null),p=Yi(s,l,t,a??Da,u),{getCellByCoordinates:x}=Vi(p,g,f,c,y,"cursor",d);return m.useImperativeHandle(h,()=>({queryAt:x}),[x]),m.useEffect(()=>{const C=d.current;!C||!n||C.setPointPalette(n)},[d,n]),m.useEffect(()=>{const C=d.current;!C||r===void 0||C.setPointSizeByZoom(r)},[d,r]),m.useEffect(()=>{const C=d.current;!C||i===void 0||C.setPointStrokeScale(i)},[d,i]),m.useEffect(()=>{const C=d.current;!C||o===void 0||C.setPointInnerFillOpacity(o)},[d,o]),m.useEffect(()=>{const C=d.current;C&&C.setPointData(p)},[d,p]),null}),Da=[],Ua=180,jr=20;function Oa(e){const t=Y(e,0,1);return t*t*(3-2*t)}function Gi(e,t,n){const[r,i]=m.useState(0),o=m.useRef(0),s=m.useRef({rafId:null,startMs:0,from:0,to:0}),a=m.useCallback(c=>{const h=Y(c,0,jr);Math.abs(o.current-h)<1e-4||(o.current=h,i(h))},[]),l=m.useCallback(()=>{const c=s.current;c.rafId!==null&&(cancelAnimationFrame(c.rafId),c.rafId=null)},[]),u=m.useCallback(c=>{const h=Y(c,0,jr),d=s.current,g=o.current;if(Math.abs(g-h)<1e-4){l(),d.to=h,a(h);return}l(),d.startMs=performance.now(),d.from=g,d.to=h;const y=b=>{const p=s.current,x=Math.max(0,b-p.startMs),C=Y(x/Ua,0,1),E=Oa(C),A=p.from+(p.to-p.from)*E;if(a(A),n.current?.(),C>=1){p.rafId=null,a(p.to);return}p.rafId=requestAnimationFrame(y)};d.rafId=requestAnimationFrame(y)},[a,l]),f=m.useCallback(c=>{const h=t.current;if(!h||typeof c!="number"||!Number.isFinite(c)){u(0);return}const d=jn(e,c,h.getZoomRange());u(d)},[e,u]);return m.useEffect(()=>()=>{l()},[l]),{regionLabelAutoLiftOffsetPx:r,syncRegionLabelAutoLiftTarget:f,cancelRegionLabelAutoLiftAnimation:l,applyRegionLabelAutoLiftOffset:a}}const Ya=6;function kt(e,t){return e.id??t}function Wa(e,t,n,r,i,o){const s=i-n,a=o-r,l=s*s+a*a;if(l<=1e-12){const g=e-n,y=t-r;return g*g+y*y}const u=Y(((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 Kr(e,t,n,r){for(let i=1;i<n.length;i+=1){const o=n[i-1],s=n[i];if(Wa(e,t,o[0],o[1],s[0],s[1])<=r)return!0}return!1}function Xa(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(Kr(e,t,n.outer,i))return!0;for(const o of n.holes)if(Kr(e,t,o,i))return!0;return!1}function Va(e,t,n,r,i,o,s){if(!e.label||!e.labelAnchor)return!1;const a=Tt(n.worldToScreen(e.labelAnchor[0],e.labelAnchor[1]));if(!a)return!1;const u=Hn(e.label,r)+r.paddingX*2,f=r.fontSize+r.paddingY*2,c=a[0],h=a[1]-r.offsetY,d=s?Y(c,u*.5+1,i-u*.5-1):c,g=s?Y(h,f*.5+1,o-f*.5-1):h,y=d-u*.5,b=d+u*.5,p=g-f*.5,x=g+f*.5;return t[0]>=y&&t[0]<=b&&t[1]>=p&&t[1]<=x}function qi(e,t="top-center"){const n=[];for(let r=0;r<e.length;r+=1){const i=e[r],o=Bt([Nt(i?.coordinates)]);if(o.length===0)continue;const s=typeof i?.label=="string"?i.label.trim():"";n.push({region:i,regionIndex:r,regionId:kt(i,r),polygons:o,label:s,labelAnchor:s?$n(o,t):null})}return n}function Ga(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),g=Ya/h;for(let y=n.length-1;y>=0;y-=1){const b=n[y];for(const x of b.polygons)if(Xa(f,c,x,g))return{region:b.region,regionIndex:b.regionIndex,regionId:b.regionId};let p=Zn(i,o?.({region:b.region,regionId:b.regionId,regionIndex:b.regionIndex,zoom:h}));if(d>0&&(p={...p,offsetY:p.offsetY+d}),!!Va(b,t,r,p,a,l,u))return{region:b.region,regionIndex:b.regionIndex,regionId:b.regionId}}return null}const Qr=[],qa=[],Jr="__region_layer__",ei="__region_label__";function Ha(e){return{color:Ri,width:Mi,lineDash:ft,lineJoin:e.lineJoin,lineCap:e.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function $a({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:g,registerDrawCallback:y,unregisterDrawCallback:b,requestOverlayRedraw:p,drawInvalidateRef:x}=xt(),C=e??Qr,E=t??qa,A=m.useMemo(()=>C.length>0?C:E.length===0?Qr:E.map((V,z)=>({id:z,coordinates:V})),[C,E]),[T,W]=m.useState(null),[U,q]=m.useState(()=>f??null),H=f!==void 0,X=H?f??null:U,$=m.useRef(null);m.useEffect(()=>{H&&q(f??null)},[H,f]);const I=m.useCallback(V=>{String(X)!==String(V)&&(H||q(V),c?.(V))},[X,H,c]),{regionLabelAutoLiftOffsetPx:k,syncRegionLabelAutoLiftTarget:B}=Gi(l,g,x),_=m.useMemo(()=>qn(n),[n]),J=m.useMemo(()=>Je(_,r),[_,r]),_e=m.useMemo(()=>Je(_,i),[_,i]),{staticLabelStyle:ce,labelStyleResolver:ke}=m.useMemo(()=>typeof s=="function"?{staticLabelStyle:void 0,labelStyleResolver:s}:{staticLabelStyle:s,labelStyleResolver:void 0},[s]),Ie=m.useMemo(()=>mn(ce),[ce]),Ce=m.useMemo(()=>{const V=[];for(let z=0;z<A.length;z+=1){const ee=A[z],K=hn(ee.coordinates);K.length!==0&&V.push({region:ee,regionIndex:z,regionKey:ee.id??z,polygons:K})}return V},[A]);m.useMemo(()=>qi(A,a),[A,a]),m.useEffect(()=>{const V=g.current;V&&B(V.getViewState().zoom)},[g,B]),m.useEffect(()=>{!(X===null?!0:A.some((K,ie)=>String(kt(K,ie))===String(X)))&&X!==null&&I(null);const z=$.current;!(z===null?!0:A.some((K,ie)=>String(kt(K,ie))===String(z)))&&z!==null&&($.current=null,W(null),h?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[A,X,h,I]);const M=m.useCallback(V=>{const z=g.current;if(!z||V.length===0)return[];const ee=new Array(V.length);for(let K=0;K<V.length;K+=1){const ie=$e(z.worldToScreen(V[K][0],V[K][1]));if(!ie)return[];ee[K]=ie}return ee},[g]),v=m.useRef({preparedRegions:Ce,hoveredRegionId:T,activeRegionId:X,resolvedStrokeStyle:_,resolvedHoverStrokeStyle:J,resolvedActiveStrokeStyle:_e,resolveStrokeStyleProp:o,worldToScreenPoints:M});v.current={preparedRegions:Ce,hoveredRegionId:T,activeRegionId:X,resolvedStrokeStyle:_,resolvedHoverStrokeStyle:J,resolvedActiveStrokeStyle:_e,resolveStrokeStyleProp:o,worldToScreenPoints:M},m.useEffect(()=>(y(Jr,10,z=>{const{preparedRegions:ee,hoveredRegionId:K,activeRegionId:ie,resolvedStrokeStyle:G,resolvedHoverStrokeStyle:ue,resolvedActiveStrokeStyle:ye,resolveStrokeStyleProp:fe,worldToScreenPoints:ne}=v.current;for(const me of ee){const{region:Z,polygons:Ae,regionIndex:Se,regionKey:ae}=me,ve=un(ie,ae)?"active":un(K,ae)?"hover":"default";let Ee=ve==="active"?ye:ve==="hover"?ue:G;if(fe){const L=fe({region:Z,regionId:ae,regionIndex:Se,state:ve});Ee=Je(Ee,L||void 0)}const be=ve==="default"?null:Ha(Ee);for(const L of Ae){const re=ne(L.outer);re.length>=4&&(be&&De(z,re,be,!0,!1),De(z,re,Ee,!0,!1));for(const he of L.holes){const D=ne(he);D.length>=4&&(be&&De(z,D,be,!0,!1),De(z,D,Ee,!0,!1))}}}}),()=>b(Jr)),[y,b]);const O=m.useRef({preparedRegions:Ce,resolvedLabelStyle:Ie,labelStyleResolver:ke,labelAnchor:a,autoLiftLabelAtMaxZoom:l,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:k,rendererRef:g});return O.current={preparedRegions:Ce,resolvedLabelStyle:Ie,labelStyleResolver:ke,labelAnchor:a,autoLiftLabelAtMaxZoom:l,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:k,rendererRef:g},m.useEffect(()=>(y(ei,50,(z,ee,K)=>{const{preparedRegions:ie,resolvedLabelStyle:G,labelStyleResolver:ue,labelAnchor:ye,autoLiftLabelAtMaxZoom:fe,clampLabelToViewport:ne,regionLabelAutoLiftOffsetPx:me,rendererRef:Z}=O.current;if(ie.length===0)return;const Ae=Math.max(1e-6,Z.current?.getViewState?.().zoom??1),Se=typeof me=="number"&&Number.isFinite(me)?Math.max(0,me):jn(fe,Ae,Z.current?.getZoomRange?.());for(const ae of ie){if(!ae.region.label)continue;const ve=$n(ae.polygons,ye);if(!ve)continue;const Ee=$e(Z.current?.worldToScreen(ve[0],ve[1])??[]);if(!Ee)continue;let be=Zn(G,ue?.({region:ae.region,regionId:ae.regionKey,regionIndex:ae.regionIndex,zoom:Ae}));Se>0&&(be={...be,offsetY:be.offsetY+Se}),Ti(z,ae.region.label,Ee,ee,K,be,ne)}}),()=>b(ei)),[y,b]),m.useEffect(()=>{p()},[Ce,T,X,_,Ie,k,p]),null}function Za({imageWidth:e,imageHeight:t,tiles:n,viewState:r,className:i,style:o}){const s=m.useRef(null),a=m.useRef(null),l=m.useMemo(()=>({width:"100%",height:"100%",display:"block",...o}),[o]);return m.useEffect(()=>{const u=s.current;if(!u)return;const f=new gi({canvas:u,imageWidth:e,imageHeight:t,initialViewState:r});return a.current=f,f.setTiles(n),()=>{f.destroy(),a.current=null}},[e,t]),m.useEffect(()=>{const u=a.current;u&&u.setTiles(n)},[n]),m.useEffect(()=>{const u=a.current;!u||!r||u.setViewState(r)},[r]),Be.jsx("canvas",{ref:s,className:i,style:l})}function ja(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 Hi{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:Me()};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-Me());this.timerId=globalThis.setTimeout(()=>{this.timerId=null,this.pump()},n)}takeNextReadyQueueItem(){if(this.queue.length===0)return null;const t=Me(),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=ja(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:Me()+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 Ka(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 Qa(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 Ja(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 Dn=.35,Un=.5,el=256,On=[{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}],tl=.1,nl=5,rl=0,il=1,ol=-100,sl=100,al=2e3;function gn(e){return e*Math.PI/180}function Kt(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 ti(e){if(!e)return Yn(On);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(On):Array.from(t.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function ll(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 cl(e,t){if(!Number.isFinite(e))return t[0]?.size??Un;if(t.length===0)return Un;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=Y((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 ni(e){return typeof e!="number"||!Number.isFinite(e)?1:Y(e,tl,nl)}function ri(e){return typeof e!="number"||!Number.isFinite(e)?0:Y(e,rl,il)}function Mn(e){return typeof e!="number"||!Number.isFinite(e)?0:Y(e,ol,sl)}function ii(e){const t=Mn(e?.brightness),n=Mn(e?.contrast),r=Mn(e?.saturation);return{brightness:t/200,contrast:n/100,saturation:r/100}}function Jn(e){return e}function An(e){return typeof e!="number"||!Number.isFinite(e)?0:Y(e,0,al)}function Qt(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:Math.max(1e-6,e)}function Cn(e){return typeof e=="function"?e:Jn}function $i(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 Zi(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 ul(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"?$i(n,t.clientX,t.clientY):null,n.classList.add("dragging"),n.setPointerCapture(t.pointerId))}function fl(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=$i(n,t.clientX,t.clientY),h=r.rotateLastAngleRad;if(r.rotateLastAngleRad=c,h!==null){const d=c-h,g=Math.atan2(Math.sin(d),Math.cos(d)),y=i.rotationDragSensitivityDegPerPixel/Dn,b=o.getViewState();o.setViewState({rotationDeg:b.rotationDeg-g*180/Math.PI*y})}}else{const c=o.getViewState(),h=Math.max(1e-6,c.zoom),d=gn(c.rotationDeg),g=Math.cos(d),y=Math.sin(d),b=(u*g-f*y)/h,p=(u*y+f*g)/h;o.setViewState({offsetX:c.offsetX-b,offsetY:c.offsetY-p})}s(),a(),l()}function hl(e,t,n){e.pointerId===n.pointerId&&Zi(t,n)}function dl(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 ml=4,gl=300;function pl(e){const{event:t,canvas:n,snapState:r,onSnapZoom:i}=e;t.preventDefault();const o=performance.now();if(o-r.lastSnapTimeMs<gl){r.accumulatedDelta=0;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)<ml)return;const s=n.getBoundingClientRect(),a=t.clientX-s.left,l=t.clientY-s.top,u=r.accumulatedDelta>0?"out":"in";r.accumulatedDelta=0,r.lastSnapTimeMs=o,i(u,a,l)}function yl(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 bl(e,t){(t||e.ctrlKey||e.metaKey)&&e.preventDefault()}function dn(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 rn(e,t){const n=dn(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,g=t.height-f+s,y=c<=h?Y(a,c,h):t.width*.5,b=d<=g?Y(l,d,g):t.height*.5;e.setCenter(y,b)}function wl(e,t){const n=Math.max(1e-6,e.getViewState().zoom),r=t.maxTierZoom+Math.log2(n);return Y(Math.floor(r),0,t.maxTierZoom)}function xl(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function ji(e,t,n){const r=dn(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=Y(Math.floor(u/i/t.tileSize),0,a-1),g=Y(Math.floor((c-1)/i/t.tileSize),0,a-1),y=Y(Math.floor(f/i/t.tileSize),0,l-1),b=Y(Math.floor((h-1)/i/t.tileSize),0,l-1);if(d>g||y>b)return[];const p=(u+c)*.5/i/t.tileSize,x=(f+h)*.5/i/t.tileSize,C=[];for(let E=y;E<=b;E+=1)for(let A=d;A<=g;A+=1){const T=A*t.tileSize*i,W=E*t.tileSize*i,U=Math.min((A+1)*t.tileSize,o)*i,q=Math.min((E+1)*t.tileSize,s)*i,H=A-p,X=E-x;C.push({key:`${n}/${A}/${E}`,tier:n,x:A,y:E,bounds:[T,W,U,q],distance2:H*H+X*X,url:Qn(t,n,A,E)})}return C.sort((E,A)=>E.distance2-A.distance2),C}function Sl(e,t){const n=wl(e,t);return{tier:n,visible:ji(e,t,n)}}function El(e){e.interactionLocked||ul({event:e.event,canvas:e.canvas,state:e.state,config:{ctrlDragRotate:e.ctrlDragRotate,rotationDragSensitivityDegPerPixel:e.rotationDragSensitivityDegPerPixel},cancelViewAnimation:e.cancelViewAnimation})}function Rl(e){e.interactionLocked||fl({event:e.event,canvas:e.canvas,state:e.state,config:{ctrlDragRotate:e.ctrlDragRotate,rotationDragSensitivityDegPerPixel:e.rotationDragSensitivityDegPerPixel},camera:e.camera,clampViewState:()=>rn(e.camera,e.source),emitViewState:e.emitViewState,requestRender:e.requestRender})}function Ml(e){e.interactionLocked||hl(e.event,e.canvas,e.state)}function Al(e){e.interactionLocked||yl({event:e.event,canvas:e.canvas,onZoomBy:e.onZoomBy})}function Cl(e){bl(e.event,e.state.dragging)}function vl(e,t){Zi(e,t)}function Il(e){return{pointerDown:t=>El({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state,ctrlDragRotate:e.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:e.getRotationDragSensitivityDegPerPixel(),cancelViewAnimation:e.cancelViewAnimation}),pointerMove:t=>Rl({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=>Ml({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){pl({event:t,canvas:e.canvas,snapState:e.zoomSnapState,onSnapZoom:e.onSnapZoom});return}dl({event:t,canvas:e.canvas,onZoomBy:e.zoomBy})},doubleClick:t=>Al({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,onZoomBy:e.zoomBy}),contextMenu:t=>Cl({event:t,canvas:e.canvas,state:e.state})}}function Pl(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 Tl(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 _l(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=Tl(t,i);i.close(),f&&(n.set(r.key,{key:r.key,texture:f,bounds:r.bounds,tier:r.tier,lastUsed:o}),Pl({gl:t,cache:n,maxCacheTiles:s}),u())}function Fl(e,t){for(const[,n]of t)e.deleteTexture(n.texture)}function kl(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 Ll(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()&&(Fl(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 Nl(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 Bl(e,t){return t<=0?new Uint8Array(0):e.length<t?new Uint8Array(t):e.subarray(0,t)}function zl(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 Dl(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?Nl(i.drawIndices,a):null,d=e.lastPointData,g=d?.fillModes instanceof Uint8Array,y=e.pointBuffersDirty||!d||d.count!==a||!Kt(d.positions,l)||!Kt(d.paletteIndices,u)||g!==s||s&&(!d?.fillModes||!Kt(d.fillModes,f)),b=e.pointBuffersDirty||c&&(!d?.drawIndices||!Kt(d.drawIndices,h))||!c&&!!d?.drawIndices,p={...e,lastPointData:{count:a,positions:l,paletteIndices:u,fillModes:f,drawIndices:c?h??void 0:void 0}};if(r||t.isContextLost())return p;const x=p.lastPointData;if(!x)return p;if(y){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=Bl(p.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),p.zeroFillModes=C}return c&&b&&(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)),p.usePointIndices=c,p.pointCount=c?h?.length??0:x.count,(y||b)&&(p.pointBuffersDirty=!1),p}function Ul(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:g,tileScheduler:y,getVisibleTiles:b,getVisibleTilesForTier:p,getViewBounds:x,intersectsBounds:C}=e;t.clearColor(.03,.06,.1,1),t.clear(t.COLOR_BUFFER_BIT);const{tier:E,visible:A}=b(),T=x(),W=new Set(A.map(B=>B.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 U=[];for(const[,B]of i)W.has(B.key)||C(B.bounds,T)&&U.push(B);U.sort((B,_)=>B.tier-_.tier);for(const B of U)B.lastUsed=o,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,B.texture),t.uniform4f(s.uBounds,B.bounds[0],B.bounds[1],B.bounds[2],B.bounds[3]),t.drawArrays(t.TRIANGLE_STRIP,0,4);let q=0;const H=[];for(const B of A){const _=i.get(B.key);if(!_){H.push(B);continue}_.lastUsed=o,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,_.texture),t.uniform4f(s.uBounds,_.bounds[0],_.bounds[1],_.bounds[2],_.bounds[3]),t.drawArrays(t.TRIANGLE_STRIP,0,4),q+=1}const X=H.slice(),$=1e6,I=[];E>0&&I.push(E-1),E<r.maxTierZoom&&I.push(E+1);for(const B of I){const _=p(B);for(const J of _)i.has(J.key)||(J.distance2+=$,X.push(J))}y.schedule(X),t.bindTexture(t.TEXTURE_2D,null),t.bindVertexArray(null);let k=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,g),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),k=u),{tier:E,visible:A.length,rendered:q,points:k,fallback:U.length,cacheHits:q,cacheMisses:H.length,drawCalls:U.length+q+(k>0?1:0)}}function oi(e){const r=Wn(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 ii(){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,_s=globalThis.GPUBufferUsage?.COPY_SRC??4,Fs=globalThis.GPUBufferUsage?.UNIFORM??64,Ls=globalThis.GPUBufferUsage?.MAP_READ??1,ks=globalThis.GPUMapMode?.READ??1;async function Ns(){const e=ii();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 Bs(){return Mt||(Mt=(async()=>{const e=ii();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:Ts}),entryPoint:"main"}});return{device:n,pipeline:i,bindGroupLayout:r}})(),Mt)}function Ct(e,t){return Math.ceil(e/t)*t}async function oi(e,t,n){const r=await Bs();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,c=o*4*Float32Array.BYTES_PER_ELEMENT,u=s*Uint32Array.BYTES_PER_ELEMENT,h=Number(r.device.limits.maxStorageBufferBindingSize);if(a>h||c>h||u>h)return null;const l=r.device.createBuffer({size:Ct(a,4),usage:Qt|vt}),f=r.device.createBuffer({size:Ct(c,4),usage:Qt|vt}),d=r.device.createBuffer({size:Ct(u,4),usage:Qt|_s}),m=r.device.createBuffer({size:16,usage:Fs|vt}),p=r.device.createBuffer({size:Ct(u,4),usage:vt|Ls});let y=!1;try{r.device.queue.writeBuffer(l,0,e.buffer,e.byteOffset,a),r.device.queue.writeBuffer(f,0,n.buffer,n.byteOffset,c),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:l}},{binding:1,resource:{buffer:f}},{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(ks),y=!0;const S=p.getMappedRange();return new Uint32Array(S.slice(0))}finally{if(y)try{p.unmap()}catch{}l.destroy(),f.destroy(),d.destroy(),m.destroy(),p.destroy()}}async function si(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,c=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)),c&&(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,I=o[S];u[A]=I.minX,u[A+1]=I.minY,u[A+2]=I.maxX,u[A+3]=I.maxY}let h=null,l=!1;try{h=await oi(e.positions,s,u),l=!!h}catch{h=null,l=!1}if(!h)return{data:dt(e,t),meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!1,candidateCount:s,bridgedToDraw:!1}};let f=0;for(let S=0;S<s;S+=1)h[S]===1&&(f+=1);const d=new Uint32Array(f);if(f>0){let S=0;for(let A=0;A<s;A+=1)h[A]===1&&(d[S]=A,S+=1)}if(f===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)),c&&(A.ids=c.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)),c&&(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(f);let A=0;for(let O=0;O<f;O+=1){const z=d[O]??0,G=e.positions[z*2],D=e.positions[z*2+1];zt(G,D,o)&&(S[A]=z,A+=1)}const I={count:s,positions:e.positions.subarray(0,s*2),paletteIndices:e.paletteIndices.subarray(0,s),drawIndices:S.subarray(0,A)};return a&&(I.fillModes=a.subarray(0,s)),c&&(I.ids=c.subarray(0,s)),{data:I,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!0,candidateCount:f,bridgedToDraw:!0}}}const m=new Float32Array(f*2),p=new Uint16Array(f),y=a?new Uint8Array(f):null,b=c?new Uint32Array(f):null;let x=0;for(let S=0;S<f;S+=1){const A=d[S]??0,I=e.positions[A*2],O=e.positions[A*2+1];zt(I,O,o)&&(m[x*2]=I,m[x*2+1]=O,p[x]=e.paletteIndices[A],y&&(y[x]=a[A]),b&&(b[x]=c[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:f,bridgedToDraw:!1}}}class ai{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 ai(()=>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 c=Math.max(0,Math.floor(e.count)),u=new Uint32Array(e.indices).subarray(0,c);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 zs(){mt.terminate("worker terminated")}async function li(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,c)=>{const u=be(),h=mt.beginRequest({kind:"data",resolve:a,reject:c,startMs:u});if(!h){a({data:dt(e,t),meta:{mode:"sync",durationMs:be()-u}});return}const l={type:"roi-clip-request",id:h.id,count:n,positions:r.buffer,paletteIndices:i.buffer,fillModes:o?.buffer,ids:s?.buffer,polygons:t??[]},f=[r.buffer,i.buffer];o&&f.push(o.buffer),s&&f.push(s.buffer);try{h.worker.postMessage(l,f)}catch(d){const m=mt.cancelRequest(h.id);m?m.reject(d):c(d)}})}async function Ds(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:ri(e,t),meta:{mode:"sync",durationMs:be()-s}});return}const c={type:"roi-clip-index-request",id:a.id,count:n,positions:r.buffer,polygons:t??[]};try{a.worker.postMessage(c,[r.buffer])}catch(u){const h=mt.cancelRequest(a.id);h?h.reject(u):o(u)}})}const Us={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};function Os(e,t,n,r,i){const o=g.useRef(0),[s,a]=g.useState(n),c=g.useMemo(()=>r.map(u=>pt(u.coordinates)).filter(u=>u!=null),[r]);return g.useEffect(()=>{const u=++o.current;let h=!1;if(!e)return a(n),()=>{h=!0};if(!n||!n.count||!n.positions||!n.paletteIndices)return a(null),()=>{h=!0};if(c.length===0)return a(Us),i?.({mode:t,durationMs:0,inputCount:n.count,outputCount:0,polygonCount:0}),()=>{h=!0};const l=(d,m)=>{if(h||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:c.length,usedWebGpu:m.usedWebGpu,candidateCount:m.candidateCount,bridgedToDraw:m.bridgedToDraw})};return(async()=>{if(t==="sync"){const d=performance.now(),m=dt(n,c);l(m,{mode:"sync",durationMs:performance.now()-d});return}if(t==="hybrid-webgpu"){const d=await si(n,c,{bridgeToDraw:!0});l(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 li(n,c);l(d.data,{mode:d.meta.mode,durationMs:d.meta.durationMs})}catch{const d=performance.now(),m=dt(n,c);l(m,{mode:"sync",durationMs:performance.now()-d})}})(),()=>{h=!0}},[e,t,n,c,i]),s}const Ys=24,Ws=1024,Xs=4,Lt=-1;function ct(e,t,n){return(e*73856093^t*19349663)>>>0&n}function Vs(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))*Xs;return Math.max(Ys,Math.min(Ws,o))}function Gs(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 qs(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=Gs(e.drawIndices??null,r),o=i?i.length:r;if(o===0)return null;const s=Vs(e.sourceWidth,e.sourceHeight,o),a=1/s,c=new Int32Array(o),u=new Int32Array(o);let h=0;if(i)for(let P=0;P<o;P+=1){const H=i[P],N=e.positions[H*2],k=e.positions[H*2+1];!Number.isFinite(N)||!Number.isFinite(k)||(c[h]=Math.floor(N*a),u[h]=Math.floor(k*a),h+=1)}else for(let P=0;P<r;P+=1){const H=e.positions[P*2],N=e.positions[P*2+1];!Number.isFinite(H)||!Number.isFinite(N)||(c[h]=Math.floor(H*a),u[h]=Math.floor(N*a),h+=1)}if(h===0)return null;let l=Math.min(h,Math.max(64,h>>>3));(!Number.isFinite(l)||l<=0)&&(l=h);let f=1;for(;f<l*2;)f<<=1;let d=f-1,m=new Int32Array(f*2),p=new Int32Array(f);m.fill(2147483647);let y=0;const b=new Int32Array(h);for(let P=0;P<h;P+=1){const H=c[P],N=u[P];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[P]=k,y+=1,y*4>f*3){const we=f;f<<=1,d=f-1;const se=new Int32Array(f*2),Re=new Int32Array(f);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[P]=k}break}if(Z===H&&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(f);A.fill(Lt);let I=0,O=0;for(let P=0;P<f;P+=1)m[P*2]!==2147483647&&(x[I*2]=m[P*2],x[I*2+1]=m[P*2+1],C[I]=O,S[I]=p[P],A[P]=I,O+=p[P],I+=1);const z=new Uint32Array(h),G=new Uint32Array(y);if(G.set(C),i)for(let P=0;P<h;P+=1){const H=A[b[P]];z[G[H]]=i[P],G[H]+=1}else{let P=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[P]];z[G[Z]]=H,G[Z]+=1,P+=1}}let D=1;for(;D<y*2;)D<<=1;const q=D-1,re=new Int32Array(D);re.fill(Lt);for(let P=0;P<y;P+=1){const H=x[P*2],N=x[P*2+1];let k=ct(H,N,q);for(;re[k]!==Lt;)k=k+1&q;re[k]=P}return{cellSize:s,safeCount:r,cellCount:y,hashCapacity:D,hashTable:re,cellKeys:x,cellOffsets:C,cellLengths:S,pointIndices:z}}function ci(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 Hs(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 ai(()=>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(Hs(e,t.pointData))},rejectPending:(e,t)=>{e.reject(t)}});function Zs(){hn.terminate("worker terminated")}function $s(e,t){const n=et(e);if(n<=0)return null;const r=e.positions.subarray(0,n*2),i=qs({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 ui(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($s(e,t));return}const a=e.positions.slice(0,n*2),c=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:c?.buffer,sourceWidth:t?.width??0,sourceHeight:t?.height??0},h=[a.buffer];c&&h.push(c.buffer);try{s.worker.postMessage(u,h)}catch(l){const f=hn.cancelRequest(s.id);f?f.reject(l):i(l)}})}const Ks=.65,js=4;function Qs(e,t,n,r,i,o,s){const a=!!(n||r||i),[c,u]=g.useState(null),h=g.useRef(null),l=g.useRef(null);g.useEffect(()=>{if(!a||!e){u(null);return}let p=!1;return ui(e,t).then(y=>{p||u(y)}),()=>{p=!0}},[a,e,t]);const f=g.useCallback(p=>{const y=s.current;if(!y||!c)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(),I=Math.max(js,S*Ks)/C;if(!Number.isFinite(I)||I<=0)return null;const{cellSize:O,cellOffsets:z,cellLengths:G,pointIndices:D,positions:q,safeCount:re}=c,P=Math.floor(b/O),H=Math.floor(x/O),N=Math.max(1,Math.ceil(I/O)),k=I*I;let Z=-1,we=k,se=0,Re=0;for(let xe=P-N;xe<=P+N;xe+=1)for(let M=H-N;M<=H+N;M+=1){const v=ci(c,xe,M);if(v<0)continue;const X=z[v],le=X+G[v];for(let Q=X;Q<le;Q+=1){const ie=D[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=c.ids?Number(c.ids[Z]):null;return{index:Z,id:Ce,coordinate:[b,x],pointCoordinate:[se,Re]}},[c]),d=g.useCallback((p,y)=>{if(!n)return;const b=p?.index??null,x=p?.id??null;h.current===b&&l.current===x||(h.current=b,l.current=x,n({index:b,id:x,coordinate:y,pointCoordinate:p?.pointCoordinate??null}))},[n]),m=g.useCallback((p,y)=>{if(!r)return;const b=f(p);b&&r({...b,button:y})},[r,f]);return g.useEffect(()=>{if(i)return i.current=f,()=>{i.current===f&&(i.current=null)}},[i,f]),g.useEffect(()=>{const p=h.current;p!==null&&(c&&p<c.safeCount||(h.current=null,l.current=null,n?.({index:null,id:null,coordinate:null,pointCoordinate:null})))},[c,n]),g.useEffect(()=>{},[o,n]),{getCellByCoordinates:f,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:c="worker",onClipStats:u,onHover:h,onClick:l},f){const{rendererRef:d,rendererSerial:m,source:p}=ot(),y=g.useRef(null),x=Os(s,c,t,a??ea,u),{getCellByCoordinates:C}=Qs(x,p,h,l,y,"cursor",d);return g.useImperativeHandle(f,()=>({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}),ea=[],ta=180,yr=20;function na(e){const t=W(e,0,1);return t*t*(3-2*t)}function ra(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(l=>{const f=W(l,0,yr);Math.abs(o.current-f)<1e-4||(o.current=f,i(f))},[]),c=g.useCallback(()=>{const l=s.current;l.rafId!==null&&(cancelAnimationFrame(l.rafId),l.rafId=null)},[]),u=g.useCallback(l=>{const f=W(l,0,yr),d=s.current,m=o.current;if(Math.abs(m-f)<1e-4){c(),d.to=f,a(f);return}c(),d.startMs=performance.now(),d.from=m,d.to=f;const p=y=>{const b=s.current,x=Math.max(0,y-b.startMs),C=W(x/ta,0,1),S=na(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,c]),h=g.useCallback(l=>{const f=t.current;if(!f||typeof l!="number"||!Number.isFinite(l)){u(0);return}const d=Pn(e,l,f.getZoomRange());u(d)},[e,u]);return g.useEffect(()=>()=>{c()},[c]),{regionLabelAutoLiftOffsetPx:r,syncRegionLabelAutoLiftTarget:h,cancelRegionLabelAutoLiftAnimation:c,applyRegionLabelAutoLiftOffset:a}}const ia=6;function dn(e,t){return e.id??t}function oa(e,t,n,r,i,o){const s=i-n,a=o-r,c=s*s+a*a;if(c<=1e-12){const m=e-n,p=t-r;return m*m+p*p}const u=W(((e-n)*s+(t-r)*a)/c,0,1),h=n+s*u,l=r+a*u,f=e-h,d=t-l;return f*f+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(oa(e,t,o[0],o[1],s[0],s[1])<=r)return!0}return!1}function sa(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 aa(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,h=r.fontSize+r.paddingY*2,l=a[0],f=a[1]-r.offsetY,d=s?W(l,u*.5+1,i-u*.5-1):l,m=s?W(f,h*.5+1,o-h*.5-1):f,p=d-u*.5,y=d+u*.5,b=m-h*.5,x=m+h*.5;return t[0]>=p&&t[0]<=y&&t[1]>=b&&t[1]<=x}function la(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,c,u=!0){const h=e[0],l=e[1],f=Math.max(1e-6,r.getViewState().zoom),d=Math.max(0,s),m=ia/f;for(let p=n.length-1;p>=0;p-=1){const y=n[p];for(const x of y.polygons)if(sa(h,l,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:f}));if(d>0&&(b={...b,offsetY:b.offsetY+d}),!!aa(y,t,r,b,a,c,u))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId}}return null}const xr=[],ca=[],Sr="__region_layer__",Er="__region_label__";function ua(e){return{color:Gr,width:qr,lineDash:Je,lineJoin:e.lineJoin,lineCap:e.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function fa({regions:e,polygons:t,strokeStyle:n,hoverStrokeStyle:r,activeStrokeStyle:i,resolveStrokeStyle:o,labelStyle:s,labelAnchor:a="top-center",autoLiftLabelAtMaxZoom:c=!1,clampLabelToViewport:u=!0,activeRegionId:h,onActiveChange:l,onHover:f,onClick:d}){const{rendererRef:m,rendererSerial:p,canvasRef:y,containerRef:b,registerDrawCallback:x,unregisterDrawCallback:C,requestOverlayRedraw:S,drawInvalidateRef:A,screenToWorld:I,worldToScreen:O,isInteractionLocked:z}=ot(),G=e??xr,D=t??ca,q=g.useMemo(()=>G.length>0?G:D.length===0?xr:D.map((U,V)=>({id:V,coordinates:U})),[G,D]),[re,P]=g.useState(null),[H,N]=g.useState(()=>h??null),k=h!==void 0,Z=k?h??null:H,we=g.useRef(null);g.useEffect(()=>{k&&N(h??null)},[k,h]);const se=g.useCallback(U=>{String(Z)!==String(U)&&(k||N(U),l?.(U))},[Z,k,l]),{regionLabelAutoLiftOffsetPx:Re,syncRegionLabelAutoLiftTarget:Ce}=ra(c,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(()=>la(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,P(null),f?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[q,Z,f,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 ze=Se({region:J,regionId:K,regionIndex:L,state:ce});ne=Ve(ne,ze||void 0)}const ue=ce==="default"?null:ua(ne);for(const ze of oe){const qe=_(ze.outer);qe.length>=4&&(ue&&Te(V,qe,ue,!0,!1),Te(V,qe,ne,!0,!1));for(const Gt of ze.holes){const st=_(Gt);st.length>=4&&(ue&&Te(V,st,ue,!0,!1),Te(V,st,ne,!0,!1))}}}}),()=>C(Sr)),[x,C]);const pe=g.useRef({preparedRegions:ie,resolvedLabelStyle:Q,labelStyleResolver:le,labelAnchor:a,autoLiftLabelAtMaxZoom:c,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:Re,rendererRef:m});pe.current={preparedRegions:ie,resolvedLabelStyle:Q,labelStyleResolver:le,labelAnchor:a,autoLiftLabelAtMaxZoom:c,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):Pn(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}),Qr(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:f,onClick:d,commitActive:se});return ye.current={preparedRegionHits:he,resolvedLabelStyle:Q,labelStyleResolver:le,regionLabelAutoLiftOffsetPx:Re,clampLabelToViewport:u,onHover:f,onClick:d,commitActive:se},g.useEffect(()=>{const U=b.current;if(!U)return;const V=te=>{if(z())return;const de=m.current;if(!de)return;const{preparedRegionHits:ae,resolvedLabelStyle:Me,labelStyleResolver:Se,regionLabelAutoLiftOffsetPx:_,clampLabelToViewport:Y,onHover:J}=ye.current,oe=I(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,P(L),J?.({region:K?.region??null,regionId:L,regionIndex:K?.regionIndex??-1,coordinate:oe}),S())},ee=te=>{if(z())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=I(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,P(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,I,O,z,S]),null}function ha({imageWidth:e,imageHeight:t,tiles:n,viewState:r,className:i,style:o}){const s=g.useRef(null),a=g.useRef(null),c=g.useMemo(()=>({width:"100%",height:"100%",display:"block",...o}),[o]);return g.useEffect(()=>{const u=s.current;if(!u)return;const h=new zr({canvas:u,imageWidth:e,imageHeight:t,initialViewState:r});return a.current=h,h.setTiles(n),()=>{h.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:c})}function da(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 fi{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=da(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,c=this.getRetryDelay(a),u={tile:t.tile,attempt:a,readyAt:be()+c},h=this.queuedByKey.get(t.tile.key);h?(h.tile=u.tile,h.readyAt=Math.min(h.readyAt,u.readyAt),h.attempt=Math.max(h.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 ma(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 ga(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 pa(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)),c=Math.max(1,Math.round(o*s));(e.width!==a||e.height!==c)&&(e.width=a,e.height=c),n.setViewport(i,o),t.viewport(0,0,a,c)}const mn=.35,gn=.5,ya=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}],ba=.1,wa=5,xa=0,Sa=1,Ea=-100,Ra=100,Ma=2e3;function Vt(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 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 Aa(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 va(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],c=t[s];if(e>c.zoom)continue;const u=Math.max(1e-6,c.zoom-a.zoom),h=W((e-a.zoom)/u,0,1);return a.size+(c.size-a.size)*h}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,ba,wa)}function Ar(e){return typeof e!="number"||!Number.isFinite(e)?0:W(e,xa,Sa)}function Jt(e){return typeof e!="number"||!Number.isFinite(e)?0:W(e,Ea,Ra)}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 In(e){return e}function en(e){return typeof e!="number"||!Number.isFinite(e)?0:W(e,0,Ma)}function Tt(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:Math.max(1e-6,e)}function tn(e){return typeof e=="function"?e:In}function hi(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 di(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 Ca(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"?hi(n,t.clientX,t.clientY):null,n.classList.add("dragging"),n.setPointerCapture(t.pointerId))}function Pa(e){const{event:t,canvas:n,state:r,config:i,camera:o,clampViewState:s,emitViewState:a,requestRender:c}=e;if(!r.dragging||t.pointerId!==r.pointerId)return;const u=t.clientX-r.lastPointerX,h=t.clientY-r.lastPointerY;if(r.lastPointerX=t.clientX,r.lastPointerY=t.clientY,r.mode==="rotate"){const l=hi(n,t.clientX,t.clientY),f=r.rotateLastAngleRad;if(r.rotateLastAngleRad=l,f!==null){const d=l-f,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 l=o.getViewState(),f=Math.max(1e-6,l.zoom),d=Vt(l.rotationDeg),m=Math.cos(d),p=Math.sin(d),y=(u*m-h*p)/f,b=(u*p+h*m)/f;o.setViewState({offsetX:l.offsetX-y,offsetY:l.offsetY-b})}s(),a(),c()}function Ta(e,t,n){e.pointerId===n.pointerId&&di(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 _a=4,Fa=300;function La(e){const{event:t,canvas:n,snapState:r,onSnapZoom:i}=e;t.preventDefault();const o=performance.now();if(o-r.lastSnapTimeMs<Fa){r.accumulatedDelta=0;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)<_a)return;const s=n.getBoundingClientRect(),a=t.clientX-s.left,c=t.clientY-s.top,u=r.accumulatedDelta>0?"out":"in";r.accumulatedDelta=0,r.lastSnapTimeMs=o,i(u,a,c)}function ka(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 Na(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,c]=e.getCenter(),u=r*.5,h=i*.5,l=u-o,f=t.width-u+o,d=h-s,m=t.height-h+s,p=l<=f?W(a,l,f):t.width*.5,y=d<=m?W(c,d,m):t.height*.5;e.setCenter(p,y)}function Ba(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 za(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function mi(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)),c=Math.max(1,Math.ceil(s/t.tileSize)),u=r[0],h=r[1],l=r[2],f=r[3],d=W(Math.floor(u/i/t.tileSize),0,a-1),m=W(Math.floor((l-1)/i/t.tileSize),0,a-1),p=W(Math.floor(h/i/t.tileSize),0,c-1),y=W(Math.floor((f-1)/i/t.tileSize),0,c-1);if(d>m||p>y)return[];const b=(u+l)*.5/i/t.tileSize,x=(h+f)*.5/i/t.tileSize,C=[];for(let S=p;S<=y;S+=1)for(let A=d;A<=m;A+=1){const I=A*t.tileSize*i,O=S*t.tileSize*i,z=Math.min((A+1)*t.tileSize,o)*i,G=Math.min((S+1)*t.tileSize,s)*i,D=A-b,q=S-x;C.push({key:`${n}/${A}/${S}`,tier:n,x:A,y:S,bounds:[I,O,z,G],distance2:D*D+q*q,url:Tn(t,n,A,S)})}return C.sort((S,A)=>S.distance2-A.distance2),C}function Da(e,t){const n=Ba(e,t);return{tier:n,visible:mi(e,t,n)}}function Ua(e){e.interactionLocked||Ca({event:e.event,canvas:e.canvas,state:e.state,config:{ctrlDragRotate:e.ctrlDragRotate,rotationDragSensitivityDegPerPixel:e.rotationDragSensitivityDegPerPixel},cancelViewAnimation:e.cancelViewAnimation})}function Oa(e){e.interactionLocked||Pa({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 Ya(e){e.interactionLocked||Ta(e.event,e.canvas,e.state)}function Wa(e){e.interactionLocked||ka({event:e.event,canvas:e.canvas,onZoomBy:e.onZoomBy})}function Xa(e){Na(e.event,e.state.dragging)}function Va(e,t){di(e,t)}function Ga(e){return{pointerDown:t=>Ua({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state,ctrlDragRotate:e.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:e.getRotationDragSensitivityDegPerPixel(),cancelViewAnimation:e.cancelViewAnimation}),pointerMove:t=>Oa({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=>Ya({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){La({event:t,canvas:e.canvas,snapState:e.zoomSnapState,onSnapZoom:e.onSnapZoom});return}Ia({event:t,canvas:e.canvas,onZoomBy:e.zoomBy})},doubleClick:t=>Wa({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,onZoomBy:e.zoomBy}),contextMenu:t=>Xa({event:t,canvas:e.canvas,state:e.state})}}function qa(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,c]of n)(!s||c.lastUsed<s.lastUsed)&&(o=a,s=c);if(!o||!s)break;t.deleteTexture(s.texture),n.delete(o)}}function Ha(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 Za(e){const{gl:t,cache:n,tile:r,bitmap:i,frameSerial:o,maxCacheTiles:s,destroyed:a,contextLost:c,requestRender:u}=e;if(a||c||t.isContextLost()){i.close();return}if(n.has(r.key)){i.close();return}const h=Ha(t,i);i.close(),h&&(n.set(r.key,{key:r.key,texture:h,bounds:r.bounds,tier:r.tier,lastUsed:o}),qa({gl:t,cache:n,maxCacheTiles:s}),u())}function $a(e,t){for(const[,n]of t)e.deleteTexture(n.texture)}function Ka(e){const{event:t,destroyed:n,contextLost:r,cancelViewAnimation:i,cancelDrag:o,tileScheduler:s,cache:a,onContextLost:c}=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(),c?.(),{handled:!0,frame:u}}function ja(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()&&($a(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 Qa(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 Ja(e,t){return t<=0?new Uint8Array(0):e.length<t?new Uint8Array(t):e.subarray(0,t)}function el(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 tl(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)),c=i.positions.subarray(0,a*2),u=i.paletteIndices.subarray(0,a),h=s?o.subarray(0,a):void 0,l=i.drawIndices instanceof Uint32Array,f=l?Qa(i.drawIndices,a):null,d=e.lastPointData,m=d?.fillModes instanceof Uint8Array,p=e.pointBuffersDirty||!d||d.count!==a||!Pt(d.positions,c)||!Pt(d.paletteIndices,u)||m!==s||s&&(!d?.fillModes||!Pt(d.fillModes,h)),y=e.pointBuffersDirty||l&&(!d?.drawIndices||!Pt(d.drawIndices,f))||!l&&!!d?.drawIndices,b={...e,lastPointData:{count:a,positions:c,paletteIndices:u,fillModes:h,drawIndices:l?f??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=Ja(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 l&&y&&(t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,n.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,f??new Uint32Array(0),t.DYNAMIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null)),b.usePointIndices=l,b.pointCount=l?f?.length??0:x.count,(p||y)&&(b.pointBuffersDirty=!1),b}function nl(e){const{gl:t,camera:n,source:r,cache:i,frameSerial:o,tileProgram:s,pointProgram:a,imageColorSettings:c,pointCount:u,usePointIndices:h,pointPaletteSize:l,pointStrokeScale:f,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(),I=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,c.brightness),t.uniform1f(s.uContrast,c.contrast),t.uniform1f(s.uSaturation,c.saturation);const z=[];for(const[,N]of i)O.has(N.key)||C(N.bounds,I)&&z.push(N);z.sort((N,k)=>N.tier-k.tier);for(const N of z)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 D=[];for(const N of A){const k=i.get(N.key);if(!k){D.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=D.slice(),re=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 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,f),t.uniform1f(a.uPointInnerFillAlpha,d),t.uniform1f(a.uPaletteSize,l),t.uniform1i(a.uPalette,1),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,a.paletteTexture),h?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:z.length,cacheHits:G,cacheMisses:D.length,drawCalls:z.length+G+(H>0?1:0)}}function Cr(e){const r=bn(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=_e(e,r,"uCamera"),o=_e(e,r,"uBounds"),s=_e(e,r,"uTexture"),a=_e(e,r,"uBrightness"),c=_e(e,r,"uContrast"),u=_e(e,r,"uSaturation"),h=e.createVertexArray(),l=e.createBuffer();if(!h||!l)throw new Error("buffer allocation failed");e.bindVertexArray(h),e.bindBuffer(e.ARRAY_BUFFER,l),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 f=e.getAttribLocation(r,"aUnit"),d=e.getAttribLocation(r,"aUv");if(f<0||d<0)throw new Error("tile attribute lookup failed");return e.enableVertexAttribArray(f),e.enableVertexAttribArray(d),e.vertexAttribPointer(f,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:h,vbo:l,uCamera:i,uBounds:o,uTexture:s,uBrightness:a,uContrast:c,uSaturation:u}}function Pr(e){const r=bn(e,`#version 300 es
|
|
110
110
|
precision highp float;
|
|
111
111
|
in vec2 aPosition;
|
|
112
112
|
in uint aTerm;
|
|
@@ -149,7 +149,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
149
149
|
outColor = vec4(color.rgb * alpha, alpha);
|
|
150
150
|
} else {
|
|
151
151
|
float s = uPointStrokeScale;
|
|
152
|
-
float ringWidth =
|
|
152
|
+
float ringWidth = s * mix(0.18, 0.35, smoothstep(3.0, 16.0, uPointSize));
|
|
153
153
|
float innerRadius = 1.0 - ringWidth;
|
|
154
154
|
float innerMask = smoothstep(innerRadius - aa, innerRadius + aa, r);
|
|
155
155
|
float ringAlpha = outerMask * innerMask * color.a;
|
|
@@ -159,7 +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=Oe(e,r,"uCamera"),o=Oe(e,r,"uPointSize"),s=Oe(e,r,"uPointStrokeScale"),a=Oe(e,r,"uPointInnerFillAlpha"),l=Oe(e,r,"uPalette"),u=Oe(e,r,"uPaletteSize"),f=e.createVertexArray(),c=e.createBuffer(),h=e.createBuffer(),d=e.createBuffer(),g=e.createBuffer(),y=e.createTexture();if(!f||!c||!h||!d||!g||!y)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 b=e.getAttribLocation(r,"aPosition");if(b<0)throw new Error("point position attribute not found");e.enableVertexAttribArray(b),e.vertexAttribPointer(b,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,h),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const p=e.getAttribLocation(r,"aTerm");if(p<0)throw new Error("point term attribute not found");e.enableVertexAttribArray(p),e.vertexAttribIPointer(p,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,g),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,y),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:g,paletteTexture:y,uCamera:i,uPointSize:o,uPointStrokeScale:s,uPointInnerFillAlpha:a,uPalette:l,uPaletteSize:u}}function Ki(e){e.animation=null,e.frame!==null&&(cancelAnimationFrame(e.frame),e.frame=null)}function Ol(e){const{state:t,camera:n,target:r,durationMs:i,easing:o,onUpdate:s}=e,a=n.getViewState();Ki(t),t.animation={startMs:Me(),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,Me()-u.startMs),c=u.durationMs<=0?1:Y(f/u.durationMs,0,1);let h=c;try{h=u.easing(c)}catch{h=c}if(Number.isFinite(h)||(h=c),h=Y(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 Yl(e){const t=Math.max(e*.5,1e-6),n=Math.max(1,e*8);return{minZoom:t,maxZoom:Math.max(t,n)}}function Wl(e,t,n){const r=Yl(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 Xl(e,t,n,r,i){const o=e.getViewState(),s={zoom:typeof r.zoom=="number"&&Number.isFinite(r.zoom)?Y(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 ai(e,t,n,r,i){const o=Math.min(t/e.width,n/e.height),s=Number.isFinite(o)&&o>0?o:1,a=Y(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 Vl(e,t,n,r,i,o){const s=e.getViewState(),a=Y(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=gn(s.rotationDeg),g=Math.cos(d),y=Math.sin(d),b=c/a*g-h/a*y,p=c/a*y+h/a*g,x=l-b,C=u-p;return{zoom:a,offsetX:x-f.width/(2*a),offsetY:C-f.height/(2*a)}}function Gl(e,t,n,r,i,o){const s=e.getViewState(),a=Y(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=gn(s.rotationDeg),g=Math.cos(d),y=Math.sin(d),b=c/a*g-h/a*y,p=c/a*y+h/a*g,x=l-b,C=u-p;return{zoom:a,offsetX:x-f.width/(2*a),offsetY:C-f.height/(2*a)}}const li=250;function ci(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 ql(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 ui(e,t,n,r,i){const o=e.camera.getViewState(),[s,a]=e.camera.screenToWorld(n,r),l=e.camera.getViewportSize(),u=Y(t,e.minZoom,e.maxZoom);if(u===o.zoom)return;const f=gn(o.rotationDeg),c=Math.cos(f),h=Math.sin(f),d=n-l.width*.5,g=r-l.height*.5;e.cancelViewAnimation();const y=x=>{const C=d/x*c-g/x*h,E=d/x*h+g/x*c;return{offsetX:s-C-l.width/(2*x),offsetY:a-E-l.height/(2*x)}},b=y(u);e.viewAnimationState.animation={startMs:Me(),durationMs:Math.max(0,i),from:o,to:{zoom:u,offsetX:b.offsetX,offsetY:b.offsetY,rotationDeg:o.rotationDeg},easing:Jn};const p=()=>{const x=e.viewAnimationState.animation;if(!x)return;const C=Math.max(0,Me()-x.startMs),E=Y(C/i,0,1),A=Y(E*E*(3-2*E),0,1),T=o.zoom+(u-o.zoom)*A,{offsetX:W,offsetY:U}=y(T);e.camera.setViewState({zoom:T,offsetX:W,offsetY:U,rotationDeg:o.rotationDeg});const q=E>=1;q&&(e.clampViewState(),e.viewAnimationState.animation=null,e.viewAnimationState.frame=null),e.onViewStateChange(e.camera.getViewState()),e.requestRender(),q||(e.viewAnimationState.frame=requestAnimationFrame(p))};e.viewAnimationState.frame=requestAnimationFrame(p)}class er{constructor(t,n,r={}){R(this,"canvas");R(this,"source");R(this,"gl");R(this,"camera",new mi);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",Dn);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",Jn);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(On));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});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):Dn,this.pointSizeStops=ti(r.pointSizeByZoom),this.pointStrokeScale=ni(r.pointStrokeScale),this.pointInnerFillOpacity=ri(r.pointInnerFillOpacity),this.imageColorSettings=ii(r.imageColorSettings),this.minZoomOverride=Qt(r.minZoom),this.maxZoomOverride=Qt(r.maxZoom),this.viewTransitionDurationMs=An(r.viewTransition?.duration),this.viewTransitionEasing=Cn(r.viewTransition?.easing),this.zoomSnaps=ci(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=oi(this.gl),this.pointProgram=si(this.gl),this.tileScheduler=new Hi({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)=>_l({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=Il({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),Ka(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=Wl(this.fitZoom,this.minZoomOverride,this.maxZoomOverride);this.minZoom=t.minZoom,this.maxZoom=t.maxZoom}resolveTargetViewState(t){return Xl(this.camera,this.minZoom,this.maxZoom,t,()=>rn(this.camera,this.source))}cancelViewAnimation(){Ki(this.viewAnimationState)}startViewAnimation(t,n,r){Ol({state:this.viewAnimationState,camera:this.camera,target:t,durationMs:n,easing:r,onUpdate:()=>{rn(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=Qt(t),i=Qt(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();Ln(s,o)||this.applyViewStateAndRender(o)}setViewTransition(t){this.viewTransitionDurationMs=An(t?.duration),this.viewTransitionEasing=Cn(t?.easing)}setViewState(t,n){const r=this.resolveTargetViewState(t),i=this.camera.getViewState();if(Ln(i,r))return;const o=An(n?.duration??this.viewTransitionDurationMs),s=Cn(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=zl(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,t);this.applyPointBufferRuntime(n),!(!t||t.length===0)&&this.requestRender()}setPointData(t){const n=Dl(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=ti(t);ll(this.pointSizeStops,n)||(this.pointSizeStops=n,this.requestRender())}setPointStrokeScale(t){const n=ni(t);this.pointStrokeScale!==n&&(this.pointStrokeScale=n,this.requestRender())}setPointInnerFillOpacity(t){const n=ri(t);this.pointInnerFillOpacity!==n&&(this.pointInnerFillOpacity=n,this.requestRender())}setImageColorSettings(t){const n=ii(t),r=this.imageColorSettings;r.brightness===n.brightness&&r.contrast===n.contrast&&r.saturation===n.saturation||(this.imageColorSettings=n,this.requestRender())}cancelDrag(){vl(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 dn(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=cl(n,this.pointSizeStops);return Y(r,Un,el)}fitToImage(t){const n=this.canvas.getBoundingClientRect(),r=Math.max(1,n.width||1),i=Math.max(1,n.height||1),o=ai(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=Vl(this.camera,this.minZoom,this.maxZoom,t,n,r);o&&this.setViewState(o,i)}zoomTo(t,n,r,i){const o=Gl(this.camera,this.minZoom,this.maxZoom,t,n,r);o&&this.setViewState(o,i)}setZoomSnaps(t,n){this.zoomSnaps=ci(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:()=>rn(this.camera,this.source),onViewStateChange:t=>this.onViewStateChange?.(t),requestRender:()=>this.requestRender()}}handleSnapZoom(t,n,r){const i=this.zoomSnaps.filter(s=>s>=this.minZoom&&s<=this.maxZoom),o=ql(i,this.camera.getViewState().zoom,t,this.zoomSnapFitAsMin);if(o){if(o.type==="fit"){const s=this.canvas.getBoundingClientRect(),a=Math.max(1,s.width||1),l=Math.max(1,s.height||1),u=ai(this.source,a,l,this.minZoom,this.maxZoom);this.fitZoom=u.fitZoom,this.applyZoomBounds(),ui(this.getZoomPivotAnimationContext(),u.target.zoom,n,r,li);return}ui(this.getZoomPivotAnimationContext(),o.zoom,n,r,li)}}render(){if(this.destroyed||this.contextLost||this.gl.isContextLost())return;const t=this.onStats?Me():0;this.frameSerial+=1;const n=Ul({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:()=>Sl(this.camera,this.source),getVisibleTilesForTier:r=>ji(this.camera,this.source,r),getViewBounds:()=>dn(this.camera),intersectsBounds:xl});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:Me()-t})}}requestRender(){this.frame!==null||this.destroyed||this.contextLost||this.gl.isContextLost()||(this.frame=requestAnimationFrame(()=>{this.frame=null,this.render()}))}resize(){Ja(this.canvas,this.gl,this.camera),this.requestRender()}onWebGlContextLost(t){const n=kl({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=oi(this.gl),this.pointProgram=si(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.requestRender(),this.onContextRestored?.())}destroy(){const t=Ll({destroyed:this.destroyed,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),resizeObserver:this.resizeObserver,removeCanvasEventListeners:()=>Qa(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 Hl=[];function $l({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:g,zoomSnaps:y,zoomSnapFitAsMin:b,pointSizeByZoom:p,pointStrokeScale:x,pointInnerFillOpacity:C,onPointerWorldMove:E,debugOverlay:A=!1,debugOverlayStyle:T,className:W,style:U,children:q}){const H=m.useRef(null),X=m.useRef(null),$=m.useRef(null),I=m.useRef(null),k=m.useRef(null),B=m.useRef(Hl),_=m.useRef(!1),J=m.useRef(new Set),_e=m.useRef(n),ce=m.useRef(r),ke=m.useRef(i),Ie=m.useRef(o),Ce=m.useRef(s),[M,v]=m.useState(null),O=m.useRef(A);m.useEffect(()=>{_e.current=n},[n]),m.useEffect(()=>{ce.current=r},[r]),m.useEffect(()=>{ke.current=i},[i]),m.useEffect(()=>{Ie.current=o},[o]),m.useEffect(()=>{Ce.current=s},[s]),m.useEffect(()=>{O.current=A,A||v(null)},[A]);const V=m.useMemo(()=>({position:"relative",width:"100%",height:"100%",...U}),[U]),z=m.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)",...T}),[T]),ee=m.useCallback(L=>{ce.current?.(L),O.current&&v(L)},[]),K=m.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]),ie=m.useCallback(()=>{const L=X.current;if(!L)return;const re=L.getContext("2d");if(!re)return;const he=Math.max(1,window.devicePixelRatio||1),D=L.getBoundingClientRect(),we=Math.max(1,Math.round(D.width*he)),de=Math.max(1,Math.round(D.height*he));(L.width!==we||L.height!==de)&&(L.width=we,L.height=de);const ge=D.width,Fe=D.height;re.setTransform(1,0,0,1,0,0),re.clearRect(0,0,L.width,L.height),re.setTransform(he,0,0,he,0,0);const je=B.current;for(let qe=0;qe<je.length;qe+=1)re.save(),je[qe].draw(re,ge,Fe),re.restore()},[]),G=m.useCallback(()=>{_.current||(_.current=!0,requestAnimationFrame(()=>{_.current=!1,ie()}))},[ie]),ue=m.useCallback((L,re,he)=>{const D=B.current.filter(we=>we.id!==L);D.push({id:L,priority:re,draw:he}),D.sort((we,de)=>we.priority-de.priority),B.current=D,G()},[G]),ye=m.useCallback(L=>{B.current=B.current.filter(re=>re.id!==L),G()},[G]),fe=m.useCallback((L,re)=>{re?J.current.add(L):J.current.delete(L),$.current?.setInteractionLock(J.current.size>0)},[]),ne=m.useCallback(()=>J.current.size>0,[]),me=m.useCallback((L,re)=>{const he=$.current;return he?Tt(he.worldToScreen(L,re)):null},[]),Z=m.useCallback((L,re)=>{const he=$.current;if(!he)return null;const D=he.screenToWorld(L,re);if(!Array.isArray(D)||D.length<2)return null;const we=Number(D[0]),de=Number(D[1]);return!Number.isFinite(we)||!Number.isFinite(de)?null:[we,de]},[]),Ae=m.useCallback(L=>{_e.current?.(L),I.current?.(),k.current?.(),G()},[G]);m.useEffect(()=>{const L=H.current;if(!L||!e)return;const re=new er(L,e,{onViewStateChange:Ae,onStats:ee,onTileError:he=>{ke.current?.(he)},onContextLost:()=>{Ie.current?.()},onContextRestored:()=>{Ce.current?.()},authToken:f,imageColorSettings:a,ctrlDragRotate:c,pointSizeByZoom:p,pointStrokeScale:x,pointInnerFillOpacity:C,minZoom:h,maxZoom:d,viewTransition:g,zoomSnaps:y,zoomSnapFitAsMin:b});return $.current=re,t&&re.setViewState(t),re.setInteractionLock(J.current.size>0),()=>{re.destroy(),$.current=null}},[e,ee,f,c,Ae]),m.useEffect(()=>{const L=$.current;!L||!t||L.isViewAnimating()||L.setViewState(t)},[t]),m.useEffect(()=>{$.current?.fitToImage()},[l]),m.useEffect(()=>{$.current?.resetRotation()},[u]),m.useEffect(()=>{$.current?.setZoomRange(h,d)},[h,d]),m.useEffect(()=>{$.current?.setViewTransition(g)},[g]),m.useEffect(()=>{$.current?.setZoomSnaps(y,b)},[y,b]),m.useEffect(()=>{$.current?.setImageColorSettings(a)},[a]),m.useEffect(()=>{const L=X.current;if(!L)return;I.current=G,G();const re=new ResizeObserver(()=>G());return re.observe(L),()=>{re.disconnect(),I.current===G&&(I.current=null)}},[G]);const Se=m.useMemo(()=>({source:e,rendererRef:$,canvasRef:H,drawInvalidateRef:I,overviewInvalidateRef:k,worldToScreen:me,screenToWorld:Z,registerDrawCallback:ue,unregisterDrawCallback:ye,requestOverlayRedraw:G,setInteractionLock:fe,isInteractionLocked:ne}),[e,me,Z,ue,ye,G,fe,ne]),ae=m.useRef(E);m.useEffect(()=>{ae.current=E},[E]);const ve=m.useCallback(L=>{const re=ae.current;if(!re)return;const he=Z(L.clientX,L.clientY),D=!!he&&he[0]>=0&&he[1]>=0&&!!e&&he[0]<=e.width&&he[1]<=e.height;re({coordinate:he,clientX:L.clientX,clientY:L.clientY,insideImage:D})},[Z,e]),Ee=m.useCallback(()=>{ae.current?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1})},[]),be=ne()?"crosshair":"grab";return Be.jsx(oa,{value:Se,children:Be.jsxs("div",{className:W,style:V,onPointerMove:E?ve:void 0,onPointerLeave:E?Ee:void 0,children:[Be.jsx("canvas",{ref:H,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none",cursor:be}}),Be.jsx("canvas",{ref:X,className:"wsi-overlay-canvas",style:{position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",pointerEvents:"none",touchAction:"none"}}),q,A&&Be.jsx("pre",{"data-open-plant-debug-overlay":!0,style:z,children:K})]})})}function Zl(e){const t=[];for(let n=0;n<e.length;n+=1){const r=e[n],i=Bt([Nt(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 jl=128,vn=[];function bt(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 Kl(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(jl,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=bt(c.minX,t,r,a,s),d=bt(c.maxX,t,r,a,s),g=bt(c.minY,n,i,l,s),y=bt(c.maxY,n,i,l,s);for(let b=g;b<=y;b+=1)for(let p=h;p<=d;p+=1)u[b*s+p].push(f)}return{minX:t,minY:n,maxX:r,maxY:i,gridSize:s,cellWidth:a,cellHeight:l,buckets:u}}function Ql(e,t,n){if(!e||t<e.minX||t>e.maxX||n<e.minY||n>e.maxY)return vn;const r=bt(t,e.minX,e.maxX,e.cellWidth,e.gridSize),i=bt(n,e.minY,e.maxY,e.cellHeight,e.gridSize);return e.buckets[i*e.gridSize+r]??vn}function Jl(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 Qi(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 g=d.length;for(let y=0;y<d.length;y+=1)d[y]<r||(g-=1);if(g===d.length)i=d;else if(g>0){const y=new Uint32Array(g);let b=0;for(let p=0;p<d.length;p+=1){const x=d[p];x>=r||(y[b]=x,b+=1)}i=y}else i=new Uint32Array(0)}const o=i?i.length:r,s=Zl(t??[]);if(!e||o===0||s.length===0)return{groups:[],inputPointCount:o,pointsInsideAnyRegion:0,unmatchedPointCount:o};const a=new Map,l=new Map,u=Kl(s);let f=0;for(let d=0;d<o;d+=1){const g=i?i[d]:d,y=e.positions[g*2],b=e.positions[g*2+1];if(!Number.isFinite(y)||!Number.isFinite(b))continue;let p=null;const x=Ql(u,y,b);if(x.length===0)continue;for(const A of x){const T=s[A];let W=!1;for(const U of T.polygons)if(xi(y,b,U)){W=!0;break}W&&(!p||T.area<p.area)&&(p=T)}if(!p)continue;f+=1;const C=e.paletteIndices[g]??0,E=a.get(p.regionIndex)??new Map;E.set(C,(E.get(C)??0)+1),a.set(p.regionIndex,E),l.set(p.regionIndex,(l.get(p.regionIndex)??0)+1)}const c=n.includeEmptyRegions??!1,h=[];for(const d of s){const g=l.get(d.regionIndex)??0;if(!c&&g<=0)continue;const y=a.get(d.regionIndex)??new Map,b=Array.from(y.entries()).map(([p,x])=>({termId:Jl(p,n.paletteIndexToTermId),paletteIndex:p,count:x})).sort((p,x)=>x.count-p.count||p.paletteIndex-x.paletteIndex);h.push({regionId:d.regionId,regionIndex:d.regionIndex,totalCount:g,termCounts:b})}return{groups:h,inputPointCount:o,pointsInsideAnyRegion:f,unmatchedPointCount:Math.max(0,o-f)}}function ec({rendererRef:e,viewState:t,fitNonce:n,rotationResetNonce:r,pointPalette:i,pointSizeByZoom:o,pointStrokeScale:s,pointInnerFillOpacity:a,minZoom:l,maxZoom:u,viewTransition:f,zoomSnaps:c,zoomSnapFitAsMin:h,imageColorSettings:d,renderPointData:g,interactionLock:y,syncRegionLabelAutoLiftTarget:b}){m.useEffect(()=>{const p=e.current;!p||!t||p.isViewAnimating()||p.setViewState(t)},[t]),m.useEffect(()=>{const p=e.current;p&&p.fitToImage()},[n]),m.useEffect(()=>{const p=e.current;p&&p.resetRotation()},[r]),m.useEffect(()=>{const p=e.current;!p||!i||p.setPointPalette(i)},[i]),m.useEffect(()=>{const p=e.current;p&&p.setPointSizeByZoom(o)},[o]),m.useEffect(()=>{const p=e.current;p&&p.setPointStrokeScale(s)},[s]),m.useEffect(()=>{const p=e.current;p&&p.setPointInnerFillOpacity(a)},[a]),m.useEffect(()=>{const p=e.current;p&&b(p.getViewState().zoom)},[b,l,u]),m.useEffect(()=>{const p=e.current;p&&(p.setZoomRange(l,u),b(p.getViewState().zoom))},[l,u,b]),m.useEffect(()=>{const p=e.current;p&&p.setViewTransition(f)},[f]),m.useEffect(()=>{const p=e.current;p&&p.setZoomSnaps(c,h)},[c,h]),m.useEffect(()=>{const p=e.current;p&&p.setImageColorSettings(d)},[d]),m.useEffect(()=>{const p=e.current;p&&p.setPointData(g)},[g]),m.useEffect(()=>{const p=e.current;p&&p.setInteractionLock(y)},[y])}const In=[],tc=[];function nc({source:e,viewState:t,imageColorSettings:n=null,onViewStateChange:r,onStats:i,onTileError:o,onContextLost:s,onContextRestored:a,debugOverlay:l=!1,debugOverlayStyle:u,fitNonce:f=0,rotationResetNonce:c=0,authToken:h="",ctrlDragRotate:d=!0,pointData:g=null,pointPalette:y=null,pointSizeByZoom:b,pointStrokeScale:p,pointInnerFillOpacity:x,minZoom:C,maxZoom:E,viewTransition:A,roiRegions:T,roiPolygons:W,clipPointsToRois:U=!1,clipMode:q="worker",onClipStats:H,onRoiPointGroups:X,roiPaletteIndexToTermId:$,interactionLock:I=!1,drawTool:k="cursor",stampOptions:B,brushOptions:_,drawFillColor:J,regionStrokeStyle:_e,regionStrokeHoverStyle:ce,regionStrokeActiveStyle:ke,patchStrokeStyle:Ie,resolveRegionStrokeStyle:Ce,resolveRegionLabelStyle:M,overlayShapes:v,customLayers:O,patchRegions:V,regionLabelStyle:z,regionLabelAnchor:ee="top-center",drawAreaTooltip:K,autoLiftRegionLabelAtMaxZoom:ie=!1,clampRegionLabelToViewport:G=!0,onPointerWorldMove:ue,onPointHover:ye,onPointClick:fe,onRegionHover:ne,onRegionClick:me,activeRegionId:Z,onActiveRegionChange:Ae,getCellByCoordinatesRef:Se,onDrawComplete:ae,onPatchComplete:ve,zoomSnaps:Ee,zoomSnapFitAsMin:be,overviewMapConfig:L,className:re,style:he}){const D=L?.show??!1,we=L?.options,de=m.useRef(null),ge=m.useRef(null),Fe=m.useRef(null),je=m.useRef(null),qe=m.useRef(r),zt=m.useRef(i),Dt=m.useRef(o),St=m.useRef(s),Ut=m.useRef(a),w=m.useRef(l),[S,P]=m.useState(null),[F,Q]=m.useState(()=>Z??null),xe=Z!==void 0,j=xe?Z??null:F,[pe,Re]=m.useState(null),[oe,Le]=m.useState(null),Pe=m.useRef(null),Ve=T??In,dt=V??In,tt=W??tc,nt=(O?.length??0)>0,pn=m.useMemo(()=>({position:"relative",width:"100%",height:"100%",...he}),[he]),Et=m.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)",...u}),[u]),Ke=m.useMemo(()=>Ve.length>0?Ve:tt.length===0?In:tt.map((N,te)=>({id:te,coordinates:N})),[Ve,tt]),rt=m.useMemo(()=>qi(Ke,ee),[Ke,ee]),tr=m.useMemo(()=>mn(z),[z]),{regionLabelAutoLiftOffsetPx:yn,syncRegionLabelAutoLiftTarget:Rt,cancelRegionLabelAutoLiftAnimation:nr,applyRegionLabelAutoLiftOffset:rr}=Gi(ie,ge,Fe),Ot=Yi(U,q,g,Ke,H),{getCellByCoordinates:ir,emitPointHover:mt,emitPointClick:Yt}=Vi(Ot,e,ye,fe,Se,k,ge);m.useEffect(()=>{xe&&Q(Z??null)},[xe,Z]);const it=m.useCallback(N=>{String(j)!==String(N)&&(xe||Q(N),Ae?.(N))},[j,xe,Ae]);m.useEffect(()=>{qe.current=r},[r]),m.useEffect(()=>{zt.current=i},[i]),m.useEffect(()=>{Dt.current=o},[o]),m.useEffect(()=>{St.current=s},[s]),m.useEffect(()=>{Ut.current=a},[a]),m.useEffect(()=>{w.current=l,l||Le(null)},[l]);const or=m.useCallback(N=>{zt.current?.(N),w.current&&Le(N)},[]),eo=m.useMemo(()=>oe?[`tier ${oe.tier} | frame ${oe.frameMs?.toFixed(2)??"-"} ms | drawCalls ${oe.drawCalls??"-"}`,`tiles visible ${oe.visible} | rendered ${oe.rendered} | fallback ${oe.fallback}`,`cache size ${oe.cache} | hit ${oe.cacheHits??"-"} | miss ${oe.cacheMisses??"-"}`,`queue inflight ${oe.inflight} | queued ${oe.queued??"-"} | retries ${oe.retries??"-"} | failed ${oe.failed??"-"} | aborted ${oe.aborted??"-"}`,`points ${oe.points}`].join(`
|
|
164
|
-
`):"stats: waiting for first frame...",[oe]);m.useEffect(()=>{!(j===null?!0:Ke.some((se,Te)=>String(kt(se,Te))===String(j)))&&j!==null&&it(null);const te=Pe.current;!(te===null?!0:Ke.some((se,Te)=>String(kt(se,Te))===String(te)))&&te!==null&&(Pe.current=null,P(null),ne?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[Ke,j,ne,it]);const sr=m.useCallback(N=>{Rt(N.zoom),nt&&Re(N);const te=qe.current;te&&te(N),Fe.current?.(),je.current?.()},[nt,Rt]);m.useEffect(()=>{k!=="cursor"&&Pe.current!==null&&(Pe.current=null,P(null),ne?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[k,ne]);const ot=m.useCallback((N,te)=>{const le=ge.current;if(!le)return null;const se=le.screenToWorld(N,te);if(!Array.isArray(se)||se.length<2)return null;const Te=Number(se[0]),Ne=Number(se[1]);return!Number.isFinite(Te)||!Number.isFinite(Ne)?null:[Te,Ne]},[]),ar=m.useCallback((N,te)=>{const le=ge.current;if(!le)return null;const se=le.worldToScreen(N,te);return Tt(se)},[]),Wt=m.useCallback((N,te)=>{const le=de.current;if(!le)return null;const se=le.getBoundingClientRect();if(!Number.isFinite(se.width)||!Number.isFinite(se.height)||se.width<=0||se.height<=0)return null;const Te=N-se.left,Ne=te-se.top;return!Number.isFinite(Te)||!Number.isFinite(Ne)?null:{screenCoord:[Te,Ne],canvasWidth:Math.max(1,se.width),canvasHeight:Math.max(1,se.height)}},[]),gt=m.useCallback((N,te,le,se)=>{const Te=ge.current;return Te?Ga(N,te,rt,Te,tr,M,yn,le,se,G):null},[rt,tr,M,yn,G]),lr=m.useCallback(()=>{ge.current?.requestRender(),Fe.current?.(),je.current?.()},[]),cr=m.useMemo(()=>pe??ge.current?.getViewState()??null,[pe]),ur=m.useMemo(()=>{if(!e)return null;const N=cr;return N?{source:e,viewState:N,drawTool:k,interactionLock:I,worldToScreen:ar,screenToWorld:ot,requestRedraw:lr}:null},[e,cr,k,I,ar,ot,lr]),to=m.useCallback(N=>{const te=N.target===de.current,le=ot(N.clientX,N.clientY);if(ue){const so=!!le&&le[0]>=0&&le[1]>=0&&!!e&&le[0]<=e.width&&le[1]<=e.height;ue({coordinate:le,clientX:N.clientX,clientY:N.clientY,insideImage:so})}if(k!=="cursor")return;if(!te){mt(null,null),Pe.current!==null&&(Pe.current=null,P(null),ne?.({region:null,regionId:null,regionIndex:-1,coordinate:null}));return}if(!le){mt(null,null);return}if(ye&&mt(ir(le),le),!rt.length)return;const se=Wt(N.clientX,N.clientY);if(!se)return;const Te=gt(le,se.screenCoord,se.canvasWidth,se.canvasHeight),Ne=Te?.regionId??null,bn=Pe.current;String(bn)!==String(Ne)&&(Pe.current=Ne,P(Ne),ne?.({region:Te?.region??null,regionId:Ne,regionIndex:Te?.regionIndex??-1,coordinate:le}))},[k,rt,ot,ne,ue,e,mt,ir,ye,Wt,gt]),no=m.useCallback(()=>{ue?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1}),mt(null,null),Pe.current!==null&&(Pe.current=null,P(null),ne?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[ne,ue,mt]),ro=m.useCallback(N=>{if(k!=="cursor"||N.target!==de.current)return;const te=ot(N.clientX,N.clientY);if(!te)return;if(Yt(te,N.button),!rt.length){it(null);return}const le=Wt(N.clientX,N.clientY);if(!le)return;const se=gt(te,le.screenCoord,le.canvasWidth,le.canvasHeight);if(!se){it(null);return}const Te=j!==null&&String(j)===String(se.regionId)?null:se.regionId;it(Te),me?.({region:se.region,regionId:se.regionId,regionIndex:se.regionIndex,coordinate:te})},[k,rt,ot,me,j,it,Yt,Wt,gt]),io=m.useCallback(N=>{if(k!=="brush"||_?.clickSelectRoi!==!0||!rt.length)return!1;const te=ge.current,le=de.current;if(!te||!le)return!1;const se=le.getBoundingClientRect();if(se.width<=0||se.height<=0)return!1;const Te=Tt(te.worldToScreen(N[0],N[1]));if(!Te)return!1;const Ne=gt(N,Te,se.width,se.height);if(!Ne)return!1;const bn=j!==null&&String(j)===String(Ne.regionId)?null:Ne.regionId;return it(bn),me?.({region:Ne.region,regionId:Ne.regionId,regionIndex:Ne.regionIndex,coordinate:N}),!0},[k,_?.clickSelectRoi,rt,j,it,me,gt]),oo=m.useCallback(N=>{if(!fe||k!=="cursor"||N.target!==de.current)return;N.preventDefault();const te=ot(N.clientX,N.clientY);te&&Yt(te,N.button)},[k,ot,Yt,fe]);return m.useEffect(()=>{const N=de.current;if(!N||!e)return;const te=new er(N,e,{onViewStateChange:sr,onStats:or,onTileError:le=>{Dt.current?.(le)},onContextLost:()=>{St.current?.()},onContextRestored:()=>{Ut.current?.()},authToken:h,imageColorSettings:n,ctrlDragRotate:d,pointSizeByZoom:b,pointStrokeScale:p,pointInnerFillOpacity:x,minZoom:C,maxZoom:E,viewTransition:A,zoomSnaps:Ee,zoomSnapFitAsMin:be});return ge.current=te,t&&te.setViewState(t),Rt(te.getViewState().zoom),te.setInteractionLock(I),nt&&Re(te.getViewState()),()=>{nr(),rr(0),te.destroy(),ge.current=null}},[e,or,h,d,sr,nt,Rt,nr,rr]),ec({rendererRef:ge,viewState:t,fitNonce:f,rotationResetNonce:c,pointPalette:y,pointSizeByZoom:b,pointStrokeScale:p,pointInnerFillOpacity:x,minZoom:C,maxZoom:E,viewTransition:A,zoomSnaps:Ee,zoomSnapFitAsMin:be,imageColorSettings:n,renderPointData:Ot,interactionLock:I,syncRegionLabelAutoLiftTarget:Rt}),m.useEffect(()=>{if(!X)return;const te=Qi(U?Ot:g,Ke,{paletteIndexToTermId:$,includeEmptyRegions:!0});X(te)},[X,U,g,Ot,Ke,$]),Be.jsxs("div",{className:re,style:pn,onPointerMove:to,onPointerLeave:no,onClick:ro,onContextMenu:oo,children:[Be.jsx("canvas",{ref:de,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none",cursor:k==="cursor"&&S!==null?"pointer":I?"crosshair":"grab"}}),e&&ur&&Array.isArray(O)&&O.length>0?O.map((N,te)=>Be.jsx("div",{className:N.className,style:{position:"absolute",inset:0,zIndex:N.zIndex??3,pointerEvents:N.pointerEvents??"none",...N.style},children:N.render(ur)},N.id??te)):null,e?Be.jsx(Kn,{tool:k,enabled:k!=="cursor",imageWidth:e.width,imageHeight:e.height,imageMpp:e.mpp,imageZoom:e.maxTierZoom,stampOptions:B,brushOptions:_,drawFillColor:J,projectorRef:ge,onBrushTap:io,viewStateSignal:t,persistedRegions:Ke,patchRegions:dt,regionStrokeStyle:_e,regionStrokeHoverStyle:ce,regionStrokeActiveStyle:ke,patchStrokeStyle:Ie,resolveRegionStrokeStyle:Ce,resolveRegionLabelStyle:M,overlayShapes:v,hoveredRegionId:S,activeRegionId:j,regionLabelStyle:z,regionLabelAnchor:ee,drawAreaTooltip:K,autoLiftRegionLabelAtMaxZoom:ie,clampRegionLabelToViewport:G,regionLabelAutoLiftOffsetPx:yn,invalidateRef:Fe,onDrawComplete:ae,onPatchComplete:ve}):null,l?Be.jsx("pre",{"data-open-plant-debug-overlay":!0,style:Et,children:eo}):null,e&&D&&Be.jsx(Li,{source:e,projectorRef:ge,authToken:h,options:we,invalidateRef:je,className:L?.className,style:L?.style})]})}function fi(e,t,n,r){return[Math.min(e,n),Math.min(t,r),Math.max(e,n),Math.max(t,r)]}function hi(e,t){return!(e[2]<t[0]||e[0]>t[2]||e[3]<t[1]||e[1]>t[3])}class rc{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=fi(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),g=this.toCellY(c.minY),y=this.toCellY(c.maxY);for(let b=g;b<=y;b+=1)for(let p=h;p<=d;p+=1)this.buckets[b*this.gridSize+p].push(f)}}search(t){if(this.items.length===0)return[];if(!Array.isArray(t)||t.length<4)return[];const n=fi(t[0],t[1],t[2],t[3]);if(!hi(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];hi(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 ic(e){return new rc(e)}function oc(e){return e.replace(/^\s*SRID\s*=\s*\d+\s*;\s*/i,"")}function sc(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function ac(e){return e>="0"&&e<="9"}function di(e){return e==="+"||e==="-"||e==="."||ac(e)}class lc{constructor(t){R(this,"text");R(this,"index",0);this.text=oc(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=Ji(i);return s?{type:"Polygon",coordinates:s}:null}const o=uc(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()&&sc(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||!di(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(!di(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 cc(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 Ji(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(!cc(i))return null;r.push([i[0],i[1]])}t.push(r)}return t}function uc(e){if(!Array.isArray(e))return null;const t=[];for(const n of e){const r=Ji(n);if(!r)return null;t.push(r)}return t}function fc(e){return typeof e!="string"?null:new lc(e).parse()}exports.DEFAULT_POINT_COLOR=Vn;exports.DrawLayer=Kn;exports.DrawingLayer=sa;exports.M1TileRenderer=gi;exports.OverlayLayer=aa;exports.OverviewMap=Li;exports.PatchLayer=ma;exports.PointLayer=za;exports.RegionLayer=$a;exports.TileScheduler=Hi;exports.TileViewerCanvas=Za;exports.WsiTileRenderer=er;exports.WsiViewer=$l;exports.WsiViewerCanvas=nc;exports.buildPointSpatialIndexAsync=Xi;exports.buildTermPalette=Vo;exports.calcScaleLength=Wo;exports.calcScaleResolution=Gn;exports.clamp=Y;exports.closeRing=Ye;exports.computeRoiPointGroups=Qi;exports.createCircle=Bn;exports.createRectangle=fn;exports.createSpatialIndex=ic;exports.filterPointDataByPolygons=_t;exports.filterPointDataByPolygonsHybrid=Di;exports.filterPointDataByPolygonsInWorker=Oi;exports.filterPointIndicesByPolygons=Ni;exports.filterPointIndicesByPolygonsInWorker=Ma;exports.getWebGpuCapabilities=Sa;exports.hexToRgba=Si;exports.isSameViewState=Ln;exports.lookupCellIndex=Wi;exports.normalizeImageInfo=ca;exports.parseWkt=fc;exports.prefilterPointsByBoundsWebGpu=zi;exports.terminatePointHitIndexWorker=ka;exports.terminateRoiClipWorker=Ra;exports.toBearerToken=Xo;exports.toRoiGeometry=Nt;exports.toTileUrl=Qn;exports.useViewerContext=xt;
|
|
162
|
+
}`),i=_e(e,r,"uCamera"),o=_e(e,r,"uPointSize"),s=_e(e,r,"uPointStrokeScale"),a=_e(e,r,"uPointInnerFillAlpha"),c=_e(e,r,"uPalette"),u=_e(e,r,"uPaletteSize"),h=e.createVertexArray(),l=e.createBuffer(),f=e.createBuffer(),d=e.createBuffer(),m=e.createBuffer(),p=e.createTexture();if(!h||!l||!f||!d||!m||!p)throw new Error("point buffer allocation failed");e.bindVertexArray(h),e.bindBuffer(e.ARRAY_BUFFER,l),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,f),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:h,posBuffer:l,termBuffer:f,fillModeBuffer:d,indexBuffer:m,paletteTexture:p,uCamera:i,uPointSize:o,uPointStrokeScale:s,uPointInnerFillAlpha:a,uPalette:c,uPaletteSize:u}}function gi(e){e.animation=null,e.frame!==null&&(cancelAnimationFrame(e.frame),e.frame=null)}function rl(e){const{state:t,camera:n,target:r,durationMs:i,easing:o,onUpdate:s}=e,a=n.getViewState();gi(t),t.animation={startMs:be(),durationMs:Math.max(0,i),from:a,to:r,easing:o};const c=()=>{const u=t.animation;if(!u)return;const h=Math.max(0,be()-u.startMs),l=u.durationMs<=0?1:W(h/u.durationMs,0,1);let f=l;try{f=u.easing(l)}catch{f=l}if(Number.isFinite(f)||(f=l),f=W(f,0,1),n.setViewState({zoom:u.from.zoom+(u.to.zoom-u.from.zoom)*f,offsetX:u.from.offsetX+(u.to.offsetX-u.from.offsetX)*f,offsetY:u.from.offsetY+(u.to.offsetY-u.from.offsetY)*f,rotationDeg:u.from.rotationDeg+(u.to.rotationDeg-u.from.rotationDeg)*f}),s(),l>=1){t.animation=null,t.frame=null;return}t.frame=requestAnimationFrame(c)};t.frame=requestAnimationFrame(c)}function il(e){const t=Math.max(e*.5,1e-6),n=Math.max(1,e*8);return{minZoom:t,maxZoom:Math.max(t,n)}}function ol(e,t,n){const r=il(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 sl(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 Tr(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),c=t/a,u=n/a;return{fitZoom:s,target:{zoom:a,offsetX:(e.width-c)*.5,offsetY:(e.height-u)*.5,rotationDeg:0}}}function al(e,t,n,r,i,o){const s=e.getViewState(),a=W(s.zoom*r,t,n);if(a===s.zoom)return null;const[c,u]=e.screenToWorld(i,o),h=e.getViewportSize(),l=i-h.width*.5,f=o-h.height*.5,d=Vt(s.rotationDeg),m=Math.cos(d),p=Math.sin(d),y=l/a*m-f/a*p,b=l/a*p+f/a*m,x=c-y,C=u-b;return{zoom:a,offsetX:x-h.width/(2*a),offsetY:C-h.height/(2*a)}}function ll(e,t,n,r,i,o){const s=e.getViewState(),a=W(r,t,n);if(a===s.zoom)return null;const[c,u]=e.screenToWorld(i,o),h=e.getViewportSize(),l=i-h.width*.5,f=o-h.height*.5,d=Vt(s.rotationDeg),m=Math.cos(d),p=Math.sin(d),y=l/a*m-f/a*p,b=l/a*p+f/a*m,x=c-y,C=u-b;return{zoom:a,offsetX:x-h.width/(2*a),offsetY:C-h.height/(2*a)}}const Ir=250;function _r(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 cl(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 Fr(e,t,n,r,i){const o=e.camera.getViewState(),[s,a]=e.camera.screenToWorld(n,r),c=e.camera.getViewportSize(),u=W(t,e.minZoom,e.maxZoom);if(u===o.zoom)return;const h=Vt(o.rotationDeg),l=Math.cos(h),f=Math.sin(h),d=n-c.width*.5,m=r-c.height*.5;e.cancelViewAnimation();const p=x=>{const C=d/x*l-m/x*f,S=d/x*f+m/x*l;return{offsetX:s-C-c.width/(2*x),offsetY:a-S-c.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:In};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),I=o.zoom+(u-o.zoom)*A,{offsetX:O,offsetY:z}=p(I);e.camera.setViewState({zoom:I,offsetX:O,offsetY:z,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 pi{constructor(t,n,r={}){R(this,"canvas");R(this,"source");R(this,"gl");R(this,"camera",new Br);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",In);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});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=Tt(r.minZoom),this.maxZoomOverride=Tt(r.maxZoom),this.viewTransitionDurationMs=en(r.viewTransition?.duration),this.viewTransitionEasing=tn(r.viewTransition?.easing),this.zoomSnaps=_r(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=Pr(this.gl),this.tileScheduler=new fi({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)=>Za({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,c)=>{this.onTileError?.({tile:s,error:a,attemptCount:c}),console.warn("tile load failed",s.url,a)}}),this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(t);const o=Ga({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,c)=>this.zoomBy(s,a,c),getUseZoomSnaps:()=>this.zoomSnaps.length>0,onSnapZoom:(s,a,c)=>this.handleSnapZoom(s,a,c),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),ma(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=ol(this.fitZoom,this.minZoomOverride,this.maxZoomOverride);this.minZoom=t.minZoom,this.maxZoom=t.maxZoom}resolveTargetViewState(t){return sl(this.camera,this.minZoom,this.maxZoom,t,()=>kt(this.camera,this.source))}cancelViewAnimation(){gi(this.viewAnimationState)}startViewAnimation(t,n,r){rl({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=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();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=el(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,t);this.applyPointBufferRuntime(n),!(!t||t.length===0)&&this.requestRender()}setPointData(t){const n=tl(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);Aa(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(){Va(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=va(n,this.pointSizeStops);return W(r,gn,ya)}fitToImage(t){const n=this.canvas.getBoundingClientRect(),r=Math.max(1,n.width||1),i=Math.max(1,n.height||1),o=Tr(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=al(this.camera,this.minZoom,this.maxZoom,t,n,r);o&&this.setViewState(o,i)}zoomTo(t,n,r,i){const o=ll(this.camera,this.minZoom,this.maxZoom,t,n,r);o&&this.setViewState(o,i)}setZoomSnaps(t,n){this.zoomSnaps=_r(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.zoomSnaps.filter(s=>s>=this.minZoom&&s<=this.maxZoom),o=cl(i,this.camera.getViewState().zoom,t,this.zoomSnapFitAsMin);if(o){if(o.type==="fit"){const s=this.canvas.getBoundingClientRect(),a=Math.max(1,s.width||1),c=Math.max(1,s.height||1),u=Tr(this.source,a,c,this.minZoom,this.maxZoom);this.fitZoom=u.fitZoom,this.applyZoomBounds(),Fr(this.getZoomPivotAnimationContext(),u.target.zoom,n,r,Ir);return}Fr(this.getZoomPivotAnimationContext(),o.zoom,n,r,Ir)}}render(){if(this.destroyed||this.contextLost||this.gl.isContextLost())return;const t=this.onStats?be():0;this.frameSerial+=1;const n=nl({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:()=>Da(this.camera,this.source),getVisibleTilesForTier:r=>mi(this.camera,this.source,r),getViewBounds:()=>Xt(this.camera),intersectsBounds:za});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(){pa(this.canvas,this.gl,this.camera),this.requestRender()}onWebGlContextLost(t){const n=Ka({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=Pr(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=ja({destroyed:this.destroyed,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),resizeObserver:this.resizeObserver,removeCanvasEventListeners:()=>ga(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 ul=[];function fl({source:e,viewState:t,onViewStateChange:n,onStats:r,onTileError:i,onContextLost:o,onContextRestored:s,imageColorSettings:a=null,fitNonce:c=0,rotationResetNonce:u=0,authToken:h="",ctrlDragRotate:l=!0,minZoom:f,maxZoom:d,viewTransition:m,zoomSnaps:p,zoomSnapFitAsMin:y,onPointerWorldMove:b,debugOverlay:x=!1,debugOverlayStyle:C,className:S,style:A,children:I}){const O=g.useRef(null),z=g.useRef(null),G=g.useRef(null),D=g.useRef(null),q=g.useRef(null),re=g.useRef(null),P=g.useRef(ul),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=P.current;for(let ze=0;ze<ue.length;ze+=1)Y.save(),ue[ze].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=P.current.filter(L=>L.id!==_);oe.push({id:_,priority:Y,draw:J}),oe.sort((L,K)=>L.priority-K.priority),P.current=oe,$()},[$]),ye=g.useCallback(_=>{P.current=P.current.filter(Y=>Y.id!==_),$()},[$]),U=g.useCallback((_,Y)=>{Y?N.current.add(_):N.current.delete(_),D.current?.setInteractionLock(N.current.size>0)},[]),V=g.useCallback(()=>N.current.size>0,[]),ee=g.useCallback((_,Y)=>{const J=D.current;return J?En(J.worldToScreen(_,Y)):null},[]),B=g.useCallback((_,Y)=>{const J=D.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 _=z.current;if(!_||!e)return;const Y=new pi(_,e,{onViewStateChange:te,onStats:ie,onTileError:J=>{we.current?.(J)},onContextLost:()=>{se.current?.()},onContextRestored:()=>{Re.current?.()},authToken:h,imageColorSettings:a,ctrlDragRotate:l,minZoom:f,maxZoom:d,viewTransition:m,zoomSnaps:p,zoomSnapFitAsMin:y});return D.current=Y,xe(J=>J+1),t&&Y.setViewState(t),Y.setInteractionLock(N.current.size>0),()=>{Y.destroy(),D.current=null}},[e,ie,l,te]),g.useEffect(()=>{D.current?.setAuthToken(h)},[h]),g.useEffect(()=>{const _=D.current;!_||!t||_.isViewAnimating()||_.setViewState(t)},[t]),g.useEffect(()=>{D.current?.fitToImage()},[c]),g.useEffect(()=>{D.current?.resetRotation()},[u]),g.useEffect(()=>{D.current?.setZoomRange(f,d)},[f,d]),g.useEffect(()=>{D.current?.setViewTransition(m)},[m]),g.useEffect(()=>{D.current?.setZoomSnaps(p,y)},[p,y]),g.useEffect(()=>{D.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:D,rendererSerial:Ce,canvasRef:z,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(bs,{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:z,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"}}),I,x&&Ye.jsx("pre",{"data-open-plant-debug-overlay":!0,style:Q,children:he})]})})}function hl(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,c=-1/0,u=-1/0;for(const h of i)o+=h.area,h.minX<s&&(s=h.minX),h.minY<a&&(a=h.minY),h.maxX>c&&(c=h.maxX),h.maxY>u&&(u=h.maxY);!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(c)||!Number.isFinite(u)||t.push({regionId:r.id??n,regionIndex:n,polygons:i,area:Math.max(1e-6,o),minX:s,minY:a,maxX:c,maxY:u})}return t}const dl=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 ml(e){if(e.length===0)return null;let t=1/0,n=1/0,r=-1/0,i=-1/0;for(const h of e)h.minX<t&&(t=h.minX),h.minY<n&&(n=h.minY),h.maxX>r&&(r=h.maxX),h.maxY>i&&(i=h.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(dl,o)),a=r>t?(r-t)/s:1,c=i>n?(i-n)/s:1,u=Array.from({length:s*s},()=>[]);for(let h=0;h<e.length;h+=1){const l=e[h],f=rt(l.minX,t,r,a,s),d=rt(l.maxX,t,r,a,s),m=rt(l.minY,n,i,c,s),p=rt(l.maxY,n,i,c,s);for(let y=m;y<=p;y+=1)for(let b=f;b<=d;b+=1)u[y*s+b].push(h)}return{minX:t,minY:n,maxX:r,maxY:i,gridSize:s,cellWidth:a,cellHeight:c,buckets:u}}function gl(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 pl(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 yl(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=hl(t??[]);if(!e||o===0||s.length===0)return{groups:[],inputPointCount:o,pointsInsideAnyRegion:0,unmatchedPointCount:o};const a=new Map,c=new Map,u=ml(s);let h=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=gl(u,p,y);if(x.length===0)continue;for(const A of x){const I=s[A];let O=!1;for(const z of I.polygons)if(Wr(p,y,z)){O=!0;break}O&&(!b||I.area<b.area)&&(b=I)}if(!b)continue;h+=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),c.set(b.regionIndex,(c.get(b.regionIndex)??0)+1)}const l=n.includeEmptyRegions??!1,f=[];for(const d of s){const m=c.get(d.regionIndex)??0;if(!l&&m<=0)continue;const p=a.get(d.regionIndex)??new Map,y=Array.from(p.entries()).map(([b,x])=>({termId:pl(b,n.paletteIndexToTermId),paletteIndex:b,count:x})).sort((b,x)=>x.count-b.count||b.paletteIndex-x.paletteIndex);f.push({regionId:d.regionId,regionIndex:d.regionIndex,totalCount:m,termCounts:y})}return{groups:f,inputPointCount:o,pointsInsideAnyRegion:h,unmatchedPointCount:Math.max(0,o-h)}}function Lr(e,t,n,r){return[Math.min(e,n),Math.min(t,r),Math.max(e,n),Math.max(t,r)]}function kr(e,t){return!(e[2]<t[0]||e[0]>t[2]||e[3]<t[1]||e[1]>t[3])}class bl{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 h of t){if(!h||!Number.isFinite(h.minX)||!Number.isFinite(h.minY)||!Number.isFinite(h.maxX)||!Number.isFinite(h.maxY))continue;const l=Lr(h.minX,h.minY,h.maxX,h.maxY);r=Math.min(r,l[0]),i=Math.min(i,l[1]),o=Math.max(o,l[2]),s=Math.max(s,l[3]),n.push({minX:l[0],minY:l[1],maxX:l[2],maxY:l[3],value:h.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),c=Math.max(0,s-i);this.cellWidth=a>0?a/this.gridSize:1,this.cellHeight=c>0?c/this.gridSize:1;const u=this.gridSize*this.gridSize;this.buckets=Array.from({length:u},()=>[]);for(let h=0;h<n.length;h+=1){const l=n[h],f=this.toCellX(l.minX),d=this.toCellX(l.maxX),m=this.toCellY(l.minY),p=this.toCellY(l.maxY);for(let y=m;y<=p;y+=1)for(let b=f;b<=d;b+=1)this.buckets[y*this.gridSize+b].push(h)}}search(t){if(this.items.length===0)return[];if(!Array.isArray(t)||t.length<4)return[];const n=Lr(t[0],t[1],t[2],t[3]);if(!kr(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(),c=[];for(let u=o;u<=s;u+=1)for(let h=r;h<=i;h+=1){const l=this.buckets[u*this.gridSize+h];if(!(!l||l.length===0))for(const f of l){if(this.visited[f]===a)continue;this.visited[f]=a;const d=this.items[f];kr(n,[d.minX,d.minY,d.maxX,d.maxY])&&c.push(d)}}return c}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 wl(e){return new bl(e)}function xl(e){return e.replace(/^\s*SRID\s*=\s*\d+\s*;\s*/i,"")}function Sl(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function El(e){return e>="0"&&e<="9"}function Nr(e){return e==="+"||e==="-"||e==="."||El(e)}class Rl{constructor(t){R(this,"text");R(this,"index",0);this.text=xl(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=yi(i);return s?{type:"Polygon",coordinates:s}:null}const o=Al(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()&&Sl(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||!Nr(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(!Nr(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 Ml(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 yi(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(!Ml(i))return null;r.push([i[0],i[1]])}t.push(r)}return t}function Al(e){if(!Array.isArray(e))return null;const t=[];for(const n of e){const r=yi(n);if(!r)return null;t.push(r)}return t}function vl(e){return typeof e!="string"?null:new Rl(e).parse()}exports.DEFAULT_POINT_COLOR=xn;exports.DrawLayer=ei;exports.DrawingLayer=ws;exports.M1TileRenderer=zr;exports.OverlayLayer=xs;exports.OverviewMap=vs;exports.PatchLayer=Ps;exports.PointLayer=Js;exports.RegionLayer=fa;exports.TileScheduler=fi;exports.TileViewerCanvas=ha;exports.WsiTileRenderer=pi;exports.WsiViewer=fl;exports.buildPointSpatialIndexAsync=ui;exports.buildTermPalette=no;exports.calcScaleLength=eo;exports.calcScaleResolution=Sn;exports.clamp=W;exports.closeRing=Fe;exports.computeRoiPointGroups=yl;exports.createCircle=fn;exports.createRectangle=Yt;exports.createSpatialIndex=wl;exports.filterPointDataByPolygons=dt;exports.filterPointDataByPolygonsHybrid=si;exports.filterPointDataByPolygonsInWorker=li;exports.filterPointIndicesByPolygons=ri;exports.filterPointIndicesByPolygonsInWorker=Ds;exports.getWebGpuCapabilities=Ns;exports.hexToRgba=Xr;exports.isSameViewState=cn;exports.lookupCellIndex=ci;exports.normalizeImageInfo=Es;exports.parseWkt=vl;exports.prefilterPointsByBoundsWebGpu=oi;exports.terminatePointHitIndexWorker=Zs;exports.terminateRoiClipWorker=zs;exports.toBearerToken=to;exports.toRoiGeometry=pt;exports.toTileUrl=Tn;exports.useViewerContext=ot;
|
|
165
164
|
//# sourceMappingURL=index.cjs.map
|