open-plant 1.4.8 → 1.4.9
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 +8 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1248 -1232
- package/dist/index.js.map +1 -1
- package/dist/types/react/wsi-viewer.d.ts +5 -1
- package/dist/types/react/wsi-viewer.d.ts.map +1 -1
- package/dist/types/wsi/wsi-input-handlers.d.ts +4 -0
- package/dist/types/wsi/wsi-input-handlers.d.ts.map +1 -1
- package/dist/types/wsi/wsi-renderer-types.d.ts +4 -0
- package/dist/types/wsi/wsi-renderer-types.d.ts.map +1 -1
- package/dist/types/wsi/wsi-tile-renderer.d.ts +7 -0
- package/dist/types/wsi/wsi-tile-renderer.d.ts.map +1 -1
- package/dist/types/wsi/wsi-tile-visibility.d.ts +1 -1
- package/dist/types/wsi/wsi-tile-visibility.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var qi=Object.defineProperty;var Zi=(t,e,n)=>e in t?qi(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var S=(t,e,n)=>Zi(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ye=require("react/jsx-runtime"),p=require("react");var
|
|
1
|
+
"use strict";var qi=Object.defineProperty;var Zi=(t,e,n)=>e in t?qi(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var S=(t,e,n)=>Zi(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ye=require("react/jsx-runtime"),p=require("react");var ct=typeof document<"u"?document.currentScript:null;function Xn(t,e,n){const r=t.createShader(e);if(!r)throw new Error("Failed to create shader.");if(t.shaderSource(r,n),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const o=t.getShaderInfoLog(r)??"unknown shader error";throw t.deleteShader(r),new Error(o)}return r}function pt(t,e,n){const r=Xn(t,t.VERTEX_SHADER,e),i=Xn(t,t.FRAGMENT_SHADER,n),o=t.createProgram();if(!o)throw t.deleteShader(r),t.deleteShader(i),new Error("Failed to create program.");if(t.attachShader(o,r),t.attachShader(o,i),t.linkProgram(o),t.deleteShader(r),t.deleteShader(i),!t.getProgramParameter(o,t.LINK_STATUS)){const a=t.getProgramInfoLog(o)??"unknown link error";throw t.deleteProgram(o),new Error(a)}return o}function Fe(t,e,n){const r=t.getUniformLocation(e,n);if(!r)throw new Error(`Failed to get uniform location: ${n}`);return r}function $i(t){const e=t.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,stencil:!1,preserveDrawingBuffer:!1,powerPreference:"high-performance"});if(!e)throw new Error("WebGL2 is not available.");return e}function tn(t){return t*Math.PI/180}class $r{constructor(){S(this,"viewportWidth",1);S(this,"viewportHeight",1);S(this,"viewState",{offsetX:0,offsetY:0,zoom:1,rotationDeg:0})}setViewport(e,n){this.viewportWidth=Math.max(1,e),this.viewportHeight=Math.max(1,n)}getViewportSize(){return{width:this.viewportWidth,height:this.viewportHeight}}setViewState(e){e.offsetX!==void 0&&(this.viewState.offsetX=e.offsetX),e.offsetY!==void 0&&(this.viewState.offsetY=e.offsetY),e.zoom!==void 0&&(this.viewState.zoom=Math.max(1e-4,e.zoom)),typeof e.rotationDeg=="number"&&Number.isFinite(e.rotationDeg)&&(this.viewState.rotationDeg=e.rotationDeg)}getViewState(){return{...this.viewState}}getCenter(){const e=Math.max(1e-6,this.viewState.zoom);return[this.viewState.offsetX+this.viewportWidth/(2*e),this.viewState.offsetY+this.viewportHeight/(2*e)]}setCenter(e,n){const r=Math.max(1e-6,this.viewState.zoom);this.viewState.offsetX=e-this.viewportWidth/(2*r),this.viewState.offsetY=n-this.viewportHeight/(2*r)}screenToWorld(e,n){const r=Math.max(1e-6,this.viewState.zoom),[i,o]=this.getCenter(),s=this.viewState.rotationDeg??0,a=(e-this.viewportWidth*.5)/r,l=(n-this.viewportHeight*.5)/r,u=tn(s),f=Math.cos(u),c=Math.sin(u);return[i+a*f-l*c,o+a*c+l*f]}worldToScreen(e,n){const r=Math.max(1e-6,this.viewState.zoom),[i,o]=this.getCenter(),s=this.viewState.rotationDeg??0,a=e-i,l=n-o,u=tn(s),f=Math.cos(u),c=Math.sin(u),h=a*f+l*c,d=-a*c+l*f;return[this.viewportWidth*.5+h*r,this.viewportHeight*.5+d*r]}getViewCorners(){const e=this.viewportWidth,n=this.viewportHeight;return[this.screenToWorld(0,0),this.screenToWorld(e,0),this.screenToWorld(e,n),this.screenToWorld(0,n)]}getMatrix(){const e=Math.max(1e-6,this.viewState.zoom),n=this.viewState.rotationDeg??0;if(n===0){const m=this.viewportWidth/e,g=this.viewportHeight/e,y=2/m,b=-2/g,x=-1-this.viewState.offsetX*y,A=1-this.viewState.offsetY*b;return new Float32Array([y,0,0,0,b,0,x,A,1])}const[r,i]=this.getCenter(),o=tn(n),s=Math.cos(o),a=Math.sin(o),l=2*e*s/this.viewportWidth,u=2*e*a/this.viewportWidth,f=2*e*a/this.viewportHeight,c=-2*e*s/this.viewportHeight,h=-(l*r+u*i),d=-(f*r+c*i);return new Float32Array([l,f,0,u,c,0,h,d,1])}}const Ki=`#version 300 es
|
|
2
2
|
precision highp float;
|
|
3
3
|
|
|
4
4
|
in vec2 aUnit;
|
|
@@ -29,8 +29,8 @@ out vec4 outColor;
|
|
|
29
29
|
void main() {
|
|
30
30
|
outColor = texture(uTexture, vUv);
|
|
31
31
|
}
|
|
32
|
-
`;class Kr{constructor(e){S(this,"canvas");S(this,"gl");S(this,"camera",new $r);S(this,"imageWidth");S(this,"imageHeight");S(this,"clearColor");S(this,"program");S(this,"vao");S(this,"quadBuffer");S(this,"uCameraLocation");S(this,"uBoundsLocation");S(this,"uTextureLocation");S(this,"resizeObserver");S(this,"tiles",[]);S(this,"frameId",null);S(this,"loadVersion",0);S(this,"destroyed",!1);S(this,"fitted",!1);S(this,"controlledViewState",!1);this.canvas=e.canvas,this.imageWidth=Math.max(1,e.imageWidth),this.imageHeight=Math.max(1,e.imageHeight),this.clearColor=e.clearColor??[.03,.05,.08,1],this.gl=$i(this.canvas),this.program=
|
|
33
|
-
`);const o=e+(n?" ":"│ ");t.left&&fn(t.left,o,!1,r,i),t.right&&fn(t.right,o,!0,r,i)}}class vn{constructor(e=Qi){this._root=null,this._size=0,this._comparator=e}insert(e,n){return this._size++,this._root=nn(e,n,this._root,this._comparator)}add(e,n){const r=new et(e,n);this._root===null&&(r.left=r.right=null,this._size++,this._root=r);const i=this._comparator,o=je(e,this._root,i),s=i(e,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(e){this._root=this._remove(e,this._root,this._comparator)}_remove(e,n,r){let i;return n===null?null:(n=je(e,n,r),r(e,n.key)===0?(n.left===null?i=n.right:(i=je(e,n.left,r),i.right=n.right),this._size--,i):n)}pop(){let e=this._root;if(e){for(;e.left;)e=e.left;return this._root=je(e.key,this._root,this._comparator),this._root=this._remove(e.key,this._root,this._comparator),{key:e.key,data:e.data}}return null}findStatic(e){let n=this._root;const r=this._comparator;for(;n;){const i=r(e,n.key);if(i===0)return n;i<0?n=n.left:n=n.right}return null}find(e){return this._root&&(this._root=je(e,this._root,this._comparator),this._comparator(e,this._root.key)!==0)?null:this._root}contains(e){let n=this._root;const r=this._comparator;for(;n;){const i=r(e,n.key);if(i===0)return!0;i<0?n=n.left:n=n.right}return!1}forEach(e,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(),e.call(n,r),r=r.right):o=!0;return this}range(e,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,e)>=0&&r.call(i,a))return this;a=a.right}return this}keys(){const e=[];return this.forEach(({key:n})=>{e.push(n)}),e}values(){const e=[];return this.forEach(({data:n})=>{e.push(n)}),e}min(){return this._root?this.minNode(this._root).key:null}max(){return this._root?this.maxNode(this._root).key:null}minNode(e=this._root){if(e)for(;e.left;)e=e.left;return e}maxNode(e=this._root){if(e)for(;e.right;)e=e.right;return e}at(e){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===e)return n;i++,n=n.right}else r=!0;return null}next(e){let n=this._root,r=null;if(e.right){for(r=e.right;r.left;)r=r.left;return r}const i=this._comparator;for(;n;){const o=i(e.key,n.key);if(o===0)break;o<0?(r=n,n=n.left):n=n.right}return r}prev(e){let n=this._root,r=null;if(e.left!==null){for(r=e.left;r.right;)r=r.right;return r}const i=this._comparator;for(;n;){const o=i(e.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 to(this._root)}load(e,n=[],r=!1){let i=e.length;const o=this._comparator;if(r&&mn(e,n,0,i-1,o),this._root===null)this._root=hn(e,n,0,i),this._size=i;else{const s=no(this.toList(),eo(e,n),o);i=this._size+i,this._root=dn({head:s},0,i)}return this}isEmpty(){return this._root===null}get size(){return this._size}get root(){return this._root}toString(e=n=>String(n.key)){const n=[];return fn(this._root,"",!0,r=>n.push(r),e),n.join("")}update(e,n,r){const i=this._comparator;let{left:o,right:s}=Vn(e,this._root,i);i(e,n)<0?s=nn(n,r,s,i):o=nn(n,r,o,i),this._root=Ji(o,s,i)}split(e){return Vn(e,this._root,this._comparator)}*[Symbol.iterator](){let e=this._root;const n=[];let r=!1;for(;!r;)e!==null?(n.push(e),e=e.left):n.length!==0?(e=n.pop(),yield e,e=e.right):r=!0}}function hn(t,e,n,r){const i=r-n;if(i>0){const o=n+Math.floor(i/2),s=t[o],a=e[o],l=new et(s,a);return l.left=hn(t,e,n,o),l.right=hn(t,e,o+1,r),l}return null}function eo(t,e){const n=new et(null,null);let r=n;for(let i=0;i<t.length;i++)r=r.next=new et(t[i],e[i]);return r.next=null,n.next}function to(t){let e=t;const n=[];let r=!1;const i=new et(null,null);let o=i;for(;!r;)e?(n.push(e),e=e.left):n.length>0?(e=o=o.next=n.pop(),e=e.right):r=!0;return o.next=null,i.next}function dn(t,e,n){const r=n-e;if(r>0){const i=e+Math.floor(r/2),o=dn(t,e,i),s=t.head;return s.left=o,t.head=t.head.next,s.right=dn(t,i+1,n),s}return null}function no(t,e,n){const r=new et(null,null);let i=r,o=t,s=e;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 mn(t,e,n,r,i){if(n>=r)return;const o=t[n+r>>1];let s=n-1,a=r+1;for(;;){do s++;while(i(t[s],o)<0);do a--;while(i(t[a],o)>0);if(s>=a)break;let l=t[s];t[s]=t[a],t[a]=l,l=e[s],e[s]=e[a],e[a]=l}mn(t,e,n,a,i),mn(t,e,a+1,r,i)}const Ze=11102230246251565e-32,Pe=134217729,ro=(3+8*Ze)*Ze;function rn(t,e,n,r,i){let o,s,a,l,u=e[0],f=r[0],c=0,h=0;f>u==f>-u?(o=u,u=e[++c]):(o=f,f=r[++h]);let d=0;if(c<t&&h<n)for(f>u==f>-u?(s=u+o,a=o-(s-u),u=e[++c]):(s=f+o,a=o-(s-f),f=r[++h]),o=s,a!==0&&(i[d++]=a);c<t&&h<n;)f>u==f>-u?(s=o+u,l=s-o,a=o-(s-l)+(u-l),u=e[++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<t;)s=o+u,l=s-o,a=o-(s-l)+(u-l),u=e[++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 io(t,e){let n=e[0];for(let r=1;r<t;r++)n+=e[r];return n}function Rt(t){return new Float64Array(t)}const oo=(3+16*Ze)*Ze,so=(2+12*Ze)*Ze,ao=(9+64*Ze)*Ze*Ze,ot=Rt(4),Gn=Rt(8),Hn=Rt(12),qn=Rt(16),_e=Rt(4);function lo(t,e,n,r,i,o,s){let a,l,u,f,c,h,d,m,g,y,b,x,M,w,T,A,k,L;const W=t-i,D=n-i,G=e-o,U=r-o;w=W*U,h=Pe*W,d=h-(h-W),m=W-d,h=Pe*U,g=h-(h-U),y=U-g,T=m*y-(w-d*g-m*g-d*y),A=G*D,h=Pe*G,d=h-(h-G),m=G-d,h=Pe*D,g=h-(h-D),y=D-g,k=m*y-(A-d*g-m*g-d*y),b=T-k,c=T-b,ot[0]=T-(b+c)+(c-k),x=w+b,c=x-w,M=w-(x-c)+(b-c),b=M-A,c=M-b,ot[1]=M-(b+c)+(c-A),L=x+b,c=L-x,ot[2]=x-(L-c)+(b-c),ot[3]=L;let v=io(4,ot),Y=so*s;if(v>=Y||-v>=Y||(c=t-W,a=t-(W+c)+(c-i),c=n-D,u=n-(D+c)+(c-i),c=e-G,l=e-(G+c)+(c-o),c=r-U,f=r-(U+c)+(c-o),a===0&&l===0&&u===0&&f===0)||(Y=ao*s+ro*Math.abs(v),v+=W*f+U*a-(G*u+D*l),v>=Y||-v>=Y))return v;w=a*U,h=Pe*a,d=h-(h-a),m=a-d,h=Pe*U,g=h-(h-U),y=U-g,T=m*y-(w-d*g-m*g-d*y),A=l*D,h=Pe*l,d=h-(h-l),m=l-d,h=Pe*D,g=h-(h-D),y=D-g,k=m*y-(A-d*g-m*g-d*y),b=T-k,c=T-b,_e[0]=T-(b+c)+(c-k),x=w+b,c=x-w,M=w-(x-c)+(b-c),b=M-A,c=M-b,_e[1]=M-(b+c)+(c-A),L=x+b,c=L-x,_e[2]=x-(L-c)+(b-c),_e[3]=L;const B=rn(4,ot,4,_e,Gn);w=W*f,h=Pe*W,d=h-(h-W),m=W-d,h=Pe*f,g=h-(h-f),y=f-g,T=m*y-(w-d*g-m*g-d*y),A=G*u,h=Pe*G,d=h-(h-G),m=G-d,h=Pe*u,g=h-(h-u),y=u-g,k=m*y-(A-d*g-m*g-d*y),b=T-k,c=T-b,_e[0]=T-(b+c)+(c-k),x=w+b,c=x-w,M=w-(x-c)+(b-c),b=M-A,c=M-b,_e[1]=M-(b+c)+(c-A),L=x+b,c=L-x,_e[2]=x-(L-c)+(b-c),_e[3]=L;const z=rn(B,Gn,4,_e,Hn);w=a*f,h=Pe*a,d=h-(h-a),m=a-d,h=Pe*f,g=h-(h-f),y=f-g,T=m*y-(w-d*g-m*g-d*y),A=l*u,h=Pe*l,d=h-(h-l),m=l-d,h=Pe*u,g=h-(h-u),y=u-g,k=m*y-(A-d*g-m*g-d*y),b=T-k,c=T-b,_e[0]=T-(b+c)+(c-k),x=w+b,c=x-w,M=w-(x-c)+(b-c),b=M-A,c=M-b,_e[1]=M-(b+c)+(c-A),L=x+b,c=L-x,_e[2]=x-(L-c)+(b-c),_e[3]=L;const Z=rn(z,Hn,4,_e,qn);return qn[Z-1]}function co(t,e,n,r,i,o){const s=(e-o)*(n-i),a=(t-i)*(r-o),l=s-a,u=Math.abs(s+a);return Math.abs(l)>=oo*u?l:-lo(t,e,n,r,i,o,u)}const ft=(t,e)=>t.ll.x<=e.x&&e.x<=t.ur.x&&t.ll.y<=e.y&&e.y<=t.ur.y,gn=(t,e)=>{if(e.ur.x<t.ll.x||t.ur.x<e.ll.x||e.ur.y<t.ll.y||t.ur.y<e.ll.y)return null;const n=t.ll.x<e.ll.x?e.ll.x:t.ll.x,r=t.ur.x<e.ur.x?t.ur.x:e.ur.x,i=t.ll.y<e.ll.y?e.ll.y:t.ll.y,o=t.ur.y<e.ur.y?t.ur.y:e.ur.y;return{ll:{x:n,y:i},ur:{x:r,y:o}}};let Qe=Number.EPSILON;Qe===void 0&&(Qe=Math.pow(2,-52));const uo=Qe*Qe,Zn=(t,e)=>{if(-Qe<t&&t<Qe&&-Qe<e&&e<Qe)return 0;const n=t-e;return n*n<uo*t*e?0:t<e?-1:1};class fo{constructor(){this.reset()}reset(){this.xRounder=new $n,this.yRounder=new $n}round(e,n){return{x:this.xRounder.round(e),y:this.yRounder.round(n)}}}class $n{constructor(){this.tree=new vn,this.round(0)}round(e){const n=this.tree.add(e),r=this.tree.prev(n);if(r!==null&&Zn(n.key,r.key)===0)return this.tree.remove(e),r.key;const i=this.tree.next(n);return i!==null&&Zn(n.key,i.key)===0?(this.tree.remove(e),i.key):e}}const pt=new fo,kt=(t,e)=>t.x*e.y-t.y*e.x,jr=(t,e)=>t.x*e.x+t.y*e.y,Kn=(t,e,n)=>{const r=co(t.x,t.y,e.x,e.y,n.x,n.y);return r>0?-1:r<0?1:0},Yt=t=>Math.sqrt(jr(t,t)),ho=(t,e,n)=>{const r={x:e.x-t.x,y:e.y-t.y},i={x:n.x-t.x,y:n.y-t.y};return kt(i,r)/Yt(i)/Yt(r)},mo=(t,e,n)=>{const r={x:e.x-t.x,y:e.y-t.y},i={x:n.x-t.x,y:n.y-t.y};return jr(i,r)/Yt(i)/Yt(r)},jn=(t,e,n)=>e.y===0?null:{x:t.x+e.x/e.y*(n-t.y),y:n},Qn=(t,e,n)=>e.x===0?null:{x:n,y:t.y+e.y/e.x*(n-t.x)},go=(t,e,n,r)=>{if(e.x===0)return Qn(n,r,t.x);if(r.x===0)return Qn(t,e,n.x);if(e.y===0)return jn(n,r,t.y);if(r.y===0)return jn(t,e,n.y);const i=kt(e,r);if(i==0)return null;const o={x:n.x-t.x,y:n.y-t.y},s=kt(o,e)/i,a=kt(o,r)/i,l=t.x+a*e.x,u=n.x+s*r.x,f=t.y+a*e.y,c=n.y+s*r.y,h=(l+u)/2,d=(f+c)/2;return{x:h,y:d}};class Ue{static compare(e,n){const r=Ue.comparePoints(e.point,n.point);return r!==0?r:(e.point!==n.point&&e.link(n),e.isLeft!==n.isLeft?e.isLeft?1:-1:Je.compare(e.segment,n.segment))}static comparePoints(e,n){return e.x<n.x?-1:e.x>n.x?1:e.y<n.y?-1:e.y>n.y?1:0}constructor(e,n){e.events===void 0?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=n}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const n=e.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 e=this.point.events.length;for(let n=0;n<e;n++){const r=this.point.events[n];if(r.segment.consumedBy===void 0)for(let i=n+1;i<e;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 e=[];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()&&e.push(i)}return e}getLeftmostComparator(e){const n=new Map,r=i=>{const o=i.otherSE;n.set(i,{sine:ho(this.point,e.point,o.point),cosine:mo(this.point,e.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 po=0;class Je{static compare(e,n){const r=e.leftSE.point.x,i=n.leftSE.point.x,o=e.rightSE.point.x,s=n.rightSE.point.x;if(s<r)return 1;if(o<i)return-1;const a=e.leftSE.point.y,l=n.leftSE.point.y,u=e.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=e.comparePoint(n.leftSE.point);if(c<0)return 1;if(c>0)return-1;const h=n.comparePoint(e.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(e.leftSE.point);if(c!==0)return c;const h=e.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(e.rightSE.point);if(c!==0)return c}if(o>s){const c=e.comparePoint(n.rightSE.point);if(c<0)return 1;if(c>0)return-1}if(o!==s){const c=u-a,h=o-r,d=f-l,m=s-i;if(c>h&&d<m)return 1;if(c<h&&d>m)return-1}return o>s?1:o<s||u<f?-1:u>f?1:e.id<n.id?-1:e.id>n.id?1:0}constructor(e,n,r,i){this.id=++po,this.leftSE=e,e.segment=this,e.otherSE=n,this.rightSE=n,n.segment=this,n.otherSE=e,this.rings=r,this.windings=i}static fromRing(e,n,r){let i,o,s;const a=Ue.comparePoints(e,n);if(a<0)i=e,o=n,s=1;else if(a>0)i=n,o=e,s=-1;else throw new Error(`Tried to create degenerate segment at [${e.x}, ${e.y}]`);const l=new Ue(i,!0),u=new Ue(o,!1);return new Je(l,u,[r],[s])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,n=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e<n?e:n},ur:{x:this.rightSE.point.x,y:e>n?e:n}}}vector(){return{x:this.rightSE.point.x-this.leftSE.point.x,y:this.rightSE.point.y-this.leftSE.point.y}}isAnEndpoint(e){return e.x===this.leftSE.point.x&&e.y===this.leftSE.point.y||e.x===this.rightSE.point.x&&e.y===this.rightSE.point.y}comparePoint(e){if(this.isAnEndpoint(e))return 0;const n=this.leftSE.point,r=this.rightSE.point,i=this.vector();if(n.x===r.x)return e.x===n.x?0:e.x<n.x?1:-1;const o=(e.y-n.y)/i.y,s=n.x+o*i.x;if(e.x===s)return 0;const a=(e.x-n.x)/i.x,l=n.y+a*i.y;return e.y===l?0:e.y<l?-1:1}getIntersection(e){const n=this.bbox(),r=e.bbox(),i=gn(n,r);if(i===null)return null;const o=this.leftSE.point,s=this.rightSE.point,a=e.leftSE.point,l=e.rightSE.point,u=ft(n,a)&&this.comparePoint(a)===0,f=ft(r,o)&&e.comparePoint(o)===0,c=ft(n,l)&&this.comparePoint(l)===0,h=ft(r,s)&&e.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=go(o,this.vector(),a,e.vector());return d===null||!ft(i,d)?null:pt.round(d.x,d.y)}split(e){const n=[],r=e.events!==void 0,i=new Ue(e,!0),o=new Ue(e,!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 Ue.comparePoints(a.leftSE.point,a.rightSE.point)>0&&a.swapEvents(),Ue.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),r&&(i.checkForConsuming(),o.checkForConsuming()),n}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let n=0,r=this.windings.length;n<r;n++)this.windings[n]*=-1}consume(e){let n=this,r=e;for(;n.consumedBy;)n=n.consumedBy;for(;r.consumedBy;)r=r.consumedBy;const i=Je.compare(n,r);if(i!==0){if(i>0){const o=n;n=r,r=o}if(n.prev===r){const o=n;n=r,r=o}for(let o=0,s=r.rings.length;o<s;o++){const a=r.rings[o],l=r.windings[o],u=n.rings.indexOf(a);u===-1?(n.rings.push(a),n.windings.push(l)):n.windings[u]+=l}r.rings=null,r.windings=null,r.consumedBy=n,r.leftSE.consumedBy=n.leftSE,r.rightSE.consumedBy=n.rightSE}}prevInResult(){return this._prevInResult!==void 0?this._prevInResult:(this.prev?this.prev.isInResult()?this._prevInResult=this.prev:this._prevInResult=this.prev.prevInResult():this._prevInResult=null,this._prevInResult)}beforeState(){if(this._beforeState!==void 0)return this._beforeState;if(!this.prev)this._beforeState={rings:[],windings:[],multiPolys:[]};else{const e=this.prev.consumedBy||this.prev;this._beforeState=e.afterState()}return this._beforeState}afterState(){if(this._afterState!==void 0)return this._afterState;const e=this.beforeState();this._afterState={rings:e.rings.slice(0),windings:e.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 e=this.beforeState().multiPolys,n=this.afterState().multiPolys;switch(Xe.type){case"union":{const r=e.length===0,i=n.length===0;this._isInResult=r!==i;break}case"intersection":{let r,i;e.length<n.length?(r=e.length,i=n.length):(r=n.length,i=e.length),this._isInResult=i===Xe.numMultiPolys&&r<i;break}case"xor":{const r=Math.abs(e.length-n.length);this._isInResult=r%2===1;break}case"difference":{const r=i=>i.length===1&&i[0].isSubject;this._isInResult=r(e)!==r(n);break}default:throw new Error(`Unrecognized operation type found ${Xe.type}`)}return this._isInResult}}class Jn{constructor(e,n,r){if(!Array.isArray(e)||e.length===0)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=n,this.isExterior=r,this.segments=[],typeof e[0][0]!="number"||typeof e[0][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const i=pt.round(e[0][0],e[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=e.length;s<a;s++){if(typeof e[s][0]!="number"||typeof e[s][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");let l=pt.round(e[s][0],e[s][1]);l.x===o.x&&l.y===o.y||(this.segments.push(Je.fromRing(o,l,this)),l.x<this.bbox.ll.x&&(this.bbox.ll.x=l.x),l.y<this.bbox.ll.y&&(this.bbox.ll.y=l.y),l.x>this.bbox.ur.x&&(this.bbox.ur.x=l.x),l.y>this.bbox.ur.y&&(this.bbox.ur.y=l.y),o=l)}(i.x!==o.x||i.y!==o.y)&&this.segments.push(Je.fromRing(o,i,this))}getSweepEvents(){const e=[];for(let n=0,r=this.segments.length;n<r;n++){const i=this.segments[n];e.push(i.leftSE),e.push(i.rightSE)}return e}}class yo{constructor(e,n){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");this.exteriorRing=new Jn(e[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=e.length;r<i;r++){const o=new Jn(e[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 e=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++)e.push(i[o])}return e}}class er{constructor(e,n){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");try{typeof e[0][0][0]=="number"&&(e=[e])}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=e.length;r<i;r++){const o=new yo(e[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 e=[];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++)e.push(i[o])}return e}}class Xt{static factory(e){const n=[];for(let r=0,i=e.length;r<i;r++){const o=e[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 g=u[0].point,y=u[u.length-1].point;throw new Error(`Unable to complete output ring starting at [${g.x}, ${g.y}]. Last matching segment found ends at [${y.x}, ${y.y}].`)}if(h.length===1){l=h[0].otherSE;break}let d=null;for(let g=0,y=c.length;g<y;g++)if(c[g].point===a.point){d=g;break}if(d!==null){const g=c.splice(d)[0],y=u.splice(g.index);y.unshift(y[0].otherSE),n.push(new Xt(y.reverse()));continue}c.push({index:u.length,point:a.point});const m=a.getLeftmostComparator(s);l=h.sort(m)[0].otherSE;break}n.push(new Xt(u))}return n}constructor(e){this.events=e;for(let n=0,r=e.length;n<r;n++)e[n].segment.ringOut=this;this.poly=null}getGeom(){let e=this.events[0].point;const n=[e];for(let u=1,f=this.events.length-1;u<f;u++){const c=this.events[u].point,h=this.events[u+1].point;Kn(c,e,h)!==0&&(n.push(c),e=c)}if(n.length===1)return null;const r=n[0],i=n[1];Kn(r,e,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 e=this.enclosingRing();this._isExteriorRing=e?!e.isExteriorRing():!0}return this._isExteriorRing}enclosingRing(){return this._enclosingRing===void 0&&(this._enclosingRing=this._calcEnclosingRing()),this._enclosingRing}_calcEnclosingRing(){let e=this.events[0];for(let i=1,o=this.events.length;i<o;i++){const s=this.events[i];Ue.compare(e,s)>0&&(e=s)}let n=e.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 tr{constructor(e){this.exteriorRing=e,e.poly=this,this.interiorRings=[]}addInterior(e){this.interiorRings.push(e),e.poly=this}getGeom(){const e=[this.exteriorRing.getGeom()];if(e[0]===null)return null;for(let n=0,r=this.interiorRings.length;n<r;n++){const i=this.interiorRings[n].getGeom();i!==null&&e.push(i)}return e}}class bo{constructor(e){this.rings=e,this.polys=this._composePolys(e)}getGeom(){const e=[];for(let n=0,r=this.polys.length;n<r;n++){const i=this.polys[n].getGeom();i!==null&&e.push(i)}return e}_composePolys(e){const n=[];for(let r=0,i=e.length;r<i;r++){const o=e[r];if(!o.poly)if(o.isExteriorRing())n.push(new tr(o));else{const s=o.enclosingRing();s.poly||n.push(new tr(s)),s.poly.addInterior(o)}}return n}}class xo{constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Je.compare;this.queue=e,this.tree=new vn(n),this.segments=[]}process(e){const n=e.segment,r=[];if(e.consumedBy)return e.isLeft?this.queue.remove(e.otherSE):this.tree.remove(n),r;const i=e.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(e.isLeft){let u=null;if(a){const c=a.getIntersection(n);if(c!==null&&(n.isAnEndpoint(c)||(u=c),!a.isAnEndpoint(c))){const h=this._splitSafely(a,c);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}}let f=null;if(l){const c=l.getIntersection(n);if(c!==null&&(n.isAnEndpoint(c)||(f=c),!l.isAnEndpoint(c))){const h=this._splitSafely(l,c);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}}if(u!==null||f!==null){let c=null;u===null?c=f:f===null?c=u:c=Ue.comparePoints(u,f)<=0?u:f,this.queue.remove(n.rightSE),r.push(n.rightSE);const h=n.split(c);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}r.length>0?(this.tree.remove(n),r.push(e)):(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(e,n){this.tree.remove(e);const r=e.rightSE;this.queue.remove(r);const i=e.split(n);return i.push(r),e.consumedBy===void 0&&this.tree.add(e),i}}const nr=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_QUEUE_SIZE||1e6,wo=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS||1e6;class So{run(e,n,r){Xe.type=e,pt.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(Xe.numMultiPolys=i.length,Xe.type==="difference"){const c=i[0];let h=1;for(;h<i.length;)gn(i[h].bbox,c.bbox)!==null?h++:i.splice(h,1)}if(Xe.type==="intersection")for(let c=0,h=i.length;c<h;c++){const d=i[c];for(let m=c+1,g=i.length;m<g;m++)if(gn(d.bbox,i[m].bbox)===null)return[]}const o=new vn(Ue.compare);for(let c=0,h=i.length;c<h;c++){const d=i[c].getSweepEvents();for(let m=0,g=d.length;m<g;m++)if(o.insert(d[m]),o.size>nr)throw new Error("Infinite loop when putting segment endpoints in a priority queue (queue size too big).")}const s=new xo(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>nr)throw new Error("Infinite loop when passing sweep line over endpoints (queue size too big).");if(s.segments.length>wo)throw new Error("Infinite loop when passing sweep line over endpoints (too many sweep line segments).");const h=s.process(c);for(let d=0,m=h.length;d<m;d++){const g=h[d];g.consumedBy===void 0&&o.insert(g)}a=o.size,l=o.pop()}pt.reset();const u=Xt.factory(s.segments);return new bo(u).getGeom()}}const Xe=new So,Ro=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Xe.run("union",t,n)},Eo=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Xe.run("intersection",t,n)},Ao=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Xe.run("xor",t,n)},Mo=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Xe.run("difference",t,n)};var To={union:Ro,intersection:Eo,xor:Ao,difference:Mo};function ct(t){return t==null?null:Qr(t)||Jr(t)||Co(t)?t:null}function rr(t){return typeof t=="number"&&Number.isFinite(t)}function Ut(t){return Array.isArray(t)&&t.length>=2&&rr(t[0])&&rr(t[1])}function Qr(t){return Array.isArray(t)&&t.length>0&&t.every(e=>Ut(e))}function Jr(t){return Array.isArray(t)&&t.length>0&&t.every(e=>Qr(e))}function Co(t){return Array.isArray(t)&&t.length>0&&t.every(e=>Jr(e))}function Be(t){if(!Array.isArray(t)||t.length<3)return[];const e=[];for(const i of t){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=e[e.length-1];a&&a[0]===o&&a[1]===s||e.push([o,s])}if(e.length<3)return[];const n=e[0],r=e[e.length-1];return(n[0]!==r[0]||n[1]!==r[1])&&e.push([n[0],n[1]]),e.length>=4?e:[]}function yt(t){if(!Array.isArray(t)||t.length<4)return 0;let e=0;for(let n=0;n<t.length-1;n+=1){const r=t[n],i=t[n+1];e+=r[0]*i[1]-i[0]*r[1]}return e*.5}function on(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const o of t){const s=Be(o);s.length>=4&&e.push(s)}if(e.length===0)return[];if(e.length===1)return[e[0]];let n=0,r=0;for(let o=0;o<e.length;o+=1){const s=Math.abs(yt(e[o]));s<=r||(r=s,n=o)}const i=[e[n]];for(let o=0;o<e.length;o+=1)o!==n&&i.push(e[o]);return i}function ei(t){if(!Array.isArray(t)||t.length===0)return[];const e=t[0];if(Ut(e)){const i=on([t]);return i.length>0?[i]:[]}if(!Array.isArray(e)||e.length===0)return[];const n=e[0];if(Ut(n)){const i=on(t);return i.length>0?[i]:[]}if(!Array.isArray(n)||n.length===0||!Ut(n[0]))return[];const r=[];for(const i of t){const o=on(i);o.length>0&&r.push(o)}return r}function ir(t,e,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>e==u>e)continue;t<(l-s)*(e-a)/(u-a)+s&&(r=!r)}return r}function ut(t){const e=[];for(const n of t??[]){const r=ei(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(yt(o));for(let c=1;c<i.length;c+=1)f-=Math.abs(yt(i[c]));e.push({outer:o,holes:i.slice(1),minX:s,minY:a,maxX:l,maxY:u,area:Math.max(1e-6,f)})}}return e}function ti(t,e,n){if(t<n.minX||t>n.maxX||e<n.minY||e>n.maxY||!ir(t,e,n.outer))return!1;for(const r of n.holes)if(ir(t,e,r))return!1;return!0}function bt(t,e,n){for(const r of n)if(ti(t,e,r))return!0;return!1}const Pn=[160,160,160,255];function I(t,e,n){return Math.max(e,Math.min(n,t))}function In(t,e,n){const r=Number(t),i=Number(e),o=Number(n);return!Number.isFinite(r)||r<=0?1:!Number.isFinite(i)||!Number.isFinite(o)?r:Math.pow(2,i-o)*r}function vo(t,e,n){let i=100*In(t,e,n);if(Number(t)){let o="μm";return i>1e3&&(i/=1e3,o="mm"),`${i.toPrecision(3)} ${o}`}return`${Math.round(i*1e3)/1e3} pixels`}function ye(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function nt(t){const e=t.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER;return Math.max(0,Math.min(Math.floor(t.count??0),Math.floor((t.positions?.length??0)/2),t.paletteIndices?.length??0,e))}function pn(t,e){return!t&&!e?!0:!t||!e?!1:Math.abs((t.zoom??0)-(e.zoom??0))<1e-6&&Math.abs((t.offsetX??0)-(e.offsetX??0))<1e-6&&Math.abs((t.offsetY??0)-(e.offsetY??0))<1e-6&&Math.abs((t.rotationDeg??0)-(e.rotationDeg??0))<1e-6}function Po(t){const e=String(t??"").trim();if(!e)return"";if(/^bearer\s+/i.test(e)){const n=e.replace(/^bearer\s+/i,"").trim();return n?`Bearer ${n}`:""}return`Bearer ${e}`}function ni(t){const n=String(t??"").trim().match(/^#?([0-9a-fA-F]{6})$/);if(!n)return[...Pn];const r=Number.parseInt(n[1],16);return[r>>16&255,r>>8&255,r&255,255]}function Io(t){const e=[[...Pn]],n=new Map;for(const i of t??[]){const o=String(i?.termId??"");!o||n.has(o)||(n.set(o,e.length),e.push(ni(i?.termColor)))}const r=new Uint8Array(e.length*4);for(let i=0;i<e.length;i+=1)r[i*4]=e[i][0],r[i*4+1]=e[i][1],r[i*4+2]=e[i][2],r[i*4+3]=e[i][3];return{colors:r,termToPaletteIndex:n}}const _o=[6,4,2],Fo=64,Lo=.04,Do=1,No=4,Vt=1e-6,Bo=.1;function ko(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const n of t){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=e[e.length-1];o&&Math.abs(o[0]-r)<1e-9&&Math.abs(o[1]-i)<1e-9||e.push([r,i])}return e}function or(t,e,n){if(e<=Vt||n<8)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([t[0]+Math.cos(o)*e,t[1]+Math.sin(o)*e])}return Be(r)}function Uo(t,e,n,r){const i=e[0]-t[0],o=e[1]-t[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(Vt,n);return Be([[t[0]+u*c,t[1]+f*c],[e[0]+u*c,e[1]+f*c],[e[0]-u*c,e[1]-f*c],[t[0]-u*c,t[1]-f*c]])}function sr(t,e){if(!t.length)return[];let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,l]of t)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(e,1);return Be([[n-s,r-s],[i+s,r-s],[i+s,o+s],[n-s,o+s]])}function Tt(t,e){return Be(e?t.map(([n,r])=>[I(n,e[0],e[2]),I(r,e[1],e[3])]):t)}function ar(t,e){return Number.isFinite(t)?Number(t.toFixed(e)):t}function zo(t,e){if(!Array.isArray(t)||t.length===0)return[];const n=[];for(const r of t){if(!Array.isArray(r)||r.length<2)continue;const i=ar(Number(r[0]),e),o=ar(Number(r[1]),e);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 Oo(t,e){if(!Array.isArray(t)||t.length===0)return[];const n=t.map(r=>zo(r,e)).filter(r=>r.length>=4);return n.length>0?n:[]}function Wo(t,e){const n=t.map(i=>Oo(i,e)).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=To.union(r,[n[i]]),!Array.isArray(r)||r.length===0)return null}catch(i){return console.error("buildBrushStrokePolygon union failed",e,i),null}return r.length>0?r:null}function Yo(t){if(t.length===0)return null;for(const e of _o){const n=Wo(t,e);if(n)return n}return null}function Xo(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const n of t){if(!Array.isArray(n)||n.length<2)continue;const r=Number(n[0]),i=Number(n[1]);!Number.isFinite(r)||!Number.isFinite(i)||e.push([r,i])}return Be(e)}function Vo(t){let e=[],n=0;for(const r of t){if(!Array.isArray(r)||r.length===0)continue;const i=Xo(r[0]??[]);if(i.length<4)continue;const o=Math.abs(yt(i));o<=n||(n=o,e=i)}return e}function Go(t,e=1e-9){const n=Be(t);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)<=e||r.push(s)}return r.push(r[0]),Be(r)}function Ho(t,e,n){const r=n[0]-e[0],i=n[1]-e[1],o=r*r+i*i;if(o<=1e-12){const c=t[0]-e[0],h=t[1]-e[1];return c*c+h*h}const s=I(((t[0]-e[0])*r+(t[1]-e[1])*i)/o,0,1),a=e[0]+r*s,l=e[1]+i*s,u=t[0]-a,f=t[1]-l;return u*u+f*f}function qo(t,e){if(t.length<=2||e<=0)return t.slice();const n=new Uint8Array(t.length);n[0]=1,n[t.length-1]=1;const r=e*e,i=[[0,t.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=Ho(t[c],t[a],t[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<t.length;s+=1)n[s]&&o.push(t[s]);return o}function Zo(t,e){const n=Be(t);if(n.length<5||e<=0)return n;const r=n.slice(0,-1),i=qo(r,e);return i.length<3?n:Be(i)}function $o(t,e){let n=Be(t);if(e<=0||n.length<5)return n;for(let r=0;r<e;r+=1){const i=n.slice(0,-1);if(i.length<3)break;const o=[];for(let s=0;s<i.length;s+=1){const a=i[s],l=i[(s+1)%i.length];o.push([a[0]*.75+l[0]*.25,a[1]*.75+l[1]*.25],[a[0]*.25+l[0]*.75,a[1]*.25+l[1]*.75])}n=Be(o)}return n}function Ko(t,e){const n=ko(t),r=Math.max(Vt,Number(e.radius)||0);if(n.length===0||!Number.isFinite(r))return[];const i=Math.max(12,Math.floor(e.circleSides||Fo));if(n.length===1)return Tt(or(n[0],r,i),e.clipBounds);const o=[],s=Math.max(Vt,r*Bo);for(let h=0;h<n.length;h+=1){const d=n[h],m=or(d,r,i);if(m.length>=4&&o.push([m]),h===0)continue;const g=Uo(n[h-1],d,r,s);g.length>=4&&o.push([g])}const a=Yo(o),l=a?Vo(a):[];if(!l.length)return Tt(sr(n,r),e.clipBounds);const u=typeof e.simplifyTolerance=="number"&&Number.isFinite(e.simplifyTolerance)?Math.max(0,e.simplifyTolerance):Math.max(.25,r*Lo),f=typeof e.smoothingPasses=="number"&&Number.isFinite(e.smoothingPasses)?Math.round(I(e.smoothingPasses,0,No)):Do,c=Zo($o(Go(l,1e-9),f),u);return c.length<4?Tt(sr(n,r),e.clipBounds):Tt(c,e.clipBounds)}const tt=[],lr=[],He={color:"#ff4d4f",width:2,lineDash:tt,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},ri={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},ii="rgba(23, 23, 25, 0.1)",oi=6,Oe={fontFamily:"Pretendard, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:11,fontWeight:600,textColor:"#171719",backgroundColor:"#FFCC00",borderColor:"rgba(0, 0, 0, 0)",borderWidth:0,paddingX:8,paddingY:4,offsetY:10,borderRadius:4},Ke={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},cr={x:16,y:-24},jo=20,ur=1e-6,fr="transparent",Qo=3,Jo=2,si=96,es=1,hr=1e3,ai=2,li=2,ts=4096,ns=.2,rs=1.12,is=.89,os=32,ss="#000000",as=.1,ls="#FFCF00",cs="#FF0000",us=1.5,dr=[2,2],fs=1,hs=.25,ds=4,ms=1,gs=0,ps=4,ys=1.5;function Gt(t,e,n){return[I(t[0],0,e),I(t[1],0,n)]}function _n(t){if(!Array.isArray(t)||t.length<2)return null;const e=Number(t[0]),n=Number(t[1]);return!Number.isFinite(e)||!Number.isFinite(n)?null:[e,n]}const We=_n;function Le(t){return Be(t)}function zt(t){return Math.abs(yt(Le(t)))}function mr(t){if(!Array.isArray(t)||t.length===0)return[0,0,0,0];let e=1/0,n=1/0,r=-1/0,i=-1/0;for(const[o,s]of t)o<e&&(e=o),o>r&&(r=o),s<n&&(n=s),s>i&&(i=s);return[e,n,r,i]}function xt(t,e,n=!1){if(e.length!==0){t.moveTo(e[0][0],e[0][1]);for(let r=1;r<e.length;r+=1)t.lineTo(e[r][0],e[r][1]);n&&t.closePath()}}function Ie(t,e,n,r=!1,i=!1,o="rgba(255, 77, 79, 0.16)"){e.length!==0&&(t.beginPath(),xt(t,e,r),i&&r&&(t.fillStyle=o,t.fill()),t.strokeStyle=n.color,t.lineWidth=n.width,t.lineJoin=n.lineJoin,t.lineCap=n.lineCap,t.shadowColor=n.shadowColor,t.shadowBlur=n.shadowBlur,t.shadowOffsetX=n.shadowOffsetX,t.shadowOffsetY=n.shadowOffsetY,t.setLineDash(n.lineDash),t.stroke(),t.setLineDash(tt),t.shadowColor="rgba(0, 0, 0, 0)",t.shadowBlur=0,t.shadowOffsetX=0,t.shadowOffsetY=0)}function Fn(t){const e=Array.isArray(t?.lineDash)?t.lineDash.filter(s=>Number.isFinite(s)&&s>=0):tt,n=typeof t?.width=="number"&&Number.isFinite(t.width)?Math.max(0,t.width):He.width,r=typeof t?.shadowBlur=="number"&&Number.isFinite(t.shadowBlur)?Math.max(0,t.shadowBlur):He.shadowBlur,i=typeof t?.shadowOffsetX=="number"&&Number.isFinite(t.shadowOffsetX)?t.shadowOffsetX:He.shadowOffsetX,o=typeof t?.shadowOffsetY=="number"&&Number.isFinite(t.shadowOffsetY)?t.shadowOffsetY:He.shadowOffsetY;return{color:t?.color||He.color,width:n,lineDash:e.length?e:tt,lineJoin:t?.lineJoin||He.lineJoin,lineCap:t?.lineCap||He.lineCap,shadowColor:t?.shadowColor||He.shadowColor,shadowBlur:r,shadowOffsetX:i,shadowOffsetY:o}}function qe(t,e){return e?Fn({color:e.color??t.color,width:e.width??t.width,lineDash:e.lineDash??t.lineDash,lineJoin:e.lineJoin??t.lineJoin,lineCap:e.lineCap??t.lineCap,shadowColor:e.shadowColor??t.shadowColor,shadowBlur:e.shadowBlur??t.shadowBlur,shadowOffsetX:e.shadowOffsetX??t.shadowOffsetX,shadowOffsetY:e.shadowOffsetY??t.shadowOffsetY}):t}function Ht(t,e){return t==null||e===null||e===void 0?!1:String(t)===String(e)}function gr(t){return typeof t=="number"&&Number.isFinite(t)}function bs(t){return Array.isArray(t)&&t.length>=2&&gr(t[0])&&gr(t[1])}function xs(t){return Array.isArray(t)&&t.length>=2&&t.every(e=>bs(e))}function ci(t,e){if(!(!Array.isArray(t)||t.length===0)){if(xs(t)){e.push(t.map(([n,r])=>[n,r]));return}for(const n of t)ci(n,e)}}function pr(t,e){const n=[];ci(t,n);const r=[];for(const i of n){if(i.length<2)continue;const o=e?Le(i):i;o.length>=(e?4:2)&&r.push(o)}return r}function mt(t,e){return typeof t!="number"||!Number.isFinite(t)||t<=0?e:t}function ws(t,e){return typeof t!="number"||!Number.isFinite(t)?e:I(t,0,1)}function ui(t,e,n,r,i,o){const s=Math.max(0,Math.min(o,r*.5,i*.5));t.beginPath(),t.moveTo(e+s,n),t.lineTo(e+r-s,n),t.quadraticCurveTo(e+r,n,e+r,n+s),t.lineTo(e+r,n+i-s),t.quadraticCurveTo(e+r,n+i,e+r-s,n+i),t.lineTo(e+s,n+i),t.quadraticCurveTo(e,n+i,e,n+i-s),t.lineTo(e,n+s),t.quadraticCurveTo(e,n,e+s,n),t.closePath()}function Ss(t){const e=t[0];return Array.isArray(e)&&Array.isArray(e[0])}function qt(t,e,n){if(!t||!e)return[];if(n){const r=n.worldToScreen(t[0],t[1]),i=n.worldToScreen(e[0],e[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 qt(t,e);s.push(l)}return Le(s)}}return Le([[t[0],t[1]],[e[0],t[1]],[e[0],e[1]],[t[0],e[1]]])}function yn(t,e,n=si){if(!t||!e)return[];const r=(t[0]+e[0])*.5,i=(t[1]+e[1])*.5,o=Math.hypot(e[0]-t[0],e[1]-t[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 Le(s)}function Zt(t){const e=ei(ct(t));if(e.length===0)return[];const n=[];for(const r of e){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 Rs(t){if(!Array.isArray(t))return dr;const e=t.filter(n=>Number.isFinite(n)&&n>=0);return e.length>0?e:dr}function Es(t){return typeof t!="number"||!Number.isFinite(t)?fs:I(t,hs,ds)}function As(t){return typeof t!="number"||!Number.isFinite(t)?ms:Math.round(I(t,gs,ps))}function Ms(t){const e=mt(t?.radius,os),n=mt(t?.cursorLineWidth,us),r=Es(t?.edgeDetail),i=As(t?.edgeSmoothing);return{radius:e,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:t?.clickSelectRoi===!0,fillColor:t?.fillColor||ss,fillOpacity:ws(t?.fillOpacity,as),cursorColor:t?.cursorColor||ls,cursorActiveColor:t?.cursorActiveColor||cs,cursorLineWidth:n,cursorLineDash:Rs(t?.cursorLineDash)}}function Ts(t,e,n){if(!e.isDrawing||e.screenPoints.length===0)return;const r=e.screenPoints;if(r.length===0)return;const i=n.radius;if(!(!Number.isFinite(i)||i<=0)){if(t.save(),t.globalAlpha=n.fillOpacity,t.fillStyle=n.fillColor,t.strokeStyle=n.fillColor,t.lineCap="round",t.lineJoin="round",t.lineWidth=i*2,r.length===1)t.beginPath(),t.arc(r[0][0],r[0][1],i,0,Math.PI*2),t.fill();else{t.beginPath(),t.moveTo(r[0][0],r[0][1]);for(let o=1;o<r.length;o+=1)t.lineTo(r[o][0],r[o][1]);t.stroke()}t.restore()}}function Cs(t,e,n,r){const i=e.cursor;if(!i)return;const o=e.cursorScreen??We(n?.worldToScreen(i[0],i[1])??[]);if(!o)return;const s=r.radius;!Number.isFinite(s)||s<=0||(t.save(),t.beginPath(),t.arc(o[0],o[1],s,0,Math.PI*2),t.strokeStyle=e.isDrawing?r.cursorActiveColor:r.cursorColor,t.lineWidth=r.cursorLineWidth,t.setLineDash(r.cursorLineDash),t.stroke(),t.setLineDash(tt),t.restore())}const vs=.58,Ps=4096,Is=.5;let Ct=null;const vt=new Map;function _s(){if(Ct)return Ct;if(typeof document>"u")return null;const e=document.createElement("canvas").getContext("2d");return e?(Ct=e,Ct):null}function Ln(t,e){const n=`${e.fontWeight}|${e.fontSize}|${e.fontFamily}|${t}`,r=vt.get(n);if(r!==void 0)return r;const i=t.length*e.fontSize*vs,o=_s();let s=i;if(o){o.font=`${e.fontWeight} ${e.fontSize}px ${e.fontFamily}`;const a=o.measureText(t).width;Number.isFinite(a)&&a>=0&&(s=a)}return vt.size>Ps&&vt.clear(),vt.set(n,s),s}function Fs(t,e="top-center"){if(!t.length)return null;let n=1/0;for(const o of t)o[1]<n&&(n=o[1]);if(!Number.isFinite(n))return null;let r=1/0,i=-1/0;for(const o of t)Math.abs(o[1]-n)>Is||(o[0]<r&&(r=o[0]),o[0]>i&&(i=o[0]));return!Number.isFinite(r)||!Number.isFinite(i)?null:e==="top-center"?[(r+i)*.5,n]:[r,n]}function Dn(t,e="top-center"){let n=null;for(const r of t){const i=Fs(r.outer,e);i&&(!n||i[1]<n[1]||i[1]===n[1]&&i[0]<n[0])&&(n=i)}return n}function Nn(t){const e=typeof t?.paddingX=="number"&&Number.isFinite(t.paddingX)?Math.max(0,t.paddingX):Oe.paddingX,n=typeof t?.paddingY=="number"&&Number.isFinite(t.paddingY)?Math.max(0,t.paddingY):Oe.paddingY,r=typeof t?.fontSize=="number"&&Number.isFinite(t.fontSize)?Math.max(8,t.fontSize):Oe.fontSize,i=typeof t?.borderWidth=="number"&&Number.isFinite(t.borderWidth)?Math.max(0,t.borderWidth):Oe.borderWidth,o=typeof t?.offsetY=="number"&&Number.isFinite(t.offsetY)?t.offsetY:Oe.offsetY,s=typeof t?.borderRadius=="number"&&Number.isFinite(t.borderRadius)?Math.max(0,t.borderRadius):Oe.borderRadius;return{fontFamily:t?.fontFamily||Oe.fontFamily,fontSize:r,fontWeight:t?.fontWeight||Oe.fontWeight,textColor:t?.textColor||Oe.textColor,backgroundColor:t?.backgroundColor||Oe.backgroundColor,borderColor:t?.borderColor||Oe.borderColor,borderWidth:i,paddingX:e,paddingY:n,offsetY:o,borderRadius:s}}function Bn(t,e){return e?Nn({fontFamily:e.fontFamily??t.fontFamily,fontSize:e.fontSize??t.fontSize,fontWeight:e.fontWeight??t.fontWeight,textColor:e.textColor??t.textColor,backgroundColor:e.backgroundColor??t.backgroundColor,borderColor:e.borderColor??t.borderColor,borderWidth:e.borderWidth??t.borderWidth,paddingX:e.paddingX??t.paddingX,paddingY:e.paddingY??t.paddingY,offsetY:e.offsetY??t.offsetY,borderRadius:e.borderRadius??t.borderRadius}):t}function kn(t,e,n,r){if(!t||!n)return 0;const i=Number(n.minZoom),o=Number(n.maxZoom);if(!Number.isFinite(i)||!Number.isFinite(o)||o-i<=ur||!Number.isFinite(e))return 0;let s=o;r!=null&&Number.isFinite(r)&&(s=I(r,i,o));const a=Math.max(ur,Math.abs(s)*1e-9);return e>=s-a?jo:0}function Ls(t){const e=typeof t?.fontSize=="number"&&Number.isFinite(t.fontSize)?Math.max(8,t.fontSize):Ke.fontSize,n=typeof t?.borderRadius=="number"&&Number.isFinite(t.borderRadius)?Math.max(0,t.borderRadius):Ke.borderRadius,r=typeof t?.paddingX=="number"&&Number.isFinite(t.paddingX)?Math.max(0,t.paddingX):Ke.paddingX,i=typeof t?.paddingY=="number"&&Number.isFinite(t.paddingY)?Math.max(0,t.paddingY):Ke.paddingY;return{fontFamily:t?.fontFamily||Ke.fontFamily,fontSize:e,fontWeight:t?.fontWeight||Ke.fontWeight,textColor:t?.textColor||Ke.textColor,backgroundColor:t?.backgroundColor||Ke.backgroundColor,borderRadius:n,paddingX:r,paddingY:i}}function Ds(t){const e=typeof t?.x=="number"&&Number.isFinite(t.x)?t.x:cr.x,n=typeof t?.y=="number"&&Number.isFinite(t.y)?t.y:cr.y;return{x:e,y:n}}function Ns(t){return Number.isFinite(t)?`${Math.max(0,t).toFixed(3)} mm²`:"0.000 mm²"}function Bs(t){const e=typeof t?.format=="function"?t.format:Ns,n=Ds(t?.cursorOffset);return{enabled:t?.enabled===!0,format:e,style:Ls(t?.style),cursorOffsetX:n.x,cursorOffsetY:n.y}}function fi(t,e,n,r,i,o,s=!0){const a=e.trim();if(!a)return;t.save(),t.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,t.textAlign="center",t.textBaseline="middle";const u=Ln(a,o)+o.paddingX*2,f=o.fontSize+o.paddingY*2,c=n[0],h=n[1]-o.offsetY,d=s?I(c,u*.5+1,r-u*.5-1):c,m=s?I(h,f*.5+1,i-f*.5-1):h,g=d-u*.5,y=m-f*.5;t.fillStyle=o.backgroundColor,t.strokeStyle=o.borderColor,t.lineWidth=o.borderWidth,ui(t,g,y,u,f,o.borderRadius),t.fill(),o.borderWidth>0&&t.stroke(),t.fillStyle=o.textColor,t.fillText(a,d,m+.5),t.restore()}function ks(t,e,n,r,i,o,s,a){const l=e.trim();if(!l)return;t.save(),t.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,t.textAlign="center",t.textBaseline="middle";const f=Ln(l,o)+o.paddingX*2,c=o.fontSize+o.paddingY*2,h=I(n[0]+s,f*.5+1,r-f*.5-1),d=I(n[1]+a,c*.5+1,i-c*.5-1),m=h-f*.5,g=d-c*.5;t.fillStyle=o.backgroundColor,ui(t,m,g,f,c,o.borderRadius),t.fill(),t.fillStyle=o.textColor,t.fillText(l,h,d+.5),t.restore()}function Us(t,e,n,r){if(!(e.length<4||n.length===0)){t.save(),t.beginPath(),xt(t,e,!0);for(const i of n)i.length<4||xt(t,i,!0);t.fillStyle=r,t.fill("evenodd"),t.restore()}}function hi(t){const{ctx:e,overlayShapes:n,imageOuterRing:r,worldToScreenPoints:i,baseStrokeStyle:o,onInvertedFillDebug:s}=t,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??Ss(u.coordinates),c=pr(u.coordinates,f);if(u.invertedFill?.fillColor){const d=[],m=pr(u.coordinates,!0);for(const g of m){const y=i(g);y.length>=4&&d.push(y)}a&&s&&s({id:u.id??l,outerRingPoints:r.length,sourceRingCount:m.length,holeRingCount:d.length,fillColor:u.invertedFill.fillColor}),Us(e,r,d,u.invertedFill.fillColor)}if(c.length===0)continue;const h=qe(o,u.stroke??u.strokeStyle);for(const d of c){const m=i(d);m.length<2||Ie(e,m,h,f,u.fill??!1)}}}function Pt(t){return typeof t=="string"&&(t==="stamp-rectangle"||t==="stamp-circle"||t==="stamp-rectangle-4096px"||t==="stamp-rectangle-2mm2"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2")}function zs(t){return{rectangleAreaMm2:mt(t?.rectangleAreaMm2,ai),circleAreaMm2:mt(t?.circleAreaMm2,li),rectanglePixelSize:mt(t?.rectanglePixelSize,ts)}}const yr=1e3;function Os(t){return t*yr*yr}function br(t,e,n){if(!t||!Number.isFinite(e)||e<=0)return[];if(n){const r=n.worldToScreen(t[0],t[1]),i=n.worldToScreen(t[0]+e,t[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 Le(a)}}return Le([[t[0]-e,t[1]-e],[t[0]+e,t[1]-e],[t[0]+e,t[1]+e],[t[0]-e,t[1]+e]])}function Ws(t,e,n=si){if(!t||!Number.isFinite(e)||e<=0)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([t[0]+Math.cos(o)*e,t[1]+Math.sin(o)*e])}return Le(r)}function Ys(t){const{stampTool:e,center:n,resolvedStampOptions:r,imageWidth:i,imageHeight:o,micronsToWorldPixels:s,getRectangleProjection:a}=t;if(!n)return[];if(e==="stamp-rectangle-4096px"){const c=r.rectanglePixelSize*.5;return br(n,c,a()).map(h=>Gt(h,i,o))}let l=0;if(e==="stamp-rectangle"||e==="stamp-rectangle-2mm2"?l=e==="stamp-rectangle-2mm2"?ai:r.rectangleAreaMm2:(e==="stamp-circle"||e==="stamp-circle-2mm2"||e==="stamp-circle-hpf-0.2mm2")&&(l=e==="stamp-circle-hpf-0.2mm2"?ns:e==="stamp-circle-2mm2"?li:r.circleAreaMm2),!Number.isFinite(l)||l<=0)return[];const u=Os(l);let f=[];if(e==="stamp-rectangle"||e==="stamp-rectangle-2mm2"){const c=s(Math.sqrt(u)*.5);f=br(n,c,a())}else if(e==="stamp-circle"||e==="stamp-circle-2mm2"||e==="stamp-circle-hpf-0.2mm2"){const c=s(Math.sqrt(u/Math.PI));f=Ws(n,c)}return f.length?f.map(c=>Gt(c,i,o)):[]}function Xs(t){return{color:ii,width:oi,lineDash:tt,lineJoin:t.lineJoin,lineCap:t.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function Vs(t){if(typeof t!="string")return fr;const e=t.trim();return e.length>0?e:fr}function xr(t){return Array.isArray(t)&&t.length>=4&&zt(t)>es}function di({tool:t,imageWidth:e,imageHeight:n,imageMpp:r,imageZoom:i,stampOptions:o,brushOptions:s,projectorRef:a,onBrushTap:l,onDrawComplete:u,onPatchComplete:f,enabled:c,viewStateSignal:h,persistedRegions:d,patchRegions:m,persistedPolygons:g,drawFillColor:y,regionStrokeStyle:b,regionStrokeHoverStyle:x,regionStrokeActiveStyle:M,patchStrokeStyle:w,resolveRegionStrokeStyle:T,resolveRegionLabelStyle:A,overlayShapes:k,hoveredRegionId:L=null,activeRegionId:W=null,regionLabelStyle:D,drawAreaTooltip:G,autoLiftRegionLabelAtMaxZoom:U=!1,regionLabelAnchor:v="top-center",clampRegionLabelToViewport:Y=!0,regionLabelAutoLiftOffsetPx:B,invalidateRef:z,className:Z,style:ae}){const te=p.useRef(null),Te=p.useRef(!1),Se=p.useRef(new Map),Ce=p.useRef(t),P=p.useRef({isDrawing:!1,pointerId:null,start:null,current:null,cursor:null,cursorScreen:null,points:[],screenPoints:[],stampCenter:null}),C=c??t!=="cursor",H=p.useMemo(()=>d&&d.length>0?d:!g||g.length===0?lr:g.map((R,E)=>({id:E,coordinates:R})),[d,g]),he=p.useMemo(()=>m??lr,[m]),J=p.useMemo(()=>{const R=[];for(let E=0;E<H.length;E+=1){const F=H[E],N=Zt(F.coordinates);N.length!==0&&R.push({region:F,regionIndex:E,regionKey:F.id??E,polygons:N})}return R},[H]),le=p.useMemo(()=>{const R=[];for(let E=0;E<he.length;E+=1){const F=he[E],N=Zt(F.coordinates);N.length!==0&&R.push({region:F,regionIndex:E,regionKey:F.id??E,polygons:N})}return R},[he]),ce=p.useMemo(()=>Fn(b),[b]),ge=p.useMemo(()=>qe(ce,x),[ce,x]),oe=p.useMemo(()=>qe(ce,M),[ce,M]),re=p.useMemo(()=>qe(ri,w),[w]),be=p.useMemo(()=>Vs(y),[y]),de=p.useMemo(()=>Nn(D),[D]),X=p.useMemo(()=>Bs(G),[G]),K=p.useMemo(()=>zs(o),[o]),$=p.useMemo(()=>Ms(s),[s]),ee=p.useMemo(()=>({position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",touchAction:"none",pointerEvents:C?"auto":"none",cursor:C?t==="brush"?"none":"crosshair":"default",...ae}),[C,t,ae]),ne=p.useCallback(()=>{const R=te.current;if(!R)return;const E=R.getBoundingClientRect(),F=Math.max(1,window.devicePixelRatio||1),N=Math.max(1,Math.round(E.width*F)),Q=Math.max(1,Math.round(E.height*F));(R.width!==N||R.height!==Q)&&(R.width=N,R.height=Q)},[]),ue=p.useCallback(R=>{const E=a.current;if(!E||R.length===0)return[];const F=new Array(R.length);for(let N=0;N<R.length;N+=1){const Q=We(E.worldToScreen(R[N][0],R[N][1]));if(!Q)return[];F[N]=Q}return F},[a]),Re=p.useCallback(R=>{const E=a.current,F=te.current;if(!E||!F)return null;const N=F.getBoundingClientRect(),Q=We(E.screenToWorld(N.left+R[0],N.top+R[1]));return Q?Gt(Q,e,n):null},[a,e,n]),xe=p.useCallback(()=>{const R=a.current,E=R?.getViewState?.().rotationDeg??0;if(!(Math.abs(E%360)<.01||!R))return{worldToScreen:(F,N)=>We(R.worldToScreen(F,N)),screenToWorld:Re}},[a,Re]),we=p.useCallback(R=>{if(!Number.isFinite(R)||R<=0)return 0;const E=typeof r=="number"&&Number.isFinite(r)&&r>0?r:1,F=typeof i=="number"&&Number.isFinite(i)?i:0,N=a.current?.getViewState?.().zoom,Q=typeof N=="number"&&Number.isFinite(N)&&N>0?N:1,Ae=F+Math.log2(Q),fe=Math.max(1e-9,In(E,F,Ae));return R/fe/Q},[r,i,a]),pe=p.useCallback((R,E)=>Ys({stampTool:R,center:E,resolvedStampOptions:K,imageWidth:e,imageHeight:n,micronsToWorldPixels:we,getRectangleProjection:xe}),[we,e,n,K,xe]),O=p.useCallback(()=>{const R=P.current;return Pt(t)?pe(t,R.stampCenter):t==="brush"?[]:R.isDrawing?t==="freehand"?R.points:t==="rectangle"?qt(R.start,R.current,xe()):t==="circular"?yn(R.start,R.current):[]:[]},[t,pe,xe]),q=p.useCallback(()=>{ne();const R=te.current;if(!R)return;const E=R.getContext("2d");if(!E)return;const F=Math.max(1,window.devicePixelRatio||1),N=R.width/F,Q=R.height/F;if(E.setTransform(1,0,0,1,0,0),E.clearRect(0,0,R.width,R.height),E.setTransform(F,0,0,F,0,0),J.length>0)for(const fe of J){const{region:me,polygons:Ee,regionIndex:Me,regionKey:De}=fe,ze=Ht(W,De)?"active":Ht(L,De)?"hover":"default";let $e=ze==="active"?oe:ze==="hover"?ge:ce;if(T){const Mt=T({region:me,regionId:De,regionIndex:Me,state:ze});$e=qe($e,Mt||void 0)}const At=ze==="default"?null:Xs($e);for(const Mt of Ee){const Jt=ue(Mt.outer);Jt.length>=4&&(At&&Ie(E,Jt,At,!0,!1),Ie(E,Jt,$e,!0,!1));for(const Hi of Mt.holes){const en=ue(Hi);en.length>=4&&(At&&Ie(E,en,At,!0,!1),Ie(E,en,$e,!0,!1))}}}if(le.length>0)for(const fe of le)for(const me of fe.polygons){const Ee=ue(me.outer);Ee.length>=4&&Ie(E,Ee,re,!0,!1);for(const Me of me.holes){const De=ue(Me);De.length>=4&&Ie(E,De,re,!0,!1)}}if(Array.isArray(k)&&k.length>0){const fe=ue(Le([[0,0],[e,0],[e,n],[0,n]]));hi({ctx:E,overlayShapes:k,imageOuterRing:fe,worldToScreenPoints:ue,baseStrokeStyle:ce,onInvertedFillDebug:globalThis.__OPEN_PLANT_DEBUG_OVERLAY__?me=>{const Ee=String(me.id),Me=`${me.outerRingPoints}|${me.sourceRingCount}|${me.holeRingCount}|${me.fillColor}`;Se.current.get(Ee)!==Me&&(Se.current.set(Ee,Me),console.debug("[open-plant] invertedFill",me))}:void 0})}const Ae=O();if(C){if(t==="brush")Ts(E,P.current,$),Cs(E,P.current,a.current,$);else if(Ae.length>0)if(t==="freehand"){const fe=ue(Ae);fe.length>=2&&Ie(E,fe,ce,!1,!1),fe.length>=3&&Ie(E,ue(Le(Ae)),ce,!0,!0,be)}else{const fe=ue(Ae);fe.length>=4&&Ie(E,fe,ce,!0,!0,be)}}if(J.length>0){const fe=Math.max(1e-6,a.current?.getViewState?.().zoom??1),me=typeof B=="number"&&Number.isFinite(B)?Math.max(0,B):kn(U,fe,a.current?.getZoomRange?.(),a.current?.getRegionLabelAutoLiftCapZoom?.());for(const Ee of J){if(!Ee.region.label)continue;const Me=Dn(Ee.polygons,v);if(!Me)continue;const De=We(a.current?.worldToScreen(Me[0],Me[1])??[]);if(!De)continue;let ze=Bn(de,A?.({region:Ee.region,regionId:Ee.regionKey,regionIndex:Ee.regionIndex,zoom:fe}));me>0&&(ze={...ze,offsetY:ze.offsetY+me}),fi(E,Ee.region.label,De,N,Q,ze,Y)}}if(X.enabled&&C&&(t==="freehand"||t==="rectangle"||t==="circular")){const fe=P.current;if(fe.isDrawing){const me=t==="freehand"?Le(Ae):Ae;if(me.length>=4){const Ee=zt(me),Me=typeof r=="number"&&Number.isFinite(r)&&r>0?r:0,De=Me>0?Ee*Me*Me/(hr*hr):0,ze=X.format(De),$e=fe.cursorScreen??(fe.current?We(a.current?.worldToScreen(fe.current[0],fe.current[1])??[]):null);$e&&ks(E,ze,$e,N,Q,X.style,X.cursorOffsetX,X.cursorOffsetY)}}}},[C,t,O,ne,ue,e,n,a,J,k,L,W,ce,ge,oe,be,le,re,T,A,de,X,U,v,Y,B,r,$]),_=p.useCallback(()=>{Te.current||(Te.current=!0,requestAnimationFrame(()=>{Te.current=!1,q()}))},[q]),V=p.useCallback((R=!1)=>{const E=P.current,F=te.current;F&&E.pointerId!==null&&F.hasPointerCapture(E.pointerId)&&F.releasePointerCapture(E.pointerId),E.isDrawing=!1,E.pointerId=null,E.start=null,E.current=null,E.points=[],E.screenPoints=[],E.stampCenter=null,R||(E.cursor=null,E.cursorScreen=null)},[]),j=p.useCallback(R=>{const E=a.current;if(!E||e<=0||n<=0)return null;const F=We(E.screenToWorld(R.clientX,R.clientY));return F?Gt(F,e,n):null},[a,e,n]),ie=p.useCallback(R=>{const E=te.current;if(!E)return null;const F=E.getBoundingClientRect(),N=I(R.clientX-F.left,0,F.width),Q=I(R.clientY-F.top,0,F.height);return!Number.isFinite(N)||!Number.isFinite(Q)?null:[N,Q]},[]),se=p.useCallback(()=>{const R=P.current;if(!R.isDrawing){V(!0),_();return}let E=[];if(t==="freehand")R.points.length>=Qo&&(E=Le(R.points));else if(t==="rectangle")E=qt(R.start,R.current,xe());else if(t==="circular")E=yn(R.start,R.current);else if(t==="brush"){const F=R.points[R.points.length-1]??R.current??R.start;if($.clickSelectRoi&&F&&R.points.length<=1&&l?.(F)){V(!0),_();return}const N=Math.max(.25,$.edgeDetail),Q=R.screenPoints.length>0?R.screenPoints:ue(R.points),Ae=Math.max(.5,$.radius*.04/N),fe=Ko(Q,{radius:$.radius,circleSides:Math.max(16,Math.round(32*N)),simplifyTolerance:Ae,smoothingPasses:$.edgeSmoothing}),me=[];for(const Ee of fe){const Me=Re(Ee);Me&&me.push(Me)}E=Le(me)}(t==="freehand"||t==="rectangle"||t==="circular"||t==="brush")&&xr(E)&&u&&u({tool:t,intent:t==="brush"?"brush":"roi",coordinates:E,bbox:mr(E),areaPx:zt(E)}),V(!0),_()},[t,u,V,_,ue,Re,xe,$.radius,$.edgeDetail,$.edgeSmoothing,$.clickSelectRoi,l]),ve=p.useCallback((R,E)=>{const F=pe(R,E);if(!xr(F))return;const N=R==="stamp-rectangle-4096px"?"patch":"roi",Q={tool:R,intent:N,coordinates:F,bbox:mr(F),areaPx:zt(F)};u?.(Q),N==="patch"&&f&&f(Q)},[pe,u,f]),ke=p.useCallback((R,E,F)=>{const N=Math.max(ys,$.radius*.1),Q=N*N,Ae=R.screenPoints[R.screenPoints.length-1];if(!Ae){R.points.push(E),R.screenPoints.push(F),R.current=E;return}const fe=F[0]-Ae[0],me=F[1]-Ae[1];fe*fe+me*me>=Q?(R.points.push(E),R.screenPoints.push(F)):(R.points[R.points.length-1]=E,R.screenPoints[R.screenPoints.length-1]=F),R.current=E},[$.radius]),Ge=p.useCallback(R=>{if(!C||t==="cursor"||R.button!==0)return;const E=j(R);if(!E)return;const F=ie(R);if(!F)return;if(R.preventDefault(),R.stopPropagation(),Pt(t)){const Ae=P.current;Ae.stampCenter=E,ve(t,E),_();return}const N=te.current;N&&N.setPointerCapture(R.pointerId);const Q=P.current;Q.isDrawing=!0,Q.pointerId=R.pointerId,Q.start=E,Q.current=E,Q.cursor=E,Q.cursorScreen=F,Q.points=t==="freehand"||t==="brush"?[E]:[],Q.screenPoints=t==="brush"?[F]:[],_()},[C,t,j,ie,ve,_]),Qt=p.useCallback(R=>{if(!C||t==="cursor")return;const E=j(R);if(!E)return;const F=ie(R);if(!F)return;const N=P.current;if(N.cursor=E,N.cursorScreen=F,Pt(t)){N.stampCenter=E,R.preventDefault(),R.stopPropagation(),_();return}if(t==="brush"){if(!N.isDrawing||N.pointerId!==R.pointerId){_();return}R.preventDefault(),R.stopPropagation(),ke(N,E,F),_();return}if(!(!N.isDrawing||N.pointerId!==R.pointerId)){if(R.preventDefault(),R.stopPropagation(),t==="freehand"){const Q=a.current,Ae=Math.max(1e-6,Q?.getViewState?.().zoom??1),fe=Jo/Ae,me=fe*fe,Ee=N.points[N.points.length-1];if(!Ee)N.points.push(E);else{const Me=E[0]-Ee[0],De=E[1]-Ee[1];Me*Me+De*De>=me&&N.points.push(E)}}else N.current=E;_()}},[C,t,j,ie,_,a,ke]),it=p.useCallback(R=>{const E=P.current;if(!E.isDrawing||E.pointerId!==R.pointerId)return;R.preventDefault(),R.stopPropagation();const F=j(R),N=ie(R);F&&(E.cursor=F,N&&(E.cursorScreen=N),t==="brush"?N&&ke(E,F,N):E.current=F);const Q=te.current;Q&&Q.hasPointerCapture(R.pointerId)&&Q.releasePointerCapture(R.pointerId),se()},[se,j,ie,t,ke]),Gi=p.useCallback(()=>{const R=P.current;let E=!1;t==="brush"&&!R.isDrawing&&R.cursor&&(R.cursor=null,R.cursorScreen=null,E=!0),Pt(t)&&R.stampCenter&&(R.stampCenter=null,E=!0),E&&_()},[t,_]);return p.useEffect(()=>{ne(),_();const R=te.current;if(!R)return;const E=new ResizeObserver(()=>{ne(),_()});return E.observe(R),()=>{E.disconnect()}},[ne,_]),p.useEffect(()=>{C||V(),_()},[C,_,V]),p.useEffect(()=>{Ce.current!==t&&(Ce.current=t,V(),_())},[t,V,_]),p.useEffect(()=>{_()},[h,H,k,_]),p.useEffect(()=>{if(z)return z.current=_,()=>{z.current===_&&(z.current=null)}},[z,_]),p.useEffect(()=>{if(!C)return;const R=E=>{E.key==="Escape"&&(V(),_())};return window.addEventListener("keydown",R),()=>{window.removeEventListener("keydown",R)}},[C,V,_]),Ye.jsx("canvas",{ref:te,className:Z,style:ee,onPointerDown:Ge,onPointerMove:Qt,onPointerUp:it,onPointerCancel:it,onPointerLeave:Gi,onContextMenu:R=>{C&&R.preventDefault()},onWheel:R=>{if(!C)return;const E=te.current,F=a.current;if(!E||typeof F?.zoomBy!="function")return;R.preventDefault(),R.stopPropagation();const N=E.getBoundingClientRect(),Q=R.clientX-N.left,Ae=R.clientY-N.top;F.zoomBy(R.deltaY<0?rs:is,Q,Ae),_()}})}const mi=p.createContext(null),Gs=mi.Provider;function rt(){const t=p.useContext(mi);if(!t)throw new Error("useViewerContext must be used within a <WsiViewer>");return t}function Hs({tool:t="cursor",stampOptions:e,brushOptions:n,fillColor:r,areaTooltip:i,onComplete:o,onPatchComplete:s,onBrushTap:a}){const{source:l,rendererRef:u,rendererSerial:f,setInteractionLock:c}=rt(),h=t!=="cursor";p.useEffect(()=>(c("drawing-layer",h),()=>c("drawing-layer",!1)),[h,c]);const d=p.useMemo(()=>u.current?.getViewState(),[f]);return l?Ye.jsx(di,{tool:t,enabled:h,imageWidth:l.width,imageHeight:l.height,imageMpp:l.mpp,imageZoom:l.maxTierZoom,stampOptions:e,brushOptions:n,drawFillColor:r,projectorRef:u,onBrushTap:a,viewStateSignal:d,drawAreaTooltip:i,onDrawComplete:o,onPatchComplete:s}):null}function wr(t,e,n,r){return[Math.min(t,n),Math.min(e,r),Math.max(t,n),Math.max(e,r)]}function Sr(t,e){return!(t[2]<e[0]||t[0]>e[2]||t[3]<e[1]||t[1]>e[3])}class qs{constructor(e=16){S(this,"targetNodeSize");S(this,"items",[]);S(this,"globalBounds",[0,0,0,0]);S(this,"gridSize",1);S(this,"cellWidth",1);S(this,"cellHeight",1);S(this,"buckets",[]);S(this,"visited",new Uint32Array(0));S(this,"querySerial",1);const n=Number.isFinite(e)?Math.floor(e):16;this.targetNodeSize=Math.max(1,n)}load(e){if(!Array.isArray(e)||e.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 e){if(!f||!Number.isFinite(f.minX)||!Number.isFinite(f.minY)||!Number.isFinite(f.maxX)||!Number.isFinite(f.maxY))continue;const c=wr(f.minX,f.minY,f.maxX,f.maxY);r=Math.min(r,c[0]),i=Math.min(i,c[1]),o=Math.max(o,c[2]),s=Math.max(s,c[3]),n.push({minX:c[0],minY:c[1],maxX:c[2],maxY:c[3],value:f.value})}if(this.items=n,this.visited=new Uint32Array(n.length),this.querySerial=1,n.length===0||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(o)||!Number.isFinite(s)){this.globalBounds=[0,0,0,0],this.gridSize=1,this.cellWidth=1,this.cellHeight=1,this.buckets=[];return}this.globalBounds=[r,i,o,s],this.gridSize=Math.max(1,Math.ceil(Math.sqrt(n.length/this.targetNodeSize)));const a=Math.max(0,o-r),l=Math.max(0,s-i);this.cellWidth=a>0?a/this.gridSize:1,this.cellHeight=l>0?l/this.gridSize:1;const u=this.gridSize*this.gridSize;this.buckets=Array.from({length:u},()=>[]);for(let f=0;f<n.length;f+=1){const c=n[f],h=this.toCellX(c.minX),d=this.toCellX(c.maxX),m=this.toCellY(c.minY),g=this.toCellY(c.maxY);for(let y=m;y<=g;y+=1)for(let b=h;b<=d;b+=1)this.buckets[y*this.gridSize+b].push(f)}}search(e){if(this.items.length===0)return[];if(!Array.isArray(e)||e.length<4)return[];const n=wr(e[0],e[1],e[2],e[3]);if(!Sr(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];Sr(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(e){const n=this.globalBounds[0],r=this.globalBounds[2];if(this.gridSize<=1||r<=n)return 0;const i=(e-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(e){const n=this.globalBounds[1],r=this.globalBounds[3];if(this.gridSize<=1||r<=n)return 0;const i=(e-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 gi(t){return new qs(t)}const Zs=`#version 300 es
|
|
32
|
+
`;class Kr{constructor(e){S(this,"canvas");S(this,"gl");S(this,"camera",new $r);S(this,"imageWidth");S(this,"imageHeight");S(this,"clearColor");S(this,"program");S(this,"vao");S(this,"quadBuffer");S(this,"uCameraLocation");S(this,"uBoundsLocation");S(this,"uTextureLocation");S(this,"resizeObserver");S(this,"tiles",[]);S(this,"frameId",null);S(this,"loadVersion",0);S(this,"destroyed",!1);S(this,"fitted",!1);S(this,"controlledViewState",!1);this.canvas=e.canvas,this.imageWidth=Math.max(1,e.imageWidth),this.imageHeight=Math.max(1,e.imageHeight),this.clearColor=e.clearColor??[.03,.05,.08,1],this.gl=$i(this.canvas),this.program=pt(this.gl,Ki,ji);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=Fe(this.gl,this.program,"uCamera"),this.uBoundsLocation=Fe(this.gl,this.program,"uBounds"),this.uTextureLocation=Fe(this.gl,this.program,"uTexture"),e.initialViewState&&(this.controlledViewState=!0,this.camera.setViewState(e.initialViewState)),this.resizeObserver=new ResizeObserver(()=>{this.resize()}),this.resizeObserver.observe(this.canvas),this.resize()}async setTiles(e){if(this.destroyed)return;const n=++this.loadVersion,r=await Promise.all(e.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(e){this.controlledViewState=!0,this.camera.setViewState(e),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(e,n){try{const r=await fetch(e.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:e.id,bounds:e.bounds,texture:s}}catch(r){return console.error(`[M1TileRenderer] tile load failed: ${e.id}`,r),null}}resize(){if(this.destroyed)return;const e=this.canvas.getBoundingClientRect(),n=Math.max(1,e.width||this.canvas.clientWidth||1),r=Math.max(1,e.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 e=this.camera.getViewportSize(),n=Math.min(e.width/this.imageWidth,e.height/this.imageHeight),r=Number.isFinite(n)&&n>0?n:1,i=e.width/r,o=e.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 e of this.tiles)this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,e.texture),this.gl.uniform4f(this.uBoundsLocation,e.bounds[0],e.bounds[1],e.bounds[2],e.bounds[3]),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindVertexArray(null)}}disposeTiles(e){for(const n of e)this.gl.deleteTexture(n.texture)}}class et{constructor(e,n){this.next=null,this.key=e,this.data=n,this.left=null,this.right=null}}function Qi(t,e){return t>e?1:t<e?-1:0}function je(t,e,n){const r=new et(null,null);let i=r,o=r;for(;;){const s=n(t,e.key);if(s<0){if(e.left===null)break;if(n(t,e.left.key)<0){const a=e.left;if(e.left=a.right,a.right=e,e=a,e.left===null)break}o.left=e,o=e,e=e.left}else if(s>0){if(e.right===null)break;if(n(t,e.right.key)>0){const a=e.right;if(e.right=a.left,a.left=e,e=a,e.right===null)break}i.right=e,i=e,e=e.right}else break}return i.right=e.left,o.left=e.right,e.left=r.right,e.right=r.left,e}function nn(t,e,n,r){const i=new et(t,e);if(n===null)return i.left=i.right=null,i;n=je(t,n,r);const o=r(t,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 Vn(t,e,n){let r=null,i=null;if(e){e=je(t,e,n);const o=n(e.key,t);o===0?(r=e.left,i=e.right):o<0?(i=e.right,e.right=null,r=e):(r=e.left,e.left=null,i=e)}return{left:r,right:i}}function Ji(t,e,n){return e===null?t:(t===null||(e=je(t.key,e,n),e.left=t),e)}function fn(t,e,n,r,i){if(t){r(`${e}${n?"└── ":"├── "}${i(t)}
|
|
33
|
+
`);const o=e+(n?" ":"│ ");t.left&&fn(t.left,o,!1,r,i),t.right&&fn(t.right,o,!0,r,i)}}class vn{constructor(e=Qi){this._root=null,this._size=0,this._comparator=e}insert(e,n){return this._size++,this._root=nn(e,n,this._root,this._comparator)}add(e,n){const r=new et(e,n);this._root===null&&(r.left=r.right=null,this._size++,this._root=r);const i=this._comparator,o=je(e,this._root,i),s=i(e,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(e){this._root=this._remove(e,this._root,this._comparator)}_remove(e,n,r){let i;return n===null?null:(n=je(e,n,r),r(e,n.key)===0?(n.left===null?i=n.right:(i=je(e,n.left,r),i.right=n.right),this._size--,i):n)}pop(){let e=this._root;if(e){for(;e.left;)e=e.left;return this._root=je(e.key,this._root,this._comparator),this._root=this._remove(e.key,this._root,this._comparator),{key:e.key,data:e.data}}return null}findStatic(e){let n=this._root;const r=this._comparator;for(;n;){const i=r(e,n.key);if(i===0)return n;i<0?n=n.left:n=n.right}return null}find(e){return this._root&&(this._root=je(e,this._root,this._comparator),this._comparator(e,this._root.key)!==0)?null:this._root}contains(e){let n=this._root;const r=this._comparator;for(;n;){const i=r(e,n.key);if(i===0)return!0;i<0?n=n.left:n=n.right}return!1}forEach(e,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(),e.call(n,r),r=r.right):o=!0;return this}range(e,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,e)>=0&&r.call(i,a))return this;a=a.right}return this}keys(){const e=[];return this.forEach(({key:n})=>{e.push(n)}),e}values(){const e=[];return this.forEach(({data:n})=>{e.push(n)}),e}min(){return this._root?this.minNode(this._root).key:null}max(){return this._root?this.maxNode(this._root).key:null}minNode(e=this._root){if(e)for(;e.left;)e=e.left;return e}maxNode(e=this._root){if(e)for(;e.right;)e=e.right;return e}at(e){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===e)return n;i++,n=n.right}else r=!0;return null}next(e){let n=this._root,r=null;if(e.right){for(r=e.right;r.left;)r=r.left;return r}const i=this._comparator;for(;n;){const o=i(e.key,n.key);if(o===0)break;o<0?(r=n,n=n.left):n=n.right}return r}prev(e){let n=this._root,r=null;if(e.left!==null){for(r=e.left;r.right;)r=r.right;return r}const i=this._comparator;for(;n;){const o=i(e.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 to(this._root)}load(e,n=[],r=!1){let i=e.length;const o=this._comparator;if(r&&mn(e,n,0,i-1,o),this._root===null)this._root=hn(e,n,0,i),this._size=i;else{const s=no(this.toList(),eo(e,n),o);i=this._size+i,this._root=dn({head:s},0,i)}return this}isEmpty(){return this._root===null}get size(){return this._size}get root(){return this._root}toString(e=n=>String(n.key)){const n=[];return fn(this._root,"",!0,r=>n.push(r),e),n.join("")}update(e,n,r){const i=this._comparator;let{left:o,right:s}=Vn(e,this._root,i);i(e,n)<0?s=nn(n,r,s,i):o=nn(n,r,o,i),this._root=Ji(o,s,i)}split(e){return Vn(e,this._root,this._comparator)}*[Symbol.iterator](){let e=this._root;const n=[];let r=!1;for(;!r;)e!==null?(n.push(e),e=e.left):n.length!==0?(e=n.pop(),yield e,e=e.right):r=!0}}function hn(t,e,n,r){const i=r-n;if(i>0){const o=n+Math.floor(i/2),s=t[o],a=e[o],l=new et(s,a);return l.left=hn(t,e,n,o),l.right=hn(t,e,o+1,r),l}return null}function eo(t,e){const n=new et(null,null);let r=n;for(let i=0;i<t.length;i++)r=r.next=new et(t[i],e[i]);return r.next=null,n.next}function to(t){let e=t;const n=[];let r=!1;const i=new et(null,null);let o=i;for(;!r;)e?(n.push(e),e=e.left):n.length>0?(e=o=o.next=n.pop(),e=e.right):r=!0;return o.next=null,i.next}function dn(t,e,n){const r=n-e;if(r>0){const i=e+Math.floor(r/2),o=dn(t,e,i),s=t.head;return s.left=o,t.head=t.head.next,s.right=dn(t,i+1,n),s}return null}function no(t,e,n){const r=new et(null,null);let i=r,o=t,s=e;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 mn(t,e,n,r,i){if(n>=r)return;const o=t[n+r>>1];let s=n-1,a=r+1;for(;;){do s++;while(i(t[s],o)<0);do a--;while(i(t[a],o)>0);if(s>=a)break;let l=t[s];t[s]=t[a],t[a]=l,l=e[s],e[s]=e[a],e[a]=l}mn(t,e,n,a,i),mn(t,e,a+1,r,i)}const qe=11102230246251565e-32,Pe=134217729,ro=(3+8*qe)*qe;function rn(t,e,n,r,i){let o,s,a,l,u=e[0],f=r[0],c=0,h=0;f>u==f>-u?(o=u,u=e[++c]):(o=f,f=r[++h]);let d=0;if(c<t&&h<n)for(f>u==f>-u?(s=u+o,a=o-(s-u),u=e[++c]):(s=f+o,a=o-(s-f),f=r[++h]),o=s,a!==0&&(i[d++]=a);c<t&&h<n;)f>u==f>-u?(s=o+u,l=s-o,a=o-(s-l)+(u-l),u=e[++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<t;)s=o+u,l=s-o,a=o-(s-l)+(u-l),u=e[++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 io(t,e){let n=e[0];for(let r=1;r<t;r++)n+=e[r];return n}function Rt(t){return new Float64Array(t)}const oo=(3+16*qe)*qe,so=(2+12*qe)*qe,ao=(9+64*qe)*qe*qe,st=Rt(4),Gn=Rt(8),Hn=Rt(12),qn=Rt(16),_e=Rt(4);function lo(t,e,n,r,i,o,s){let a,l,u,f,c,h,d,m,g,y,b,x,A,w,T,M,z,L;const V=t-i,H=n-i,W=e-o,D=r-o;w=V*D,h=Pe*V,d=h-(h-V),m=V-d,h=Pe*D,g=h-(h-D),y=D-g,T=m*y-(w-d*g-m*g-d*y),M=W*H,h=Pe*W,d=h-(h-W),m=W-d,h=Pe*H,g=h-(h-H),y=H-g,z=m*y-(M-d*g-m*g-d*y),b=T-z,c=T-b,st[0]=T-(b+c)+(c-z),x=w+b,c=x-w,A=w-(x-c)+(b-c),b=A-M,c=A-b,st[1]=A-(b+c)+(c-M),L=x+b,c=L-x,st[2]=x-(L-c)+(b-c),st[3]=L;let C=io(4,st),Y=so*s;if(C>=Y||-C>=Y||(c=t-V,a=t-(V+c)+(c-i),c=n-H,u=n-(H+c)+(c-i),c=e-W,l=e-(W+c)+(c-o),c=r-D,f=r-(D+c)+(c-o),a===0&&l===0&&u===0&&f===0)||(Y=ao*s+ro*Math.abs(C),C+=V*f+D*a-(W*u+H*l),C>=Y||-C>=Y))return C;w=a*D,h=Pe*a,d=h-(h-a),m=a-d,h=Pe*D,g=h-(h-D),y=D-g,T=m*y-(w-d*g-m*g-d*y),M=l*H,h=Pe*l,d=h-(h-l),m=l-d,h=Pe*H,g=h-(h-H),y=H-g,z=m*y-(M-d*g-m*g-d*y),b=T-z,c=T-b,_e[0]=T-(b+c)+(c-z),x=w+b,c=x-w,A=w-(x-c)+(b-c),b=A-M,c=A-b,_e[1]=A-(b+c)+(c-M),L=x+b,c=L-x,_e[2]=x-(L-c)+(b-c),_e[3]=L;const O=rn(4,st,4,_e,Gn);w=V*f,h=Pe*V,d=h-(h-V),m=V-d,h=Pe*f,g=h-(h-f),y=f-g,T=m*y-(w-d*g-m*g-d*y),M=W*u,h=Pe*W,d=h-(h-W),m=W-d,h=Pe*u,g=h-(h-u),y=u-g,z=m*y-(M-d*g-m*g-d*y),b=T-z,c=T-b,_e[0]=T-(b+c)+(c-z),x=w+b,c=x-w,A=w-(x-c)+(b-c),b=A-M,c=A-b,_e[1]=A-(b+c)+(c-M),L=x+b,c=L-x,_e[2]=x-(L-c)+(b-c),_e[3]=L;const N=rn(O,Gn,4,_e,Hn);w=a*f,h=Pe*a,d=h-(h-a),m=a-d,h=Pe*f,g=h-(h-f),y=f-g,T=m*y-(w-d*g-m*g-d*y),M=l*u,h=Pe*l,d=h-(h-l),m=l-d,h=Pe*u,g=h-(h-u),y=u-g,z=m*y-(M-d*g-m*g-d*y),b=T-z,c=T-b,_e[0]=T-(b+c)+(c-z),x=w+b,c=x-w,A=w-(x-c)+(b-c),b=A-M,c=A-b,_e[1]=A-(b+c)+(c-M),L=x+b,c=L-x,_e[2]=x-(L-c)+(b-c),_e[3]=L;const Z=rn(N,Hn,4,_e,qn);return qn[Z-1]}function co(t,e,n,r,i,o){const s=(e-o)*(n-i),a=(t-i)*(r-o),l=s-a,u=Math.abs(s+a);return Math.abs(l)>=oo*u?l:-lo(t,e,n,r,i,o,u)}const ht=(t,e)=>t.ll.x<=e.x&&e.x<=t.ur.x&&t.ll.y<=e.y&&e.y<=t.ur.y,gn=(t,e)=>{if(e.ur.x<t.ll.x||t.ur.x<e.ll.x||e.ur.y<t.ll.y||t.ur.y<e.ll.y)return null;const n=t.ll.x<e.ll.x?e.ll.x:t.ll.x,r=t.ur.x<e.ur.x?t.ur.x:e.ur.x,i=t.ll.y<e.ll.y?e.ll.y:t.ll.y,o=t.ur.y<e.ur.y?t.ur.y:e.ur.y;return{ll:{x:n,y:i},ur:{x:r,y:o}}};let Qe=Number.EPSILON;Qe===void 0&&(Qe=Math.pow(2,-52));const uo=Qe*Qe,Zn=(t,e)=>{if(-Qe<t&&t<Qe&&-Qe<e&&e<Qe)return 0;const n=t-e;return n*n<uo*t*e?0:t<e?-1:1};class fo{constructor(){this.reset()}reset(){this.xRounder=new $n,this.yRounder=new $n}round(e,n){return{x:this.xRounder.round(e),y:this.yRounder.round(n)}}}class $n{constructor(){this.tree=new vn,this.round(0)}round(e){const n=this.tree.add(e),r=this.tree.prev(n);if(r!==null&&Zn(n.key,r.key)===0)return this.tree.remove(e),r.key;const i=this.tree.next(n);return i!==null&&Zn(n.key,i.key)===0?(this.tree.remove(e),i.key):e}}const yt=new fo,Ut=(t,e)=>t.x*e.y-t.y*e.x,jr=(t,e)=>t.x*e.x+t.y*e.y,Kn=(t,e,n)=>{const r=co(t.x,t.y,e.x,e.y,n.x,n.y);return r>0?-1:r<0?1:0},Xt=t=>Math.sqrt(jr(t,t)),ho=(t,e,n)=>{const r={x:e.x-t.x,y:e.y-t.y},i={x:n.x-t.x,y:n.y-t.y};return Ut(i,r)/Xt(i)/Xt(r)},mo=(t,e,n)=>{const r={x:e.x-t.x,y:e.y-t.y},i={x:n.x-t.x,y:n.y-t.y};return jr(i,r)/Xt(i)/Xt(r)},jn=(t,e,n)=>e.y===0?null:{x:t.x+e.x/e.y*(n-t.y),y:n},Qn=(t,e,n)=>e.x===0?null:{x:n,y:t.y+e.y/e.x*(n-t.x)},go=(t,e,n,r)=>{if(e.x===0)return Qn(n,r,t.x);if(r.x===0)return Qn(t,e,n.x);if(e.y===0)return jn(n,r,t.y);if(r.y===0)return jn(t,e,n.y);const i=Ut(e,r);if(i==0)return null;const o={x:n.x-t.x,y:n.y-t.y},s=Ut(o,e)/i,a=Ut(o,r)/i,l=t.x+a*e.x,u=n.x+s*r.x,f=t.y+a*e.y,c=n.y+s*r.y,h=(l+u)/2,d=(f+c)/2;return{x:h,y:d}};class ke{static compare(e,n){const r=ke.comparePoints(e.point,n.point);return r!==0?r:(e.point!==n.point&&e.link(n),e.isLeft!==n.isLeft?e.isLeft?1:-1:Je.compare(e.segment,n.segment))}static comparePoints(e,n){return e.x<n.x?-1:e.x>n.x?1:e.y<n.y?-1:e.y>n.y?1:0}constructor(e,n){e.events===void 0?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=n}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const n=e.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 e=this.point.events.length;for(let n=0;n<e;n++){const r=this.point.events[n];if(r.segment.consumedBy===void 0)for(let i=n+1;i<e;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 e=[];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()&&e.push(i)}return e}getLeftmostComparator(e){const n=new Map,r=i=>{const o=i.otherSE;n.set(i,{sine:ho(this.point,e.point,o.point),cosine:mo(this.point,e.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 po=0;class Je{static compare(e,n){const r=e.leftSE.point.x,i=n.leftSE.point.x,o=e.rightSE.point.x,s=n.rightSE.point.x;if(s<r)return 1;if(o<i)return-1;const a=e.leftSE.point.y,l=n.leftSE.point.y,u=e.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=e.comparePoint(n.leftSE.point);if(c<0)return 1;if(c>0)return-1;const h=n.comparePoint(e.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(e.leftSE.point);if(c!==0)return c;const h=e.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(e.rightSE.point);if(c!==0)return c}if(o>s){const c=e.comparePoint(n.rightSE.point);if(c<0)return 1;if(c>0)return-1}if(o!==s){const c=u-a,h=o-r,d=f-l,m=s-i;if(c>h&&d<m)return 1;if(c<h&&d>m)return-1}return o>s?1:o<s||u<f?-1:u>f?1:e.id<n.id?-1:e.id>n.id?1:0}constructor(e,n,r,i){this.id=++po,this.leftSE=e,e.segment=this,e.otherSE=n,this.rightSE=n,n.segment=this,n.otherSE=e,this.rings=r,this.windings=i}static fromRing(e,n,r){let i,o,s;const a=ke.comparePoints(e,n);if(a<0)i=e,o=n,s=1;else if(a>0)i=n,o=e,s=-1;else throw new Error(`Tried to create degenerate segment at [${e.x}, ${e.y}]`);const l=new ke(i,!0),u=new ke(o,!1);return new Je(l,u,[r],[s])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,n=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e<n?e:n},ur:{x:this.rightSE.point.x,y:e>n?e:n}}}vector(){return{x:this.rightSE.point.x-this.leftSE.point.x,y:this.rightSE.point.y-this.leftSE.point.y}}isAnEndpoint(e){return e.x===this.leftSE.point.x&&e.y===this.leftSE.point.y||e.x===this.rightSE.point.x&&e.y===this.rightSE.point.y}comparePoint(e){if(this.isAnEndpoint(e))return 0;const n=this.leftSE.point,r=this.rightSE.point,i=this.vector();if(n.x===r.x)return e.x===n.x?0:e.x<n.x?1:-1;const o=(e.y-n.y)/i.y,s=n.x+o*i.x;if(e.x===s)return 0;const a=(e.x-n.x)/i.x,l=n.y+a*i.y;return e.y===l?0:e.y<l?-1:1}getIntersection(e){const n=this.bbox(),r=e.bbox(),i=gn(n,r);if(i===null)return null;const o=this.leftSE.point,s=this.rightSE.point,a=e.leftSE.point,l=e.rightSE.point,u=ht(n,a)&&this.comparePoint(a)===0,f=ht(r,o)&&e.comparePoint(o)===0,c=ht(n,l)&&this.comparePoint(l)===0,h=ht(r,s)&&e.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=go(o,this.vector(),a,e.vector());return d===null||!ht(i,d)?null:yt.round(d.x,d.y)}split(e){const n=[],r=e.events!==void 0,i=new ke(e,!0),o=new ke(e,!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 ke.comparePoints(a.leftSE.point,a.rightSE.point)>0&&a.swapEvents(),ke.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),r&&(i.checkForConsuming(),o.checkForConsuming()),n}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let n=0,r=this.windings.length;n<r;n++)this.windings[n]*=-1}consume(e){let n=this,r=e;for(;n.consumedBy;)n=n.consumedBy;for(;r.consumedBy;)r=r.consumedBy;const i=Je.compare(n,r);if(i!==0){if(i>0){const o=n;n=r,r=o}if(n.prev===r){const o=n;n=r,r=o}for(let o=0,s=r.rings.length;o<s;o++){const a=r.rings[o],l=r.windings[o],u=n.rings.indexOf(a);u===-1?(n.rings.push(a),n.windings.push(l)):n.windings[u]+=l}r.rings=null,r.windings=null,r.consumedBy=n,r.leftSE.consumedBy=n.leftSE,r.rightSE.consumedBy=n.rightSE}}prevInResult(){return this._prevInResult!==void 0?this._prevInResult:(this.prev?this.prev.isInResult()?this._prevInResult=this.prev:this._prevInResult=this.prev.prevInResult():this._prevInResult=null,this._prevInResult)}beforeState(){if(this._beforeState!==void 0)return this._beforeState;if(!this.prev)this._beforeState={rings:[],windings:[],multiPolys:[]};else{const e=this.prev.consumedBy||this.prev;this._beforeState=e.afterState()}return this._beforeState}afterState(){if(this._afterState!==void 0)return this._afterState;const e=this.beforeState();this._afterState={rings:e.rings.slice(0),windings:e.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 e=this.beforeState().multiPolys,n=this.afterState().multiPolys;switch(Xe.type){case"union":{const r=e.length===0,i=n.length===0;this._isInResult=r!==i;break}case"intersection":{let r,i;e.length<n.length?(r=e.length,i=n.length):(r=n.length,i=e.length),this._isInResult=i===Xe.numMultiPolys&&r<i;break}case"xor":{const r=Math.abs(e.length-n.length);this._isInResult=r%2===1;break}case"difference":{const r=i=>i.length===1&&i[0].isSubject;this._isInResult=r(e)!==r(n);break}default:throw new Error(`Unrecognized operation type found ${Xe.type}`)}return this._isInResult}}class Jn{constructor(e,n,r){if(!Array.isArray(e)||e.length===0)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=n,this.isExterior=r,this.segments=[],typeof e[0][0]!="number"||typeof e[0][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const i=yt.round(e[0][0],e[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=e.length;s<a;s++){if(typeof e[s][0]!="number"||typeof e[s][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");let l=yt.round(e[s][0],e[s][1]);l.x===o.x&&l.y===o.y||(this.segments.push(Je.fromRing(o,l,this)),l.x<this.bbox.ll.x&&(this.bbox.ll.x=l.x),l.y<this.bbox.ll.y&&(this.bbox.ll.y=l.y),l.x>this.bbox.ur.x&&(this.bbox.ur.x=l.x),l.y>this.bbox.ur.y&&(this.bbox.ur.y=l.y),o=l)}(i.x!==o.x||i.y!==o.y)&&this.segments.push(Je.fromRing(o,i,this))}getSweepEvents(){const e=[];for(let n=0,r=this.segments.length;n<r;n++){const i=this.segments[n];e.push(i.leftSE),e.push(i.rightSE)}return e}}class yo{constructor(e,n){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");this.exteriorRing=new Jn(e[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=e.length;r<i;r++){const o=new Jn(e[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 e=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++)e.push(i[o])}return e}}class er{constructor(e,n){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");try{typeof e[0][0][0]=="number"&&(e=[e])}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=e.length;r<i;r++){const o=new yo(e[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 e=[];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++)e.push(i[o])}return e}}class Vt{static factory(e){const n=[];for(let r=0,i=e.length;r<i;r++){const o=e[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 g=u[0].point,y=u[u.length-1].point;throw new Error(`Unable to complete output ring starting at [${g.x}, ${g.y}]. Last matching segment found ends at [${y.x}, ${y.y}].`)}if(h.length===1){l=h[0].otherSE;break}let d=null;for(let g=0,y=c.length;g<y;g++)if(c[g].point===a.point){d=g;break}if(d!==null){const g=c.splice(d)[0],y=u.splice(g.index);y.unshift(y[0].otherSE),n.push(new Vt(y.reverse()));continue}c.push({index:u.length,point:a.point});const m=a.getLeftmostComparator(s);l=h.sort(m)[0].otherSE;break}n.push(new Vt(u))}return n}constructor(e){this.events=e;for(let n=0,r=e.length;n<r;n++)e[n].segment.ringOut=this;this.poly=null}getGeom(){let e=this.events[0].point;const n=[e];for(let u=1,f=this.events.length-1;u<f;u++){const c=this.events[u].point,h=this.events[u+1].point;Kn(c,e,h)!==0&&(n.push(c),e=c)}if(n.length===1)return null;const r=n[0],i=n[1];Kn(r,e,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 e=this.enclosingRing();this._isExteriorRing=e?!e.isExteriorRing():!0}return this._isExteriorRing}enclosingRing(){return this._enclosingRing===void 0&&(this._enclosingRing=this._calcEnclosingRing()),this._enclosingRing}_calcEnclosingRing(){let e=this.events[0];for(let i=1,o=this.events.length;i<o;i++){const s=this.events[i];ke.compare(e,s)>0&&(e=s)}let n=e.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 tr{constructor(e){this.exteriorRing=e,e.poly=this,this.interiorRings=[]}addInterior(e){this.interiorRings.push(e),e.poly=this}getGeom(){const e=[this.exteriorRing.getGeom()];if(e[0]===null)return null;for(let n=0,r=this.interiorRings.length;n<r;n++){const i=this.interiorRings[n].getGeom();i!==null&&e.push(i)}return e}}class bo{constructor(e){this.rings=e,this.polys=this._composePolys(e)}getGeom(){const e=[];for(let n=0,r=this.polys.length;n<r;n++){const i=this.polys[n].getGeom();i!==null&&e.push(i)}return e}_composePolys(e){const n=[];for(let r=0,i=e.length;r<i;r++){const o=e[r];if(!o.poly)if(o.isExteriorRing())n.push(new tr(o));else{const s=o.enclosingRing();s.poly||n.push(new tr(s)),s.poly.addInterior(o)}}return n}}class xo{constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Je.compare;this.queue=e,this.tree=new vn(n),this.segments=[]}process(e){const n=e.segment,r=[];if(e.consumedBy)return e.isLeft?this.queue.remove(e.otherSE):this.tree.remove(n),r;const i=e.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(e.isLeft){let u=null;if(a){const c=a.getIntersection(n);if(c!==null&&(n.isAnEndpoint(c)||(u=c),!a.isAnEndpoint(c))){const h=this._splitSafely(a,c);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}}let f=null;if(l){const c=l.getIntersection(n);if(c!==null&&(n.isAnEndpoint(c)||(f=c),!l.isAnEndpoint(c))){const h=this._splitSafely(l,c);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}}if(u!==null||f!==null){let c=null;u===null?c=f:f===null?c=u:c=ke.comparePoints(u,f)<=0?u:f,this.queue.remove(n.rightSE),r.push(n.rightSE);const h=n.split(c);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}r.length>0?(this.tree.remove(n),r.push(e)):(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(e,n){this.tree.remove(e);const r=e.rightSE;this.queue.remove(r);const i=e.split(n);return i.push(r),e.consumedBy===void 0&&this.tree.add(e),i}}const nr=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_QUEUE_SIZE||1e6,wo=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS||1e6;class So{run(e,n,r){Xe.type=e,yt.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(Xe.numMultiPolys=i.length,Xe.type==="difference"){const c=i[0];let h=1;for(;h<i.length;)gn(i[h].bbox,c.bbox)!==null?h++:i.splice(h,1)}if(Xe.type==="intersection")for(let c=0,h=i.length;c<h;c++){const d=i[c];for(let m=c+1,g=i.length;m<g;m++)if(gn(d.bbox,i[m].bbox)===null)return[]}const o=new vn(ke.compare);for(let c=0,h=i.length;c<h;c++){const d=i[c].getSweepEvents();for(let m=0,g=d.length;m<g;m++)if(o.insert(d[m]),o.size>nr)throw new Error("Infinite loop when putting segment endpoints in a priority queue (queue size too big).")}const s=new xo(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>nr)throw new Error("Infinite loop when passing sweep line over endpoints (queue size too big).");if(s.segments.length>wo)throw new Error("Infinite loop when passing sweep line over endpoints (too many sweep line segments).");const h=s.process(c);for(let d=0,m=h.length;d<m;d++){const g=h[d];g.consumedBy===void 0&&o.insert(g)}a=o.size,l=o.pop()}yt.reset();const u=Vt.factory(s.segments);return new bo(u).getGeom()}}const Xe=new So,Eo=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Xe.run("union",t,n)},Ro=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Xe.run("intersection",t,n)},Ao=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Xe.run("xor",t,n)},Mo=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Xe.run("difference",t,n)};var To={union:Eo,intersection:Ro,xor:Ao,difference:Mo};function ut(t){return t==null?null:Qr(t)||Jr(t)||Co(t)?t:null}function rr(t){return typeof t=="number"&&Number.isFinite(t)}function zt(t){return Array.isArray(t)&&t.length>=2&&rr(t[0])&&rr(t[1])}function Qr(t){return Array.isArray(t)&&t.length>0&&t.every(e=>zt(e))}function Jr(t){return Array.isArray(t)&&t.length>0&&t.every(e=>Qr(e))}function Co(t){return Array.isArray(t)&&t.length>0&&t.every(e=>Jr(e))}function Be(t){if(!Array.isArray(t)||t.length<3)return[];const e=[];for(const i of t){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=e[e.length-1];a&&a[0]===o&&a[1]===s||e.push([o,s])}if(e.length<3)return[];const n=e[0],r=e[e.length-1];return(n[0]!==r[0]||n[1]!==r[1])&&e.push([n[0],n[1]]),e.length>=4?e:[]}function bt(t){if(!Array.isArray(t)||t.length<4)return 0;let e=0;for(let n=0;n<t.length-1;n+=1){const r=t[n],i=t[n+1];e+=r[0]*i[1]-i[0]*r[1]}return e*.5}function on(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const o of t){const s=Be(o);s.length>=4&&e.push(s)}if(e.length===0)return[];if(e.length===1)return[e[0]];let n=0,r=0;for(let o=0;o<e.length;o+=1){const s=Math.abs(bt(e[o]));s<=r||(r=s,n=o)}const i=[e[n]];for(let o=0;o<e.length;o+=1)o!==n&&i.push(e[o]);return i}function ei(t){if(!Array.isArray(t)||t.length===0)return[];const e=t[0];if(zt(e)){const i=on([t]);return i.length>0?[i]:[]}if(!Array.isArray(e)||e.length===0)return[];const n=e[0];if(zt(n)){const i=on(t);return i.length>0?[i]:[]}if(!Array.isArray(n)||n.length===0||!zt(n[0]))return[];const r=[];for(const i of t){const o=on(i);o.length>0&&r.push(o)}return r}function ir(t,e,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>e==u>e)continue;t<(l-s)*(e-a)/(u-a)+s&&(r=!r)}return r}function ft(t){const e=[];for(const n of t??[]){const r=ei(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(bt(o));for(let c=1;c<i.length;c+=1)f-=Math.abs(bt(i[c]));e.push({outer:o,holes:i.slice(1),minX:s,minY:a,maxX:l,maxY:u,area:Math.max(1e-6,f)})}}return e}function ti(t,e,n){if(t<n.minX||t>n.maxX||e<n.minY||e>n.maxY||!ir(t,e,n.outer))return!1;for(const r of n.holes)if(ir(t,e,r))return!1;return!0}function xt(t,e,n){for(const r of n)if(ti(t,e,r))return!0;return!1}const Pn=[160,160,160,255];function _(t,e,n){return Math.max(e,Math.min(n,t))}function In(t,e,n){const r=Number(t),i=Number(e),o=Number(n);return!Number.isFinite(r)||r<=0?1:!Number.isFinite(i)||!Number.isFinite(o)?r:Math.pow(2,i-o)*r}function vo(t,e,n){let i=100*In(t,e,n);if(Number(t)){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 rt(t){const e=t.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER;return Math.max(0,Math.min(Math.floor(t.count??0),Math.floor((t.positions?.length??0)/2),t.paletteIndices?.length??0,e))}function pn(t,e){return!t&&!e?!0:!t||!e?!1:Math.abs((t.zoom??0)-(e.zoom??0))<1e-6&&Math.abs((t.offsetX??0)-(e.offsetX??0))<1e-6&&Math.abs((t.offsetY??0)-(e.offsetY??0))<1e-6&&Math.abs((t.rotationDeg??0)-(e.rotationDeg??0))<1e-6}function Po(t){const e=String(t??"").trim();if(!e)return"";if(/^bearer\s+/i.test(e)){const n=e.replace(/^bearer\s+/i,"").trim();return n?`Bearer ${n}`:""}return`Bearer ${e}`}function ni(t){const n=String(t??"").trim().match(/^#?([0-9a-fA-F]{6})$/);if(!n)return[...Pn];const r=Number.parseInt(n[1],16);return[r>>16&255,r>>8&255,r&255,255]}function Io(t){const e=[[...Pn]],n=new Map;for(const i of t??[]){const o=String(i?.termId??"");!o||n.has(o)||(n.set(o,e.length),e.push(ni(i?.termColor)))}const r=new Uint8Array(e.length*4);for(let i=0;i<e.length;i+=1)r[i*4]=e[i][0],r[i*4+1]=e[i][1],r[i*4+2]=e[i][2],r[i*4+3]=e[i][3];return{colors:r,termToPaletteIndex:n}}const _o=[6,4,2],Fo=64,Lo=.04,Do=1,No=4,Gt=1e-6,Bo=.1;function ko(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const n of t){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=e[e.length-1];o&&Math.abs(o[0]-r)<1e-9&&Math.abs(o[1]-i)<1e-9||e.push([r,i])}return e}function or(t,e,n){if(e<=Gt||n<8)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([t[0]+Math.cos(o)*e,t[1]+Math.sin(o)*e])}return Be(r)}function Uo(t,e,n,r){const i=e[0]-t[0],o=e[1]-t[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(Gt,n);return Be([[t[0]+u*c,t[1]+f*c],[e[0]+u*c,e[1]+f*c],[e[0]-u*c,e[1]-f*c],[t[0]-u*c,t[1]-f*c]])}function sr(t,e){if(!t.length)return[];let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,l]of t)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(e,1);return Be([[n-s,r-s],[i+s,r-s],[i+s,o+s],[n-s,o+s]])}function Ct(t,e){return Be(e?t.map(([n,r])=>[_(n,e[0],e[2]),_(r,e[1],e[3])]):t)}function ar(t,e){return Number.isFinite(t)?Number(t.toFixed(e)):t}function zo(t,e){if(!Array.isArray(t)||t.length===0)return[];const n=[];for(const r of t){if(!Array.isArray(r)||r.length<2)continue;const i=ar(Number(r[0]),e),o=ar(Number(r[1]),e);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 Oo(t,e){if(!Array.isArray(t)||t.length===0)return[];const n=t.map(r=>zo(r,e)).filter(r=>r.length>=4);return n.length>0?n:[]}function Wo(t,e){const n=t.map(i=>Oo(i,e)).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=To.union(r,[n[i]]),!Array.isArray(r)||r.length===0)return null}catch(i){return console.error("buildBrushStrokePolygon union failed",e,i),null}return r.length>0?r:null}function Yo(t){if(t.length===0)return null;for(const e of _o){const n=Wo(t,e);if(n)return n}return null}function Xo(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const n of t){if(!Array.isArray(n)||n.length<2)continue;const r=Number(n[0]),i=Number(n[1]);!Number.isFinite(r)||!Number.isFinite(i)||e.push([r,i])}return Be(e)}function Vo(t){let e=[],n=0;for(const r of t){if(!Array.isArray(r)||r.length===0)continue;const i=Xo(r[0]??[]);if(i.length<4)continue;const o=Math.abs(bt(i));o<=n||(n=o,e=i)}return e}function Go(t,e=1e-9){const n=Be(t);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)<=e||r.push(s)}return r.push(r[0]),Be(r)}function Ho(t,e,n){const r=n[0]-e[0],i=n[1]-e[1],o=r*r+i*i;if(o<=1e-12){const c=t[0]-e[0],h=t[1]-e[1];return c*c+h*h}const s=_(((t[0]-e[0])*r+(t[1]-e[1])*i)/o,0,1),a=e[0]+r*s,l=e[1]+i*s,u=t[0]-a,f=t[1]-l;return u*u+f*f}function qo(t,e){if(t.length<=2||e<=0)return t.slice();const n=new Uint8Array(t.length);n[0]=1,n[t.length-1]=1;const r=e*e,i=[[0,t.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=Ho(t[c],t[a],t[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<t.length;s+=1)n[s]&&o.push(t[s]);return o}function Zo(t,e){const n=Be(t);if(n.length<5||e<=0)return n;const r=n.slice(0,-1),i=qo(r,e);return i.length<3?n:Be(i)}function $o(t,e){let n=Be(t);if(e<=0||n.length<5)return n;for(let r=0;r<e;r+=1){const i=n.slice(0,-1);if(i.length<3)break;const o=[];for(let s=0;s<i.length;s+=1){const a=i[s],l=i[(s+1)%i.length];o.push([a[0]*.75+l[0]*.25,a[1]*.75+l[1]*.25],[a[0]*.25+l[0]*.75,a[1]*.25+l[1]*.75])}n=Be(o)}return n}function Ko(t,e){const n=ko(t),r=Math.max(Gt,Number(e.radius)||0);if(n.length===0||!Number.isFinite(r))return[];const i=Math.max(12,Math.floor(e.circleSides||Fo));if(n.length===1)return Ct(or(n[0],r,i),e.clipBounds);const o=[],s=Math.max(Gt,r*Bo);for(let h=0;h<n.length;h+=1){const d=n[h],m=or(d,r,i);if(m.length>=4&&o.push([m]),h===0)continue;const g=Uo(n[h-1],d,r,s);g.length>=4&&o.push([g])}const a=Yo(o),l=a?Vo(a):[];if(!l.length)return Ct(sr(n,r),e.clipBounds);const u=typeof e.simplifyTolerance=="number"&&Number.isFinite(e.simplifyTolerance)?Math.max(0,e.simplifyTolerance):Math.max(.25,r*Lo),f=typeof e.smoothingPasses=="number"&&Number.isFinite(e.smoothingPasses)?Math.round(_(e.smoothingPasses,0,No)):Do,c=Zo($o(Go(l,1e-9),f),u);return c.length<4?Ct(sr(n,r),e.clipBounds):Ct(c,e.clipBounds)}const nt=[],lr=[],Ge={color:"#ff4d4f",width:2,lineDash:nt,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},ri={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},ii="rgba(23, 23, 25, 0.1)",oi=6,Oe={fontFamily:"Pretendard, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:11,fontWeight:600,textColor:"#171719",backgroundColor:"#FFCC00",borderColor:"rgba(0, 0, 0, 0)",borderWidth:0,paddingX:8,paddingY:4,offsetY:10,borderRadius:4},Ke={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},cr={x:16,y:-24},jo=20,ur=1e-6,fr="transparent",Qo=3,Jo=2,si=96,es=1,hr=1e3,ai=2,li=2,ts=4096,ns=.2,rs=1.12,is=.89,os=32,ss="#000000",as=.1,ls="#FFCF00",cs="#FF0000",us=1.5,dr=[2,2],fs=1,hs=.25,ds=4,ms=1,gs=0,ps=4,ys=1.5;function Ht(t,e,n){return[_(t[0],0,e),_(t[1],0,n)]}function _n(t){if(!Array.isArray(t)||t.length<2)return null;const e=Number(t[0]),n=Number(t[1]);return!Number.isFinite(e)||!Number.isFinite(n)?null:[e,n]}const We=_n;function Le(t){return Be(t)}function Ot(t){return Math.abs(bt(Le(t)))}function mr(t){if(!Array.isArray(t)||t.length===0)return[0,0,0,0];let e=1/0,n=1/0,r=-1/0,i=-1/0;for(const[o,s]of t)o<e&&(e=o),o>r&&(r=o),s<n&&(n=s),s>i&&(i=s);return[e,n,r,i]}function wt(t,e,n=!1){if(e.length!==0){t.moveTo(e[0][0],e[0][1]);for(let r=1;r<e.length;r+=1)t.lineTo(e[r][0],e[r][1]);n&&t.closePath()}}function Ie(t,e,n,r=!1,i=!1,o="rgba(255, 77, 79, 0.16)"){e.length!==0&&(t.beginPath(),wt(t,e,r),i&&r&&(t.fillStyle=o,t.fill()),t.strokeStyle=n.color,t.lineWidth=n.width,t.lineJoin=n.lineJoin,t.lineCap=n.lineCap,t.shadowColor=n.shadowColor,t.shadowBlur=n.shadowBlur,t.shadowOffsetX=n.shadowOffsetX,t.shadowOffsetY=n.shadowOffsetY,t.setLineDash(n.lineDash),t.stroke(),t.setLineDash(nt),t.shadowColor="rgba(0, 0, 0, 0)",t.shadowBlur=0,t.shadowOffsetX=0,t.shadowOffsetY=0)}function Fn(t){const e=Array.isArray(t?.lineDash)?t.lineDash.filter(s=>Number.isFinite(s)&&s>=0):nt,n=typeof t?.width=="number"&&Number.isFinite(t.width)?Math.max(0,t.width):Ge.width,r=typeof t?.shadowBlur=="number"&&Number.isFinite(t.shadowBlur)?Math.max(0,t.shadowBlur):Ge.shadowBlur,i=typeof t?.shadowOffsetX=="number"&&Number.isFinite(t.shadowOffsetX)?t.shadowOffsetX:Ge.shadowOffsetX,o=typeof t?.shadowOffsetY=="number"&&Number.isFinite(t.shadowOffsetY)?t.shadowOffsetY:Ge.shadowOffsetY;return{color:t?.color||Ge.color,width:n,lineDash:e.length?e:nt,lineJoin:t?.lineJoin||Ge.lineJoin,lineCap:t?.lineCap||Ge.lineCap,shadowColor:t?.shadowColor||Ge.shadowColor,shadowBlur:r,shadowOffsetX:i,shadowOffsetY:o}}function He(t,e){return e?Fn({color:e.color??t.color,width:e.width??t.width,lineDash:e.lineDash??t.lineDash,lineJoin:e.lineJoin??t.lineJoin,lineCap:e.lineCap??t.lineCap,shadowColor:e.shadowColor??t.shadowColor,shadowBlur:e.shadowBlur??t.shadowBlur,shadowOffsetX:e.shadowOffsetX??t.shadowOffsetX,shadowOffsetY:e.shadowOffsetY??t.shadowOffsetY}):t}function qt(t,e){return t==null||e===null||e===void 0?!1:String(t)===String(e)}function gr(t){return typeof t=="number"&&Number.isFinite(t)}function bs(t){return Array.isArray(t)&&t.length>=2&&gr(t[0])&&gr(t[1])}function xs(t){return Array.isArray(t)&&t.length>=2&&t.every(e=>bs(e))}function ci(t,e){if(!(!Array.isArray(t)||t.length===0)){if(xs(t)){e.push(t.map(([n,r])=>[n,r]));return}for(const n of t)ci(n,e)}}function pr(t,e){const n=[];ci(t,n);const r=[];for(const i of n){if(i.length<2)continue;const o=e?Le(i):i;o.length>=(e?4:2)&&r.push(o)}return r}function gt(t,e){return typeof t!="number"||!Number.isFinite(t)||t<=0?e:t}function ws(t,e){return typeof t!="number"||!Number.isFinite(t)?e:_(t,0,1)}function ui(t,e,n,r,i,o){const s=Math.max(0,Math.min(o,r*.5,i*.5));t.beginPath(),t.moveTo(e+s,n),t.lineTo(e+r-s,n),t.quadraticCurveTo(e+r,n,e+r,n+s),t.lineTo(e+r,n+i-s),t.quadraticCurveTo(e+r,n+i,e+r-s,n+i),t.lineTo(e+s,n+i),t.quadraticCurveTo(e,n+i,e,n+i-s),t.lineTo(e,n+s),t.quadraticCurveTo(e,n,e+s,n),t.closePath()}function Ss(t){const e=t[0];return Array.isArray(e)&&Array.isArray(e[0])}function Zt(t,e,n){if(!t||!e)return[];if(n){const r=n.worldToScreen(t[0],t[1]),i=n.worldToScreen(e[0],e[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 Zt(t,e);s.push(l)}return Le(s)}}return Le([[t[0],t[1]],[e[0],t[1]],[e[0],e[1]],[t[0],e[1]]])}function yn(t,e,n=si){if(!t||!e)return[];const r=(t[0]+e[0])*.5,i=(t[1]+e[1])*.5,o=Math.hypot(e[0]-t[0],e[1]-t[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 Le(s)}function $t(t){const e=ei(ut(t));if(e.length===0)return[];const n=[];for(const r of e){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 Es(t){if(!Array.isArray(t))return dr;const e=t.filter(n=>Number.isFinite(n)&&n>=0);return e.length>0?e:dr}function Rs(t){return typeof t!="number"||!Number.isFinite(t)?fs:_(t,hs,ds)}function As(t){return typeof t!="number"||!Number.isFinite(t)?ms:Math.round(_(t,gs,ps))}function Ms(t){const e=gt(t?.radius,os),n=gt(t?.cursorLineWidth,us),r=Rs(t?.edgeDetail),i=As(t?.edgeSmoothing);return{radius:e,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:t?.clickSelectRoi===!0,fillColor:t?.fillColor||ss,fillOpacity:ws(t?.fillOpacity,as),cursorColor:t?.cursorColor||ls,cursorActiveColor:t?.cursorActiveColor||cs,cursorLineWidth:n,cursorLineDash:Es(t?.cursorLineDash)}}function Ts(t,e,n){if(!e.isDrawing||e.screenPoints.length===0)return;const r=e.screenPoints;if(r.length===0)return;const i=n.radius;if(!(!Number.isFinite(i)||i<=0)){if(t.save(),t.globalAlpha=n.fillOpacity,t.fillStyle=n.fillColor,t.strokeStyle=n.fillColor,t.lineCap="round",t.lineJoin="round",t.lineWidth=i*2,r.length===1)t.beginPath(),t.arc(r[0][0],r[0][1],i,0,Math.PI*2),t.fill();else{t.beginPath(),t.moveTo(r[0][0],r[0][1]);for(let o=1;o<r.length;o+=1)t.lineTo(r[o][0],r[o][1]);t.stroke()}t.restore()}}function Cs(t,e,n,r){const i=e.cursor;if(!i)return;const o=e.cursorScreen??We(n?.worldToScreen(i[0],i[1])??[]);if(!o)return;const s=r.radius;!Number.isFinite(s)||s<=0||(t.save(),t.beginPath(),t.arc(o[0],o[1],s,0,Math.PI*2),t.strokeStyle=e.isDrawing?r.cursorActiveColor:r.cursorColor,t.lineWidth=r.cursorLineWidth,t.setLineDash(r.cursorLineDash),t.stroke(),t.setLineDash(nt),t.restore())}const vs=.58,Ps=4096,Is=.5;let vt=null;const Pt=new Map;function _s(){if(vt)return vt;if(typeof document>"u")return null;const e=document.createElement("canvas").getContext("2d");return e?(vt=e,vt):null}function Ln(t,e){const n=`${e.fontWeight}|${e.fontSize}|${e.fontFamily}|${t}`,r=Pt.get(n);if(r!==void 0)return r;const i=t.length*e.fontSize*vs,o=_s();let s=i;if(o){o.font=`${e.fontWeight} ${e.fontSize}px ${e.fontFamily}`;const a=o.measureText(t).width;Number.isFinite(a)&&a>=0&&(s=a)}return Pt.size>Ps&&Pt.clear(),Pt.set(n,s),s}function Fs(t,e="top-center"){if(!t.length)return null;let n=1/0;for(const o of t)o[1]<n&&(n=o[1]);if(!Number.isFinite(n))return null;let r=1/0,i=-1/0;for(const o of t)Math.abs(o[1]-n)>Is||(o[0]<r&&(r=o[0]),o[0]>i&&(i=o[0]));return!Number.isFinite(r)||!Number.isFinite(i)?null:e==="top-center"?[(r+i)*.5,n]:[r,n]}function Dn(t,e="top-center"){let n=null;for(const r of t){const i=Fs(r.outer,e);i&&(!n||i[1]<n[1]||i[1]===n[1]&&i[0]<n[0])&&(n=i)}return n}function Nn(t){const e=typeof t?.paddingX=="number"&&Number.isFinite(t.paddingX)?Math.max(0,t.paddingX):Oe.paddingX,n=typeof t?.paddingY=="number"&&Number.isFinite(t.paddingY)?Math.max(0,t.paddingY):Oe.paddingY,r=typeof t?.fontSize=="number"&&Number.isFinite(t.fontSize)?Math.max(8,t.fontSize):Oe.fontSize,i=typeof t?.borderWidth=="number"&&Number.isFinite(t.borderWidth)?Math.max(0,t.borderWidth):Oe.borderWidth,o=typeof t?.offsetY=="number"&&Number.isFinite(t.offsetY)?t.offsetY:Oe.offsetY,s=typeof t?.borderRadius=="number"&&Number.isFinite(t.borderRadius)?Math.max(0,t.borderRadius):Oe.borderRadius;return{fontFamily:t?.fontFamily||Oe.fontFamily,fontSize:r,fontWeight:t?.fontWeight||Oe.fontWeight,textColor:t?.textColor||Oe.textColor,backgroundColor:t?.backgroundColor||Oe.backgroundColor,borderColor:t?.borderColor||Oe.borderColor,borderWidth:i,paddingX:e,paddingY:n,offsetY:o,borderRadius:s}}function Bn(t,e){return e?Nn({fontFamily:e.fontFamily??t.fontFamily,fontSize:e.fontSize??t.fontSize,fontWeight:e.fontWeight??t.fontWeight,textColor:e.textColor??t.textColor,backgroundColor:e.backgroundColor??t.backgroundColor,borderColor:e.borderColor??t.borderColor,borderWidth:e.borderWidth??t.borderWidth,paddingX:e.paddingX??t.paddingX,paddingY:e.paddingY??t.paddingY,offsetY:e.offsetY??t.offsetY,borderRadius:e.borderRadius??t.borderRadius}):t}function kn(t,e,n,r){if(!t||!n)return 0;const i=Number(n.minZoom),o=Number(n.maxZoom);if(!Number.isFinite(i)||!Number.isFinite(o)||o-i<=ur||!Number.isFinite(e))return 0;let s=o;r!=null&&Number.isFinite(r)&&(s=_(r,i,o));const a=Math.max(ur,Math.abs(s)*1e-9);return e>=s-a?jo:0}function Ls(t){const e=typeof t?.fontSize=="number"&&Number.isFinite(t.fontSize)?Math.max(8,t.fontSize):Ke.fontSize,n=typeof t?.borderRadius=="number"&&Number.isFinite(t.borderRadius)?Math.max(0,t.borderRadius):Ke.borderRadius,r=typeof t?.paddingX=="number"&&Number.isFinite(t.paddingX)?Math.max(0,t.paddingX):Ke.paddingX,i=typeof t?.paddingY=="number"&&Number.isFinite(t.paddingY)?Math.max(0,t.paddingY):Ke.paddingY;return{fontFamily:t?.fontFamily||Ke.fontFamily,fontSize:e,fontWeight:t?.fontWeight||Ke.fontWeight,textColor:t?.textColor||Ke.textColor,backgroundColor:t?.backgroundColor||Ke.backgroundColor,borderRadius:n,paddingX:r,paddingY:i}}function Ds(t){const e=typeof t?.x=="number"&&Number.isFinite(t.x)?t.x:cr.x,n=typeof t?.y=="number"&&Number.isFinite(t.y)?t.y:cr.y;return{x:e,y:n}}function Ns(t){return Number.isFinite(t)?`${Math.max(0,t).toFixed(3)} mm²`:"0.000 mm²"}function Bs(t){const e=typeof t?.format=="function"?t.format:Ns,n=Ds(t?.cursorOffset);return{enabled:t?.enabled===!0,format:e,style:Ls(t?.style),cursorOffsetX:n.x,cursorOffsetY:n.y}}function fi(t,e,n,r,i,o,s=!0){const a=e.trim();if(!a)return;t.save(),t.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,t.textAlign="center",t.textBaseline="middle";const u=Ln(a,o)+o.paddingX*2,f=o.fontSize+o.paddingY*2,c=n[0],h=n[1]-o.offsetY,d=s?_(c,u*.5+1,r-u*.5-1):c,m=s?_(h,f*.5+1,i-f*.5-1):h,g=d-u*.5,y=m-f*.5;t.fillStyle=o.backgroundColor,t.strokeStyle=o.borderColor,t.lineWidth=o.borderWidth,ui(t,g,y,u,f,o.borderRadius),t.fill(),o.borderWidth>0&&t.stroke(),t.fillStyle=o.textColor,t.fillText(a,d,m+.5),t.restore()}function ks(t,e,n,r,i,o,s,a){const l=e.trim();if(!l)return;t.save(),t.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,t.textAlign="center",t.textBaseline="middle";const f=Ln(l,o)+o.paddingX*2,c=o.fontSize+o.paddingY*2,h=_(n[0]+s,f*.5+1,r-f*.5-1),d=_(n[1]+a,c*.5+1,i-c*.5-1),m=h-f*.5,g=d-c*.5;t.fillStyle=o.backgroundColor,ui(t,m,g,f,c,o.borderRadius),t.fill(),t.fillStyle=o.textColor,t.fillText(l,h,d+.5),t.restore()}function Us(t,e,n,r){if(!(e.length<4||n.length===0)){t.save(),t.beginPath(),wt(t,e,!0);for(const i of n)i.length<4||wt(t,i,!0);t.fillStyle=r,t.fill("evenodd"),t.restore()}}function hi(t){const{ctx:e,overlayShapes:n,imageOuterRing:r,worldToScreenPoints:i,baseStrokeStyle:o,onInvertedFillDebug:s}=t,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??Ss(u.coordinates),c=pr(u.coordinates,f);if(u.invertedFill?.fillColor){const d=[],m=pr(u.coordinates,!0);for(const g of m){const y=i(g);y.length>=4&&d.push(y)}a&&s&&s({id:u.id??l,outerRingPoints:r.length,sourceRingCount:m.length,holeRingCount:d.length,fillColor:u.invertedFill.fillColor}),Us(e,r,d,u.invertedFill.fillColor)}if(c.length===0)continue;const h=He(o,u.stroke??u.strokeStyle);for(const d of c){const m=i(d);m.length<2||Ie(e,m,h,f,u.fill??!1)}}}function It(t){return typeof t=="string"&&(t==="stamp-rectangle"||t==="stamp-circle"||t==="stamp-rectangle-4096px"||t==="stamp-rectangle-2mm2"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2")}function zs(t){return{rectangleAreaMm2:gt(t?.rectangleAreaMm2,ai),circleAreaMm2:gt(t?.circleAreaMm2,li),rectanglePixelSize:gt(t?.rectanglePixelSize,ts)}}const yr=1e3;function Os(t){return t*yr*yr}function br(t,e,n){if(!t||!Number.isFinite(e)||e<=0)return[];if(n){const r=n.worldToScreen(t[0],t[1]),i=n.worldToScreen(t[0]+e,t[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 Le(a)}}return Le([[t[0]-e,t[1]-e],[t[0]+e,t[1]-e],[t[0]+e,t[1]+e],[t[0]-e,t[1]+e]])}function Ws(t,e,n=si){if(!t||!Number.isFinite(e)||e<=0)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([t[0]+Math.cos(o)*e,t[1]+Math.sin(o)*e])}return Le(r)}function Ys(t){const{stampTool:e,center:n,resolvedStampOptions:r,imageWidth:i,imageHeight:o,micronsToWorldPixels:s,getRectangleProjection:a}=t;if(!n)return[];if(e==="stamp-rectangle-4096px"){const c=r.rectanglePixelSize*.5;return br(n,c,a()).map(h=>Ht(h,i,o))}let l=0;if(e==="stamp-rectangle"||e==="stamp-rectangle-2mm2"?l=e==="stamp-rectangle-2mm2"?ai:r.rectangleAreaMm2:(e==="stamp-circle"||e==="stamp-circle-2mm2"||e==="stamp-circle-hpf-0.2mm2")&&(l=e==="stamp-circle-hpf-0.2mm2"?ns:e==="stamp-circle-2mm2"?li:r.circleAreaMm2),!Number.isFinite(l)||l<=0)return[];const u=Os(l);let f=[];if(e==="stamp-rectangle"||e==="stamp-rectangle-2mm2"){const c=s(Math.sqrt(u)*.5);f=br(n,c,a())}else if(e==="stamp-circle"||e==="stamp-circle-2mm2"||e==="stamp-circle-hpf-0.2mm2"){const c=s(Math.sqrt(u/Math.PI));f=Ws(n,c)}return f.length?f.map(c=>Ht(c,i,o)):[]}function Xs(t){return{color:ii,width:oi,lineDash:nt,lineJoin:t.lineJoin,lineCap:t.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function Vs(t){if(typeof t!="string")return fr;const e=t.trim();return e.length>0?e:fr}function xr(t){return Array.isArray(t)&&t.length>=4&&Ot(t)>es}function di({tool:t,imageWidth:e,imageHeight:n,imageMpp:r,imageZoom:i,stampOptions:o,brushOptions:s,projectorRef:a,onBrushTap:l,onDrawComplete:u,onPatchComplete:f,enabled:c,viewStateSignal:h,persistedRegions:d,patchRegions:m,persistedPolygons:g,drawFillColor:y,regionStrokeStyle:b,regionStrokeHoverStyle:x,regionStrokeActiveStyle:A,patchStrokeStyle:w,resolveRegionStrokeStyle:T,resolveRegionLabelStyle:M,overlayShapes:z,hoveredRegionId:L=null,activeRegionId:V=null,regionLabelStyle:H,drawAreaTooltip:W,autoLiftRegionLabelAtMaxZoom:D=!1,regionLabelAnchor:C="top-center",clampRegionLabelToViewport:Y=!0,regionLabelAutoLiftOffsetPx:O,invalidateRef:N,className:Z,style:oe}){const ne=p.useRef(null),Me=p.useRef(!1),we=p.useRef(new Map),Te=p.useRef(t),v=p.useRef({isDrawing:!1,pointerId:null,start:null,current:null,cursor:null,cursorScreen:null,points:[],screenPoints:[],stampCenter:null}),I=c??t!=="cursor",B=p.useMemo(()=>d&&d.length>0?d:!g||g.length===0?lr:g.map((E,R)=>({id:R,coordinates:E})),[d,g]),fe=p.useMemo(()=>m??lr,[m]),Q=p.useMemo(()=>{const E=[];for(let R=0;R<B.length;R+=1){const F=B[R],k=$t(F.coordinates);k.length!==0&&E.push({region:F,regionIndex:R,regionKey:F.id??R,polygons:k})}return E},[B]),se=p.useMemo(()=>{const E=[];for(let R=0;R<fe.length;R+=1){const F=fe[R],k=$t(F.coordinates);k.length!==0&&E.push({region:F,regionIndex:R,regionKey:F.id??R,polygons:k})}return E},[fe]),le=p.useMemo(()=>Fn(b),[b]),de=p.useMemo(()=>He(le,x),[le,x]),ae=p.useMemo(()=>He(le,A),[le,A]),ge=p.useMemo(()=>He(ri,w),[w]),ie=p.useMemo(()=>Vs(y),[y]),he=p.useMemo(()=>Nn(H),[H]),q=p.useMemo(()=>Bs(W),[W]),K=p.useMemo(()=>zs(o),[o]),$=p.useMemo(()=>Ms(s),[s]),re=p.useMemo(()=>({position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",touchAction:"none",pointerEvents:I?"auto":"none",cursor:I?t==="brush"?"none":"crosshair":"default",...oe}),[I,t,oe]),J=p.useCallback(()=>{const E=ne.current;if(!E)return;const R=E.getBoundingClientRect(),F=Math.max(1,window.devicePixelRatio||1),k=Math.max(1,Math.round(R.width*F)),j=Math.max(1,Math.round(R.height*F));(E.width!==k||E.height!==j)&&(E.width=k,E.height=j)},[]),ce=p.useCallback(E=>{const R=a.current;if(!R||E.length===0)return[];const F=new Array(E.length);for(let k=0;k<E.length;k+=1){const j=We(R.worldToScreen(E[k][0],E[k][1]));if(!j)return[];F[k]=j}return F},[a]),xe=p.useCallback(E=>{const R=a.current,F=ne.current;if(!R||!F)return null;const k=F.getBoundingClientRect(),j=We(R.screenToWorld(k.left+E[0],k.top+E[1]));return j?Ht(j,e,n):null},[a,e,n]),Ee=p.useCallback(()=>{const E=a.current,R=E?.getViewState?.().rotationDeg??0;if(!(Math.abs(R%360)<.01||!E))return{worldToScreen:(F,k)=>We(E.worldToScreen(F,k)),screenToWorld:xe}},[a,xe]),pe=p.useCallback(E=>{if(!Number.isFinite(E)||E<=0)return 0;const R=typeof r=="number"&&Number.isFinite(r)&&r>0?r:1,F=typeof i=="number"&&Number.isFinite(i)?i:0,k=a.current?.getViewState?.().zoom,j=typeof k=="number"&&Number.isFinite(k)&&k>0?k:1,Re=F+Math.log2(j),ue=Math.max(1e-9,In(R,F,Re));return E/ue/j},[r,i,a]),ye=p.useCallback((E,R)=>Ys({stampTool:E,center:R,resolvedStampOptions:K,imageWidth:e,imageHeight:n,micronsToWorldPixels:pe,getRectangleProjection:Ee}),[pe,e,n,K,Ee]),ve=p.useCallback(()=>{const E=v.current;return It(t)?ye(t,E.stampCenter):t==="brush"?[]:E.isDrawing?t==="freehand"?E.points:t==="rectangle"?Zt(E.start,E.current,Ee()):t==="circular"?yn(E.start,E.current):[]:[]},[t,ye,Ee]),U=p.useCallback(()=>{J();const E=ne.current;if(!E)return;const R=E.getContext("2d");if(!R)return;const F=Math.max(1,window.devicePixelRatio||1),k=E.width/F,j=E.height/F;if(R.setTransform(1,0,0,1,0,0),R.clearRect(0,0,E.width,E.height),R.setTransform(F,0,0,F,0,0),Q.length>0)for(const ue of Q){const{region:me,polygons:Se,regionIndex:Ae,regionKey:De}=ue,ze=qt(V,De)?"active":qt(L,De)?"hover":"default";let $e=ze==="active"?ae:ze==="hover"?de:le;if(T){const Tt=T({region:me,regionId:De,regionIndex:Ae,state:ze});$e=He($e,Tt||void 0)}const Mt=ze==="default"?null:Xs($e);for(const Tt of Se){const Jt=ce(Tt.outer);Jt.length>=4&&(Mt&&Ie(R,Jt,Mt,!0,!1),Ie(R,Jt,$e,!0,!1));for(const Hi of Tt.holes){const en=ce(Hi);en.length>=4&&(Mt&&Ie(R,en,Mt,!0,!1),Ie(R,en,$e,!0,!1))}}}if(se.length>0)for(const ue of se)for(const me of ue.polygons){const Se=ce(me.outer);Se.length>=4&&Ie(R,Se,ge,!0,!1);for(const Ae of me.holes){const De=ce(Ae);De.length>=4&&Ie(R,De,ge,!0,!1)}}if(Array.isArray(z)&&z.length>0){const ue=ce(Le([[0,0],[e,0],[e,n],[0,n]]));hi({ctx:R,overlayShapes:z,imageOuterRing:ue,worldToScreenPoints:ce,baseStrokeStyle:le,onInvertedFillDebug:globalThis.__OPEN_PLANT_DEBUG_OVERLAY__?me=>{const Se=String(me.id),Ae=`${me.outerRingPoints}|${me.sourceRingCount}|${me.holeRingCount}|${me.fillColor}`;we.current.get(Se)!==Ae&&(we.current.set(Se,Ae),console.debug("[open-plant] invertedFill",me))}:void 0})}const Re=ve();if(I){if(t==="brush")Ts(R,v.current,$),Cs(R,v.current,a.current,$);else if(Re.length>0)if(t==="freehand"){const ue=ce(Re);ue.length>=2&&Ie(R,ue,le,!1,!1),ue.length>=3&&Ie(R,ce(Le(Re)),le,!0,!0,ie)}else{const ue=ce(Re);ue.length>=4&&Ie(R,ue,le,!0,!0,ie)}}if(Q.length>0){const ue=Math.max(1e-6,a.current?.getViewState?.().zoom??1),me=typeof O=="number"&&Number.isFinite(O)?Math.max(0,O):kn(D,ue,a.current?.getZoomRange?.(),a.current?.getRegionLabelAutoLiftCapZoom?.());for(const Se of Q){if(!Se.region.label)continue;const Ae=Dn(Se.polygons,C);if(!Ae)continue;const De=We(a.current?.worldToScreen(Ae[0],Ae[1])??[]);if(!De)continue;let ze=Bn(he,M?.({region:Se.region,regionId:Se.regionKey,regionIndex:Se.regionIndex,zoom:ue}));me>0&&(ze={...ze,offsetY:ze.offsetY+me}),fi(R,Se.region.label,De,k,j,ze,Y)}}if(q.enabled&&I&&(t==="freehand"||t==="rectangle"||t==="circular")){const ue=v.current;if(ue.isDrawing){const me=t==="freehand"?Le(Re):Re;if(me.length>=4){const Se=Ot(me),Ae=typeof r=="number"&&Number.isFinite(r)&&r>0?r:0,De=Ae>0?Se*Ae*Ae/(hr*hr):0,ze=q.format(De),$e=ue.cursorScreen??(ue.current?We(a.current?.worldToScreen(ue.current[0],ue.current[1])??[]):null);$e&&ks(R,ze,$e,k,j,q.style,q.cursorOffsetX,q.cursorOffsetY)}}}},[I,t,ve,J,ce,e,n,a,Q,z,L,V,le,de,ae,ie,se,ge,T,M,he,q,D,C,Y,O,r,$]),P=p.useCallback(()=>{Me.current||(Me.current=!0,requestAnimationFrame(()=>{Me.current=!1,U()}))},[U]),X=p.useCallback((E=!1)=>{const R=v.current,F=ne.current;F&&R.pointerId!==null&&F.hasPointerCapture(R.pointerId)&&F.releasePointerCapture(R.pointerId),R.isDrawing=!1,R.pointerId=null,R.start=null,R.current=null,R.points=[],R.screenPoints=[],R.stampCenter=null,E||(R.cursor=null,R.cursorScreen=null)},[]),G=p.useCallback(E=>{const R=a.current;if(!R||e<=0||n<=0)return null;const F=We(R.screenToWorld(E.clientX,E.clientY));return F?Ht(F,e,n):null},[a,e,n]),te=p.useCallback(E=>{const R=ne.current;if(!R)return null;const F=R.getBoundingClientRect(),k=_(E.clientX-F.left,0,F.width),j=_(E.clientY-F.top,0,F.height);return!Number.isFinite(k)||!Number.isFinite(j)?null:[k,j]},[]),ee=p.useCallback(()=>{const E=v.current;if(!E.isDrawing){X(!0),P();return}let R=[];if(t==="freehand")E.points.length>=Qo&&(R=Le(E.points));else if(t==="rectangle")R=Zt(E.start,E.current,Ee());else if(t==="circular")R=yn(E.start,E.current);else if(t==="brush"){const F=E.points[E.points.length-1]??E.current??E.start;if($.clickSelectRoi&&F&&E.points.length<=1&&l?.(F)){X(!0),P();return}const k=Math.max(.25,$.edgeDetail),j=E.screenPoints.length>0?E.screenPoints:ce(E.points),Re=Math.max(.5,$.radius*.04/k),ue=Ko(j,{radius:$.radius,circleSides:Math.max(16,Math.round(32*k)),simplifyTolerance:Re,smoothingPasses:$.edgeSmoothing}),me=[];for(const Se of ue){const Ae=xe(Se);Ae&&me.push(Ae)}R=Le(me)}(t==="freehand"||t==="rectangle"||t==="circular"||t==="brush")&&xr(R)&&u&&u({tool:t,intent:t==="brush"?"brush":"roi",coordinates:R,bbox:mr(R),areaPx:Ot(R)}),X(!0),P()},[t,u,X,P,ce,xe,Ee,$.radius,$.edgeDetail,$.edgeSmoothing,$.clickSelectRoi,l]),Ce=p.useCallback((E,R)=>{const F=ye(E,R);if(!xr(F))return;const k=E==="stamp-rectangle-4096px"?"patch":"roi",j={tool:E,intent:k,coordinates:F,bbox:mr(F),areaPx:Ot(F)};u?.(j),k==="patch"&&f&&f(j)},[ye,u,f]),Ue=p.useCallback((E,R,F)=>{const k=Math.max(ys,$.radius*.1),j=k*k,Re=E.screenPoints[E.screenPoints.length-1];if(!Re){E.points.push(R),E.screenPoints.push(F),E.current=R;return}const ue=F[0]-Re[0],me=F[1]-Re[1];ue*ue+me*me>=j?(E.points.push(R),E.screenPoints.push(F)):(E.points[E.points.length-1]=R,E.screenPoints[E.screenPoints.length-1]=F),E.current=R},[$.radius]),Ze=p.useCallback(E=>{if(!I||t==="cursor"||E.button!==0)return;const R=G(E);if(!R)return;const F=te(E);if(!F)return;if(E.preventDefault(),E.stopPropagation(),It(t)){const Re=v.current;Re.stampCenter=R,Ce(t,R),P();return}const k=ne.current;k&&k.setPointerCapture(E.pointerId);const j=v.current;j.isDrawing=!0,j.pointerId=E.pointerId,j.start=R,j.current=R,j.cursor=R,j.cursorScreen=F,j.points=t==="freehand"||t==="brush"?[R]:[],j.screenPoints=t==="brush"?[F]:[],P()},[I,t,G,te,Ce,P]),tt=p.useCallback(E=>{if(!I||t==="cursor")return;const R=G(E);if(!R)return;const F=te(E);if(!F)return;const k=v.current;if(k.cursor=R,k.cursorScreen=F,It(t)){k.stampCenter=R,E.preventDefault(),E.stopPropagation(),P();return}if(t==="brush"){if(!k.isDrawing||k.pointerId!==E.pointerId){P();return}E.preventDefault(),E.stopPropagation(),Ue(k,R,F),P();return}if(!(!k.isDrawing||k.pointerId!==E.pointerId)){if(E.preventDefault(),E.stopPropagation(),t==="freehand"){const j=a.current,Re=Math.max(1e-6,j?.getViewState?.().zoom??1),ue=Jo/Re,me=ue*ue,Se=k.points[k.points.length-1];if(!Se)k.points.push(R);else{const Ae=R[0]-Se[0],De=R[1]-Se[1];Ae*Ae+De*De>=me&&k.points.push(R)}}else k.current=R;P()}},[I,t,G,te,P,a,Ue]),ot=p.useCallback(E=>{const R=v.current;if(!R.isDrawing||R.pointerId!==E.pointerId)return;E.preventDefault(),E.stopPropagation();const F=G(E),k=te(E);F&&(R.cursor=F,k&&(R.cursorScreen=k),t==="brush"?k&&Ue(R,F,k):R.current=F);const j=ne.current;j&&j.hasPointerCapture(E.pointerId)&&j.releasePointerCapture(E.pointerId),ee()},[ee,G,te,t,Ue]),Gi=p.useCallback(()=>{const E=v.current;let R=!1;t==="brush"&&!E.isDrawing&&E.cursor&&(E.cursor=null,E.cursorScreen=null,R=!0),It(t)&&E.stampCenter&&(E.stampCenter=null,R=!0),R&&P()},[t,P]);return p.useEffect(()=>{J(),P();const E=ne.current;if(!E)return;const R=new ResizeObserver(()=>{J(),P()});return R.observe(E),()=>{R.disconnect()}},[J,P]),p.useEffect(()=>{I||X(),P()},[I,P,X]),p.useEffect(()=>{Te.current!==t&&(Te.current=t,X(),P())},[t,X,P]),p.useEffect(()=>{P()},[h,B,z,P]),p.useEffect(()=>{if(N)return N.current=P,()=>{N.current===P&&(N.current=null)}},[N,P]),p.useEffect(()=>{if(!I)return;const E=R=>{R.key==="Escape"&&(X(),P())};return window.addEventListener("keydown",E),()=>{window.removeEventListener("keydown",E)}},[I,X,P]),Ye.jsx("canvas",{ref:ne,className:Z,style:re,onPointerDown:Ze,onPointerMove:tt,onPointerUp:ot,onPointerCancel:ot,onPointerLeave:Gi,onContextMenu:E=>{I&&E.preventDefault()},onWheel:E=>{if(!I)return;const R=ne.current,F=a.current;if(!R||typeof F?.zoomBy!="function")return;E.preventDefault(),E.stopPropagation();const k=R.getBoundingClientRect(),j=E.clientX-k.left,Re=E.clientY-k.top;F.zoomBy(E.deltaY<0?rs:is,j,Re),P()}})}const mi=p.createContext(null),Gs=mi.Provider;function it(){const t=p.useContext(mi);if(!t)throw new Error("useViewerContext must be used within a <WsiViewer>");return t}function Hs({tool:t="cursor",stampOptions:e,brushOptions:n,fillColor:r,areaTooltip:i,onComplete:o,onPatchComplete:s,onBrushTap:a}){const{source:l,rendererRef:u,rendererSerial:f,setInteractionLock:c}=it(),h=t!=="cursor";p.useEffect(()=>(c("drawing-layer",h),()=>c("drawing-layer",!1)),[h,c]);const d=p.useMemo(()=>u.current?.getViewState(),[f]);return l?Ye.jsx(di,{tool:t,enabled:h,imageWidth:l.width,imageHeight:l.height,imageMpp:l.mpp,imageZoom:l.maxTierZoom,stampOptions:e,brushOptions:n,drawFillColor:r,projectorRef:u,onBrushTap:a,viewStateSignal:d,drawAreaTooltip:i,onDrawComplete:o,onPatchComplete:s}):null}function wr(t,e,n,r){return[Math.min(t,n),Math.min(e,r),Math.max(t,n),Math.max(e,r)]}function Sr(t,e){return!(t[2]<e[0]||t[0]>e[2]||t[3]<e[1]||t[1]>e[3])}class qs{constructor(e=16){S(this,"targetNodeSize");S(this,"items",[]);S(this,"globalBounds",[0,0,0,0]);S(this,"gridSize",1);S(this,"cellWidth",1);S(this,"cellHeight",1);S(this,"buckets",[]);S(this,"visited",new Uint32Array(0));S(this,"querySerial",1);const n=Number.isFinite(e)?Math.floor(e):16;this.targetNodeSize=Math.max(1,n)}load(e){if(!Array.isArray(e)||e.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 e){if(!f||!Number.isFinite(f.minX)||!Number.isFinite(f.minY)||!Number.isFinite(f.maxX)||!Number.isFinite(f.maxY))continue;const c=wr(f.minX,f.minY,f.maxX,f.maxY);r=Math.min(r,c[0]),i=Math.min(i,c[1]),o=Math.max(o,c[2]),s=Math.max(s,c[3]),n.push({minX:c[0],minY:c[1],maxX:c[2],maxY:c[3],value:f.value})}if(this.items=n,this.visited=new Uint32Array(n.length),this.querySerial=1,n.length===0||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(o)||!Number.isFinite(s)){this.globalBounds=[0,0,0,0],this.gridSize=1,this.cellWidth=1,this.cellHeight=1,this.buckets=[];return}this.globalBounds=[r,i,o,s],this.gridSize=Math.max(1,Math.ceil(Math.sqrt(n.length/this.targetNodeSize)));const a=Math.max(0,o-r),l=Math.max(0,s-i);this.cellWidth=a>0?a/this.gridSize:1,this.cellHeight=l>0?l/this.gridSize:1;const u=this.gridSize*this.gridSize;this.buckets=Array.from({length:u},()=>[]);for(let f=0;f<n.length;f+=1){const c=n[f],h=this.toCellX(c.minX),d=this.toCellX(c.maxX),m=this.toCellY(c.minY),g=this.toCellY(c.maxY);for(let y=m;y<=g;y+=1)for(let b=h;b<=d;b+=1)this.buckets[y*this.gridSize+b].push(f)}}search(e){if(this.items.length===0)return[];if(!Array.isArray(e)||e.length<4)return[];const n=wr(e[0],e[1],e[2],e[3]);if(!Sr(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];Sr(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(e){const n=this.globalBounds[0],r=this.globalBounds[2];if(this.gridSize<=1||r<=n)return 0;const i=(e-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(e){const n=this.globalBounds[1],r=this.globalBounds[3];if(this.gridSize<=1||r<=n)return 0;const i=(e-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 gi(t){return new qs(t)}const Zs=`#version 300 es
|
|
34
34
|
precision highp float;
|
|
35
35
|
in vec2 aCenter;
|
|
36
36
|
in float aWeight;
|
|
@@ -100,7 +100,7 @@ void main() {
|
|
|
100
100
|
float alpha = gradientColor.a * clamp(uOpacity, 0.0, 1.0);
|
|
101
101
|
if (alpha <= 0.0001) discard;
|
|
102
102
|
outColor = vec4(gradientColor.rgb * alpha, alpha);
|
|
103
|
-
}`;class Qs{constructor(){S(this,"canvas");S(this,"gl");S(this,"accumProgram");S(this,"colorProgram");S(this,"accumVao");S(this,"colorVao");S(this,"pointBuffer");S(this,"quadBuffer");S(this,"accumTexture");S(this,"gradientTexture");S(this,"framebuffer");S(this,"accumInternalFormat");S(this,"accumTextureFormat");S(this,"accumTextureType");S(this,"uAccumResolution");S(this,"uAccumPointSize");S(this,"uAccumCoreRatio");S(this,"uAccumPointAlpha");S(this,"uColorAccumTexture");S(this,"uColorGradientTexture");S(this,"uColorOpacity");S(this,"uColorCutoff");S(this,"uColorGain");S(this,"uColorResolution");S(this,"uColorGamma");S(this,"uColorBias");S(this,"uColorStretch");S(this,"pointCapacity",0);S(this,"interleavedCapacity",0);S(this,"interleavedBuffer",null);S(this,"gradientKey","");this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,preserveDrawingBuffer:!0,premultipliedAlpha:!0,powerPreference:"high-performance"});if(!e)throw new Error("WebGL2 is not available for heatmap rendering.");this.gl=e;const r=!!e.getExtension("EXT_color_buffer_float");this.accumInternalFormat=r?e.RGBA16F:e.RGBA8,this.accumTextureFormat=e.RGBA,this.accumTextureType=r?e.HALF_FLOAT:e.UNSIGNED_BYTE,this.accumProgram=gt(e,Zs,$s),this.colorProgram=gt(e,Ks,js);const i=e.createVertexArray(),o=e.createVertexArray(),s=e.createBuffer(),a=e.createBuffer(),l=e.createTexture(),u=e.createTexture(),f=e.createFramebuffer();if(!i||!o||!s||!a||!l||!u||!f)throw new Error("Failed to allocate heatmap WebGL resources.");this.accumVao=i,this.colorVao=o,this.pointBuffer=s,this.quadBuffer=a,this.accumTexture=l,this.gradientTexture=u,this.framebuffer=f;const c=e.getUniformLocation(this.accumProgram,"uResolution"),h=e.getUniformLocation(this.accumProgram,"uPointSize"),d=e.getUniformLocation(this.accumProgram,"uCoreRatio"),m=e.getUniformLocation(this.accumProgram,"uPointAlpha"),g=e.getUniformLocation(this.colorProgram,"uAccumTexture"),y=e.getUniformLocation(this.colorProgram,"uGradientTexture"),b=e.getUniformLocation(this.colorProgram,"uOpacity"),x=e.getUniformLocation(this.colorProgram,"uCutoff"),M=e.getUniformLocation(this.colorProgram,"uGain"),w=e.getUniformLocation(this.colorProgram,"uGamma"),T=e.getUniformLocation(this.colorProgram,"uBias"),A=e.getUniformLocation(this.colorProgram,"uStretch"),k=e.getUniformLocation(this.colorProgram,"uResolution");if(!c||!h||!d||!m||!g||!y||!b||!x||!M||!w||!T||!A||!k)throw new Error("Failed to resolve heatmap WebGL uniforms.");this.uAccumResolution=c,this.uAccumPointSize=h,this.uAccumCoreRatio=d,this.uAccumPointAlpha=m,this.uColorAccumTexture=g,this.uColorGradientTexture=y,this.uColorOpacity=b,this.uColorCutoff=x,this.uColorGain=M,this.uColorGamma=w,this.uColorBias=T,this.uColorStretch=A,this.uColorResolution=k,e.bindVertexArray(this.accumVao),e.bindBuffer(e.ARRAY_BUFFER,this.pointBuffer),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const L=e.getAttribLocation(this.accumProgram,"aCenter"),W=e.getAttribLocation(this.accumProgram,"aWeight");if(L<0||W<0)throw new Error("Failed to resolve heatmap WebGL attributes.");e.enableVertexAttribArray(L),e.vertexAttribPointer(L,2,e.FLOAT,!1,12,0),e.enableVertexAttribArray(W),e.vertexAttribPointer(W,1,e.FLOAT,!1,12,8),e.bindVertexArray(null),e.bindVertexArray(this.colorVao),e.bindBuffer(e.ARRAY_BUFFER,this.quadBuffer),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),e.STATIC_DRAW);const D=e.getAttribLocation(this.colorProgram,"aPosition");if(D<0)throw new Error("Failed to resolve heatmap color position attribute.");e.enableVertexAttribArray(D),e.vertexAttribPointer(D,2,e.FLOAT,!1,8,0),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),e.bindTexture(e.TEXTURE_2D,this.accumTexture),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.bindTexture(e.TEXTURE_2D,null),e.bindTexture(e.TEXTURE_2D,this.gradientTexture),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.bindTexture(e.TEXTURE_2D,null),this.ensureCanvasSize(1,1)}render(e){if(e.count<=0||e.width<=0||e.height<=0)return!1;this.ensureCanvasSize(e.width,e.height),this.ensureGradientTexture(e.gradient),this.uploadPointData(e.positions,e.weights,e.count);const n=this.gl;return n.disable(n.SCISSOR_TEST),n.disable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.bindFramebuffer(n.FRAMEBUFFER,this.framebuffer),n.viewport(0,0,e.width,e.height),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.useProgram(this.accumProgram),n.bindVertexArray(this.accumVao),n.uniform2f(this.uAccumResolution,e.width,e.height),n.uniform1f(this.uAccumPointSize,Math.max(1,(e.kernelRadiusPx+e.blurRadiusPx)*2)),n.uniform1f(this.uAccumCoreRatio,e.kernelRadiusPx/Math.max(1e-6,e.kernelRadiusPx+e.blurRadiusPx)),n.uniform1f(this.uAccumPointAlpha,Math.max(0,e.pointAlpha)),n.enable(n.BLEND),n.blendEquation(n.FUNC_ADD),n.blendFuncSeparate(n.ONE,n.ONE,n.ONE,n.ONE),n.drawArrays(n.POINTS,0,e.count),n.disable(n.BLEND),n.bindVertexArray(null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,e.width,e.height),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.useProgram(this.colorProgram),n.bindVertexArray(this.colorVao),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,this.accumTexture),n.uniform1i(this.uColorAccumTexture,0),n.activeTexture(n.TEXTURE1),n.bindTexture(n.TEXTURE_2D,this.gradientTexture),n.uniform1i(this.uColorGradientTexture,1),n.uniform1f(this.uColorOpacity,e.opacity),n.uniform1f(this.uColorCutoff,e.cutoff??.008),n.uniform1f(this.uColorGain,e.gain??2.6),n.uniform1f(this.uColorGamma,e.gamma??1),n.uniform1f(this.uColorBias,e.bias??0),n.uniform1f(this.uColorStretch,e.stretch??1),n.uniform2f(this.uColorResolution,e.width,e.height),n.drawArrays(n.TRIANGLE_STRIP,0,4),n.bindVertexArray(null),n.bindTexture(n.TEXTURE_2D,null),n.flush(),!0}destroy(){const e=this.gl;e.deleteTexture(this.accumTexture),e.deleteTexture(this.gradientTexture),e.deleteFramebuffer(this.framebuffer),e.deleteBuffer(this.pointBuffer),e.deleteBuffer(this.quadBuffer),e.deleteVertexArray(this.accumVao),e.deleteVertexArray(this.colorVao),e.deleteProgram(this.accumProgram),e.deleteProgram(this.colorProgram),this.canvas.width=0,this.canvas.height=0}ensureCanvasSize(e,n){const r=Math.max(1,Math.round(e)),i=Math.max(1,Math.round(n));this.canvas.width!==r&&(this.canvas.width=r),this.canvas.height!==i&&(this.canvas.height=i);const o=this.gl;o.bindTexture(o.TEXTURE_2D,this.accumTexture),o.texImage2D(o.TEXTURE_2D,0,this.accumInternalFormat,r,i,0,this.accumTextureFormat,this.accumTextureType,null),o.bindFramebuffer(o.FRAMEBUFFER,this.framebuffer),o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,this.accumTexture,0);const s=o.checkFramebufferStatus(o.FRAMEBUFFER);if(o.bindFramebuffer(o.FRAMEBUFFER,null),s!==o.FRAMEBUFFER_COMPLETE)throw new Error(`Heatmap framebuffer incomplete: ${s}`)}ensureGradientTexture(e){const n=e.join("|");if(this.gradientKey===n)return;const r=document.createElement("canvas");r.width=256,r.height=1;const i=r.getContext("2d");if(!i)throw new Error("Failed to create heatmap gradient canvas.");const o=i.createLinearGradient(0,0,256,0),s=e.length>1?e:["#00000000","#3876FF","#4CDDDD","#FFE75C","#FF8434","#FF3434"],a=1/Math.max(1,s.length-1);for(let f=0;f<s.length;f+=1)o.addColorStop(f*a,s[f]);i.clearRect(0,0,256,1),i.fillStyle=o,i.fillRect(0,0,256,1);const l=i.getImageData(0,0,256,1).data,u=this.gl;u.bindTexture(u.TEXTURE_2D,this.gradientTexture),u.texImage2D(u.TEXTURE_2D,0,u.RGBA,256,1,0,u.RGBA,u.UNSIGNED_BYTE,l),u.bindTexture(u.TEXTURE_2D,null),this.gradientKey=n}uploadPointData(e,n,r){const i=this.gl,o=r*3,s=o*4;i.bindBuffer(i.ARRAY_BUFFER,this.pointBuffer),r>this.pointCapacity&&(i.bufferData(i.ARRAY_BUFFER,s,i.DYNAMIC_DRAW),this.pointCapacity=r),o>this.interleavedCapacity&&(this.interleavedCapacity=o,this.interleavedBuffer=new Float32Array(o));const a=this.interleavedBuffer;if(!a)throw new Error("Failed to allocate heatmap upload buffer.");for(let l=0;l<r;l+=1){const u=l*2,f=l*3;a[f]=e[u]??0,a[f+1]=e[u+1]??0,a[f+2]=n[l]??0}i.bufferSubData(i.ARRAY_BUFFER,0,a.subarray(0,o)),i.bindBuffer(i.ARRAY_BUFFER,null)}}const Rr="__open_plant_heatmap_layer__",Js=["#00000000","#3876FF","#4CDDDD","#FFE75C","#FF8434","#FF3434"],ea=3,ta=2,na=.9,ra=52e3,ia="screen",oa=2.2,bn=128,$t=1600,sa=1.9,aa=4.2,xn=3e3,pi=Math.SQRT2,la=2048,ca=.9,Ve=16;function Et(t,e){return e.maxTierZoom+Math.log2(Math.max(1e-6,t))}function Un(t,e){return Math.max(1e-6,2**(t-e.maxTierZoom))}function ua(t,e,n){if(!Number.isFinite(n)||Math.abs(n)<1e-6)return Math.max(1e-6,t);const r=Et(t,e)-n;return Un(r,e)}function fa(t){return!Number.isFinite(t)||Math.abs(t)<1e-6?0:Math.round(t*1.5/Math.max(1e-6,Math.log2(pi)))}function yi(t){const e=I(t,0,Ve);return I(.55+Math.sqrt(Math.max(0,e))*.48,.55,6)}function ha(t){const e=Math.max(0,t);return e<=1?.18:e<=2?.3:e<=4?.48:e<=8?.7:e<=16?.86:1}function bi(t){return .022-I(t,0,Ve)/Ve*.015}function xi(t){const e=I(t,0,Ve);return .18+Math.pow(Math.max(0,e),.72)*.42+Math.log2(e+1)*.24}function wi(t){return yi(t)}function Si(t){const n=I(t,0,Ve)/Ve;return I(.46-n*.34,.12,.46)}function Ri(t,e,n){const i=I(t,0,Ve)/Ve,o=Et(e,n),s=n.maxTierZoom-3.2,a=n.maxTierZoom-1.15,l=I((o-s)/Math.max(1e-6,a-s),0,1),u=1.12+Math.pow(i,.82)*1.18,f=1+l*(.48+i*.92);return u*f}function da(t,e,n){const r=Math.max(0,t),i=Math.max(1e-6,e),o=Math.log1p(r)/Math.log1p(i);return I(o,0,1)}function ma(t){return ca}function ga(t,e){if(t.length===0)return 1;const n=Math.min(t.length,la),r=new Array(n);let i=1;for(let f=0;f<n;f+=1){const c=Math.min(t.length-1,Math.floor((f+.5)*t.length/n)),h=Math.max(0,t[c]?.weight??0);r[f]=h,h>i&&(i=h)}for(let f=0;f<t.length;f+=1){const c=Math.max(0,t[f]?.weight??0);c>i&&(i=c)}r.sort((f,c)=>f-c);const o=ma(),s=Math.max(0,Math.min(r.length-1,Math.floor((r.length-1)*o))),a=r[s]??i;return Math.max(1,Math.min(i,Math.max(a*1.08,i*.14)))}function Ei(t,e,n){const r=Et(t,e),i=e.maxTierZoom-2.45,o=e.maxTierZoom-1.2,s=r<=i?1:r>=o?0:(()=>{const a=I((r-i)/Math.max(1e-6,o-i),0,1);return 1-a*a*(3-2*a)})();return I(s,0,1)}function pa(t){if(t>=1)return 1;const e=1/Math.max(t,1e-6);return 1+Math.log2(e)*.28}function ya(t,e,n,r){const i=Math.max(1,t,e),o=typeof window>"u"?1:I(window.devicePixelRatio||1,1,2.4),s=r<=.35?1.42:r<=.55?1.26:r<=.8?1.14:1,a=n>16e4?896:n>8e4?1152:n>3e4?1408:$t,l=bn/i,u=$t/i;return I(a*o*s/i,l,u)}function wn(t){const e=t.heatmapScale??ya(t.logicalWidth,t.logicalHeight,t.totalPointCount,t.rawZoom),n=Math.max(bn,Math.min($t,Math.round(t.logicalWidth*e))),r=Math.max(bn,Math.min($t,Math.round(t.logicalHeight*e))),i=n/Math.max(1,t.logicalWidth),o=r/Math.max(1,t.logicalHeight),s=Math.min(i,o),a=Math.max(1e-6,t.rawZoom),l=Math.max(.75,t.radius*sa*s),u=Math.max(.6,t.blur*aa*s),f=(l+u)/Math.max(1e-6,a*s),c=Math.max(f*.4,.62/Math.max(1e-6,a*s));return{heatmapScale:e,rasterWidth:n,rasterHeight:r,rasterScaleX:i,rasterScaleY:o,rawZoom:a,kernelRadiusPx:l,blurRadiusPx:u,outerWorldRadius:f,desiredCellWorldSize:c}}function zn(t){if(!t)return 0;const e=Math.floor(t.positions.length/2),n=t.weights?t.weights.length:Number.MAX_SAFE_INTEGER;return Math.max(0,Math.min(Math.floor(t.count),e,n))}function It(t,e){const n=Number.isFinite(t)?Math.round(t*1024):0;return Math.imul(e^n,73244475)>>>0}function ba(t,e,n=2654435769){let r=Math.imul(n^(t|0),2246822507)>>>0;return r=Math.imul(r^(e|0),3266489909)>>>0,r^=r>>>16,r>>>0}function xa(t){return(t>>>0)/4294967295}function Ai(t){let e=2166136261;for(let n=0;n<t.length;n+=1){const r=t[n];e=Math.imul(e^r.outer.length,16777619)>>>0;for(let i=0;i<r.outer.length;i+=1){const o=r.outer[i];e=It(o[0],e),e=It(o[1],e)}e=Math.imul(e^r.holes.length,16777619)>>>0;for(let i=0;i<r.holes.length;i+=1){const o=r.holes[i];e=Math.imul(e^o.length,16777619)>>>0;for(let s=0;s<o.length;s+=1){const a=o[s];e=It(a[0],e),e=It(a[1],e)}}}return`${t.length}:${e>>>0}`}function On(t,e,n){return t.dataRef===e&&t.clipKey===n?!0:e?t.clipKey===n&&t.inputCount===zn(e)&&t.positionsRef===e.positions&&t.weightsRef===e.weights:!1}function wa(t,e,n,r){const i=zn(t);if(!t||i<=0)return null;let o=new Float32Array(i),s=new Float32Array(i),a=new Float32Array(i),l=0,u=1/0,f=1/0,c=-1/0,h=-1/0;for(let M=0;M<i;M+=1){const w=t.positions[M*2],T=t.positions[M*2+1];if(!Number.isFinite(w)||!Number.isFinite(T)||e.length>0&&!bt(w,T,e))continue;const A=t.weights?.[M],k=typeof A=="number"&&Number.isFinite(A)?Math.max(0,A):1;k<=0||(o[l]=w,s[l]=T,a[l]=k,l+=1,w<u&&(u=w),w>c&&(c=w),T<f&&(f=T),T>h&&(h=T))}if(l===0||!Number.isFinite(u)||!Number.isFinite(f)||!Number.isFinite(c)||!Number.isFinite(h))return null;l<i&&(o=o.slice(0,l),s=s.slice(0,l),a=a.slice(0,l));const d=[];for(let M=0;M<l;M+=1){const w=o[M],T=s[M];d.push({minX:w,minY:T,maxX:w,maxY:T,value:M})}const m=gi(64);m.load(d);const g=Math.max(r?.width??0,r?.height??0,c-u,h-f,1),y=[];let b=.5,x=0;for(;b<=g&&x<32;)y.push(b),b*=pi,x+=1;return y.length===0&&y.push(1),{dataRef:t,sourceRef:r,positionsRef:t.positions,weightsRef:t.weights,inputCount:i,clipRef:e,clipKey:n,pointCount:l,xs:o,ys:s,ws:a,pointIndex:m,cellSizes:y,levels:Array.from({length:y.length},()=>null)}}function Sn(t,e,n){const r=t.pointIndex.search([e[0]-n,e[1]-n,e[2]+n,e[3]+n]),i=new Array(r.length);let o=0;for(let s=0;s<r.length;s+=1){const a=r[s];a&&(i[o]=a.value,o+=1)}return i.length=o,i}function Mi(t,e){const n=Math.max(xn,e);return t<=n?1:I(n/Math.max(1,t),1/65536,1)}function Ti(t){return t>=1?1:Math.max(1,Math.round(1/Math.max(1e-6,t)))}function Sa(t,e){if(e>=1)return!0;const n=ba(t,1374496523,1757159915);return xa(n)<=I(e,0,1)}function Ci(t,e,n,r){const i=Math.max(1,n*r),o=Math.PI*e*e,s=Math.max(1,t)*o/i;return I(.085/Math.sqrt(Math.max(1,s)),.012,.075)}function Er(t,e,n,r){if(!Number.isFinite(t)||t<=0)return e;const i=e>=t?n:r;return t+(e-t)*I(i,0,1)}function Ra(t){if(t.webgl!==void 0)return t.webgl;if(typeof document>"u")return t.webgl=null,null;try{t.webgl=new Qs}catch(e){if(!t.webglWarningIssued&&typeof console<"u"&&typeof console.warn=="function"){const n=e instanceof Error?e.message:String(e);console.warn(`[open-plant] HeatmapLayer disabled because WebGL2 heatmap initialization failed: ${n}`),t.webglWarningIssued=!0}t.webgl=null}return t.webgl}function Ar(t,e){const n=[];for(let r=0;r<e.length;r+=1){const i=e[r];if(!i)continue;const o=t.worldToScreen(i[0],i[1]);if(!Array.isArray(o)||o.length<2)continue;const s=Number(o[0]),a=Number(o[1]);!Number.isFinite(s)||!Number.isFinite(a)||n.push([s,a])}return n}function Ea(t,e,n){if(n.length!==0){t.beginPath();for(let r=0;r<n.length;r+=1){const i=n[r],o=Ar(e,i.outer);o.length>=3&&xt(t,o,!0);for(let s=0;s<i.holes.length;s+=1){const a=Ar(e,i.holes[s]);a.length>=3&&xt(t,a,!0)}}t.clip("evenodd")}}function vi(t,e,n,r,i){const o=t.sourceData;return o&&o.sourceRef===i&&On(o,e,r)?o:(t.sourceData=wa(e,n,r,i),t.fixedState=null,t.screenLevelIndex=-1,t.sourceData)}function Aa(t){const{sourceData:e,renderer:n,source:r,logicalWidth:i,logicalHeight:o,radius:s,blur:a,fixedZoom:l,maxRenderedPoints:u}=t,f=Math.max(1e-6,n.getViewState().zoom),c=l??Et(f,r),h=Un(c,r),d=wn({logicalWidth:i,logicalHeight:o,totalPointCount:e.pointCount,rawZoom:h,radius:s,blur:a}),m=n.getViewBounds(),g=Sn(e,m,d.outerWorldRadius),y=Mi(g.length,u),b=Ti(y),x=Math.min(d.rasterScaleX,d.rasterScaleY);return{dataRef:e.dataRef,positionsRef:e.positionsRef,weightsRef:e.weightsRef,inputCount:e.inputCount,clipRef:e.clipRef,clipKey:e.clipKey,referenceZoom:c,referenceRawZoom:h,heatmapScale:d.heatmapScale,kernelWorldRadius:d.kernelRadiusPx/Math.max(1e-6,h*x),blurWorldRadius:d.blurRadiusPx/Math.max(1e-6,h*x),sampleProbability:y,sampleStride:b,pointAlpha:Ci(g.length,d.kernelRadiusPx+d.blurRadiusPx,d.rasterWidth,d.rasterHeight)}}function Mr(t){const{ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,frame:a,sourceData:l,visiblePointIndices:u,sampleProbability:f,sampleStride:c,pointAlpha:h,gradient:d,opacity:m,densityContrast:g,backgroundColor:y,clipPolygons:b}=t,x=Ra(n);if(!x||u.length===0)return 0;const M=Math.min(u.length,Math.max(64,Math.ceil(u.length*Math.min(1,f*1.15))));M>n.webglCapacity&&(n.webglCapacity=M,n.webglPositions=new Float32Array(M*2),n.webglWeights=new Float32Array(M));const w=n.webglPositions,T=n.webglWeights;if(!w||!T)return 0;const A=a.kernelRadiusPx+a.blurRadiusPx,k=pa(f);let L=0;for(let D=0;D<u.length;D+=1){const G=u[D];if(!Sa(G,f))continue;const U=l.xs[G],v=l.ys[G];if(!Number.isFinite(U)||!Number.isFinite(v))continue;const Y=r.worldToScreen(U,v);if(!Array.isArray(Y)||Y.length<2)continue;const B=Number(Y[0]),z=Number(Y[1]);if(!Number.isFinite(B)||!Number.isFinite(z))continue;const Z=B*a.rasterScaleX,ae=z*a.rasterScaleY;if(Z<-A||ae<-A||Z>a.rasterWidth+A||ae>a.rasterHeight+A)continue;const te=L*2;w[te]=Z,w[te+1]=ae,T[L]=Math.max(0,(l.ws[G]??0)*k),L+=1}return L<=0||!x.render({width:a.rasterWidth,height:a.rasterHeight,positions:w,weights:T,count:L,kernelRadiusPx:a.kernelRadiusPx,blurRadiusPx:a.blurRadiusPx,pointAlpha:h,gradient:d,opacity:m,cutoff:bi(g),gain:xi(g),gamma:wi(g),bias:Si(g),stretch:Ri(g,a.rawZoom,i)})?0:(e.save(),b.length>0&&Ea(e,r,b),y&&(e.fillStyle=y,e.fillRect(0,0,o,s)),e.globalAlpha=1,e.imageSmoothingEnabled=!0,e.drawImage(x.canvas,0,0,a.rasterWidth,a.rasterHeight,0,0,o,s),e.restore(),L)}function Ma(t){const{ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,state:a}=t,l=vi(n,a.data,a.clipPolygons,a.clipKey,i);if(!l||l.cellSizes.length===0||l.pointCount<=0)return null;const u=Math.max(1e-6,r.getViewState().zoom),f=Ei(u,i,a.zoomThreshold),c=r.getViewBounds();if(f<=.001)return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:0,renderedBinCount:0,sampleStride:1,maxDensity:0};if(a.scaleMode!=="fixed-zoom"){const b=wn({logicalWidth:o,logicalHeight:s,totalPointCount:l.pointCount,rawZoom:u,radius:a.radius,blur:a.blur}),x=Sn(l,c,b.outerWorldRadius);if(x.length===0)return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:0,renderedBinCount:0,sampleStride:1,maxDensity:0};const M=Mi(x.length,a.maxRenderedPoints),w=Ti(M),T=Ci(x.length,b.kernelRadiusPx+b.blurRadiusPx,b.rasterWidth,b.rasterHeight);n.screenLevelIndex=-1,n.screenSecondaryLevelIndex=-1,n.screenSecondaryLevelWeight=0,n.screenNormalizationMaxWeight=1,n.screenPointAlpha=Er(n.screenPointAlpha,T,.12,.08),n.screenVisibilityStrength=r.isViewAnimating()?Er(n.screenVisibilityStrength,f,.16,.12):f;const A=Mr({ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,frame:b,sourceData:l,visiblePointIndices:x,sampleProbability:M,sampleStride:w,pointAlpha:n.screenPointAlpha*Math.max(.08,n.screenVisibilityStrength),gradient:a.gradient,opacity:a.opacity*n.screenVisibilityStrength,densityContrast:a.densityContrast,backgroundColor:a.backgroundColor,clipPolygons:a.clipPolygons});return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:x.length,renderedBinCount:A,sampleStride:w,maxDensity:Math.round(n.screenPointAlpha*255)}}const h=n.fixedState;if(!h)return null;const d=wn({logicalWidth:o,logicalHeight:s,totalPointCount:l.pointCount,rawZoom:u,radius:a.radius,blur:a.blur,heatmapScale:h.heatmapScale}),m=Math.min(d.rasterScaleX,d.rasterScaleY);d.kernelRadiusPx=Math.max(.75,h.kernelWorldRadius*u*m),d.blurRadiusPx=Math.max(.6,h.blurWorldRadius*u*m),d.outerWorldRadius=h.kernelWorldRadius+h.blurWorldRadius;const g=Sn(l,c,d.outerWorldRadius);if(g.length===0)return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:0,renderedBinCount:0,sampleStride:1,maxDensity:0};n.screenPointAlpha=h.pointAlpha,n.screenVisibilityStrength=f;const y=Mr({ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,frame:d,sourceData:l,visiblePointIndices:g,sampleProbability:h.sampleProbability,sampleStride:h.sampleStride,pointAlpha:h.pointAlpha*Math.max(.08,f),gradient:a.gradient,opacity:a.opacity*f,densityContrast:a.densityContrast,backgroundColor:a.backgroundColor,clipPolygons:a.clipPolygons});return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:g.length,renderedBinCount:y,sampleStride:h.sampleStride,maxDensity:Math.round(h.pointAlpha*255)}}function Ta({data:t,visible:e=!0,opacity:n=na,radius:r=ea,blur:i=ta,gradient:o=Js,backgroundColor:s=null,scaleMode:a=ia,fixedZoom:l,zoomThreshold:u=0,densityContrast:f=oa,clipToRegions:c,zIndex:h=5,maxRenderedPoints:d=ra,onStats:m}){const{rendererRef:g,source:y,registerDrawCallback:b,unregisterDrawCallback:x,requestOverlayRedraw:M}=rt(),w=p.useMemo(()=>{const L=(c??[]).map(W=>ct(W?.coordinates)).filter(W=>W!=null);return ut(L)},[c]),T=p.useMemo(()=>Ai(w),[w]),A=p.useRef({sourceData:null,fixedState:null,screenLevelIndex:-1,screenSecondaryLevelIndex:-1,screenSecondaryLevelWeight:0,screenPointAlpha:0,screenNormalizationMaxWeight:1,screenVisibilityStrength:1,webgl:void 0,webglWarningIssued:!1,webglPositions:null,webglWeights:null,webglCapacity:0}),k=p.useRef({data:t,visible:e,opacity:n,radius:I(r,.05,128),blur:I(i,.05,128),gradient:o,backgroundColor:s,scaleMode:a,fixedZoom:l,zoomThreshold:u,densityContrast:I(f,0,Ve),clipPolygons:w,clipKey:T,maxRenderedPoints:Math.max(xn,Math.floor(d)),onStats:m});return k.current={data:t,visible:e,opacity:n,radius:I(r,.05,128),blur:I(i,.05,128),gradient:o,backgroundColor:s,scaleMode:a,fixedZoom:l,zoomThreshold:u,densityContrast:I(f,0,Ve),clipPolygons:w,clipKey:T,maxRenderedPoints:Math.max(xn,Math.floor(d)),onStats:m},p.useEffect(()=>(b(Rr,h,(W,D,G)=>{const U=k.current,v=A.current,Y=g.current;if(!U.visible||!U.data||!Y||!y)return;const B=vi(v,U.data,U.clipPolygons,U.clipKey,y);if(!B)return;U.scaleMode==="fixed-zoom"&&(!v.fixedState||!On(v.fixedState,U.data,U.clipKey)||U.fixedZoom!==void 0&&Math.abs(v.fixedState.referenceZoom-U.fixedZoom)>1e-6)?v.fixedState=Aa({sourceData:B,renderer:Y,source:y,logicalWidth:D,logicalHeight:G,radius:U.radius,blur:U.blur,fixedZoom:U.fixedZoom,zoomThreshold:U.zoomThreshold,densityContrast:U.densityContrast,maxRenderedPoints:U.maxRenderedPoints}):U.scaleMode!=="fixed-zoom"&&(v.fixedState=null);const Z=performance.now(),ae=Ma({ctx:W,runtime:v,renderer:Y,source:y,logicalWidth:D,logicalHeight:G,state:U});!ae||!U.onStats||U.onStats({...ae,renderTimeMs:performance.now()-Z})}),()=>{x(Rr),A.current.sourceData=null,A.current.fixedState=null,A.current.screenLevelIndex=-1,A.current.screenSecondaryLevelIndex=-1,A.current.screenSecondaryLevelWeight=0,A.current.screenPointAlpha=0,A.current.screenNormalizationMaxWeight=1,A.current.screenVisibilityStrength=1,A.current.webgl?.destroy(),A.current.webgl=void 0,A.current.webglPositions=null,A.current.webglWeights=null,A.current.webglCapacity=0}),[b,x,g,y,h]),p.useEffect(()=>{A.current.sourceData=null,A.current.fixedState=null,A.current.screenLevelIndex=-1,A.current.screenSecondaryLevelIndex=-1,A.current.screenSecondaryLevelWeight=0,A.current.screenPointAlpha=0,A.current.screenNormalizationMaxWeight=1,A.current.screenVisibilityStrength=1,M()},[t?.positions,t?.weights,t?.count,T,M]),p.useEffect(()=>{A.current.fixedState=null,A.current.screenSecondaryLevelIndex=-1,A.current.screenSecondaryLevelWeight=0,A.current.screenPointAlpha=0,A.current.screenNormalizationMaxWeight=1,A.current.screenVisibilityStrength=1,M()},[r,i,a,l,u,f,d,M]),p.useEffect(()=>{M()},[e,n,o,s,M]),null}const Ca={applyZoomThreshold:ua,buildClipKey:Ai,resolveCellSupportFactor:ha,resolveContinuousZoom:Et,resolveDensityCutoff:bi,resolveDensityBias:Si,resolveDensityGain:xi,resolveDensityGamma:wi,resolveDensityStretch:Ri,resolveNormalizedDensityWeight:da,resolveNormalizationUpperWeight:ga,resolveDensityWeightExponent:yi,resolveRawZoomFromContinuousZoom:Un,resolvePointCount:zn,resolveThresholdLevelBias:fa,resolveZoomVisibilityStrength:Ei,isSameHeatmapInput:On},Tr="__overlay_layer__";function va({shapes:t}){const{rendererRef:e,source:n,registerDrawCallback:r,unregisterDrawCallback:i,requestOverlayRedraw:o}=rt(),s=p.useCallback(l=>{const u=e.current;if(!u||l.length===0)return[];const f=new Array(l.length);for(let c=0;c<l.length;c+=1){const h=We(u.worldToScreen(l[c][0],l[c][1]));if(!h)return[];f[c]=h}return f},[]),a=p.useRef({shapes:t,worldToScreenPoints:s,source:n});return a.current={shapes:t,worldToScreenPoints:s,source:n},p.useEffect(()=>(r(Tr,30,u=>{const{shapes:f,worldToScreenPoints:c,source:h}=a.current;if(!Array.isArray(f)||f.length===0||!h)return;const d=c(Le([[0,0],[h.width,0],[h.width,h.height],[0,h.height]]));hi({ctx:u,overlayShapes:f,imageOuterRing:d,worldToScreenPoints:c,baseStrokeStyle:He})}),()=>i(Tr)),[r,i]),p.useEffect(()=>{o()},[t,o]),null}function Cr(t){return String(t??"").replace(/\/+$/,"")}function Pi(t){const e=String(t??"");return e.startsWith("/")?e:`/${e}`}function Pa(t){const e=Cr(t);if(!e)return"";if(/\/TileGroup\d+$/i.test(e))return e;let n=null;try{n=new URL(e)}catch{n=null}if(n){const r=`${n.protocol}//${n.host}`,i=Cr(n.pathname||"");return/\/ims$/i.test(i)?`${r}${i}`:/\/tiles$/i.test(i)?`${r}${i}`:`${r}${i}/tiles`}return/\/ims$/i.test(e)?"/ims":/\/tiles$/i.test(e)?`${e}`:`${e}/tiles`}function Ia(t,e){const n=t?.imsInfo??{},r=!!t?.imsInfo,i=Number(n.width??t?.width??0),o=Number(n.height??t?.height??0),s=Number(n.tileSize??t?.tileSize??0),a=Number(n.zoom??t?.zoom??0),l=String(n.path??t?.path??""),u=Number(n.mpp??t?.mpp??0);if(!i||!o||!s||!l)throw new Error("Incomplete image metadata: width/height/tileSize/path required");const f=Array.isArray(t?.terms)?t.terms.map(m=>({termId:String(m?.termId??""),termName:String(m?.termName??""),termColor:String(m?.termColor??"")})):[],c=Pi(l),h=Pa(e),d=t?.tileUrlBuilder??(r?(m,g,y)=>`${h}${c}/${m}/${y}_${g}.webp`:void 0);return{id:t?._id||t?.id||"unknown",name:t?.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:e,terms:f,tileUrlBuilder:d}}function Wn(t,e,n,r){if(t.tileUrlBuilder)return t.tileUrlBuilder(e,n,r,t.tilePath,t.tileBaseUrl);const i=Pi(t.tilePath);return`${t.tileBaseUrl}${i}/${e}/${r}_${n}.webp`}function _a(t,e){if(!e)return!1;const n=new URL(t,typeof window<"u"?window.location.href:void 0).hostname.toLowerCase();return!(n.includes("amazonaws.com")||n.startsWith("s3.")||n.includes(".s3."))}const Ne={width:200,height:125,margin:16,position:"bottom-right",borderRadius:6,borderWidth:0,backgroundColor:"rgba(4, 10, 18, 0.88)",borderColor:"rgba(230, 244, 255, 0.35)",viewportBorderColor:"rgba(255, 106, 61, 0.95)",viewportBorderStyle:"dash",viewportFillColor:"transparent",interactive:!0,showThumbnail:!0,maxThumbnailTiles:16};function vr(t,e,n,r){const i=e.length;if(!(i<3)){for(let o=0;o<i;o+=1){const s=e[o],a=e[(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;t.beginPath(),t.moveTo(s[0],s[1]),t.lineTo(a[0],a[1]),t.setLineDash([h,d]),t.lineDashOffset=0,t.stroke()}t.setLineDash([]),t.lineDashOffset=0}}function Pr(t,e,n=1e-4){return Math.abs(t[0]-e[0])<=n&&Math.abs(t[1]-e[1])<=n}function Ir(t){const e=[];for(const n of t){const r=e[e.length-1];(!r||!Pr(r,n))&&e.push(n)}return e.length>1&&Pr(e[0],e[e.length-1])&&e.pop(),e}function _r(t,e,n){const r=e[0]-t[0];if(Math.abs(r)<1e-6)return[n,t[1]];const i=(n-t[0])/r;return[n,t[1]+(e[1]-t[1])*i]}function Fr(t,e,n){const r=e[1]-t[1];if(Math.abs(r)<1e-6)return[t[0],n];const i=(n-t[1])/r;return[t[0]+(e[0]-t[0])*i,n]}function Fa(t,e,n,r,i){let o=Ir(t);if(o.length<3)return[];const s=[{inside:a=>a[0]>=e,intersect:(a,l)=>_r(a,l,e)},{inside:a=>a[0]<=r,intersect:(a,l)=>_r(a,l,r)},{inside:a=>a[1]>=n,intersect:(a,l)=>Fr(a,l,n)},{inside:a=>a[1]<=i,intersect:(a,l)=>Fr(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=Ir(o)}return o.length>=3?o:[]}function st(t,e,n=1){return typeof t!="number"||!Number.isFinite(t)?e:Math.max(n,t)}function ht(t){return Array.isArray(t)&&t.length===4&&Number.isFinite(t[0])&&Number.isFinite(t[1])&&Number.isFinite(t[2])&&Number.isFinite(t[3])}const La={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 Da({source:t,projectorRef:e,authToken:n="",options:r,invalidateRef:i,className:o,style:s}){const a=p.useRef(null),l=p.useRef(null),u=p.useRef(null),f=p.useRef({active:!1,pointerId:null}),c=p.useRef(null),h=p.useRef(!1),d=st(r?.width,Ne.width,64),m=st(r?.height,Ne.height,48),g=p.useMemo(()=>{const P=Math.max(1,t.width),C=Math.max(1,t.height),H=P/C,he=d/m;let J,le;return H>he?(J=d,le=d/H):(le=m,J=m*H),{x:(d-J)/2,y:(m-le)/2,w:J,h:le}},[t.width,t.height,d,m]),y=st(r?.margin,Ne.margin,0),b=st(r?.borderRadius,Ne.borderRadius,0),x=st(r?.borderWidth,Ne.borderWidth,0),M=Math.max(1,Math.round(st(r?.maxThumbnailTiles,Ne.maxThumbnailTiles,1))),w=r?.backgroundColor||Ne.backgroundColor,T=r?.borderColor||Ne.borderColor,A=r?.viewportBorderColor||Ne.viewportBorderColor,k=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:Ne.viewportBorderStyle,L=r?.viewportFillColor??Ne.viewportFillColor,W=r?.interactive??Ne.interactive,D=r?.showThumbnail??Ne.showThumbnail,G=r?.position||Ne.position,U=r?.onClose,v=r?.closeIcon,Y=r?.closeButtonStyle,B=p.useMemo(()=>{const P={};return G==="top-left"||G==="bottom-left"?P.left=y:P.right=y,G==="top-left"||G==="top-right"?P.top=y:P.bottom=y,{position:"absolute",...P,width:d,height:m,borderRadius:b,overflow:"hidden",zIndex:4,pointerEvents:W?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[y,G,d,m,b,W,s]),z=p.useCallback(()=>{const P=a.current;if(!P)return;const C=P.getContext("2d");if(!C)return;const H=d,he=m,J=Math.max(1,window.devicePixelRatio||1),le=Math.max(1,Math.round(H*J)),ce=Math.max(1,Math.round(he*J));(P.width!==le||P.height!==ce)&&(P.width=le,P.height=ce),C.setTransform(1,0,0,1,0,0),C.clearRect(0,0,P.width,P.height),C.setTransform(J,0,0,J,0,0),C.fillStyle=w,C.fillRect(0,0,H,he);const{x:ge,y:oe,w:re,h:be}=g,de=l.current;de&&C.drawImage(de,ge,oe,re,be),C.strokeStyle=T,C.lineWidth=x,C.strokeRect(x*.5,x*.5,H-x,he-x);const X=e.current,K=X?.getViewBounds?.(),$=X?.getViewCorners?.(),ee=Array.isArray($)&&$.length>=4&&$.every(j=>Array.isArray(j)&&j.length>=2&&Number.isFinite(j[0])&&Number.isFinite(j[1]))?$:null,ne=ht(K)?K:ht(u.current)?u.current:null;ht(K)&&(u.current=K);const ue=re/Math.max(1,t.width),Re=be/Math.max(1,t.height),xe=k==="dash";if(ee){const j=ee.map(se=>[ge+se[0]*ue,oe+se[1]*Re]),ie=Fa(j,ge,oe,ge+re,oe+be);if(ie.length>=3){C.beginPath();for(let se=0;se<ie.length;se+=1)se===0?C.moveTo(ie[se][0],ie[se][1]):C.lineTo(ie[se][0],ie[se][1]);C.closePath(),C.fillStyle=L,C.fill(),C.strokeStyle=A,C.lineWidth=2.25,xe?vr(C,ie,4,3):C.stroke();return}}if(!ne)return;const we=I(ge+ne[0]*ue,ge,ge+re),pe=I(oe+ne[1]*Re,oe,oe+be),O=I(ge+ne[2]*ue,ge,ge+re),q=I(oe+ne[3]*Re,oe,oe+be),_=Math.max(1,O-we),V=Math.max(1,q-pe);if(C.fillStyle=L,C.fillRect(we,pe,_,V),C.strokeStyle=A,C.lineWidth=2.25,xe){const j=[[we+.5,pe+.5],[we+.5+Math.max(1,_-1),pe+.5],[we+.5+Math.max(1,_-1),pe+.5+Math.max(1,V-1)],[we+.5,pe+.5+Math.max(1,V-1)]];vr(C,j,4,3)}else C.strokeRect(we+.5,pe+.5,Math.max(1,_-1),Math.max(1,V-1))},[d,m,g,w,T,x,e,t.width,t.height,L,A,k]),Z=p.useCallback(()=>{h.current||(h.current=!0,c.current=requestAnimationFrame(()=>{h.current=!1,c.current=null,z()}))},[z]),ae=p.useCallback((P,C)=>{const H=a.current;if(!H)return null;const he=H.getBoundingClientRect();if(!he.width||!he.height)return null;const J=he.width/d,le=he.height/m,ce=g.x*J,ge=g.y*le,oe=g.w*J,re=g.h*le,be=I((P-he.left-ce)/oe,0,1),de=I((C-he.top-ge)/re,0,1);return[be*t.width,de*t.height]},[t.width,t.height,d,m,g]),te=p.useCallback((P,C)=>{const H=e.current;if(!H)return;if(H.setViewCenter){H.setViewCenter(P,C),Z();return}const he=H.getViewBounds?.(),J=ht(he)?he:ht(u.current)?u.current:null;if(!J)return;const le=Math.max(1e-6,J[2]-J[0]),ce=Math.max(1e-6,J[3]-J[1]);H.setViewState({offsetX:P-le*.5,offsetY:C-ce*.5}),Z()},[e,Z]),Te=p.useCallback(P=>{if(!W||P.button!==0)return;const C=a.current;if(!C)return;const H=ae(P.clientX,P.clientY);H&&(P.preventDefault(),P.stopPropagation(),C.setPointerCapture(P.pointerId),f.current={active:!0,pointerId:P.pointerId},te(H[0],H[1]))},[W,ae,te]),Se=p.useCallback(P=>{const C=f.current;if(!C.active||C.pointerId!==P.pointerId)return;const H=ae(P.clientX,P.clientY);H&&(P.preventDefault(),P.stopPropagation(),te(H[0],H[1]))},[ae,te]),Ce=p.useCallback(P=>{const C=f.current;if(!C.active||C.pointerId!==P.pointerId)return;const H=a.current;if(H&&H.hasPointerCapture(P.pointerId))try{H.releasePointerCapture(P.pointerId)}catch{}f.current={active:!1,pointerId:null},Z()},[Z]);return p.useEffect(()=>{let P=!1;l.current=null,Z();const C=0,H=2**(t.maxTierZoom-C),he=Math.ceil(t.width/H),J=Math.ceil(t.height/H),le=Math.max(1,Math.ceil(he/t.tileSize)),ce=Math.max(1,Math.ceil(J/t.tileSize)),ge=le*ce;if(!D||ge>M)return;const oe=document.createElement("canvas");oe.width=Math.max(1,Math.round(g.w)),oe.height=Math.max(1,Math.round(g.h));const re=oe.getContext("2d");if(!re)return;re.fillStyle=w,re.fillRect(0,0,oe.width,oe.height);const be=[];for(let de=0;de<ce;de+=1)for(let X=0;X<le;X+=1){const K=X*t.tileSize*H,$=de*t.tileSize*H,ee=Math.min((X+1)*t.tileSize,he)*H,ne=Math.min((de+1)*t.tileSize,J)*H;be.push({url:Wn(t,C,X,de),bounds:[K,$,ee,ne]})}return Promise.allSettled(be.map(async de=>{const X=_a(de.url,n),K=await fetch(de.url,{headers:X?{Authorization:n}:void 0});if(!K.ok)throw new Error(`HTTP ${K.status}`);const $=await createImageBitmap(await K.blob());return{tile:de,bitmap:$}})).then(de=>{if(P){for(const $ of de)$.status==="fulfilled"&&$.value.bitmap.close();return}const X=oe.width/Math.max(1,t.width),K=oe.height/Math.max(1,t.height);for(const $ of de){if($.status!=="fulfilled")continue;const{tile:{bounds:ee},bitmap:ne}=$.value,ue=ee[0]*X,Re=ee[1]*K,xe=Math.max(1,(ee[2]-ee[0])*X),we=Math.max(1,(ee[3]-ee[1])*K);re.drawImage(ne,ue,Re,xe,we),ne.close()}l.current=oe,Z()}),()=>{P=!0}},[t,n,g,w,D,M,Z]),p.useEffect(()=>{Z()},[Z]),p.useEffect(()=>{if(i)return i.current=Z,()=>{i.current===Z&&(i.current=null)}},[i,Z]),p.useEffect(()=>()=>{f.current={active:!1,pointerId:null},c.current!==null&&(cancelAnimationFrame(c.current),c.current=null),h.current=!1},[]),Ye.jsxs("div",{className:o,style:B,children:[Ye.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:Te,onPointerMove:Se,onPointerUp:Ce,onPointerCancel:Ce,onContextMenu:P=>{P.preventDefault()},onWheel:P=>{P.preventDefault(),P.stopPropagation()}}),U&&Ye.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:P=>{P.stopPropagation(),U()},style:Y?{...Y}:{...La},children:v??"×"})]})}const Lr="__patch_layer__",Na=[];function Ba({regions:t,strokeStyle:e}){const{rendererRef:n,registerDrawCallback:r,unregisterDrawCallback:i,requestOverlayRedraw:o}=rt(),s=t??Na,a=p.useMemo(()=>qe(ri,e),[e]),l=p.useMemo(()=>{const c=[];for(let h=0;h<s.length;h+=1){const d=s[h],m=Zt(d.coordinates);m.length!==0&&c.push({region:d,regionIndex:h,regionKey:d.id??h,polygons:m})}return c},[s]),u=p.useCallback(c=>{const h=n.current;if(!h||c.length===0)return[];const d=new Array(c.length);for(let m=0;m<c.length;m+=1){const g=We(h.worldToScreen(c[m][0],c[m][1]));if(!g)return[];d[m]=g}return d},[]),f=p.useRef({prepared:l,resolvedStrokeStyle:a,worldToScreenPoints:u});return f.current={prepared:l,resolvedStrokeStyle:a,worldToScreenPoints:u},p.useEffect(()=>(r(Lr,20,h=>{const{prepared:d,resolvedStrokeStyle:m,worldToScreenPoints:g}=f.current;for(const y of d)for(const b of y.polygons){const x=g(b.outer);x.length>=4&&Ie(h,x,m,!0,!1);for(const M of b.holes){const w=g(M);w.length>=4&&Ie(h,w,m,!0,!1)}}}),()=>i(Lr)),[r,i]),p.useEffect(()=>{o()},[l,a,o]),null}function wt(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return null;const n=ut(e??[]);if(n.length===0){const m={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return t.fillModes instanceof Uint8Array&&(m.fillModes=new Uint8Array(0)),t.ids instanceof Uint32Array&&(m.ids=new Uint32Array(0)),m}const r=nt(t),i=t.positions,o=t.paletteIndices,s=t.fillModes instanceof Uint8Array&&t.fillModes.length>=r?t.fillModes:null,a=t.ids instanceof Uint32Array&&t.ids.length>=r?t.ids:null,l=new Float32Array(r*2),u=new Uint16Array(r),f=s?new Uint8Array(r):null,c=a?new Uint32Array(r):null;let h=0;for(let m=0;m<r;m+=1){const g=i[m*2],y=i[m*2+1];bt(g,y,n)&&(l[h*2]=g,l[h*2+1]=y,u[h]=o[m],f&&(f[h]=s[m]),c&&(c[h]=a[m]),h+=1)}const d={count:h,positions:l.subarray(0,h*2),paletteIndices:u.subarray(0,h)};return f&&(d.fillModes=f.subarray(0,h)),c&&(d.ids=c.subarray(0,h)),d}function Ii(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return new Uint32Array(0);const n=ut(e??[]);if(n.length===0)return new Uint32Array(0);const r=nt(t);if(r===0)return new Uint32Array(0);const i=t.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];bt(l,u,n)&&(o[s]=a,s+=1)}return o.subarray(0,s)}let _t=null;const ka=`
|
|
103
|
+
}`;class Qs{constructor(){S(this,"canvas");S(this,"gl");S(this,"accumProgram");S(this,"colorProgram");S(this,"accumVao");S(this,"colorVao");S(this,"pointBuffer");S(this,"quadBuffer");S(this,"accumTexture");S(this,"gradientTexture");S(this,"framebuffer");S(this,"accumInternalFormat");S(this,"accumTextureFormat");S(this,"accumTextureType");S(this,"uAccumResolution");S(this,"uAccumPointSize");S(this,"uAccumCoreRatio");S(this,"uAccumPointAlpha");S(this,"uColorAccumTexture");S(this,"uColorGradientTexture");S(this,"uColorOpacity");S(this,"uColorCutoff");S(this,"uColorGain");S(this,"uColorResolution");S(this,"uColorGamma");S(this,"uColorBias");S(this,"uColorStretch");S(this,"pointCapacity",0);S(this,"interleavedCapacity",0);S(this,"interleavedBuffer",null);S(this,"gradientKey","");this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,preserveDrawingBuffer:!0,premultipliedAlpha:!0,powerPreference:"high-performance"});if(!e)throw new Error("WebGL2 is not available for heatmap rendering.");this.gl=e;const r=!!e.getExtension("EXT_color_buffer_float");this.accumInternalFormat=r?e.RGBA16F:e.RGBA8,this.accumTextureFormat=e.RGBA,this.accumTextureType=r?e.HALF_FLOAT:e.UNSIGNED_BYTE,this.accumProgram=pt(e,Zs,$s),this.colorProgram=pt(e,Ks,js);const i=e.createVertexArray(),o=e.createVertexArray(),s=e.createBuffer(),a=e.createBuffer(),l=e.createTexture(),u=e.createTexture(),f=e.createFramebuffer();if(!i||!o||!s||!a||!l||!u||!f)throw new Error("Failed to allocate heatmap WebGL resources.");this.accumVao=i,this.colorVao=o,this.pointBuffer=s,this.quadBuffer=a,this.accumTexture=l,this.gradientTexture=u,this.framebuffer=f;const c=e.getUniformLocation(this.accumProgram,"uResolution"),h=e.getUniformLocation(this.accumProgram,"uPointSize"),d=e.getUniformLocation(this.accumProgram,"uCoreRatio"),m=e.getUniformLocation(this.accumProgram,"uPointAlpha"),g=e.getUniformLocation(this.colorProgram,"uAccumTexture"),y=e.getUniformLocation(this.colorProgram,"uGradientTexture"),b=e.getUniformLocation(this.colorProgram,"uOpacity"),x=e.getUniformLocation(this.colorProgram,"uCutoff"),A=e.getUniformLocation(this.colorProgram,"uGain"),w=e.getUniformLocation(this.colorProgram,"uGamma"),T=e.getUniformLocation(this.colorProgram,"uBias"),M=e.getUniformLocation(this.colorProgram,"uStretch"),z=e.getUniformLocation(this.colorProgram,"uResolution");if(!c||!h||!d||!m||!g||!y||!b||!x||!A||!w||!T||!M||!z)throw new Error("Failed to resolve heatmap WebGL uniforms.");this.uAccumResolution=c,this.uAccumPointSize=h,this.uAccumCoreRatio=d,this.uAccumPointAlpha=m,this.uColorAccumTexture=g,this.uColorGradientTexture=y,this.uColorOpacity=b,this.uColorCutoff=x,this.uColorGain=A,this.uColorGamma=w,this.uColorBias=T,this.uColorStretch=M,this.uColorResolution=z,e.bindVertexArray(this.accumVao),e.bindBuffer(e.ARRAY_BUFFER,this.pointBuffer),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const L=e.getAttribLocation(this.accumProgram,"aCenter"),V=e.getAttribLocation(this.accumProgram,"aWeight");if(L<0||V<0)throw new Error("Failed to resolve heatmap WebGL attributes.");e.enableVertexAttribArray(L),e.vertexAttribPointer(L,2,e.FLOAT,!1,12,0),e.enableVertexAttribArray(V),e.vertexAttribPointer(V,1,e.FLOAT,!1,12,8),e.bindVertexArray(null),e.bindVertexArray(this.colorVao),e.bindBuffer(e.ARRAY_BUFFER,this.quadBuffer),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),e.STATIC_DRAW);const H=e.getAttribLocation(this.colorProgram,"aPosition");if(H<0)throw new Error("Failed to resolve heatmap color position attribute.");e.enableVertexAttribArray(H),e.vertexAttribPointer(H,2,e.FLOAT,!1,8,0),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),e.bindTexture(e.TEXTURE_2D,this.accumTexture),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.bindTexture(e.TEXTURE_2D,null),e.bindTexture(e.TEXTURE_2D,this.gradientTexture),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.bindTexture(e.TEXTURE_2D,null),this.ensureCanvasSize(1,1)}render(e){if(e.count<=0||e.width<=0||e.height<=0)return!1;this.ensureCanvasSize(e.width,e.height),this.ensureGradientTexture(e.gradient),this.uploadPointData(e.positions,e.weights,e.count);const n=this.gl;return n.disable(n.SCISSOR_TEST),n.disable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.bindFramebuffer(n.FRAMEBUFFER,this.framebuffer),n.viewport(0,0,e.width,e.height),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.useProgram(this.accumProgram),n.bindVertexArray(this.accumVao),n.uniform2f(this.uAccumResolution,e.width,e.height),n.uniform1f(this.uAccumPointSize,Math.max(1,(e.kernelRadiusPx+e.blurRadiusPx)*2)),n.uniform1f(this.uAccumCoreRatio,e.kernelRadiusPx/Math.max(1e-6,e.kernelRadiusPx+e.blurRadiusPx)),n.uniform1f(this.uAccumPointAlpha,Math.max(0,e.pointAlpha)),n.enable(n.BLEND),n.blendEquation(n.FUNC_ADD),n.blendFuncSeparate(n.ONE,n.ONE,n.ONE,n.ONE),n.drawArrays(n.POINTS,0,e.count),n.disable(n.BLEND),n.bindVertexArray(null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,e.width,e.height),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.useProgram(this.colorProgram),n.bindVertexArray(this.colorVao),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,this.accumTexture),n.uniform1i(this.uColorAccumTexture,0),n.activeTexture(n.TEXTURE1),n.bindTexture(n.TEXTURE_2D,this.gradientTexture),n.uniform1i(this.uColorGradientTexture,1),n.uniform1f(this.uColorOpacity,e.opacity),n.uniform1f(this.uColorCutoff,e.cutoff??.008),n.uniform1f(this.uColorGain,e.gain??2.6),n.uniform1f(this.uColorGamma,e.gamma??1),n.uniform1f(this.uColorBias,e.bias??0),n.uniform1f(this.uColorStretch,e.stretch??1),n.uniform2f(this.uColorResolution,e.width,e.height),n.drawArrays(n.TRIANGLE_STRIP,0,4),n.bindVertexArray(null),n.bindTexture(n.TEXTURE_2D,null),n.flush(),!0}destroy(){const e=this.gl;e.deleteTexture(this.accumTexture),e.deleteTexture(this.gradientTexture),e.deleteFramebuffer(this.framebuffer),e.deleteBuffer(this.pointBuffer),e.deleteBuffer(this.quadBuffer),e.deleteVertexArray(this.accumVao),e.deleteVertexArray(this.colorVao),e.deleteProgram(this.accumProgram),e.deleteProgram(this.colorProgram),this.canvas.width=0,this.canvas.height=0}ensureCanvasSize(e,n){const r=Math.max(1,Math.round(e)),i=Math.max(1,Math.round(n));this.canvas.width!==r&&(this.canvas.width=r),this.canvas.height!==i&&(this.canvas.height=i);const o=this.gl;o.bindTexture(o.TEXTURE_2D,this.accumTexture),o.texImage2D(o.TEXTURE_2D,0,this.accumInternalFormat,r,i,0,this.accumTextureFormat,this.accumTextureType,null),o.bindFramebuffer(o.FRAMEBUFFER,this.framebuffer),o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,this.accumTexture,0);const s=o.checkFramebufferStatus(o.FRAMEBUFFER);if(o.bindFramebuffer(o.FRAMEBUFFER,null),s!==o.FRAMEBUFFER_COMPLETE)throw new Error(`Heatmap framebuffer incomplete: ${s}`)}ensureGradientTexture(e){const n=e.join("|");if(this.gradientKey===n)return;const r=document.createElement("canvas");r.width=256,r.height=1;const i=r.getContext("2d");if(!i)throw new Error("Failed to create heatmap gradient canvas.");const o=i.createLinearGradient(0,0,256,0),s=e.length>1?e:["#00000000","#3876FF","#4CDDDD","#FFE75C","#FF8434","#FF3434"],a=1/Math.max(1,s.length-1);for(let f=0;f<s.length;f+=1)o.addColorStop(f*a,s[f]);i.clearRect(0,0,256,1),i.fillStyle=o,i.fillRect(0,0,256,1);const l=i.getImageData(0,0,256,1).data,u=this.gl;u.bindTexture(u.TEXTURE_2D,this.gradientTexture),u.texImage2D(u.TEXTURE_2D,0,u.RGBA,256,1,0,u.RGBA,u.UNSIGNED_BYTE,l),u.bindTexture(u.TEXTURE_2D,null),this.gradientKey=n}uploadPointData(e,n,r){const i=this.gl,o=r*3,s=o*4;i.bindBuffer(i.ARRAY_BUFFER,this.pointBuffer),r>this.pointCapacity&&(i.bufferData(i.ARRAY_BUFFER,s,i.DYNAMIC_DRAW),this.pointCapacity=r),o>this.interleavedCapacity&&(this.interleavedCapacity=o,this.interleavedBuffer=new Float32Array(o));const a=this.interleavedBuffer;if(!a)throw new Error("Failed to allocate heatmap upload buffer.");for(let l=0;l<r;l+=1){const u=l*2,f=l*3;a[f]=e[u]??0,a[f+1]=e[u+1]??0,a[f+2]=n[l]??0}i.bufferSubData(i.ARRAY_BUFFER,0,a.subarray(0,o)),i.bindBuffer(i.ARRAY_BUFFER,null)}}const Er="__open_plant_heatmap_layer__",Js=["#00000000","#3876FF","#4CDDDD","#FFE75C","#FF8434","#FF3434"],ea=3,ta=2,na=.9,ra=52e3,ia="screen",oa=2.2,bn=128,Kt=1600,sa=1.9,aa=4.2,xn=3e3,pi=Math.SQRT2,la=2048,ca=.9,Ve=16;function At(t,e){return e.maxTierZoom+Math.log2(Math.max(1e-6,t))}function Un(t,e){return Math.max(1e-6,2**(t-e.maxTierZoom))}function ua(t,e,n){if(!Number.isFinite(n)||Math.abs(n)<1e-6)return Math.max(1e-6,t);const r=At(t,e)-n;return Un(r,e)}function fa(t){return!Number.isFinite(t)||Math.abs(t)<1e-6?0:Math.round(t*1.5/Math.max(1e-6,Math.log2(pi)))}function yi(t){const e=_(t,0,Ve);return _(.55+Math.sqrt(Math.max(0,e))*.48,.55,6)}function ha(t){const e=Math.max(0,t);return e<=1?.18:e<=2?.3:e<=4?.48:e<=8?.7:e<=16?.86:1}function bi(t){return .022-_(t,0,Ve)/Ve*.015}function xi(t){const e=_(t,0,Ve);return .18+Math.pow(Math.max(0,e),.72)*.42+Math.log2(e+1)*.24}function wi(t){return yi(t)}function Si(t){const n=_(t,0,Ve)/Ve;return _(.46-n*.34,.12,.46)}function Ei(t,e,n){const i=_(t,0,Ve)/Ve,o=At(e,n),s=n.maxTierZoom-3.2,a=n.maxTierZoom-1.15,l=_((o-s)/Math.max(1e-6,a-s),0,1),u=1.12+Math.pow(i,.82)*1.18,f=1+l*(.48+i*.92);return u*f}function da(t,e,n){const r=Math.max(0,t),i=Math.max(1e-6,e),o=Math.log1p(r)/Math.log1p(i);return _(o,0,1)}function ma(t){return ca}function ga(t,e){if(t.length===0)return 1;const n=Math.min(t.length,la),r=new Array(n);let i=1;for(let f=0;f<n;f+=1){const c=Math.min(t.length-1,Math.floor((f+.5)*t.length/n)),h=Math.max(0,t[c]?.weight??0);r[f]=h,h>i&&(i=h)}for(let f=0;f<t.length;f+=1){const c=Math.max(0,t[f]?.weight??0);c>i&&(i=c)}r.sort((f,c)=>f-c);const o=ma(),s=Math.max(0,Math.min(r.length-1,Math.floor((r.length-1)*o))),a=r[s]??i;return Math.max(1,Math.min(i,Math.max(a*1.08,i*.14)))}function Ri(t,e,n){const r=At(t,e),i=e.maxTierZoom-2.45,o=e.maxTierZoom-1.2,s=r<=i?1:r>=o?0:(()=>{const a=_((r-i)/Math.max(1e-6,o-i),0,1);return 1-a*a*(3-2*a)})();return _(s,0,1)}function pa(t){if(t>=1)return 1;const e=1/Math.max(t,1e-6);return 1+Math.log2(e)*.28}function ya(t,e,n,r){const i=Math.max(1,t,e),o=typeof window>"u"?1:_(window.devicePixelRatio||1,1,2.4),s=r<=.35?1.42:r<=.55?1.26:r<=.8?1.14:1,a=n>16e4?896:n>8e4?1152:n>3e4?1408:Kt,l=bn/i,u=Kt/i;return _(a*o*s/i,l,u)}function wn(t){const e=t.heatmapScale??ya(t.logicalWidth,t.logicalHeight,t.totalPointCount,t.rawZoom),n=Math.max(bn,Math.min(Kt,Math.round(t.logicalWidth*e))),r=Math.max(bn,Math.min(Kt,Math.round(t.logicalHeight*e))),i=n/Math.max(1,t.logicalWidth),o=r/Math.max(1,t.logicalHeight),s=Math.min(i,o),a=Math.max(1e-6,t.rawZoom),l=Math.max(.75,t.radius*sa*s),u=Math.max(.6,t.blur*aa*s),f=(l+u)/Math.max(1e-6,a*s),c=Math.max(f*.4,.62/Math.max(1e-6,a*s));return{heatmapScale:e,rasterWidth:n,rasterHeight:r,rasterScaleX:i,rasterScaleY:o,rawZoom:a,kernelRadiusPx:l,blurRadiusPx:u,outerWorldRadius:f,desiredCellWorldSize:c}}function zn(t){if(!t)return 0;const e=Math.floor(t.positions.length/2),n=t.weights?t.weights.length:Number.MAX_SAFE_INTEGER;return Math.max(0,Math.min(Math.floor(t.count),e,n))}function _t(t,e){const n=Number.isFinite(t)?Math.round(t*1024):0;return Math.imul(e^n,73244475)>>>0}function ba(t,e,n=2654435769){let r=Math.imul(n^(t|0),2246822507)>>>0;return r=Math.imul(r^(e|0),3266489909)>>>0,r^=r>>>16,r>>>0}function xa(t){return(t>>>0)/4294967295}function Ai(t){let e=2166136261;for(let n=0;n<t.length;n+=1){const r=t[n];e=Math.imul(e^r.outer.length,16777619)>>>0;for(let i=0;i<r.outer.length;i+=1){const o=r.outer[i];e=_t(o[0],e),e=_t(o[1],e)}e=Math.imul(e^r.holes.length,16777619)>>>0;for(let i=0;i<r.holes.length;i+=1){const o=r.holes[i];e=Math.imul(e^o.length,16777619)>>>0;for(let s=0;s<o.length;s+=1){const a=o[s];e=_t(a[0],e),e=_t(a[1],e)}}}return`${t.length}:${e>>>0}`}function On(t,e,n){return t.dataRef===e&&t.clipKey===n?!0:e?t.clipKey===n&&t.inputCount===zn(e)&&t.positionsRef===e.positions&&t.weightsRef===e.weights:!1}function wa(t,e,n,r){const i=zn(t);if(!t||i<=0)return null;let o=new Float32Array(i),s=new Float32Array(i),a=new Float32Array(i),l=0,u=1/0,f=1/0,c=-1/0,h=-1/0;for(let A=0;A<i;A+=1){const w=t.positions[A*2],T=t.positions[A*2+1];if(!Number.isFinite(w)||!Number.isFinite(T)||e.length>0&&!xt(w,T,e))continue;const M=t.weights?.[A],z=typeof M=="number"&&Number.isFinite(M)?Math.max(0,M):1;z<=0||(o[l]=w,s[l]=T,a[l]=z,l+=1,w<u&&(u=w),w>c&&(c=w),T<f&&(f=T),T>h&&(h=T))}if(l===0||!Number.isFinite(u)||!Number.isFinite(f)||!Number.isFinite(c)||!Number.isFinite(h))return null;l<i&&(o=o.slice(0,l),s=s.slice(0,l),a=a.slice(0,l));const d=[];for(let A=0;A<l;A+=1){const w=o[A],T=s[A];d.push({minX:w,minY:T,maxX:w,maxY:T,value:A})}const m=gi(64);m.load(d);const g=Math.max(r?.width??0,r?.height??0,c-u,h-f,1),y=[];let b=.5,x=0;for(;b<=g&&x<32;)y.push(b),b*=pi,x+=1;return y.length===0&&y.push(1),{dataRef:t,sourceRef:r,positionsRef:t.positions,weightsRef:t.weights,inputCount:i,clipRef:e,clipKey:n,pointCount:l,xs:o,ys:s,ws:a,pointIndex:m,cellSizes:y,levels:Array.from({length:y.length},()=>null)}}function Sn(t,e,n){const r=t.pointIndex.search([e[0]-n,e[1]-n,e[2]+n,e[3]+n]),i=new Array(r.length);let o=0;for(let s=0;s<r.length;s+=1){const a=r[s];a&&(i[o]=a.value,o+=1)}return i.length=o,i}function Mi(t,e){const n=Math.max(xn,e);return t<=n?1:_(n/Math.max(1,t),1/65536,1)}function Ti(t){return t>=1?1:Math.max(1,Math.round(1/Math.max(1e-6,t)))}function Sa(t,e){if(e>=1)return!0;const n=ba(t,1374496523,1757159915);return xa(n)<=_(e,0,1)}function Ci(t,e,n,r){const i=Math.max(1,n*r),o=Math.PI*e*e,s=Math.max(1,t)*o/i;return _(.085/Math.sqrt(Math.max(1,s)),.012,.075)}function Rr(t,e,n,r){if(!Number.isFinite(t)||t<=0)return e;const i=e>=t?n:r;return t+(e-t)*_(i,0,1)}function Ea(t){if(t.webgl!==void 0)return t.webgl;if(typeof document>"u")return t.webgl=null,null;try{t.webgl=new Qs}catch(e){if(!t.webglWarningIssued&&typeof console<"u"&&typeof console.warn=="function"){const n=e instanceof Error?e.message:String(e);console.warn(`[open-plant] HeatmapLayer disabled because WebGL2 heatmap initialization failed: ${n}`),t.webglWarningIssued=!0}t.webgl=null}return t.webgl}function Ar(t,e){const n=[];for(let r=0;r<e.length;r+=1){const i=e[r];if(!i)continue;const o=t.worldToScreen(i[0],i[1]);if(!Array.isArray(o)||o.length<2)continue;const s=Number(o[0]),a=Number(o[1]);!Number.isFinite(s)||!Number.isFinite(a)||n.push([s,a])}return n}function Ra(t,e,n){if(n.length!==0){t.beginPath();for(let r=0;r<n.length;r+=1){const i=n[r],o=Ar(e,i.outer);o.length>=3&&wt(t,o,!0);for(let s=0;s<i.holes.length;s+=1){const a=Ar(e,i.holes[s]);a.length>=3&&wt(t,a,!0)}}t.clip("evenodd")}}function vi(t,e,n,r,i){const o=t.sourceData;return o&&o.sourceRef===i&&On(o,e,r)?o:(t.sourceData=wa(e,n,r,i),t.fixedState=null,t.screenLevelIndex=-1,t.sourceData)}function Aa(t){const{sourceData:e,renderer:n,source:r,logicalWidth:i,logicalHeight:o,radius:s,blur:a,fixedZoom:l,maxRenderedPoints:u}=t,f=Math.max(1e-6,n.getViewState().zoom),c=l??At(f,r),h=Un(c,r),d=wn({logicalWidth:i,logicalHeight:o,totalPointCount:e.pointCount,rawZoom:h,radius:s,blur:a}),m=n.getViewBounds(),g=Sn(e,m,d.outerWorldRadius),y=Mi(g.length,u),b=Ti(y),x=Math.min(d.rasterScaleX,d.rasterScaleY);return{dataRef:e.dataRef,positionsRef:e.positionsRef,weightsRef:e.weightsRef,inputCount:e.inputCount,clipRef:e.clipRef,clipKey:e.clipKey,referenceZoom:c,referenceRawZoom:h,heatmapScale:d.heatmapScale,kernelWorldRadius:d.kernelRadiusPx/Math.max(1e-6,h*x),blurWorldRadius:d.blurRadiusPx/Math.max(1e-6,h*x),sampleProbability:y,sampleStride:b,pointAlpha:Ci(g.length,d.kernelRadiusPx+d.blurRadiusPx,d.rasterWidth,d.rasterHeight)}}function Mr(t){const{ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,frame:a,sourceData:l,visiblePointIndices:u,sampleProbability:f,sampleStride:c,pointAlpha:h,gradient:d,opacity:m,densityContrast:g,backgroundColor:y,clipPolygons:b}=t,x=Ea(n);if(!x||u.length===0)return 0;const A=Math.min(u.length,Math.max(64,Math.ceil(u.length*Math.min(1,f*1.15))));A>n.webglCapacity&&(n.webglCapacity=A,n.webglPositions=new Float32Array(A*2),n.webglWeights=new Float32Array(A));const w=n.webglPositions,T=n.webglWeights;if(!w||!T)return 0;const M=a.kernelRadiusPx+a.blurRadiusPx,z=pa(f);let L=0;for(let H=0;H<u.length;H+=1){const W=u[H];if(!Sa(W,f))continue;const D=l.xs[W],C=l.ys[W];if(!Number.isFinite(D)||!Number.isFinite(C))continue;const Y=r.worldToScreen(D,C);if(!Array.isArray(Y)||Y.length<2)continue;const O=Number(Y[0]),N=Number(Y[1]);if(!Number.isFinite(O)||!Number.isFinite(N))continue;const Z=O*a.rasterScaleX,oe=N*a.rasterScaleY;if(Z<-M||oe<-M||Z>a.rasterWidth+M||oe>a.rasterHeight+M)continue;const ne=L*2;w[ne]=Z,w[ne+1]=oe,T[L]=Math.max(0,(l.ws[W]??0)*z),L+=1}return L<=0||!x.render({width:a.rasterWidth,height:a.rasterHeight,positions:w,weights:T,count:L,kernelRadiusPx:a.kernelRadiusPx,blurRadiusPx:a.blurRadiusPx,pointAlpha:h,gradient:d,opacity:m,cutoff:bi(g),gain:xi(g),gamma:wi(g),bias:Si(g),stretch:Ei(g,a.rawZoom,i)})?0:(e.save(),b.length>0&&Ra(e,r,b),y&&(e.fillStyle=y,e.fillRect(0,0,o,s)),e.globalAlpha=1,e.imageSmoothingEnabled=!0,e.drawImage(x.canvas,0,0,a.rasterWidth,a.rasterHeight,0,0,o,s),e.restore(),L)}function Ma(t){const{ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,state:a}=t,l=vi(n,a.data,a.clipPolygons,a.clipKey,i);if(!l||l.cellSizes.length===0||l.pointCount<=0)return null;const u=Math.max(1e-6,r.getViewState().zoom),f=Ri(u,i,a.zoomThreshold),c=r.getViewBounds();if(f<=.001)return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:0,renderedBinCount:0,sampleStride:1,maxDensity:0};if(a.scaleMode!=="fixed-zoom"){const b=wn({logicalWidth:o,logicalHeight:s,totalPointCount:l.pointCount,rawZoom:u,radius:a.radius,blur:a.blur}),x=Sn(l,c,b.outerWorldRadius);if(x.length===0)return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:0,renderedBinCount:0,sampleStride:1,maxDensity:0};const A=Mi(x.length,a.maxRenderedPoints),w=Ti(A),T=Ci(x.length,b.kernelRadiusPx+b.blurRadiusPx,b.rasterWidth,b.rasterHeight);n.screenLevelIndex=-1,n.screenSecondaryLevelIndex=-1,n.screenSecondaryLevelWeight=0,n.screenNormalizationMaxWeight=1,n.screenPointAlpha=Rr(n.screenPointAlpha,T,.12,.08),n.screenVisibilityStrength=r.isViewAnimating()?Rr(n.screenVisibilityStrength,f,.16,.12):f;const M=Mr({ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,frame:b,sourceData:l,visiblePointIndices:x,sampleProbability:A,sampleStride:w,pointAlpha:n.screenPointAlpha*Math.max(.08,n.screenVisibilityStrength),gradient:a.gradient,opacity:a.opacity*n.screenVisibilityStrength,densityContrast:a.densityContrast,backgroundColor:a.backgroundColor,clipPolygons:a.clipPolygons});return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:x.length,renderedBinCount:M,sampleStride:w,maxDensity:Math.round(n.screenPointAlpha*255)}}const h=n.fixedState;if(!h)return null;const d=wn({logicalWidth:o,logicalHeight:s,totalPointCount:l.pointCount,rawZoom:u,radius:a.radius,blur:a.blur,heatmapScale:h.heatmapScale}),m=Math.min(d.rasterScaleX,d.rasterScaleY);d.kernelRadiusPx=Math.max(.75,h.kernelWorldRadius*u*m),d.blurRadiusPx=Math.max(.6,h.blurWorldRadius*u*m),d.outerWorldRadius=h.kernelWorldRadius+h.blurWorldRadius;const g=Sn(l,c,d.outerWorldRadius);if(g.length===0)return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:0,renderedBinCount:0,sampleStride:1,maxDensity:0};n.screenPointAlpha=h.pointAlpha,n.screenVisibilityStrength=f;const y=Mr({ctx:e,runtime:n,renderer:r,source:i,logicalWidth:o,logicalHeight:s,frame:d,sourceData:l,visiblePointIndices:g,sampleProbability:h.sampleProbability,sampleStride:h.sampleStride,pointAlpha:h.pointAlpha*Math.max(.08,f),gradient:a.gradient,opacity:a.opacity*f,densityContrast:a.densityContrast,backgroundColor:a.backgroundColor,clipPolygons:a.clipPolygons});return{pointCount:l.pointCount,renderTimeMs:0,visiblePointCount:g.length,renderedBinCount:y,sampleStride:h.sampleStride,maxDensity:Math.round(h.pointAlpha*255)}}function Ta({data:t,visible:e=!0,opacity:n=na,radius:r=ea,blur:i=ta,gradient:o=Js,backgroundColor:s=null,scaleMode:a=ia,fixedZoom:l,zoomThreshold:u=0,densityContrast:f=oa,clipToRegions:c,zIndex:h=5,maxRenderedPoints:d=ra,onStats:m}){const{rendererRef:g,source:y,registerDrawCallback:b,unregisterDrawCallback:x,requestOverlayRedraw:A}=it(),w=p.useMemo(()=>{const L=(c??[]).map(V=>ut(V?.coordinates)).filter(V=>V!=null);return ft(L)},[c]),T=p.useMemo(()=>Ai(w),[w]),M=p.useRef({sourceData:null,fixedState:null,screenLevelIndex:-1,screenSecondaryLevelIndex:-1,screenSecondaryLevelWeight:0,screenPointAlpha:0,screenNormalizationMaxWeight:1,screenVisibilityStrength:1,webgl:void 0,webglWarningIssued:!1,webglPositions:null,webglWeights:null,webglCapacity:0}),z=p.useRef({data:t,visible:e,opacity:n,radius:_(r,.05,128),blur:_(i,.05,128),gradient:o,backgroundColor:s,scaleMode:a,fixedZoom:l,zoomThreshold:u,densityContrast:_(f,0,Ve),clipPolygons:w,clipKey:T,maxRenderedPoints:Math.max(xn,Math.floor(d)),onStats:m});return z.current={data:t,visible:e,opacity:n,radius:_(r,.05,128),blur:_(i,.05,128),gradient:o,backgroundColor:s,scaleMode:a,fixedZoom:l,zoomThreshold:u,densityContrast:_(f,0,Ve),clipPolygons:w,clipKey:T,maxRenderedPoints:Math.max(xn,Math.floor(d)),onStats:m},p.useEffect(()=>(b(Er,h,(V,H,W)=>{const D=z.current,C=M.current,Y=g.current;if(!D.visible||!D.data||!Y||!y)return;const O=vi(C,D.data,D.clipPolygons,D.clipKey,y);if(!O)return;D.scaleMode==="fixed-zoom"&&(!C.fixedState||!On(C.fixedState,D.data,D.clipKey)||D.fixedZoom!==void 0&&Math.abs(C.fixedState.referenceZoom-D.fixedZoom)>1e-6)?C.fixedState=Aa({sourceData:O,renderer:Y,source:y,logicalWidth:H,logicalHeight:W,radius:D.radius,blur:D.blur,fixedZoom:D.fixedZoom,zoomThreshold:D.zoomThreshold,densityContrast:D.densityContrast,maxRenderedPoints:D.maxRenderedPoints}):D.scaleMode!=="fixed-zoom"&&(C.fixedState=null);const Z=performance.now(),oe=Ma({ctx:V,runtime:C,renderer:Y,source:y,logicalWidth:H,logicalHeight:W,state:D});!oe||!D.onStats||D.onStats({...oe,renderTimeMs:performance.now()-Z})}),()=>{x(Er),M.current.sourceData=null,M.current.fixedState=null,M.current.screenLevelIndex=-1,M.current.screenSecondaryLevelIndex=-1,M.current.screenSecondaryLevelWeight=0,M.current.screenPointAlpha=0,M.current.screenNormalizationMaxWeight=1,M.current.screenVisibilityStrength=1,M.current.webgl?.destroy(),M.current.webgl=void 0,M.current.webglPositions=null,M.current.webglWeights=null,M.current.webglCapacity=0}),[b,x,g,y,h]),p.useEffect(()=>{M.current.sourceData=null,M.current.fixedState=null,M.current.screenLevelIndex=-1,M.current.screenSecondaryLevelIndex=-1,M.current.screenSecondaryLevelWeight=0,M.current.screenPointAlpha=0,M.current.screenNormalizationMaxWeight=1,M.current.screenVisibilityStrength=1,A()},[t?.positions,t?.weights,t?.count,T,A]),p.useEffect(()=>{M.current.fixedState=null,M.current.screenSecondaryLevelIndex=-1,M.current.screenSecondaryLevelWeight=0,M.current.screenPointAlpha=0,M.current.screenNormalizationMaxWeight=1,M.current.screenVisibilityStrength=1,A()},[r,i,a,l,u,f,d,A]),p.useEffect(()=>{A()},[e,n,o,s,A]),null}const Ca={applyZoomThreshold:ua,buildClipKey:Ai,resolveCellSupportFactor:ha,resolveContinuousZoom:At,resolveDensityCutoff:bi,resolveDensityBias:Si,resolveDensityGain:xi,resolveDensityGamma:wi,resolveDensityStretch:Ei,resolveNormalizedDensityWeight:da,resolveNormalizationUpperWeight:ga,resolveDensityWeightExponent:yi,resolveRawZoomFromContinuousZoom:Un,resolvePointCount:zn,resolveThresholdLevelBias:fa,resolveZoomVisibilityStrength:Ri,isSameHeatmapInput:On},Tr="__overlay_layer__";function va({shapes:t}){const{rendererRef:e,source:n,registerDrawCallback:r,unregisterDrawCallback:i,requestOverlayRedraw:o}=it(),s=p.useCallback(l=>{const u=e.current;if(!u||l.length===0)return[];const f=new Array(l.length);for(let c=0;c<l.length;c+=1){const h=We(u.worldToScreen(l[c][0],l[c][1]));if(!h)return[];f[c]=h}return f},[]),a=p.useRef({shapes:t,worldToScreenPoints:s,source:n});return a.current={shapes:t,worldToScreenPoints:s,source:n},p.useEffect(()=>(r(Tr,30,u=>{const{shapes:f,worldToScreenPoints:c,source:h}=a.current;if(!Array.isArray(f)||f.length===0||!h)return;const d=c(Le([[0,0],[h.width,0],[h.width,h.height],[0,h.height]]));hi({ctx:u,overlayShapes:f,imageOuterRing:d,worldToScreenPoints:c,baseStrokeStyle:Ge})}),()=>i(Tr)),[r,i]),p.useEffect(()=>{o()},[t,o]),null}function Cr(t){return String(t??"").replace(/\/+$/,"")}function Pi(t){const e=String(t??"");return e.startsWith("/")?e:`/${e}`}function Pa(t){const e=Cr(t);if(!e)return"";if(/\/TileGroup\d+$/i.test(e))return e;let n=null;try{n=new URL(e)}catch{n=null}if(n){const r=`${n.protocol}//${n.host}`,i=Cr(n.pathname||"");return/\/ims$/i.test(i)?`${r}${i}`:/\/tiles$/i.test(i)?`${r}${i}`:`${r}${i}/tiles`}return/\/ims$/i.test(e)?"/ims":/\/tiles$/i.test(e)?`${e}`:`${e}/tiles`}function Ia(t,e){const n=t?.imsInfo??{},r=!!t?.imsInfo,i=Number(n.width??t?.width??0),o=Number(n.height??t?.height??0),s=Number(n.tileSize??t?.tileSize??0),a=Number(n.zoom??t?.zoom??0),l=String(n.path??t?.path??""),u=Number(n.mpp??t?.mpp??0);if(!i||!o||!s||!l)throw new Error("Incomplete image metadata: width/height/tileSize/path required");const f=Array.isArray(t?.terms)?t.terms.map(m=>({termId:String(m?.termId??""),termName:String(m?.termName??""),termColor:String(m?.termColor??"")})):[],c=Pi(l),h=Pa(e),d=t?.tileUrlBuilder??(r?(m,g,y)=>`${h}${c}/${m}/${y}_${g}.webp`:void 0);return{id:t?._id||t?.id||"unknown",name:t?.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:e,terms:f,tileUrlBuilder:d}}function Wn(t,e,n,r){if(t.tileUrlBuilder)return t.tileUrlBuilder(e,n,r,t.tilePath,t.tileBaseUrl);const i=Pi(t.tilePath);return`${t.tileBaseUrl}${i}/${e}/${r}_${n}.webp`}function _a(t,e){if(!e)return!1;const n=new URL(t,typeof window<"u"?window.location.href:void 0).hostname.toLowerCase();return!(n.includes("amazonaws.com")||n.startsWith("s3.")||n.includes(".s3."))}const Ne={width:200,height:125,margin:16,position:"bottom-right",borderRadius:6,borderWidth:0,backgroundColor:"rgba(4, 10, 18, 0.88)",borderColor:"rgba(230, 244, 255, 0.35)",viewportBorderColor:"rgba(255, 106, 61, 0.95)",viewportBorderStyle:"dash",viewportFillColor:"transparent",interactive:!0,showThumbnail:!0,maxThumbnailTiles:16};function vr(t,e,n,r){const i=e.length;if(!(i<3)){for(let o=0;o<i;o+=1){const s=e[o],a=e[(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;t.beginPath(),t.moveTo(s[0],s[1]),t.lineTo(a[0],a[1]),t.setLineDash([h,d]),t.lineDashOffset=0,t.stroke()}t.setLineDash([]),t.lineDashOffset=0}}function Pr(t,e,n=1e-4){return Math.abs(t[0]-e[0])<=n&&Math.abs(t[1]-e[1])<=n}function Ir(t){const e=[];for(const n of t){const r=e[e.length-1];(!r||!Pr(r,n))&&e.push(n)}return e.length>1&&Pr(e[0],e[e.length-1])&&e.pop(),e}function _r(t,e,n){const r=e[0]-t[0];if(Math.abs(r)<1e-6)return[n,t[1]];const i=(n-t[0])/r;return[n,t[1]+(e[1]-t[1])*i]}function Fr(t,e,n){const r=e[1]-t[1];if(Math.abs(r)<1e-6)return[t[0],n];const i=(n-t[1])/r;return[t[0]+(e[0]-t[0])*i,n]}function Fa(t,e,n,r,i){let o=Ir(t);if(o.length<3)return[];const s=[{inside:a=>a[0]>=e,intersect:(a,l)=>_r(a,l,e)},{inside:a=>a[0]<=r,intersect:(a,l)=>_r(a,l,r)},{inside:a=>a[1]>=n,intersect:(a,l)=>Fr(a,l,n)},{inside:a=>a[1]<=i,intersect:(a,l)=>Fr(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=Ir(o)}return o.length>=3?o:[]}function at(t,e,n=1){return typeof t!="number"||!Number.isFinite(t)?e:Math.max(n,t)}function dt(t){return Array.isArray(t)&&t.length===4&&Number.isFinite(t[0])&&Number.isFinite(t[1])&&Number.isFinite(t[2])&&Number.isFinite(t[3])}const La={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 Da({source:t,projectorRef:e,authToken:n="",options:r,invalidateRef:i,className:o,style:s}){const a=p.useRef(null),l=p.useRef(null),u=p.useRef(null),f=p.useRef({active:!1,pointerId:null}),c=p.useRef(null),h=p.useRef(!1),d=at(r?.width,Ne.width,64),m=at(r?.height,Ne.height,48),g=p.useMemo(()=>{const v=Math.max(1,t.width),I=Math.max(1,t.height),B=v/I,fe=d/m;let Q,se;return B>fe?(Q=d,se=d/B):(se=m,Q=m*B),{x:(d-Q)/2,y:(m-se)/2,w:Q,h:se}},[t.width,t.height,d,m]),y=at(r?.margin,Ne.margin,0),b=at(r?.borderRadius,Ne.borderRadius,0),x=at(r?.borderWidth,Ne.borderWidth,0),A=Math.max(1,Math.round(at(r?.maxThumbnailTiles,Ne.maxThumbnailTiles,1))),w=r?.backgroundColor||Ne.backgroundColor,T=r?.borderColor||Ne.borderColor,M=r?.viewportBorderColor||Ne.viewportBorderColor,z=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:Ne.viewportBorderStyle,L=r?.viewportFillColor??Ne.viewportFillColor,V=r?.interactive??Ne.interactive,H=r?.showThumbnail??Ne.showThumbnail,W=r?.position||Ne.position,D=r?.onClose,C=r?.closeIcon,Y=r?.closeButtonStyle,O=p.useMemo(()=>{const v={};return W==="top-left"||W==="bottom-left"?v.left=y:v.right=y,W==="top-left"||W==="top-right"?v.top=y:v.bottom=y,{position:"absolute",...v,width:d,height:m,borderRadius:b,overflow:"hidden",zIndex:4,pointerEvents:V?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[y,W,d,m,b,V,s]),N=p.useCallback(()=>{const v=a.current;if(!v)return;const I=v.getContext("2d");if(!I)return;const B=d,fe=m,Q=Math.max(1,window.devicePixelRatio||1),se=Math.max(1,Math.round(B*Q)),le=Math.max(1,Math.round(fe*Q));(v.width!==se||v.height!==le)&&(v.width=se,v.height=le),I.setTransform(1,0,0,1,0,0),I.clearRect(0,0,v.width,v.height),I.setTransform(Q,0,0,Q,0,0),I.fillStyle=w,I.fillRect(0,0,B,fe);const{x:de,y:ae,w:ge,h:ie}=g,he=l.current;he&&I.drawImage(he,de,ae,ge,ie),I.strokeStyle=T,I.lineWidth=x,I.strokeRect(x*.5,x*.5,B-x,fe-x);const q=e.current,K=q?.getViewBounds?.(),$=q?.getViewCorners?.(),re=Array.isArray($)&&$.length>=4&&$.every(G=>Array.isArray(G)&&G.length>=2&&Number.isFinite(G[0])&&Number.isFinite(G[1]))?$:null,J=dt(K)?K:dt(u.current)?u.current:null;dt(K)&&(u.current=K);const ce=ge/Math.max(1,t.width),xe=ie/Math.max(1,t.height),Ee=z==="dash";if(re){const G=re.map(ee=>[de+ee[0]*ce,ae+ee[1]*xe]),te=Fa(G,de,ae,de+ge,ae+ie);if(te.length>=3){I.beginPath();for(let ee=0;ee<te.length;ee+=1)ee===0?I.moveTo(te[ee][0],te[ee][1]):I.lineTo(te[ee][0],te[ee][1]);I.closePath(),I.fillStyle=L,I.fill(),I.strokeStyle=M,I.lineWidth=2.25,Ee?vr(I,te,4,3):I.stroke();return}}if(!J)return;const pe=_(de+J[0]*ce,de,de+ge),ye=_(ae+J[1]*xe,ae,ae+ie),ve=_(de+J[2]*ce,de,de+ge),U=_(ae+J[3]*xe,ae,ae+ie),P=Math.max(1,ve-pe),X=Math.max(1,U-ye);if(I.fillStyle=L,I.fillRect(pe,ye,P,X),I.strokeStyle=M,I.lineWidth=2.25,Ee){const G=[[pe+.5,ye+.5],[pe+.5+Math.max(1,P-1),ye+.5],[pe+.5+Math.max(1,P-1),ye+.5+Math.max(1,X-1)],[pe+.5,ye+.5+Math.max(1,X-1)]];vr(I,G,4,3)}else I.strokeRect(pe+.5,ye+.5,Math.max(1,P-1),Math.max(1,X-1))},[d,m,g,w,T,x,e,t.width,t.height,L,M,z]),Z=p.useCallback(()=>{h.current||(h.current=!0,c.current=requestAnimationFrame(()=>{h.current=!1,c.current=null,N()}))},[N]),oe=p.useCallback((v,I)=>{const B=a.current;if(!B)return null;const fe=B.getBoundingClientRect();if(!fe.width||!fe.height)return null;const Q=fe.width/d,se=fe.height/m,le=g.x*Q,de=g.y*se,ae=g.w*Q,ge=g.h*se,ie=_((v-fe.left-le)/ae,0,1),he=_((I-fe.top-de)/ge,0,1);return[ie*t.width,he*t.height]},[t.width,t.height,d,m,g]),ne=p.useCallback((v,I)=>{const B=e.current;if(!B)return;if(B.setViewCenter){B.setViewCenter(v,I),Z();return}const fe=B.getViewBounds?.(),Q=dt(fe)?fe:dt(u.current)?u.current:null;if(!Q)return;const se=Math.max(1e-6,Q[2]-Q[0]),le=Math.max(1e-6,Q[3]-Q[1]);B.setViewState({offsetX:v-se*.5,offsetY:I-le*.5}),Z()},[e,Z]),Me=p.useCallback(v=>{if(!V||v.button!==0)return;const I=a.current;if(!I)return;const B=oe(v.clientX,v.clientY);B&&(v.preventDefault(),v.stopPropagation(),I.setPointerCapture(v.pointerId),f.current={active:!0,pointerId:v.pointerId},ne(B[0],B[1]))},[V,oe,ne]),we=p.useCallback(v=>{const I=f.current;if(!I.active||I.pointerId!==v.pointerId)return;const B=oe(v.clientX,v.clientY);B&&(v.preventDefault(),v.stopPropagation(),ne(B[0],B[1]))},[oe,ne]),Te=p.useCallback(v=>{const I=f.current;if(!I.active||I.pointerId!==v.pointerId)return;const B=a.current;if(B&&B.hasPointerCapture(v.pointerId))try{B.releasePointerCapture(v.pointerId)}catch{}f.current={active:!1,pointerId:null},Z()},[Z]);return p.useEffect(()=>{let v=!1;l.current=null,Z();const I=0,B=2**(t.maxTierZoom-I),fe=Math.ceil(t.width/B),Q=Math.ceil(t.height/B),se=Math.max(1,Math.ceil(fe/t.tileSize)),le=Math.max(1,Math.ceil(Q/t.tileSize)),de=se*le;if(!H||de>A)return;const ae=document.createElement("canvas");ae.width=Math.max(1,Math.round(g.w)),ae.height=Math.max(1,Math.round(g.h));const ge=ae.getContext("2d");if(!ge)return;ge.fillStyle=w,ge.fillRect(0,0,ae.width,ae.height);const ie=[];for(let he=0;he<le;he+=1)for(let q=0;q<se;q+=1){const K=q*t.tileSize*B,$=he*t.tileSize*B,re=Math.min((q+1)*t.tileSize,fe)*B,J=Math.min((he+1)*t.tileSize,Q)*B;ie.push({url:Wn(t,I,q,he),bounds:[K,$,re,J]})}return Promise.allSettled(ie.map(async he=>{const q=_a(he.url,n),K=await fetch(he.url,{headers:q?{Authorization:n}:void 0});if(!K.ok)throw new Error(`HTTP ${K.status}`);const $=await createImageBitmap(await K.blob());return{tile:he,bitmap:$}})).then(he=>{if(v){for(const $ of he)$.status==="fulfilled"&&$.value.bitmap.close();return}const q=ae.width/Math.max(1,t.width),K=ae.height/Math.max(1,t.height);for(const $ of he){if($.status!=="fulfilled")continue;const{tile:{bounds:re},bitmap:J}=$.value,ce=re[0]*q,xe=re[1]*K,Ee=Math.max(1,(re[2]-re[0])*q),pe=Math.max(1,(re[3]-re[1])*K);ge.drawImage(J,ce,xe,Ee,pe),J.close()}l.current=ae,Z()}),()=>{v=!0}},[t,n,g,w,H,A,Z]),p.useEffect(()=>{Z()},[Z]),p.useEffect(()=>{if(i)return i.current=Z,()=>{i.current===Z&&(i.current=null)}},[i,Z]),p.useEffect(()=>()=>{f.current={active:!1,pointerId:null},c.current!==null&&(cancelAnimationFrame(c.current),c.current=null),h.current=!1},[]),Ye.jsxs("div",{className:o,style:O,children:[Ye.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:Me,onPointerMove:we,onPointerUp:Te,onPointerCancel:Te,onContextMenu:v=>{v.preventDefault()},onWheel:v=>{v.preventDefault(),v.stopPropagation()}}),D&&Ye.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:v=>{v.stopPropagation(),D()},style:Y?{...Y}:{...La},children:C??"×"})]})}const Lr="__patch_layer__",Na=[];function Ba({regions:t,strokeStyle:e}){const{rendererRef:n,registerDrawCallback:r,unregisterDrawCallback:i,requestOverlayRedraw:o}=it(),s=t??Na,a=p.useMemo(()=>He(ri,e),[e]),l=p.useMemo(()=>{const c=[];for(let h=0;h<s.length;h+=1){const d=s[h],m=$t(d.coordinates);m.length!==0&&c.push({region:d,regionIndex:h,regionKey:d.id??h,polygons:m})}return c},[s]),u=p.useCallback(c=>{const h=n.current;if(!h||c.length===0)return[];const d=new Array(c.length);for(let m=0;m<c.length;m+=1){const g=We(h.worldToScreen(c[m][0],c[m][1]));if(!g)return[];d[m]=g}return d},[]),f=p.useRef({prepared:l,resolvedStrokeStyle:a,worldToScreenPoints:u});return f.current={prepared:l,resolvedStrokeStyle:a,worldToScreenPoints:u},p.useEffect(()=>(r(Lr,20,h=>{const{prepared:d,resolvedStrokeStyle:m,worldToScreenPoints:g}=f.current;for(const y of d)for(const b of y.polygons){const x=g(b.outer);x.length>=4&&Ie(h,x,m,!0,!1);for(const A of b.holes){const w=g(A);w.length>=4&&Ie(h,w,m,!0,!1)}}}),()=>i(Lr)),[r,i]),p.useEffect(()=>{o()},[l,a,o]),null}function St(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return null;const n=ft(e??[]);if(n.length===0){const m={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return t.fillModes instanceof Uint8Array&&(m.fillModes=new Uint8Array(0)),t.ids instanceof Uint32Array&&(m.ids=new Uint32Array(0)),m}const r=rt(t),i=t.positions,o=t.paletteIndices,s=t.fillModes instanceof Uint8Array&&t.fillModes.length>=r?t.fillModes:null,a=t.ids instanceof Uint32Array&&t.ids.length>=r?t.ids:null,l=new Float32Array(r*2),u=new Uint16Array(r),f=s?new Uint8Array(r):null,c=a?new Uint32Array(r):null;let h=0;for(let m=0;m<r;m+=1){const g=i[m*2],y=i[m*2+1];xt(g,y,n)&&(l[h*2]=g,l[h*2+1]=y,u[h]=o[m],f&&(f[h]=s[m]),c&&(c[h]=a[m]),h+=1)}const d={count:h,positions:l.subarray(0,h*2),paletteIndices:u.subarray(0,h)};return f&&(d.fillModes=f.subarray(0,h)),c&&(d.ids=c.subarray(0,h)),d}function Ii(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return new Uint32Array(0);const n=ft(e??[]);if(n.length===0)return new Uint32Array(0);const r=rt(t);if(r===0)return new Uint32Array(0);const i=t.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];xt(l,u,n)&&(o[s]=a,s+=1)}return o.subarray(0,s)}let Ft=null;const ka=`
|
|
104
104
|
struct Params {
|
|
105
105
|
pointCount: u32,
|
|
106
106
|
boundsCount: u32,
|
|
@@ -131,7 +131,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
131
131
|
}
|
|
132
132
|
outputMask[i] = inside;
|
|
133
133
|
}
|
|
134
|
-
`;function Ua(){if(typeof navigator>"u")return!1;const t=navigator;return typeof t.gpu=="object"&&t.gpu!==null}function _i(){if(!Ua())return null;const e=navigator.gpu;if(!e||typeof e!="object")return null;const n=e;return typeof n.requestAdapter!="function"?null:n}const Ft=globalThis.GPUShaderStage?.COMPUTE??4,sn=globalThis.GPUBufferUsage?.STORAGE??128,Lt=globalThis.GPUBufferUsage?.COPY_DST??8,za=globalThis.GPUBufferUsage?.COPY_SRC??4,Oa=globalThis.GPUBufferUsage?.UNIFORM??64,Wa=globalThis.GPUBufferUsage?.MAP_READ??1,Ya=globalThis.GPUMapMode?.READ??1;async function Xa(){const t=_i();if(!t)return{supported:!1,features:[]};const e=await t.requestAdapter();return e?{supported:!0,adapterName:e.info?.description??e.info?.vendor??"unknown",features:Array.from(e.features),limits:{maxStorageBufferBindingSize:Number(e.limits.maxStorageBufferBindingSize),maxComputeInvocationsPerWorkgroup:Number(e.limits.maxComputeInvocationsPerWorkgroup),maxComputeWorkgroupSizeX:Number(e.limits.maxComputeWorkgroupSizeX)}}:{supported:!1,features:[]}}async function Va(){return _t||(_t=(async()=>{const t=_i();if(!t)return null;const e=await t.requestAdapter();if(!e)return null;const n=await e.requestDevice(),r=n.createBindGroupLayout({entries:[{binding:0,visibility:Ft,buffer:{type:"read-only-storage"}},{binding:1,visibility:Ft,buffer:{type:"read-only-storage"}},{binding:2,visibility:Ft,buffer:{type:"storage"}},{binding:3,visibility:Ft,buffer:{type:"uniform"}}]}),i=n.createComputePipeline({layout:n.createPipelineLayout({bindGroupLayouts:[r]}),compute:{module:n.createShaderModule({code:ka}),entryPoint:"main"}});return{device:n,pipeline:i,bindGroupLayout:r}})(),_t)}function Dt(t,e){return Math.ceil(t/e)*e}async function Fi(t,e,n){const r=await Va();if(!r)return null;const i=Math.max(0,Math.floor(e)),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(t.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:Dt(a,4),usage:sn|Lt}),h=r.device.createBuffer({size:Dt(l,4),usage:sn|Lt}),d=r.device.createBuffer({size:Dt(u,4),usage:sn|za}),m=r.device.createBuffer({size:16,usage:Oa|Lt}),g=r.device.createBuffer({size:Dt(u,4),usage:Lt|Wa});let y=!1;try{r.device.queue.writeBuffer(c,0,t.buffer,t.byteOffset,a),r.device.queue.writeBuffer(h,0,n.buffer,n.byteOffset,l),r.device.queue.writeBuffer(m,0,new Uint32Array([s,o,0,0]));const b=r.device.createBindGroup({layout:r.bindGroupLayout,entries:[{binding:0,resource:{buffer:c}},{binding:1,resource:{buffer:h}},{binding:2,resource:{buffer:d}},{binding:3,resource:{buffer:m}}]}),x=r.device.createCommandEncoder(),M=x.beginComputePass();M.setPipeline(r.pipeline),M.setBindGroup(0,b),M.dispatchWorkgroups(Math.ceil(s/256)),M.end(),x.copyBufferToBuffer(d,0,g,0,u),r.device.queue.submit([x.finish()]),await g.mapAsync(Ya),y=!0;const w=g.getMappedRange();return new Uint32Array(w.slice(0))}finally{if(y)try{g.unmap()}catch{}c.destroy(),h.destroy(),d.destroy(),m.destroy(),g.destroy()}}async function Li(t,e,n={}){const r=ye(),i=n.bridgeToDraw===!0;if(!t||!t.count||!t.positions||!t.paletteIndices)return{data:null,meta:{mode:"hybrid-webgpu",durationMs:ye()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}};const o=ut(e??[]);if(o.length===0){const w={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return t.fillModes instanceof Uint8Array&&(w.fillModes=new Uint8Array(0)),t.ids instanceof Uint32Array&&(w.ids=new Uint32Array(0)),{data:w,meta:{mode:"hybrid-webgpu",durationMs:ye()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const s=nt(t),a=t.fillModes instanceof Uint8Array&&t.fillModes.length>=s?t.fillModes:null,l=t.ids instanceof Uint32Array&&t.ids.length>=s?t.ids:null;if(s===0){const w={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(w.fillModes=new Uint8Array(0)),l&&(w.ids=new Uint32Array(0)),{data:w,meta:{mode:"hybrid-webgpu",durationMs:ye()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const u=new Float32Array(o.length*4);for(let w=0;w<o.length;w+=1){const T=w*4,A=o[w];u[T]=A.minX,u[T+1]=A.minY,u[T+2]=A.maxX,u[T+3]=A.maxY}let f=null,c=!1;try{f=await Fi(t.positions,s,u),c=!!f}catch{f=null,c=!1}if(!f)return{data:wt(t,e),meta:{mode:"hybrid-webgpu",durationMs:ye()-r,usedWebGpu:!1,candidateCount:s,bridgedToDraw:!1}};let h=0;for(let w=0;w<s;w+=1)f[w]===1&&(h+=1);const d=new Uint32Array(h);if(h>0){let w=0;for(let T=0;T<s;T+=1)f[T]===1&&(d[w]=T,w+=1)}if(h===0){if(i){const T={count:s,positions:t.positions.subarray(0,s*2),paletteIndices:t.paletteIndices.subarray(0,s),drawIndices:new Uint32Array(0)};return a&&(T.fillModes=a.subarray(0,s)),l&&(T.ids=l.subarray(0,s)),{data:T,meta:{mode:"hybrid-webgpu",durationMs:ye()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!0}}}const w={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(w.fillModes=new Uint8Array(0)),l&&(w.ids=new Uint32Array(0)),{data:w,meta:{mode:"hybrid-webgpu",durationMs:ye()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const w=new Uint32Array(h);let T=0;for(let k=0;k<h;k+=1){const L=d[k]??0,W=t.positions[L*2],D=t.positions[L*2+1];bt(W,D,o)&&(w[T]=L,T+=1)}const A={count:s,positions:t.positions.subarray(0,s*2),paletteIndices:t.paletteIndices.subarray(0,s),drawIndices:w.subarray(0,T)};return a&&(A.fillModes=a.subarray(0,s)),l&&(A.ids=l.subarray(0,s)),{data:A,meta:{mode:"hybrid-webgpu",durationMs:ye()-r,usedWebGpu:!0,candidateCount:h,bridgedToDraw:!0}}}const m=new Float32Array(h*2),g=new Uint16Array(h),y=a?new Uint8Array(h):null,b=l?new Uint32Array(h):null;let x=0;for(let w=0;w<h;w+=1){const T=d[w]??0,A=t.positions[T*2],k=t.positions[T*2+1];bt(A,k,o)&&(m[x*2]=A,m[x*2+1]=k,g[x]=t.paletteIndices[T],y&&(y[x]=a[T]),b&&(b[x]=l[T]),x+=1)}const M={count:x,positions:m.subarray(0,x*2),paletteIndices:g.subarray(0,x)};return y&&(M.fillModes=y.subarray(0,x)),b&&(M.ids=b.subarray(0,x)),{data:M,meta:{mode:"hybrid-webgpu",durationMs:ye()-r,usedWebGpu:!0,candidateCount:h,bridgedToDraw:!1}}}class Di{constructor(e,n){S(this,"worker",null);S(this,"supported",!0);S(this,"requestId",1);S(this,"pendingById",new Map);S(this,"handleMessage",e=>{const n=e.data;if(!n)return;const r=this.pendingById.get(n.id);r&&(this.pendingById.delete(n.id),this.handlers.onResponse(n,r))});S(this,"handleError",()=>{this.supported=!1,this.teardownWorker("worker crashed")});this.createWorker=e,this.handlers=n}beginRequest(e){const n=this.getOrCreateWorker();if(!n)return null;const r=this.requestId++;return this.pendingById.set(r,e),{id:r,worker:n}}cancelRequest(e){const n=this.pendingById.get(e);if(n)return this.pendingById.delete(e),n}terminate(e="worker terminated"){this.teardownWorker(e)}getOrCreateWorker(){if(!this.supported)return null;if(this.worker)return this.worker;try{const e=this.createWorker();return e.addEventListener("message",this.handleMessage),e.addEventListener("error",this.handleError),this.worker=e,e}catch{return this.supported=!1,null}}teardownWorker(e){this.worker&&(this.worker.removeEventListener("message",this.handleMessage),this.worker.removeEventListener("error",this.handleError),this.worker.terminate(),this.worker=null);const n=new Error(e);for(const[,r]of this.pendingById)this.handlers.rejectPending(r,n);this.pendingById.clear()}}const St=new Di(()=>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:lt&<.tagName.toUpperCase()==="SCRIPT"&<.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(t,e)=>{if(t.type==="roi-clip-failure"){e.reject(new Error(t.error||"worker clip failed"));return}if(t.type==="roi-clip-index-success"){if(e.kind!=="index"){e.reject(new Error("worker response mismatch: expected point data result"));return}const l=Math.max(0,Math.floor(t.count)),u=new Uint32Array(t.indices).subarray(0,l);e.resolve({indices:u,meta:{mode:"worker",durationMs:Number.isFinite(t.durationMs)?t.durationMs:ye()-e.startMs}});return}if(e.kind!=="data"){e.reject(new Error("worker response mismatch: expected index result"));return}const n=Math.max(0,Math.floor(t.count)),r=new Float32Array(t.positions),i=new Uint16Array(t.paletteIndices),o=t.fillModes?new Uint8Array(t.fillModes):null,s=t.ids?new Uint32Array(t.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)),e.resolve({data:a,meta:{mode:"worker",durationMs:Number.isFinite(t.durationMs)?t.durationMs:ye()-e.startMs}})},rejectPending:(t,e)=>{t.reject(e)}});function Ga(){St.terminate("worker terminated")}async function Ni(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return{data:null,meta:{mode:"worker",durationMs:0}};const n=nt(t),r=t.positions.slice(0,n*2),i=t.paletteIndices.slice(0,n),o=t.fillModes instanceof Uint8Array&&t.fillModes.length>=n?t.fillModes.slice(0,n):null,s=t.ids instanceof Uint32Array&&t.ids.length>=n?t.ids.slice(0,n):null;return new Promise((a,l)=>{const u=ye(),f=St.beginRequest({kind:"data",resolve:a,reject:l,startMs:u});if(!f){a({data:wt(t,e),meta:{mode:"sync",durationMs:ye()-u}});return}const c={type:"roi-clip-request",id:f.id,count:n,positions:r.buffer,paletteIndices:i.buffer,fillModes:o?.buffer,ids:s?.buffer,polygons:e??[]},h=[r.buffer,i.buffer];o&&h.push(o.buffer),s&&h.push(s.buffer);try{f.worker.postMessage(c,h)}catch(d){const m=St.cancelRequest(f.id);m?m.reject(d):l(d)}})}async function Ha(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return{indices:new Uint32Array(0),meta:{mode:"worker",durationMs:0}};const n=nt(t),r=t.positions.slice(0,n*2);return new Promise((i,o)=>{const s=ye(),a=St.beginRequest({kind:"index",resolve:i,reject:o,startMs:s});if(!a){i({indices:Ii(t,e),meta:{mode:"sync",durationMs:ye()-s}});return}const l={type:"roi-clip-index-request",id:a.id,count:n,positions:r.buffer,polygons:e??[]};try{a.worker.postMessage(l,[r.buffer])}catch(u){const f=St.cancelRequest(a.id);f?f.reject(u):o(u)}})}const qa={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};function Za(t,e,n,r,i){const o=p.useRef(0),[s,a]=p.useState(n),l=p.useMemo(()=>r.map(u=>ct(u.coordinates)).filter(u=>u!=null),[r]);return p.useEffect(()=>{const u=++o.current;let f=!1;if(!t)return a(n),()=>{f=!0};if(!n||!n.count||!n.positions||!n.paletteIndices)return a(null),()=>{f=!0};if(l.length===0)return a(qa),i?.({mode:e,durationMs:0,inputCount:n.count,outputCount:0,polygonCount:0}),()=>{f=!0};const c=(d,m)=>{if(f||u!==o.current)return;const g=n.count,y=d?.drawIndices?d.drawIndices.length:d?.count??0;a(d),i?.({mode:m.mode,durationMs:m.durationMs,inputCount:g,outputCount:y,polygonCount:l.length,usedWebGpu:m.usedWebGpu,candidateCount:m.candidateCount,bridgedToDraw:m.bridgedToDraw})};return(async()=>{if(e==="sync"){const d=performance.now(),m=wt(n,l);c(m,{mode:"sync",durationMs:performance.now()-d});return}if(e==="hybrid-webgpu"){const d=await Li(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 Ni(n,l);c(d.data,{mode:d.meta.mode,durationMs:d.meta.durationMs})}catch{const d=performance.now(),m=wt(n,l);c(m,{mode:"sync",durationMs:performance.now()-d})}})(),()=>{f=!0}},[t,e,n,l,i]),s}const $a=24,Ka=1024,ja=4,Ot=-1;function dt(t,e,n){return(t*73856093^e*19349663)>>>0&n}function Qa(t,e,n){if(t<=0||e<=0||n<=0)return 256;const r=Math.max(1,t*e),o=Math.sqrt(r/Math.max(1,n))*ja;return Math.max($a,Math.min(Ka,o))}function Ja(t,e){if(!(t instanceof Uint32Array)||t.length===0)return null;let n=!0;for(let o=0;o<t.length;o+=1)if(!(t[o]<e)){n=!1;break}if(n)return t;const r=new Uint32Array(t.length);let i=0;for(let o=0;o<t.length;o+=1)t[o]>=e||(r[i]=t[o],i+=1);return i>0?r.subarray(0,i):null}function el(t){const e=Math.max(0,Math.floor(t.count)),n=Math.floor(t.positions.length/2),r=Math.max(0,Math.min(e,n));if(r<=0)return null;const i=Ja(t.drawIndices??null,r),o=i?i.length:r;if(o===0)return null;const s=Qa(t.sourceWidth,t.sourceHeight,o),a=1/s,l=new Int32Array(o),u=new Int32Array(o);let f=0;if(i)for(let v=0;v<o;v+=1){const Y=i[v],B=t.positions[Y*2],z=t.positions[Y*2+1];!Number.isFinite(B)||!Number.isFinite(z)||(l[f]=Math.floor(B*a),u[f]=Math.floor(z*a),f+=1)}else for(let v=0;v<r;v+=1){const Y=t.positions[v*2],B=t.positions[v*2+1];!Number.isFinite(Y)||!Number.isFinite(B)||(l[f]=Math.floor(Y*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,m=new Int32Array(h*2),g=new Int32Array(h);m.fill(2147483647);let y=0;const b=new Int32Array(f);for(let v=0;v<f;v+=1){const Y=l[v],B=u[v];let z=dt(Y,B,d);for(;;){const Z=m[z*2];if(Z===2147483647){if(m[z*2]=Y,m[z*2+1]=B,g[z]=1,b[v]=z,y+=1,y*4>h*3){const ae=h;h<<=1,d=h-1;const te=new Int32Array(h*2),Te=new Int32Array(h);te.fill(2147483647);for(let Se=0;Se<ae;Se+=1){if(m[Se*2]===2147483647)continue;const Ce=m[Se*2],P=m[Se*2+1];let C=dt(Ce,P,d);for(;te[C*2]!==2147483647;)C=C+1&d;te[C*2]=Ce,te[C*2+1]=P,Te[C]=g[Se]}for(m=te,g=Te,z=dt(Y,B,d);m[z*2]!==Y||m[z*2+1]!==B;)z=z+1&d;b[v]=z}break}if(Z===Y&&m[z*2+1]===B){g[z]+=1,b[v]=z;break}z=z+1&d}}const x=new Int32Array(y*2),M=new Uint32Array(y),w=new Uint32Array(y),T=new Int32Array(h);T.fill(Ot);let A=0,k=0;for(let v=0;v<h;v+=1)m[v*2]!==2147483647&&(x[A*2]=m[v*2],x[A*2+1]=m[v*2+1],M[A]=k,w[A]=g[v],T[v]=A,k+=g[v],A+=1);const L=new Uint32Array(f),W=new Uint32Array(y);if(W.set(M),i)for(let v=0;v<f;v+=1){const Y=T[b[v]];L[W[Y]]=i[v],W[Y]+=1}else{let v=0;for(let Y=0;Y<r;Y+=1){const B=t.positions[Y*2],z=t.positions[Y*2+1];if(!Number.isFinite(B)||!Number.isFinite(z))continue;const Z=T[b[v]];L[W[Z]]=Y,W[Z]+=1,v+=1}}let D=1;for(;D<y*2;)D<<=1;const G=D-1,U=new Int32Array(D);U.fill(Ot);for(let v=0;v<y;v+=1){const Y=x[v*2],B=x[v*2+1];let z=dt(Y,B,G);for(;U[z]!==Ot;)z=z+1&G;U[z]=v}return{cellSize:s,safeCount:r,cellCount:y,hashCapacity:D,hashTable:U,cellKeys:x,cellOffsets:M,cellLengths:w,pointIndices:L}}function Bi(t,e,n){const{hashTable:r,cellKeys:i,hashMask:o}=t;let s=dt(e,n,o);for(;;){const a=r[s];if(a===Ot)return-1;if(i[a*2]===e&&i[a*2+1]===n)return a;s=s+1&o}}function tl(t,e){if(t.safeCount<=0||t.cellCount<=0)return null;const n=t.safeCount;return{cellSize:t.cellSize,safeCount:n,positions:e.positions.subarray(0,n*2),ids:e.ids instanceof Uint32Array&&e.ids.length>=n?e.ids.subarray(0,n):null,hashCapacity:t.hashCapacity,hashMask:t.hashCapacity-1,hashTable:new Int32Array(t.hashTable),cellKeys:new Int32Array(t.cellKeys),cellOffsets:new Uint32Array(t.cellOffsets),cellLengths:new Uint32Array(t.cellLengths),pointIndices:new Uint32Array(t.pointIndices)}}const Rn=new Di(()=>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:lt&<.tagName.toUpperCase()==="SCRIPT"&<.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(t,e)=>{if(t.type==="point-hit-index-failure"){e.reject(new Error(t.error||"worker index build failed"));return}e.resolve(tl(t,e.pointData))},rejectPending:(t,e)=>{t.reject(e)}});function nl(){Rn.terminate("worker terminated")}function rl(t,e){const n=nt(t);if(n<=0)return null;const r=t.positions.subarray(0,n*2),i=el({count:n,positions:r,drawIndices:t.drawIndices instanceof Uint32Array?t.drawIndices:null,sourceWidth:e?.width??0,sourceHeight:e?.height??0});return i?{cellSize:i.cellSize,safeCount:n,positions:r,ids:t.ids instanceof Uint32Array&&t.ids.length>=n?t.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 ki(t,e){if(!t||!t.positions||!t.paletteIndices)return null;const n=nt(t);return n<=0?null:new Promise((r,i)=>{const o={resolve:r,reject:i,pointData:t},s=Rn.beginRequest(o);if(!s||!s.worker){r(rl(t,e));return}const a=t.positions.slice(0,n*2),l=t.drawIndices instanceof Uint32Array&&t.drawIndices.length>0?t.drawIndices.slice():void 0,u={type:"point-hit-index-request",id:s.id,count:n,positions:a.buffer,drawIndices:l?.buffer,sourceWidth:e?.width??0,sourceHeight:e?.height??0},f=[a.buffer];l&&f.push(l.buffer);try{s.worker.postMessage(u,f)}catch(c){const h=Rn.cancelRequest(s.id);h?h.reject(c):i(c)}})}const il=.65,ol=4;function sl(t,e,n,r,i,o,s){const a=!!(n||r||i),[l,u]=p.useState(null),f=p.useRef(null),c=p.useRef(null);p.useEffect(()=>{if(!a||!t){u(null);return}let g=!1;return ki(t,e).then(y=>{g||u(y)}),()=>{g=!0}},[a,t,e]);const h=p.useCallback(g=>{const y=s.current;if(!y||!l)return null;const b=Number(g[0]),x=Number(g[1]);if(!Number.isFinite(b)||!Number.isFinite(x))return null;const M=Math.max(1e-6,y.getViewState().zoom),w=y.getPointSizeByZoom(),A=Math.max(ol,w*il)/M;if(!Number.isFinite(A)||A<=0)return null;const{cellSize:k,cellOffsets:L,cellLengths:W,pointIndices:D,positions:G,safeCount:U}=l,v=Math.floor(b/k),Y=Math.floor(x/k),B=Math.max(1,Math.ceil(A/k)),z=A*A;let Z=-1,ae=z,te=0,Te=0;for(let Ce=v-B;Ce<=v+B;Ce+=1)for(let P=Y-B;P<=Y+B;P+=1){const C=Bi(l,Ce,P);if(C<0)continue;const H=L[C],he=H+W[C];for(let J=H;J<he;J+=1){const le=D[J];if(le>=U)continue;const ce=G[le*2],ge=G[le*2+1],oe=ce-b,re=ge-x,be=oe*oe+re*re;be>ae||(ae=be,Z=le,te=ce,Te=ge)}}if(Z<0)return null;const Se=l.ids?Number(l.ids[Z]):null;return{index:Z,id:Se,coordinate:[b,x],pointCoordinate:[te,Te]}},[l]),d=p.useCallback((g,y)=>{if(!n)return;const b=g?.index??null,x=g?.id??null;f.current===b&&c.current===x||(f.current=b,c.current=x,n({index:b,id:x,coordinate:y,pointCoordinate:g?.pointCoordinate??null}))},[n]),m=p.useCallback((g,y)=>{if(!r)return;const b=h(g);b&&r({...b,button:y})},[r,h]);return p.useEffect(()=>{if(i)return i.current=h,()=>{i.current===h&&(i.current=null)}},[i,h]),p.useEffect(()=>{const g=f.current;g!==null&&(l&&g<l.safeCount||(f.current=null,c.current=null,n?.({index:null,id:null,coordinate:null,pointCoordinate:null})))},[l,n]),p.useEffect(()=>{},[o,n]),{getCellByCoordinates:h,emitPointHover:d,emitPointClick:m}}const al=p.forwardRef(function({data:e=null,palette:n=null,sizeByZoom:r,strokeScale:i,innerFillOpacity:o,clipEnabled:s=!1,clipToRegions:a,clipMode:l="worker",onClipStats:u,onHover:f,onClick:c},h){const{rendererRef:d,rendererSerial:m,source:g}=rt(),y=p.useRef(null),x=Za(s,l,e,a??ll,u),{getCellByCoordinates:M}=sl(x,g,f,c,y,"cursor",d);return p.useImperativeHandle(h,()=>({queryAt:M}),[M]),p.useEffect(()=>{const w=d.current;!w||!n||w.setPointPalette(n)},[m,n]),p.useEffect(()=>{const w=d.current;!w||r===void 0||w.setPointSizeByZoom(r)},[m,r]),p.useEffect(()=>{const w=d.current;!w||i===void 0||w.setPointStrokeScale(i)},[m,i]),p.useEffect(()=>{const w=d.current;!w||o===void 0||w.setPointInnerFillOpacity(o)},[m,o]),p.useEffect(()=>{const w=d.current;w&&w.setPointData(x)},[m,x]),null}),ll=[],cl=180,Dr=20;function ul(t){const e=I(t,0,1);return e*e*(3-2*e)}function fl(t,e,n){const[r,i]=p.useState(0),o=p.useRef(0),s=p.useRef({rafId:null,startMs:0,from:0,to:0}),a=p.useCallback(c=>{const h=I(c,0,Dr);Math.abs(o.current-h)<1e-4||(o.current=h,i(h))},[]),l=p.useCallback(()=>{const c=s.current;c.rafId!==null&&(cancelAnimationFrame(c.rafId),c.rafId=null)},[]),u=p.useCallback(c=>{const h=I(c,0,Dr),d=s.current,m=o.current;if(Math.abs(m-h)<1e-4){l(),d.to=h,a(h);return}l(),d.startMs=performance.now(),d.from=m,d.to=h;const g=y=>{const b=s.current,x=Math.max(0,y-b.startMs),M=I(x/cl,0,1),w=ul(M),T=b.from+(b.to-b.from)*w;if(a(T),n.current?.(),M>=1){b.rafId=null,a(b.to);return}b.rafId=requestAnimationFrame(g)};d.rafId=requestAnimationFrame(g)},[a,l]),f=p.useCallback(c=>{const h=e.current;if(!h||typeof c!="number"||!Number.isFinite(c)){u(0);return}const d=kn(t,c,h.getZoomRange(),h.getRegionLabelAutoLiftCapZoom());u(d)},[t,u]);return p.useEffect(()=>()=>{l()},[l]),{regionLabelAutoLiftOffsetPx:r,syncRegionLabelAutoLiftTarget:f,cancelRegionLabelAutoLiftAnimation:l,applyRegionLabelAutoLiftOffset:a}}const hl=6;function En(t,e){return t.id??e}function dl(t,e,n,r,i,o){const s=i-n,a=o-r,l=s*s+a*a;if(l<=1e-12){const m=t-n,g=e-r;return m*m+g*g}const u=I(((t-n)*s+(e-r)*a)/l,0,1),f=n+s*u,c=r+a*u,h=t-f,d=e-c;return h*h+d*d}function Nr(t,e,n,r){for(let i=1;i<n.length;i+=1){const o=n[i-1],s=n[i];if(dl(t,e,o[0],o[1],s[0],s[1])<=r)return!0}return!1}function ml(t,e,n,r){if(t<n.minX-r||t>n.maxX+r||e<n.minY-r||e>n.maxY+r)return!1;const i=r*r;if(Nr(t,e,n.outer,i))return!0;for(const o of n.holes)if(Nr(t,e,o,i))return!0;return!1}function gl(t,e,n,r,i,o,s){if(!t.label||!t.labelAnchor)return!1;const a=_n(n.worldToScreen(t.labelAnchor[0],t.labelAnchor[1]));if(!a)return!1;const u=Ln(t.label,r)+r.paddingX*2,f=r.fontSize+r.paddingY*2,c=a[0],h=a[1]-r.offsetY,d=s?I(c,u*.5+1,i-u*.5-1):c,m=s?I(h,f*.5+1,o-f*.5-1):h,g=d-u*.5,y=d+u*.5,b=m-f*.5,x=m+f*.5;return e[0]>=g&&e[0]<=y&&e[1]>=b&&e[1]<=x}function pl(t,e="top-center"){const n=[];for(let r=0;r<t.length;r+=1){const i=t[r],o=ut([ct(i?.coordinates)]);if(o.length===0)continue;const s=typeof i?.label=="string"?i.label.trim():"";n.push({region:i,regionIndex:r,regionId:En(i,r),polygons:o,label:s,labelAnchor:s?Dn(o,e):null})}return n}function Br(t,e,n,r,i,o,s,a,l,u=!0){const f=t[0],c=t[1],h=Math.max(1e-6,r.getViewState().zoom),d=Math.max(0,s),m=hl/h;for(let g=n.length-1;g>=0;g-=1){const y=n[g];for(const x of y.polygons)if(ml(f,c,x,m))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId};let b=Bn(i,o?.({region:y.region,regionId:y.regionId,regionIndex:y.regionIndex,zoom:h}));if(d>0&&(b={...b,offsetY:b.offsetY+d}),!!gl(y,e,r,b,a,l,u))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId}}return null}const kr=[],yl=[],Ur="__region_layer__",zr="__region_label__";function bl(t){return{color:ii,width:oi,lineDash:tt,lineJoin:t.lineJoin,lineCap:t.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function xl({regions:t,polygons:e,strokeStyle:n,hoverStrokeStyle:r,activeStrokeStyle:i,resolveStrokeStyle:o,labelStyle:s,labelAnchor:a="top-center",autoLiftLabelAtMaxZoom:l=!1,clampLabelToViewport:u=!0,activeRegionId:f,onActiveChange:c,onHover:h,onClick:d}){const{rendererRef:m,rendererSerial:g,canvasRef:y,containerRef:b,registerDrawCallback:x,unregisterDrawCallback:M,requestOverlayRedraw:w,drawInvalidateRef:T,registerViewStateListener:A,screenToWorld:k,worldToScreen:L,isInteractionLocked:W}=rt(),D=t??kr,G=e??yl,U=p.useMemo(()=>D.length>0?D:G.length===0?kr:G.map((X,K)=>({id:K,coordinates:X})),[D,G]),[v,Y]=p.useState(null),[B,z]=p.useState(()=>f??null),Z=f!==void 0,ae=Z?f??null:B,te=p.useRef(null);p.useEffect(()=>{Z&&z(f??null)},[Z,f]);const Te=p.useCallback(X=>{String(ae)!==String(X)&&(Z||z(X),c?.(X))},[ae,Z,c]),{regionLabelAutoLiftOffsetPx:Se,syncRegionLabelAutoLiftTarget:Ce}=fl(l,m,T),P=p.useMemo(()=>Fn(n),[n]),C=p.useMemo(()=>qe(P,r),[P,r]),H=p.useMemo(()=>qe(P,i),[P,i]),{staticLabelStyle:he,labelStyleResolver:J}=p.useMemo(()=>typeof s=="function"?{staticLabelStyle:void 0,labelStyleResolver:s}:{staticLabelStyle:s,labelStyleResolver:void 0},[s]),le=p.useMemo(()=>Nn(he),[he]),ce=p.useMemo(()=>{const X=[];for(let K=0;K<U.length;K+=1){const $=U[K],ee=Zt($.coordinates);ee.length!==0&&X.push({region:$,regionIndex:K,regionKey:$.id??K,polygons:ee})}return X},[U]),ge=p.useMemo(()=>pl(U,a),[U,a]);p.useEffect(()=>{const X=m.current;if(X)return Ce(X.getViewState().zoom),A(K=>{Ce(K.zoom)})},[g,A,Ce]),p.useEffect(()=>{!(ae===null?!0:U.some((ee,ne)=>String(En(ee,ne))===String(ae)))&&ae!==null&&Te(null);const K=te.current;!(K===null?!0:U.some((ee,ne)=>String(En(ee,ne))===String(K)))&&K!==null&&(te.current=null,Y(null),h?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[U,ae,h,Te]);const oe=p.useCallback(X=>{const K=m.current;if(!K||X.length===0)return[];const $=new Array(X.length);for(let ee=0;ee<X.length;ee+=1){const ne=We(K.worldToScreen(X[ee][0],X[ee][1]));if(!ne)return[];$[ee]=ne}return $},[]),re=p.useRef({preparedRegions:ce,hoveredRegionId:v,activeRegionId:ae,resolvedStrokeStyle:P,resolvedHoverStrokeStyle:C,resolvedActiveStrokeStyle:H,resolveStrokeStyleProp:o,worldToScreenPoints:oe});re.current={preparedRegions:ce,hoveredRegionId:v,activeRegionId:ae,resolvedStrokeStyle:P,resolvedHoverStrokeStyle:C,resolvedActiveStrokeStyle:H,resolveStrokeStyleProp:o,worldToScreenPoints:oe},p.useEffect(()=>(x(Ur,10,K=>{const{preparedRegions:$,hoveredRegionId:ee,activeRegionId:ne,resolvedStrokeStyle:ue,resolvedHoverStrokeStyle:Re,resolvedActiveStrokeStyle:xe,resolveStrokeStyleProp:we,worldToScreenPoints:pe}=re.current;for(const O of $){const{region:q,polygons:_,regionIndex:V,regionKey:j}=O,ie=Ht(ne,j)?"active":Ht(ee,j)?"hover":"default";let se=ie==="active"?xe:ie==="hover"?Re:ue;if(we){const ke=we({region:q,regionId:j,regionIndex:V,state:ie});se=qe(se,ke||void 0)}const ve=ie==="default"?null:bl(se);for(const ke of _){const Ge=pe(ke.outer);Ge.length>=4&&(ve&&Ie(K,Ge,ve,!0,!1),Ie(K,Ge,se,!0,!1));for(const Qt of ke.holes){const it=pe(Qt);it.length>=4&&(ve&&Ie(K,it,ve,!0,!1),Ie(K,it,se,!0,!1))}}}}),()=>M(Ur)),[x,M]);const be=p.useRef({preparedRegions:ce,resolvedLabelStyle:le,labelStyleResolver:J,labelAnchor:a,autoLiftLabelAtMaxZoom:l,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:Se,rendererRef:m});be.current={preparedRegions:ce,resolvedLabelStyle:le,labelStyleResolver:J,labelAnchor:a,autoLiftLabelAtMaxZoom:l,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:Se,rendererRef:m},p.useEffect(()=>(x(zr,50,(K,$,ee)=>{const{preparedRegions:ne,resolvedLabelStyle:ue,labelStyleResolver:Re,labelAnchor:xe,autoLiftLabelAtMaxZoom:we,clampLabelToViewport:pe,regionLabelAutoLiftOffsetPx:O,rendererRef:q}=be.current;if(ne.length===0)return;const _=Math.max(1e-6,q.current?.getViewState?.().zoom??1),V=typeof O=="number"&&Number.isFinite(O)?Math.max(0,O):kn(we,_,q.current?.getZoomRange?.(),q.current?.getRegionLabelAutoLiftCapZoom?.());for(const j of ne){if(!j.region.label)continue;const ie=Dn(j.polygons,xe);if(!ie)continue;const se=We(q.current?.worldToScreen(ie[0],ie[1])??[]);if(!se)continue;let ve=Bn(ue,Re?.({region:j.region,regionId:j.regionKey,regionIndex:j.regionIndex,zoom:_}));V>0&&(ve={...ve,offsetY:ve.offsetY+V}),fi(K,j.region.label,se,$,ee,ve,pe)}}),()=>M(zr)),[x,M]),p.useEffect(()=>{w()},[ce,v,ae,P,le,Se,w]);const de=p.useRef({preparedRegionHits:ge,resolvedLabelStyle:le,labelStyleResolver:J,regionLabelAutoLiftOffsetPx:Se,clampLabelToViewport:u,onHover:h,onClick:d,commitActive:Te});return de.current={preparedRegionHits:ge,resolvedLabelStyle:le,labelStyleResolver:J,regionLabelAutoLiftOffsetPx:Se,clampLabelToViewport:u,onHover:h,onClick:d,commitActive:Te},p.useEffect(()=>{const X=b.current;if(!X)return;const K=ne=>{if(W())return;const ue=m.current;if(!ue)return;const{preparedRegionHits:Re,resolvedLabelStyle:xe,labelStyleResolver:we,regionLabelAutoLiftOffsetPx:pe,clampLabelToViewport:O,onHover:q}=de.current,_=k(ne.clientX,ne.clientY);if(!_)return;let V=null,j=null;if(Re.length>0){const se=L(_[0],_[1]);if(se){const ve=y.current?.getBoundingClientRect();j=Br(_,se,Re,ue,xe,we,typeof pe=="number"?pe:0,ve?.width??0,ve?.height??0,O),V=j?.regionId??null}}const ie=te.current;String(ie)!==String(V)&&(te.current=V,Y(V),q?.({region:j?.region??null,regionId:V,regionIndex:j?.regionIndex??-1,coordinate:_}),w())},$=ne=>{if(W())return;const ue=m.current;if(!ue)return;const{preparedRegionHits:Re,resolvedLabelStyle:xe,labelStyleResolver:we,regionLabelAutoLiftOffsetPx:pe,clampLabelToViewport:O,onClick:q,commitActive:_}=de.current;if(Re.length===0)return;const V=k(ne.clientX,ne.clientY);if(!V)return;const j=L(V[0],V[1]);if(!j)return;const ie=y.current?.getBoundingClientRect(),se=Br(V,j,Re,ue,xe,we,typeof pe=="number"?pe:0,ie?.width??0,ie?.height??0,O),ve=se?.regionId??null;_(ve),se&&q&&q({region:se.region,regionId:se.regionId,regionIndex:se.regionIndex,coordinate:V})},ee=()=>{te.current!==null&&(te.current=null,Y(null),de.current.onHover?.({region:null,regionId:null,regionIndex:-1,coordinate:null}),w())};return X.addEventListener("pointermove",K),X.addEventListener("click",$),X.addEventListener("pointerleave",ee),()=>{X.removeEventListener("pointermove",K),X.removeEventListener("click",$),X.removeEventListener("pointerleave",ee)}},[b,m,y,k,L,W,w]),null}function wl({imageWidth:t,imageHeight:e,tiles:n,viewState:r,className:i,style:o}){const s=p.useRef(null),a=p.useRef(null),l=p.useMemo(()=>({width:"100%",height:"100%",display:"block",...o}),[o]);return p.useEffect(()=>{const u=s.current;if(!u)return;const f=new Kr({canvas:u,imageWidth:t,imageHeight:e,initialViewState:r});return a.current=f,f.setTiles(n),()=>{f.destroy(),a.current=null}},[t,e]),p.useEffect(()=>{const u=a.current;u&&u.setTiles(n)},[n]),p.useEffect(()=>{const u=a.current;!u||!r||u.setViewState(r)},[r]),Ye.jsx("canvas",{ref:s,className:i,style:l})}function Sl(t,e){if(!e)return!1;try{const r=new URL(t,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 Ui{constructor(e){S(this,"maxConcurrency");S(this,"maxRetries");S(this,"retryBaseDelayMs");S(this,"retryMaxDelayMs");S(this,"onTileLoad");S(this,"onTileError");S(this,"onStateChange");S(this,"authToken");S(this,"destroyed",!1);S(this,"queue",[]);S(this,"queuedByKey",new Map);S(this,"inflight",new Map);S(this,"visibleKeys",new Set);S(this,"timerId",null);S(this,"abortedCount",0);S(this,"retryCount",0);S(this,"failedCount",0);this.maxConcurrency=Math.max(1,Math.floor(e.maxConcurrency??12)),this.maxRetries=Math.max(0,Math.floor(e.maxRetries??2)),this.retryBaseDelayMs=Math.max(10,Math.floor(e.retryBaseDelayMs??120)),this.retryMaxDelayMs=Math.max(this.retryBaseDelayMs,Math.floor(e.retryMaxDelayMs??1200)),this.authToken=e.authToken??"",this.onTileLoad=e.onTileLoad,this.onTileError=e.onTileError,this.onStateChange=e.onStateChange}setAuthToken(e){this.authToken=String(e??"")}schedule(e){if(this.destroyed)return;const n=new Set;for(const r of e)n.add(r.key);this.visibleKeys=n,this.dropInvisibleQueued(n),this.abortInvisibleInflight(n);for(const r of e){if(this.inflight.has(r.key)){const s=this.inflight.get(r.key);s&&(s.tile=r);continue}const i=this.queuedByKey.get(r.key);if(i){i.tile=r;continue}const o={tile:r,attempt:0,readyAt:ye()};this.queue.push(o),this.queuedByKey.set(r.key,o)}this.sortQueue(),this.pump(),this.emitStateChange()}clear(){this.clearPumpTimer(),this.visibleKeys.clear(),this.queue=[],this.queuedByKey.clear();for(const[,e]of this.inflight)e.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(e){if(this.queue.length===0)return;const n=[];for(const r of this.queue){if(!e.has(r.tile.key)){this.queuedByKey.delete(r.tile.key);continue}n.push(r)}this.queue=n}abortInvisibleInflight(e){for(const[n,r]of this.inflight)e.has(n)||(this.inflight.delete(n),this.abortedCount+=1,r.controller.abort())}sortQueue(){this.queue.sort((e,n)=>e.readyAt!==n.readyAt?e.readyAt-n.readyAt:e.tile.distance2!==n.tile.distance2?e.tile.distance2-n.tile.distance2:e.tile.tier!==n.tile.tier?n.tile.tier-e.tile.tier:e.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 e=this.queue[0]?.readyAt;if(typeof e!="number")return;const n=Math.max(0,e-ye());this.timerId=globalThis.setTimeout(()=>{this.timerId=null,this.pump()},n)}takeNextReadyQueueItem(){if(this.queue.length===0)return null;const e=ye(),n=this.queue[0];return!n||n.readyAt>e?null:(this.queue.shift(),this.queuedByKey.delete(n.tile.key),n)}startFetch(e){const n=new AbortController,r={tile:e.tile,attempt:e.attempt,controller:n};this.inflight.set(e.tile.key,r),this.emitStateChange();const i=Sl(e.tile.url,this.authToken);fetch(e.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(e.tile.key)){o.close();return}this.onTileLoad(e.tile,o)}).catch(o=>{if(n.signal.aborted||this.destroyed)return;if(e.attempt<this.maxRetries&&this.visibleKeys.has(e.tile.key)){this.retryCount+=1;const a=e.attempt+1,l=this.getRetryDelay(a),u={tile:e.tile,attempt:a,readyAt:ye()+l},f=this.queuedByKey.get(e.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?.(e.tile,o,e.attempt+1)}).finally(()=>{this.inflight.delete(e.tile.key),this.pump(),this.emitStateChange()})}getRetryDelay(e){const n=Math.max(0,e-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 Rl(t,e){t.addEventListener("pointerdown",e.pointerDown),t.addEventListener("pointermove",e.pointerMove),t.addEventListener("pointerup",e.pointerUp),t.addEventListener("pointercancel",e.pointerUp),t.addEventListener("wheel",e.wheel,{passive:!1}),t.addEventListener("dblclick",e.doubleClick),t.addEventListener("contextmenu",e.contextMenu),t.addEventListener("webglcontextlost",e.contextLost),t.addEventListener("webglcontextrestored",e.contextRestored)}function El(t,e){t.removeEventListener("pointerdown",e.pointerDown),t.removeEventListener("pointermove",e.pointerMove),t.removeEventListener("pointerup",e.pointerUp),t.removeEventListener("pointercancel",e.pointerUp),t.removeEventListener("wheel",e.wheel),t.removeEventListener("dblclick",e.doubleClick),t.removeEventListener("contextmenu",e.contextMenu),t.removeEventListener("webglcontextlost",e.contextLost),t.removeEventListener("webglcontextrestored",e.contextRestored)}function Al(t,e,n){const r=t.getBoundingClientRect(),i=Math.max(1,r.width||t.clientWidth||1),o=Math.max(1,r.height||t.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));(t.width!==a||t.height!==l)&&(t.width=a,t.height=l),n.setViewport(i,o),e.viewport(0,0,a,l)}const An=.35,Mn=.5,Ml=256,Tn=[{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,Cl=5,vl=0,Pl=1,Il=-100,_l=100,Fl=2e3;function jt(t){return t*Math.PI/180}function Nt(t,e){return!t||!e?t===e:t.buffer===e.buffer&&t.byteOffset===e.byteOffset&&t.byteLength===e.byteLength}function Cn(t){return t.map(e=>({zoom:e.zoom,size:e.size}))}function Or(t){if(!t)return Cn(Tn);const e=new Map;for(const[n,r]of Object.entries(t)){const i=Number(n),o=Number(r);!Number.isFinite(i)||!Number.isFinite(o)||o<=0||e.set(i,o)}return e.size===0?Cn(Tn):Array.from(e.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function Ll(t,e){if(t===e)return!0;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n].zoom!==e[n].zoom||t[n].size!==e[n].size)return!1;return!0}function Dl(t,e){if(!Number.isFinite(t))return e[0]?.size??Mn;if(e.length===0)return Mn;if(e.length===1||t<=e[0].zoom)return e[0].size;for(let s=1;s<e.length;s+=1){const a=e[s-1],l=e[s];if(t>l.zoom)continue;const u=Math.max(1e-6,l.zoom-a.zoom),f=I((t-a.zoom)/u,0,1);return a.size+(l.size-a.size)*f}const n=e[e.length-1],r=e[e.length-2],i=Math.max(1e-6,n.zoom-r.zoom),o=(n.size-r.size)/i;return n.size+(t-n.zoom)*o}function Wr(t){return typeof t!="number"||!Number.isFinite(t)?1:I(t,Tl,Cl)}function Yr(t){return typeof t!="number"||!Number.isFinite(t)?0:I(t,vl,Pl)}function an(t){return typeof t!="number"||!Number.isFinite(t)?0:I(t,Il,_l)}function Xr(t){const e=an(t?.brightness),n=an(t?.contrast),r=an(t?.saturation);return{brightness:e/200,contrast:n/100,saturation:r/100}}function Yn(t){return t}function ln(t){return typeof t!="number"||!Number.isFinite(t)?0:I(t,0,Fl)}function Bt(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?null:Math.max(1e-6,t)}function cn(t){return typeof t=="function"?t:Yn}function zi(t,e,n){const r=t.getBoundingClientRect(),i=e-r.left-r.width*.5,o=n-r.top-r.height*.5;return Math.atan2(o,i)}function Oi(t,e){if(e.pointerId!==null&&t.hasPointerCapture(e.pointerId))try{t.releasePointerCapture(e.pointerId)}catch{}e.dragging=!1,e.mode="none",e.rotateLastAngleRad=null,e.pointerId=null,t.classList.remove("dragging")}function Nl(t){const{event:e,canvas:n,state:r,config:i,cancelViewAnimation:o}=t,s=i.ctrlDragRotate&&(e.ctrlKey||e.metaKey);(e.button===0||s&&e.button===2)&&(o(),s&&e.preventDefault(),r.dragging=!0,r.mode=s?"rotate":"pan",r.pointerId=e.pointerId,r.lastPointerX=e.clientX,r.lastPointerY=e.clientY,r.rotateLastAngleRad=r.mode==="rotate"?zi(n,e.clientX,e.clientY):null,n.classList.add("dragging"),n.setPointerCapture(e.pointerId))}function Bl(t){const{event:e,canvas:n,state:r,config:i,camera:o,clampViewState:s,emitViewState:a,requestRender:l}=t;if(!r.dragging||e.pointerId!==r.pointerId)return;const u=e.clientX-r.lastPointerX,f=e.clientY-r.lastPointerY;if(r.lastPointerX=e.clientX,r.lastPointerY=e.clientY,r.mode==="rotate"){const c=zi(n,e.clientX,e.clientY),h=r.rotateLastAngleRad;if(r.rotateLastAngleRad=c,h!==null){const d=c-h,m=Math.atan2(Math.sin(d),Math.cos(d)),g=i.rotationDragSensitivityDegPerPixel/An,y=o.getViewState();o.setViewState({rotationDeg:y.rotationDeg-m*180/Math.PI*g})}}else{const c=o.getViewState(),h=Math.max(1e-6,c.zoom),d=jt(c.rotationDeg),m=Math.cos(d),g=Math.sin(d),y=(u*m-f*g)/h,b=(u*g+f*m)/h;o.setViewState({offsetX:c.offsetX-y,offsetY:c.offsetY-b})}s(),a(),l()}function kl(t,e,n){t.pointerId===n.pointerId&&Oi(e,n)}function Ul(t){const{event:e,canvas:n,onZoomBy:r}=t;e.preventDefault();const i=n.getBoundingClientRect(),o=e.clientX-i.left,s=e.clientY-i.top,a=e.deltaY<0?1.12:.89;r(a,o,s)}const zl=4;function Ol(t){const{event:e,canvas:n,snapState:r,onSnapZoom:i}=t;e.preventDefault();const o=e.deltaY<0?"in":e.deltaY>0?"out":null;if(o&&r.blockedDirection)if(o!==r.blockedDirection)r.blockedDirection=null,r.accumulatedDelta=0;else return;if(r.accumulatedDelta!==0&&e.deltaY!==0&&Math.sign(r.accumulatedDelta)!==Math.sign(e.deltaY)&&(r.accumulatedDelta=0),r.accumulatedDelta+=e.deltaY,Math.abs(r.accumulatedDelta)<zl)return;const s=n.getBoundingClientRect(),a=e.clientX-s.left,l=e.clientY-s.top,u=r.accumulatedDelta>0?"out":"in";if(r.accumulatedDelta=0,!i(u,a,l)){r.blockedDirection=u;return}r.blockedDirection=null}function Wl(t){const{event:e,canvas:n,onZoomBy:r}=t,i=n.getBoundingClientRect(),o=e.clientX-i.left,s=e.clientY-i.top;r(e.shiftKey?.8:1.25,o,s)}function Yl(t,e){(e||t.ctrlKey||t.metaKey)&&t.preventDefault()}function Kt(t){const e=t.getViewCorners();let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[s,a]of e)s<n&&(n=s),s>i&&(i=s),a<r&&(r=a),a>o&&(o=a);return[n,r,i,o]}function Wt(t,e){const n=Kt(t),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]=t.getCenter(),u=r*.5,f=i*.5,c=u-o,h=e.width-u+o,d=f-s,m=e.height-f+s,g=c<=h?I(a,c,h):e.width*.5,y=d<=m?I(l,d,m):e.height*.5;t.setCenter(g,y)}function Xl(t,e){const n=Math.max(1e-6,t.getViewState().zoom),r=e.maxTierZoom+Math.log2(n);return I(Math.floor(r),0,e.maxTierZoom)}function Vl(t,e){return!(t[2]<=e[0]||t[0]>=e[2]||t[3]<=e[1]||t[1]>=e[3])}function Wi(t,e,n){const r=Kt(t),i=Math.pow(2,e.maxTierZoom-n),o=Math.ceil(e.width/i),s=Math.ceil(e.height/i),a=Math.max(1,Math.ceil(o/e.tileSize)),l=Math.max(1,Math.ceil(s/e.tileSize)),u=r[0],f=r[1],c=r[2],h=r[3],d=I(Math.floor(u/i/e.tileSize),0,a-1),m=I(Math.floor((c-1)/i/e.tileSize),0,a-1),g=I(Math.floor(f/i/e.tileSize),0,l-1),y=I(Math.floor((h-1)/i/e.tileSize),0,l-1);if(d>m||g>y)return[];const b=(u+c)*.5/i/e.tileSize,x=(f+h)*.5/i/e.tileSize,M=[];for(let w=g;w<=y;w+=1)for(let T=d;T<=m;T+=1){const A=T*e.tileSize*i,k=w*e.tileSize*i,L=Math.min((T+1)*e.tileSize,o)*i,W=Math.min((w+1)*e.tileSize,s)*i,D=T-b,G=w-x;M.push({key:`${n}/${T}/${w}`,tier:n,x:T,y:w,bounds:[A,k,L,W],distance2:D*D+G*G,url:Wn(e,n,T,w)})}return M.sort((w,T)=>w.distance2-T.distance2),M}function Gl(t,e){const n=Xl(t,e);return{tier:n,visible:Wi(t,e,n)}}function Hl(t){t.interactionLocked||Nl({event:t.event,canvas:t.canvas,state:t.state,config:{ctrlDragRotate:t.ctrlDragRotate,rotationDragSensitivityDegPerPixel:t.rotationDragSensitivityDegPerPixel},cancelViewAnimation:t.cancelViewAnimation})}function ql(t){t.interactionLocked||Bl({event:t.event,canvas:t.canvas,state:t.state,config:{ctrlDragRotate:t.ctrlDragRotate,rotationDragSensitivityDegPerPixel:t.rotationDragSensitivityDegPerPixel},camera:t.camera,clampViewState:()=>Wt(t.camera,t.source),emitViewState:t.emitViewState,requestRender:t.requestRender})}function Zl(t){t.interactionLocked||kl(t.event,t.canvas,t.state)}function $l(t){t.interactionLocked||Wl({event:t.event,canvas:t.canvas,onZoomBy:t.onZoomBy})}function Kl(t){Yl(t.event,t.state.dragging)}function jl(t,e){Oi(t,e)}function Ql(t){return{pointerDown:e=>Hl({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,state:t.state,ctrlDragRotate:t.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:t.getRotationDragSensitivityDegPerPixel(),cancelViewAnimation:t.cancelViewAnimation}),pointerMove:e=>ql({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,state:t.state,ctrlDragRotate:t.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:t.getRotationDragSensitivityDegPerPixel(),camera:t.camera,source:t.source,emitViewState:t.emitViewState,requestRender:t.requestRender}),pointerUp:e=>Zl({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,state:t.state}),wheel:e=>{if(t.getInteractionLocked()){e.preventDefault();return}if(t.getUseZoomSnaps?.()&&t.onSnapZoom&&t.zoomSnapState){Ol({event:e,canvas:t.canvas,snapState:t.zoomSnapState,onSnapZoom:t.onSnapZoom});return}Ul({event:e,canvas:t.canvas,onZoomBy:t.zoomBy})},doubleClick:e=>$l({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,onZoomBy:t.zoomBy}),contextMenu:e=>Kl({event:e,canvas:t.canvas,state:t.state})}}function Jl(t){const{gl:e,cache:n,maxCacheTiles:r}=t;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;e.deleteTexture(s.texture),n.delete(o)}}function ec(t,e){if(t.isContextLost())return null;const n=t.createTexture();return n?(t.bindTexture(t.TEXTURE_2D,n),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,1),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),t.bindTexture(t.TEXTURE_2D,null),n):null}function tc(t){const{gl:e,cache:n,tile:r,bitmap:i,frameSerial:o,maxCacheTiles:s,destroyed:a,contextLost:l,requestRender:u}=t;if(a||l||e.isContextLost()){i.close();return}if(n.has(r.key)){i.close();return}const f=ec(e,i);i.close(),f&&(n.set(r.key,{key:r.key,texture:f,bounds:r.bounds,tier:r.tier,lastUsed:o}),Jl({gl:e,cache:n,maxCacheTiles:s}),u())}function nc(t,e){for(const[,n]of e)t.deleteTexture(n.texture)}function rc(t){const{event:e,destroyed:n,contextLost:r,cancelViewAnimation:i,cancelDrag:o,tileScheduler:s,cache:a,onContextLost:l}=t;if(e.preventDefault(),n||r)return{handled:!1,frame:t.frame};let u=t.frame;return u!==null&&(cancelAnimationFrame(u),u=null),i(),o(),s.clear(),a.clear(),l?.(),{handled:!0,frame:u}}function ic(t){if(t.destroyed)return{didDestroy:!1,frame:t.frame};let e=t.frame;return e!==null&&(cancelAnimationFrame(e),e=null),t.cancelViewAnimation(),t.resizeObserver.disconnect(),t.removeCanvasEventListeners(),t.cancelDrag(),t.tileScheduler.destroy(),!t.contextLost&&!t.gl.isContextLost()&&(nc(t.gl,t.cache),t.gl.deleteBuffer(t.tileProgram.vbo),t.gl.deleteVertexArray(t.tileProgram.vao),t.gl.deleteProgram(t.tileProgram.program),t.gl.deleteBuffer(t.pointProgram.posBuffer),t.gl.deleteBuffer(t.pointProgram.termBuffer),t.gl.deleteBuffer(t.pointProgram.fillModeBuffer),t.gl.deleteBuffer(t.pointProgram.indexBuffer),t.gl.deleteTexture(t.pointProgram.paletteTexture),t.gl.deleteVertexArray(t.pointProgram.vao),t.gl.deleteProgram(t.pointProgram.program)),t.cache.clear(),{didDestroy:!0,frame:e}}function oc(t,e){if(e<=0||t.length===0)return new Uint32Array(0);let n=t.length;for(let o=0;o<t.length;o+=1)t[o]<e||(n-=1);if(n===t.length)return t;if(n<=0)return new Uint32Array(0);const r=new Uint32Array(n);let i=0;for(let o=0;o<t.length;o+=1){const s=t[o];s>=e||(r[i]=s,i+=1)}return r}function sc(t,e){return e<=0?new Uint8Array(0):t.length<e?new Uint8Array(e):t.subarray(0,e)}function ac(t,e,n,r,i){if(!i||i.length===0)return{...t,lastPointPalette:null};const o=new Uint8Array(i);if(r||e.isContextLost())return{...t,lastPointPalette:o};const s=Math.max(1,Math.floor(o.length/4));return e.bindTexture(e.TEXTURE_2D,n.paletteTexture),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,s,1,0,e.RGBA,e.UNSIGNED_BYTE,o),e.bindTexture(e.TEXTURE_2D,null),{...t,lastPointPalette:o,pointPaletteSize:s}}function lc(t,e,n,r,i){if(!i||!i.count||!i.positions||!i.paletteIndices)return{...t,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?oc(i.drawIndices,a):null,d=t.lastPointData,m=d?.fillModes instanceof Uint8Array,g=t.pointBuffersDirty||!d||d.count!==a||!Nt(d.positions,l)||!Nt(d.paletteIndices,u)||m!==s||s&&(!d?.fillModes||!Nt(d.fillModes,f)),y=t.pointBuffersDirty||c&&(!d?.drawIndices||!Nt(d.drawIndices,h))||!c&&!!d?.drawIndices,b={...t,lastPointData:{count:a,positions:l,paletteIndices:u,fillModes:f,drawIndices:c?h??void 0:void 0}};if(r||e.isContextLost())return b;const x=b.lastPointData;if(!x)return b;if(g){e.bindBuffer(e.ARRAY_BUFFER,n.posBuffer),e.bufferData(e.ARRAY_BUFFER,x.positions,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,n.termBuffer),e.bufferData(e.ARRAY_BUFFER,x.paletteIndices,e.STATIC_DRAW);const M=sc(b.zeroFillModes,a);e.bindBuffer(e.ARRAY_BUFFER,n.fillModeBuffer),e.bufferData(e.ARRAY_BUFFER,x.fillModes??M,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,null),b.zeroFillModes=M}return c&&y&&(e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n.indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,h??new Uint32Array(0),e.DYNAMIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),b.usePointIndices=c,b.pointCount=c?h?.length??0:x.count,(g||y)&&(b.pointBuffersDirty=!1),b}function cc(t){const{gl:e,camera:n,source:r,cache:i,frameSerial:o,tileProgram:s,pointProgram:a,imageColorSettings:l,pointCount:u,usePointIndices:f,pointPaletteSize:c,pointStrokeScale:h,pointInnerFillOpacity:d,pointSizePx:m,tileScheduler:g,getVisibleTiles:y,getVisibleTilesForTier:b,getViewBounds:x,intersectsBounds:M}=t;e.clearColor(.03,.06,.1,1),e.clear(e.COLOR_BUFFER_BIT);const{tier:w,visible:T}=y(),A=x(),k=new Set(T.map(B=>B.key));e.useProgram(s.program),e.bindVertexArray(s.vao),e.uniformMatrix3fv(s.uCamera,!1,n.getMatrix()),e.uniform1i(s.uTexture,0),e.uniform1f(s.uBrightness,l.brightness),e.uniform1f(s.uContrast,l.contrast),e.uniform1f(s.uSaturation,l.saturation);const L=[];for(const[,B]of i)k.has(B.key)||M(B.bounds,A)&&L.push(B);L.sort((B,z)=>B.tier-z.tier);for(const B of L)B.lastUsed=o,e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,B.texture),e.uniform4f(s.uBounds,B.bounds[0],B.bounds[1],B.bounds[2],B.bounds[3]),e.drawArrays(e.TRIANGLE_STRIP,0,4);let W=0;const D=[];for(const B of T){const z=i.get(B.key);if(!z){D.push(B);continue}z.lastUsed=o,e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,z.texture),e.uniform4f(s.uBounds,z.bounds[0],z.bounds[1],z.bounds[2],z.bounds[3]),e.drawArrays(e.TRIANGLE_STRIP,0,4),W+=1}const G=D.slice(),U=1e6,v=[];w>0&&v.push(w-1),w<r.maxTierZoom&&v.push(w+1);for(const B of v){const z=b(B);for(const Z of z)i.has(Z.key)||(Z.distance2+=U,G.push(Z))}g.schedule(G),e.bindTexture(e.TEXTURE_2D,null),e.bindVertexArray(null);let Y=0;return u>0&&(e.enable(e.BLEND),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA),e.useProgram(a.program),e.bindVertexArray(a.vao),e.uniformMatrix3fv(a.uCamera,!1,n.getMatrix()),e.uniform1f(a.uPointSize,m),e.uniform1f(a.uPointStrokeScale,h),e.uniform1f(a.uPointInnerFillAlpha,d),e.uniform1f(a.uPaletteSize,c),e.uniform1i(a.uPalette,1),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,a.paletteTexture),f?e.drawElements(e.POINTS,u,e.UNSIGNED_INT,0):e.drawArrays(e.POINTS,0,u),e.bindTexture(e.TEXTURE_2D,null),e.bindVertexArray(null),Y=u),{tier:w,visible:T.length,rendered:W,points:Y,fallback:L.length,cacheHits:W,cacheMisses:D.length,drawCalls:L.length+W+(Y>0?1:0)}}function Vr(t){const r=gt(t,`#version 300 es
|
|
134
|
+
`;function Ua(){if(typeof navigator>"u")return!1;const t=navigator;return typeof t.gpu=="object"&&t.gpu!==null}function _i(){if(!Ua())return null;const e=navigator.gpu;if(!e||typeof e!="object")return null;const n=e;return typeof n.requestAdapter!="function"?null:n}const Lt=globalThis.GPUShaderStage?.COMPUTE??4,sn=globalThis.GPUBufferUsage?.STORAGE??128,Dt=globalThis.GPUBufferUsage?.COPY_DST??8,za=globalThis.GPUBufferUsage?.COPY_SRC??4,Oa=globalThis.GPUBufferUsage?.UNIFORM??64,Wa=globalThis.GPUBufferUsage?.MAP_READ??1,Ya=globalThis.GPUMapMode?.READ??1;async function Xa(){const t=_i();if(!t)return{supported:!1,features:[]};const e=await t.requestAdapter();return e?{supported:!0,adapterName:e.info?.description??e.info?.vendor??"unknown",features:Array.from(e.features),limits:{maxStorageBufferBindingSize:Number(e.limits.maxStorageBufferBindingSize),maxComputeInvocationsPerWorkgroup:Number(e.limits.maxComputeInvocationsPerWorkgroup),maxComputeWorkgroupSizeX:Number(e.limits.maxComputeWorkgroupSizeX)}}:{supported:!1,features:[]}}async function Va(){return Ft||(Ft=(async()=>{const t=_i();if(!t)return null;const e=await t.requestAdapter();if(!e)return null;const n=await e.requestDevice(),r=n.createBindGroupLayout({entries:[{binding:0,visibility:Lt,buffer:{type:"read-only-storage"}},{binding:1,visibility:Lt,buffer:{type:"read-only-storage"}},{binding:2,visibility:Lt,buffer:{type:"storage"}},{binding:3,visibility:Lt,buffer:{type:"uniform"}}]}),i=n.createComputePipeline({layout:n.createPipelineLayout({bindGroupLayouts:[r]}),compute:{module:n.createShaderModule({code:ka}),entryPoint:"main"}});return{device:n,pipeline:i,bindGroupLayout:r}})(),Ft)}function Nt(t,e){return Math.ceil(t/e)*e}async function Fi(t,e,n){const r=await Va();if(!r)return null;const i=Math.max(0,Math.floor(e)),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(t.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:Nt(a,4),usage:sn|Dt}),h=r.device.createBuffer({size:Nt(l,4),usage:sn|Dt}),d=r.device.createBuffer({size:Nt(u,4),usage:sn|za}),m=r.device.createBuffer({size:16,usage:Oa|Dt}),g=r.device.createBuffer({size:Nt(u,4),usage:Dt|Wa});let y=!1;try{r.device.queue.writeBuffer(c,0,t.buffer,t.byteOffset,a),r.device.queue.writeBuffer(h,0,n.buffer,n.byteOffset,l),r.device.queue.writeBuffer(m,0,new Uint32Array([s,o,0,0]));const b=r.device.createBindGroup({layout:r.bindGroupLayout,entries:[{binding:0,resource:{buffer:c}},{binding:1,resource:{buffer:h}},{binding:2,resource:{buffer:d}},{binding:3,resource:{buffer:m}}]}),x=r.device.createCommandEncoder(),A=x.beginComputePass();A.setPipeline(r.pipeline),A.setBindGroup(0,b),A.dispatchWorkgroups(Math.ceil(s/256)),A.end(),x.copyBufferToBuffer(d,0,g,0,u),r.device.queue.submit([x.finish()]),await g.mapAsync(Ya),y=!0;const w=g.getMappedRange();return new Uint32Array(w.slice(0))}finally{if(y)try{g.unmap()}catch{}c.destroy(),h.destroy(),d.destroy(),m.destroy(),g.destroy()}}async function Li(t,e,n={}){const r=be(),i=n.bridgeToDraw===!0;if(!t||!t.count||!t.positions||!t.paletteIndices)return{data:null,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}};const o=ft(e??[]);if(o.length===0){const w={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return t.fillModes instanceof Uint8Array&&(w.fillModes=new Uint8Array(0)),t.ids instanceof Uint32Array&&(w.ids=new Uint32Array(0)),{data:w,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const s=rt(t),a=t.fillModes instanceof Uint8Array&&t.fillModes.length>=s?t.fillModes:null,l=t.ids instanceof Uint32Array&&t.ids.length>=s?t.ids:null;if(s===0){const w={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(w.fillModes=new Uint8Array(0)),l&&(w.ids=new Uint32Array(0)),{data:w,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const u=new Float32Array(o.length*4);for(let w=0;w<o.length;w+=1){const T=w*4,M=o[w];u[T]=M.minX,u[T+1]=M.minY,u[T+2]=M.maxX,u[T+3]=M.maxY}let f=null,c=!1;try{f=await Fi(t.positions,s,u),c=!!f}catch{f=null,c=!1}if(!f)return{data:St(t,e),meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!1,candidateCount:s,bridgedToDraw:!1}};let h=0;for(let w=0;w<s;w+=1)f[w]===1&&(h+=1);const d=new Uint32Array(h);if(h>0){let w=0;for(let T=0;T<s;T+=1)f[T]===1&&(d[w]=T,w+=1)}if(h===0){if(i){const T={count:s,positions:t.positions.subarray(0,s*2),paletteIndices:t.paletteIndices.subarray(0,s),drawIndices:new Uint32Array(0)};return a&&(T.fillModes=a.subarray(0,s)),l&&(T.ids=l.subarray(0,s)),{data:T,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!0}}}const w={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(w.fillModes=new Uint8Array(0)),l&&(w.ids=new Uint32Array(0)),{data:w,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const w=new Uint32Array(h);let T=0;for(let z=0;z<h;z+=1){const L=d[z]??0,V=t.positions[L*2],H=t.positions[L*2+1];xt(V,H,o)&&(w[T]=L,T+=1)}const M={count:s,positions:t.positions.subarray(0,s*2),paletteIndices:t.paletteIndices.subarray(0,s),drawIndices:w.subarray(0,T)};return a&&(M.fillModes=a.subarray(0,s)),l&&(M.ids=l.subarray(0,s)),{data:M,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!0,candidateCount:h,bridgedToDraw:!0}}}const m=new Float32Array(h*2),g=new Uint16Array(h),y=a?new Uint8Array(h):null,b=l?new Uint32Array(h):null;let x=0;for(let w=0;w<h;w+=1){const T=d[w]??0,M=t.positions[T*2],z=t.positions[T*2+1];xt(M,z,o)&&(m[x*2]=M,m[x*2+1]=z,g[x]=t.paletteIndices[T],y&&(y[x]=a[T]),b&&(b[x]=l[T]),x+=1)}const A={count:x,positions:m.subarray(0,x*2),paletteIndices:g.subarray(0,x)};return y&&(A.fillModes=y.subarray(0,x)),b&&(A.ids=b.subarray(0,x)),{data:A,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!0,candidateCount:h,bridgedToDraw:!1}}}class Di{constructor(e,n){S(this,"worker",null);S(this,"supported",!0);S(this,"requestId",1);S(this,"pendingById",new Map);S(this,"handleMessage",e=>{const n=e.data;if(!n)return;const r=this.pendingById.get(n.id);r&&(this.pendingById.delete(n.id),this.handlers.onResponse(n,r))});S(this,"handleError",()=>{this.supported=!1,this.teardownWorker("worker crashed")});this.createWorker=e,this.handlers=n}beginRequest(e){const n=this.getOrCreateWorker();if(!n)return null;const r=this.requestId++;return this.pendingById.set(r,e),{id:r,worker:n}}cancelRequest(e){const n=this.pendingById.get(e);if(n)return this.pendingById.delete(e),n}terminate(e="worker terminated"){this.teardownWorker(e)}getOrCreateWorker(){if(!this.supported)return null;if(this.worker)return this.worker;try{const e=this.createWorker();return e.addEventListener("message",this.handleMessage),e.addEventListener("error",this.handleError),this.worker=e,e}catch{return this.supported=!1,null}}teardownWorker(e){this.worker&&(this.worker.removeEventListener("message",this.handleMessage),this.worker.removeEventListener("error",this.handleError),this.worker.terminate(),this.worker=null);const n=new Error(e);for(const[,r]of this.pendingById)this.handlers.rejectPending(r,n);this.pendingById.clear()}}const Et=new Di(()=>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:ct&&ct.tagName.toUpperCase()==="SCRIPT"&&ct.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(t,e)=>{if(t.type==="roi-clip-failure"){e.reject(new Error(t.error||"worker clip failed"));return}if(t.type==="roi-clip-index-success"){if(e.kind!=="index"){e.reject(new Error("worker response mismatch: expected point data result"));return}const l=Math.max(0,Math.floor(t.count)),u=new Uint32Array(t.indices).subarray(0,l);e.resolve({indices:u,meta:{mode:"worker",durationMs:Number.isFinite(t.durationMs)?t.durationMs:be()-e.startMs}});return}if(e.kind!=="data"){e.reject(new Error("worker response mismatch: expected index result"));return}const n=Math.max(0,Math.floor(t.count)),r=new Float32Array(t.positions),i=new Uint16Array(t.paletteIndices),o=t.fillModes?new Uint8Array(t.fillModes):null,s=t.ids?new Uint32Array(t.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)),e.resolve({data:a,meta:{mode:"worker",durationMs:Number.isFinite(t.durationMs)?t.durationMs:be()-e.startMs}})},rejectPending:(t,e)=>{t.reject(e)}});function Ga(){Et.terminate("worker terminated")}async function Ni(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return{data:null,meta:{mode:"worker",durationMs:0}};const n=rt(t),r=t.positions.slice(0,n*2),i=t.paletteIndices.slice(0,n),o=t.fillModes instanceof Uint8Array&&t.fillModes.length>=n?t.fillModes.slice(0,n):null,s=t.ids instanceof Uint32Array&&t.ids.length>=n?t.ids.slice(0,n):null;return new Promise((a,l)=>{const u=be(),f=Et.beginRequest({kind:"data",resolve:a,reject:l,startMs:u});if(!f){a({data:St(t,e),meta:{mode:"sync",durationMs:be()-u}});return}const c={type:"roi-clip-request",id:f.id,count:n,positions:r.buffer,paletteIndices:i.buffer,fillModes:o?.buffer,ids:s?.buffer,polygons:e??[]},h=[r.buffer,i.buffer];o&&h.push(o.buffer),s&&h.push(s.buffer);try{f.worker.postMessage(c,h)}catch(d){const m=Et.cancelRequest(f.id);m?m.reject(d):l(d)}})}async function Ha(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return{indices:new Uint32Array(0),meta:{mode:"worker",durationMs:0}};const n=rt(t),r=t.positions.slice(0,n*2);return new Promise((i,o)=>{const s=be(),a=Et.beginRequest({kind:"index",resolve:i,reject:o,startMs:s});if(!a){i({indices:Ii(t,e),meta:{mode:"sync",durationMs:be()-s}});return}const l={type:"roi-clip-index-request",id:a.id,count:n,positions:r.buffer,polygons:e??[]};try{a.worker.postMessage(l,[r.buffer])}catch(u){const f=Et.cancelRequest(a.id);f?f.reject(u):o(u)}})}const qa={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};function Za(t,e,n,r,i){const o=p.useRef(0),[s,a]=p.useState(n),l=p.useMemo(()=>r.map(u=>ut(u.coordinates)).filter(u=>u!=null),[r]);return p.useEffect(()=>{const u=++o.current;let f=!1;if(!t)return a(n),()=>{f=!0};if(!n||!n.count||!n.positions||!n.paletteIndices)return a(null),()=>{f=!0};if(l.length===0)return a(qa),i?.({mode:e,durationMs:0,inputCount:n.count,outputCount:0,polygonCount:0}),()=>{f=!0};const c=(d,m)=>{if(f||u!==o.current)return;const g=n.count,y=d?.drawIndices?d.drawIndices.length:d?.count??0;a(d),i?.({mode:m.mode,durationMs:m.durationMs,inputCount:g,outputCount:y,polygonCount:l.length,usedWebGpu:m.usedWebGpu,candidateCount:m.candidateCount,bridgedToDraw:m.bridgedToDraw})};return(async()=>{if(e==="sync"){const d=performance.now(),m=St(n,l);c(m,{mode:"sync",durationMs:performance.now()-d});return}if(e==="hybrid-webgpu"){const d=await Li(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 Ni(n,l);c(d.data,{mode:d.meta.mode,durationMs:d.meta.durationMs})}catch{const d=performance.now(),m=St(n,l);c(m,{mode:"sync",durationMs:performance.now()-d})}})(),()=>{f=!0}},[t,e,n,l,i]),s}const $a=24,Ka=1024,ja=4,Wt=-1;function mt(t,e,n){return(t*73856093^e*19349663)>>>0&n}function Qa(t,e,n){if(t<=0||e<=0||n<=0)return 256;const r=Math.max(1,t*e),o=Math.sqrt(r/Math.max(1,n))*ja;return Math.max($a,Math.min(Ka,o))}function Ja(t,e){if(!(t instanceof Uint32Array)||t.length===0)return null;let n=!0;for(let o=0;o<t.length;o+=1)if(!(t[o]<e)){n=!1;break}if(n)return t;const r=new Uint32Array(t.length);let i=0;for(let o=0;o<t.length;o+=1)t[o]>=e||(r[i]=t[o],i+=1);return i>0?r.subarray(0,i):null}function el(t){const e=Math.max(0,Math.floor(t.count)),n=Math.floor(t.positions.length/2),r=Math.max(0,Math.min(e,n));if(r<=0)return null;const i=Ja(t.drawIndices??null,r),o=i?i.length:r;if(o===0)return null;const s=Qa(t.sourceWidth,t.sourceHeight,o),a=1/s,l=new Int32Array(o),u=new Int32Array(o);let f=0;if(i)for(let C=0;C<o;C+=1){const Y=i[C],O=t.positions[Y*2],N=t.positions[Y*2+1];!Number.isFinite(O)||!Number.isFinite(N)||(l[f]=Math.floor(O*a),u[f]=Math.floor(N*a),f+=1)}else for(let C=0;C<r;C+=1){const Y=t.positions[C*2],O=t.positions[C*2+1];!Number.isFinite(Y)||!Number.isFinite(O)||(l[f]=Math.floor(Y*a),u[f]=Math.floor(O*a),f+=1)}if(f===0)return null;let c=Math.min(f,Math.max(64,f>>>3));(!Number.isFinite(c)||c<=0)&&(c=f);let h=1;for(;h<c*2;)h<<=1;let d=h-1,m=new Int32Array(h*2),g=new Int32Array(h);m.fill(2147483647);let y=0;const b=new Int32Array(f);for(let C=0;C<f;C+=1){const Y=l[C],O=u[C];let N=mt(Y,O,d);for(;;){const Z=m[N*2];if(Z===2147483647){if(m[N*2]=Y,m[N*2+1]=O,g[N]=1,b[C]=N,y+=1,y*4>h*3){const oe=h;h<<=1,d=h-1;const ne=new Int32Array(h*2),Me=new Int32Array(h);ne.fill(2147483647);for(let we=0;we<oe;we+=1){if(m[we*2]===2147483647)continue;const Te=m[we*2],v=m[we*2+1];let I=mt(Te,v,d);for(;ne[I*2]!==2147483647;)I=I+1&d;ne[I*2]=Te,ne[I*2+1]=v,Me[I]=g[we]}for(m=ne,g=Me,N=mt(Y,O,d);m[N*2]!==Y||m[N*2+1]!==O;)N=N+1&d;b[C]=N}break}if(Z===Y&&m[N*2+1]===O){g[N]+=1,b[C]=N;break}N=N+1&d}}const x=new Int32Array(y*2),A=new Uint32Array(y),w=new Uint32Array(y),T=new Int32Array(h);T.fill(Wt);let M=0,z=0;for(let C=0;C<h;C+=1)m[C*2]!==2147483647&&(x[M*2]=m[C*2],x[M*2+1]=m[C*2+1],A[M]=z,w[M]=g[C],T[C]=M,z+=g[C],M+=1);const L=new Uint32Array(f),V=new Uint32Array(y);if(V.set(A),i)for(let C=0;C<f;C+=1){const Y=T[b[C]];L[V[Y]]=i[C],V[Y]+=1}else{let C=0;for(let Y=0;Y<r;Y+=1){const O=t.positions[Y*2],N=t.positions[Y*2+1];if(!Number.isFinite(O)||!Number.isFinite(N))continue;const Z=T[b[C]];L[V[Z]]=Y,V[Z]+=1,C+=1}}let H=1;for(;H<y*2;)H<<=1;const W=H-1,D=new Int32Array(H);D.fill(Wt);for(let C=0;C<y;C+=1){const Y=x[C*2],O=x[C*2+1];let N=mt(Y,O,W);for(;D[N]!==Wt;)N=N+1&W;D[N]=C}return{cellSize:s,safeCount:r,cellCount:y,hashCapacity:H,hashTable:D,cellKeys:x,cellOffsets:A,cellLengths:w,pointIndices:L}}function Bi(t,e,n){const{hashTable:r,cellKeys:i,hashMask:o}=t;let s=mt(e,n,o);for(;;){const a=r[s];if(a===Wt)return-1;if(i[a*2]===e&&i[a*2+1]===n)return a;s=s+1&o}}function tl(t,e){if(t.safeCount<=0||t.cellCount<=0)return null;const n=t.safeCount;return{cellSize:t.cellSize,safeCount:n,positions:e.positions.subarray(0,n*2),ids:e.ids instanceof Uint32Array&&e.ids.length>=n?e.ids.subarray(0,n):null,hashCapacity:t.hashCapacity,hashMask:t.hashCapacity-1,hashTable:new Int32Array(t.hashTable),cellKeys:new Int32Array(t.cellKeys),cellOffsets:new Uint32Array(t.cellOffsets),cellLengths:new Uint32Array(t.cellLengths),pointIndices:new Uint32Array(t.pointIndices)}}const En=new Di(()=>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:ct&&ct.tagName.toUpperCase()==="SCRIPT"&&ct.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(t,e)=>{if(t.type==="point-hit-index-failure"){e.reject(new Error(t.error||"worker index build failed"));return}e.resolve(tl(t,e.pointData))},rejectPending:(t,e)=>{t.reject(e)}});function nl(){En.terminate("worker terminated")}function rl(t,e){const n=rt(t);if(n<=0)return null;const r=t.positions.subarray(0,n*2),i=el({count:n,positions:r,drawIndices:t.drawIndices instanceof Uint32Array?t.drawIndices:null,sourceWidth:e?.width??0,sourceHeight:e?.height??0});return i?{cellSize:i.cellSize,safeCount:n,positions:r,ids:t.ids instanceof Uint32Array&&t.ids.length>=n?t.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 ki(t,e){if(!t||!t.positions||!t.paletteIndices)return null;const n=rt(t);return n<=0?null:new Promise((r,i)=>{const o={resolve:r,reject:i,pointData:t},s=En.beginRequest(o);if(!s||!s.worker){r(rl(t,e));return}const a=t.positions.slice(0,n*2),l=t.drawIndices instanceof Uint32Array&&t.drawIndices.length>0?t.drawIndices.slice():void 0,u={type:"point-hit-index-request",id:s.id,count:n,positions:a.buffer,drawIndices:l?.buffer,sourceWidth:e?.width??0,sourceHeight:e?.height??0},f=[a.buffer];l&&f.push(l.buffer);try{s.worker.postMessage(u,f)}catch(c){const h=En.cancelRequest(s.id);h?h.reject(c):i(c)}})}const il=.65,ol=4;function sl(t,e,n,r,i,o,s){const a=!!(n||r||i),[l,u]=p.useState(null),f=p.useRef(null),c=p.useRef(null);p.useEffect(()=>{if(!a||!t){u(null);return}let g=!1;return ki(t,e).then(y=>{g||u(y)}),()=>{g=!0}},[a,t,e]);const h=p.useCallback(g=>{const y=s.current;if(!y||!l)return null;const b=Number(g[0]),x=Number(g[1]);if(!Number.isFinite(b)||!Number.isFinite(x))return null;const A=Math.max(1e-6,y.getViewState().zoom),w=y.getPointSizeByZoom(),M=Math.max(ol,w*il)/A;if(!Number.isFinite(M)||M<=0)return null;const{cellSize:z,cellOffsets:L,cellLengths:V,pointIndices:H,positions:W,safeCount:D}=l,C=Math.floor(b/z),Y=Math.floor(x/z),O=Math.max(1,Math.ceil(M/z)),N=M*M;let Z=-1,oe=N,ne=0,Me=0;for(let Te=C-O;Te<=C+O;Te+=1)for(let v=Y-O;v<=Y+O;v+=1){const I=Bi(l,Te,v);if(I<0)continue;const B=L[I],fe=B+V[I];for(let Q=B;Q<fe;Q+=1){const se=H[Q];if(se>=D)continue;const le=W[se*2],de=W[se*2+1],ae=le-b,ge=de-x,ie=ae*ae+ge*ge;ie>oe||(oe=ie,Z=se,ne=le,Me=de)}}if(Z<0)return null;const we=l.ids?Number(l.ids[Z]):null;return{index:Z,id:we,coordinate:[b,x],pointCoordinate:[ne,Me]}},[l]),d=p.useCallback((g,y)=>{if(!n)return;const b=g?.index??null,x=g?.id??null;f.current===b&&c.current===x||(f.current=b,c.current=x,n({index:b,id:x,coordinate:y,pointCoordinate:g?.pointCoordinate??null}))},[n]),m=p.useCallback((g,y)=>{if(!r)return;const b=h(g);b&&r({...b,button:y})},[r,h]);return p.useEffect(()=>{if(i)return i.current=h,()=>{i.current===h&&(i.current=null)}},[i,h]),p.useEffect(()=>{const g=f.current;g!==null&&(l&&g<l.safeCount||(f.current=null,c.current=null,n?.({index:null,id:null,coordinate:null,pointCoordinate:null})))},[l,n]),p.useEffect(()=>{},[o,n]),{getCellByCoordinates:h,emitPointHover:d,emitPointClick:m}}const al=p.forwardRef(function({data:e=null,palette:n=null,sizeByZoom:r,strokeScale:i,innerFillOpacity:o,clipEnabled:s=!1,clipToRegions:a,clipMode:l="worker",onClipStats:u,onHover:f,onClick:c},h){const{rendererRef:d,rendererSerial:m,source:g}=it(),y=p.useRef(null),x=Za(s,l,e,a??ll,u),{getCellByCoordinates:A}=sl(x,g,f,c,y,"cursor",d);return p.useImperativeHandle(h,()=>({queryAt:A}),[A]),p.useEffect(()=>{const w=d.current;!w||!n||w.setPointPalette(n)},[m,n]),p.useEffect(()=>{const w=d.current;!w||r===void 0||w.setPointSizeByZoom(r)},[m,r]),p.useEffect(()=>{const w=d.current;!w||i===void 0||w.setPointStrokeScale(i)},[m,i]),p.useEffect(()=>{const w=d.current;!w||o===void 0||w.setPointInnerFillOpacity(o)},[m,o]),p.useEffect(()=>{const w=d.current;w&&w.setPointData(x)},[m,x]),null}),ll=[],cl=180,Dr=20;function ul(t){const e=_(t,0,1);return e*e*(3-2*e)}function fl(t,e,n){const[r,i]=p.useState(0),o=p.useRef(0),s=p.useRef({rafId:null,startMs:0,from:0,to:0}),a=p.useCallback(c=>{const h=_(c,0,Dr);Math.abs(o.current-h)<1e-4||(o.current=h,i(h))},[]),l=p.useCallback(()=>{const c=s.current;c.rafId!==null&&(cancelAnimationFrame(c.rafId),c.rafId=null)},[]),u=p.useCallback(c=>{const h=_(c,0,Dr),d=s.current,m=o.current;if(Math.abs(m-h)<1e-4){l(),d.to=h,a(h);return}l(),d.startMs=performance.now(),d.from=m,d.to=h;const g=y=>{const b=s.current,x=Math.max(0,y-b.startMs),A=_(x/cl,0,1),w=ul(A),T=b.from+(b.to-b.from)*w;if(a(T),n.current?.(),A>=1){b.rafId=null,a(b.to);return}b.rafId=requestAnimationFrame(g)};d.rafId=requestAnimationFrame(g)},[a,l]),f=p.useCallback(c=>{const h=e.current;if(!h||typeof c!="number"||!Number.isFinite(c)){u(0);return}const d=kn(t,c,h.getZoomRange(),h.getRegionLabelAutoLiftCapZoom());u(d)},[t,u]);return p.useEffect(()=>()=>{l()},[l]),{regionLabelAutoLiftOffsetPx:r,syncRegionLabelAutoLiftTarget:f,cancelRegionLabelAutoLiftAnimation:l,applyRegionLabelAutoLiftOffset:a}}const hl=6;function Rn(t,e){return t.id??e}function dl(t,e,n,r,i,o){const s=i-n,a=o-r,l=s*s+a*a;if(l<=1e-12){const m=t-n,g=e-r;return m*m+g*g}const u=_(((t-n)*s+(e-r)*a)/l,0,1),f=n+s*u,c=r+a*u,h=t-f,d=e-c;return h*h+d*d}function Nr(t,e,n,r){for(let i=1;i<n.length;i+=1){const o=n[i-1],s=n[i];if(dl(t,e,o[0],o[1],s[0],s[1])<=r)return!0}return!1}function ml(t,e,n,r){if(t<n.minX-r||t>n.maxX+r||e<n.minY-r||e>n.maxY+r)return!1;const i=r*r;if(Nr(t,e,n.outer,i))return!0;for(const o of n.holes)if(Nr(t,e,o,i))return!0;return!1}function gl(t,e,n,r,i,o,s){if(!t.label||!t.labelAnchor)return!1;const a=_n(n.worldToScreen(t.labelAnchor[0],t.labelAnchor[1]));if(!a)return!1;const u=Ln(t.label,r)+r.paddingX*2,f=r.fontSize+r.paddingY*2,c=a[0],h=a[1]-r.offsetY,d=s?_(c,u*.5+1,i-u*.5-1):c,m=s?_(h,f*.5+1,o-f*.5-1):h,g=d-u*.5,y=d+u*.5,b=m-f*.5,x=m+f*.5;return e[0]>=g&&e[0]<=y&&e[1]>=b&&e[1]<=x}function pl(t,e="top-center"){const n=[];for(let r=0;r<t.length;r+=1){const i=t[r],o=ft([ut(i?.coordinates)]);if(o.length===0)continue;const s=typeof i?.label=="string"?i.label.trim():"";n.push({region:i,regionIndex:r,regionId:Rn(i,r),polygons:o,label:s,labelAnchor:s?Dn(o,e):null})}return n}function Br(t,e,n,r,i,o,s,a,l,u=!0){const f=t[0],c=t[1],h=Math.max(1e-6,r.getViewState().zoom),d=Math.max(0,s),m=hl/h;for(let g=n.length-1;g>=0;g-=1){const y=n[g];for(const x of y.polygons)if(ml(f,c,x,m))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId};let b=Bn(i,o?.({region:y.region,regionId:y.regionId,regionIndex:y.regionIndex,zoom:h}));if(d>0&&(b={...b,offsetY:b.offsetY+d}),!!gl(y,e,r,b,a,l,u))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId}}return null}const kr=[],yl=[],Ur="__region_layer__",zr="__region_label__";function bl(t){return{color:ii,width:oi,lineDash:nt,lineJoin:t.lineJoin,lineCap:t.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function xl({regions:t,polygons:e,strokeStyle:n,hoverStrokeStyle:r,activeStrokeStyle:i,resolveStrokeStyle:o,labelStyle:s,labelAnchor:a="top-center",autoLiftLabelAtMaxZoom:l=!1,clampLabelToViewport:u=!0,activeRegionId:f,onActiveChange:c,onHover:h,onClick:d}){const{rendererRef:m,rendererSerial:g,canvasRef:y,containerRef:b,registerDrawCallback:x,unregisterDrawCallback:A,requestOverlayRedraw:w,drawInvalidateRef:T,registerViewStateListener:M,screenToWorld:z,worldToScreen:L,isInteractionLocked:V}=it(),H=t??kr,W=e??yl,D=p.useMemo(()=>H.length>0?H:W.length===0?kr:W.map((q,K)=>({id:K,coordinates:q})),[H,W]),[C,Y]=p.useState(null),[O,N]=p.useState(()=>f??null),Z=f!==void 0,oe=Z?f??null:O,ne=p.useRef(null);p.useEffect(()=>{Z&&N(f??null)},[Z,f]);const Me=p.useCallback(q=>{String(oe)!==String(q)&&(Z||N(q),c?.(q))},[oe,Z,c]),{regionLabelAutoLiftOffsetPx:we,syncRegionLabelAutoLiftTarget:Te}=fl(l,m,T),v=p.useMemo(()=>Fn(n),[n]),I=p.useMemo(()=>He(v,r),[v,r]),B=p.useMemo(()=>He(v,i),[v,i]),{staticLabelStyle:fe,labelStyleResolver:Q}=p.useMemo(()=>typeof s=="function"?{staticLabelStyle:void 0,labelStyleResolver:s}:{staticLabelStyle:s,labelStyleResolver:void 0},[s]),se=p.useMemo(()=>Nn(fe),[fe]),le=p.useMemo(()=>{const q=[];for(let K=0;K<D.length;K+=1){const $=D[K],re=$t($.coordinates);re.length!==0&&q.push({region:$,regionIndex:K,regionKey:$.id??K,polygons:re})}return q},[D]),de=p.useMemo(()=>pl(D,a),[D,a]);p.useEffect(()=>{const q=m.current;if(q)return Te(q.getViewState().zoom),M(K=>{Te(K.zoom)})},[g,M,Te]),p.useEffect(()=>{!(oe===null?!0:D.some((re,J)=>String(Rn(re,J))===String(oe)))&&oe!==null&&Me(null);const K=ne.current;!(K===null?!0:D.some((re,J)=>String(Rn(re,J))===String(K)))&&K!==null&&(ne.current=null,Y(null),h?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[D,oe,h,Me]);const ae=p.useCallback(q=>{const K=m.current;if(!K||q.length===0)return[];const $=new Array(q.length);for(let re=0;re<q.length;re+=1){const J=We(K.worldToScreen(q[re][0],q[re][1]));if(!J)return[];$[re]=J}return $},[]),ge=p.useRef({preparedRegions:le,hoveredRegionId:C,activeRegionId:oe,resolvedStrokeStyle:v,resolvedHoverStrokeStyle:I,resolvedActiveStrokeStyle:B,resolveStrokeStyleProp:o,worldToScreenPoints:ae});ge.current={preparedRegions:le,hoveredRegionId:C,activeRegionId:oe,resolvedStrokeStyle:v,resolvedHoverStrokeStyle:I,resolvedActiveStrokeStyle:B,resolveStrokeStyleProp:o,worldToScreenPoints:ae},p.useEffect(()=>(x(Ur,10,K=>{const{preparedRegions:$,hoveredRegionId:re,activeRegionId:J,resolvedStrokeStyle:ce,resolvedHoverStrokeStyle:xe,resolvedActiveStrokeStyle:Ee,resolveStrokeStyleProp:pe,worldToScreenPoints:ye}=ge.current;for(const ve of $){const{region:U,polygons:P,regionIndex:X,regionKey:G}=ve,te=qt(J,G)?"active":qt(re,G)?"hover":"default";let ee=te==="active"?Ee:te==="hover"?xe:ce;if(pe){const Ue=pe({region:U,regionId:G,regionIndex:X,state:te});ee=He(ee,Ue||void 0)}const Ce=te==="default"?null:bl(ee);for(const Ue of P){const Ze=ye(Ue.outer);Ze.length>=4&&(Ce&&Ie(K,Ze,Ce,!0,!1),Ie(K,Ze,ee,!0,!1));for(const tt of Ue.holes){const ot=ye(tt);ot.length>=4&&(Ce&&Ie(K,ot,Ce,!0,!1),Ie(K,ot,ee,!0,!1))}}}}),()=>A(Ur)),[x,A]);const ie=p.useRef({preparedRegions:le,resolvedLabelStyle:se,labelStyleResolver:Q,labelAnchor:a,autoLiftLabelAtMaxZoom:l,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:we,rendererRef:m});ie.current={preparedRegions:le,resolvedLabelStyle:se,labelStyleResolver:Q,labelAnchor:a,autoLiftLabelAtMaxZoom:l,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:we,rendererRef:m},p.useEffect(()=>(x(zr,50,(K,$,re)=>{const{preparedRegions:J,resolvedLabelStyle:ce,labelStyleResolver:xe,labelAnchor:Ee,autoLiftLabelAtMaxZoom:pe,clampLabelToViewport:ye,regionLabelAutoLiftOffsetPx:ve,rendererRef:U}=ie.current;if(J.length===0)return;const P=Math.max(1e-6,U.current?.getViewState?.().zoom??1),X=typeof ve=="number"&&Number.isFinite(ve)?Math.max(0,ve):kn(pe,P,U.current?.getZoomRange?.(),U.current?.getRegionLabelAutoLiftCapZoom?.());for(const G of J){if(!G.region.label)continue;const te=Dn(G.polygons,Ee);if(!te)continue;const ee=We(U.current?.worldToScreen(te[0],te[1])??[]);if(!ee)continue;let Ce=Bn(ce,xe?.({region:G.region,regionId:G.regionKey,regionIndex:G.regionIndex,zoom:P}));X>0&&(Ce={...Ce,offsetY:Ce.offsetY+X}),fi(K,G.region.label,ee,$,re,Ce,ye)}}),()=>A(zr)),[x,A]),p.useEffect(()=>{w()},[le,C,oe,v,se,we,w]);const he=p.useRef({preparedRegionHits:de,resolvedLabelStyle:se,labelStyleResolver:Q,regionLabelAutoLiftOffsetPx:we,clampLabelToViewport:u,onHover:h,onClick:d,commitActive:Me});return he.current={preparedRegionHits:de,resolvedLabelStyle:se,labelStyleResolver:Q,regionLabelAutoLiftOffsetPx:we,clampLabelToViewport:u,onHover:h,onClick:d,commitActive:Me},p.useEffect(()=>{const q=b.current;if(!q)return;const K=J=>{if(V())return;const ce=m.current;if(!ce)return;const{preparedRegionHits:xe,resolvedLabelStyle:Ee,labelStyleResolver:pe,regionLabelAutoLiftOffsetPx:ye,clampLabelToViewport:ve,onHover:U}=he.current,P=z(J.clientX,J.clientY);if(!P)return;let X=null,G=null;if(xe.length>0){const ee=L(P[0],P[1]);if(ee){const Ce=y.current?.getBoundingClientRect();G=Br(P,ee,xe,ce,Ee,pe,typeof ye=="number"?ye:0,Ce?.width??0,Ce?.height??0,ve),X=G?.regionId??null}}const te=ne.current;String(te)!==String(X)&&(ne.current=X,Y(X),U?.({region:G?.region??null,regionId:X,regionIndex:G?.regionIndex??-1,coordinate:P}),w())},$=J=>{if(V())return;const ce=m.current;if(!ce)return;const{preparedRegionHits:xe,resolvedLabelStyle:Ee,labelStyleResolver:pe,regionLabelAutoLiftOffsetPx:ye,clampLabelToViewport:ve,onClick:U,commitActive:P}=he.current;if(xe.length===0)return;const X=z(J.clientX,J.clientY);if(!X)return;const G=L(X[0],X[1]);if(!G)return;const te=y.current?.getBoundingClientRect(),ee=Br(X,G,xe,ce,Ee,pe,typeof ye=="number"?ye:0,te?.width??0,te?.height??0,ve),Ce=ee?.regionId??null;P(Ce),ee&&U&&U({region:ee.region,regionId:ee.regionId,regionIndex:ee.regionIndex,coordinate:X})},re=()=>{ne.current!==null&&(ne.current=null,Y(null),he.current.onHover?.({region:null,regionId:null,regionIndex:-1,coordinate:null}),w())};return q.addEventListener("pointermove",K),q.addEventListener("click",$),q.addEventListener("pointerleave",re),()=>{q.removeEventListener("pointermove",K),q.removeEventListener("click",$),q.removeEventListener("pointerleave",re)}},[b,m,y,z,L,V,w]),null}function wl({imageWidth:t,imageHeight:e,tiles:n,viewState:r,className:i,style:o}){const s=p.useRef(null),a=p.useRef(null),l=p.useMemo(()=>({width:"100%",height:"100%",display:"block",...o}),[o]);return p.useEffect(()=>{const u=s.current;if(!u)return;const f=new Kr({canvas:u,imageWidth:t,imageHeight:e,initialViewState:r});return a.current=f,f.setTiles(n),()=>{f.destroy(),a.current=null}},[t,e]),p.useEffect(()=>{const u=a.current;u&&u.setTiles(n)},[n]),p.useEffect(()=>{const u=a.current;!u||!r||u.setViewState(r)},[r]),Ye.jsx("canvas",{ref:s,className:i,style:l})}function Sl(t,e){if(!e)return!1;try{const r=new URL(t,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 Ui{constructor(e){S(this,"maxConcurrency");S(this,"maxRetries");S(this,"retryBaseDelayMs");S(this,"retryMaxDelayMs");S(this,"onTileLoad");S(this,"onTileError");S(this,"onStateChange");S(this,"authToken");S(this,"destroyed",!1);S(this,"queue",[]);S(this,"queuedByKey",new Map);S(this,"inflight",new Map);S(this,"visibleKeys",new Set);S(this,"timerId",null);S(this,"abortedCount",0);S(this,"retryCount",0);S(this,"failedCount",0);this.maxConcurrency=Math.max(1,Math.floor(e.maxConcurrency??12)),this.maxRetries=Math.max(0,Math.floor(e.maxRetries??2)),this.retryBaseDelayMs=Math.max(10,Math.floor(e.retryBaseDelayMs??120)),this.retryMaxDelayMs=Math.max(this.retryBaseDelayMs,Math.floor(e.retryMaxDelayMs??1200)),this.authToken=e.authToken??"",this.onTileLoad=e.onTileLoad,this.onTileError=e.onTileError,this.onStateChange=e.onStateChange}setAuthToken(e){this.authToken=String(e??"")}schedule(e){if(this.destroyed)return;const n=new Set;for(const r of e)n.add(r.key);this.visibleKeys=n,this.dropInvisibleQueued(n),this.abortInvisibleInflight(n);for(const r of e){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[,e]of this.inflight)e.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(e){if(this.queue.length===0)return;const n=[];for(const r of this.queue){if(!e.has(r.tile.key)){this.queuedByKey.delete(r.tile.key);continue}n.push(r)}this.queue=n}abortInvisibleInflight(e){for(const[n,r]of this.inflight)e.has(n)||(this.inflight.delete(n),this.abortedCount+=1,r.controller.abort())}sortQueue(){this.queue.sort((e,n)=>e.readyAt!==n.readyAt?e.readyAt-n.readyAt:e.tile.distance2!==n.tile.distance2?e.tile.distance2-n.tile.distance2:e.tile.tier!==n.tile.tier?n.tile.tier-e.tile.tier:e.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 e=this.queue[0]?.readyAt;if(typeof e!="number")return;const n=Math.max(0,e-be());this.timerId=globalThis.setTimeout(()=>{this.timerId=null,this.pump()},n)}takeNextReadyQueueItem(){if(this.queue.length===0)return null;const e=be(),n=this.queue[0];return!n||n.readyAt>e?null:(this.queue.shift(),this.queuedByKey.delete(n.tile.key),n)}startFetch(e){const n=new AbortController,r={tile:e.tile,attempt:e.attempt,controller:n};this.inflight.set(e.tile.key,r),this.emitStateChange();const i=Sl(e.tile.url,this.authToken);fetch(e.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(e.tile.key)){o.close();return}this.onTileLoad(e.tile,o)}).catch(o=>{if(n.signal.aborted||this.destroyed)return;if(e.attempt<this.maxRetries&&this.visibleKeys.has(e.tile.key)){this.retryCount+=1;const a=e.attempt+1,l=this.getRetryDelay(a),u={tile:e.tile,attempt:a,readyAt:be()+l},f=this.queuedByKey.get(e.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?.(e.tile,o,e.attempt+1)}).finally(()=>{this.inflight.delete(e.tile.key),this.pump(),this.emitStateChange()})}getRetryDelay(e){const n=Math.max(0,e-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 El(t,e){t.addEventListener("pointerdown",e.pointerDown),t.addEventListener("pointermove",e.pointerMove),t.addEventListener("pointerup",e.pointerUp),t.addEventListener("pointercancel",e.pointerUp),t.addEventListener("wheel",e.wheel,{passive:!1}),t.addEventListener("dblclick",e.doubleClick),t.addEventListener("contextmenu",e.contextMenu),t.addEventListener("webglcontextlost",e.contextLost),t.addEventListener("webglcontextrestored",e.contextRestored)}function Rl(t,e){t.removeEventListener("pointerdown",e.pointerDown),t.removeEventListener("pointermove",e.pointerMove),t.removeEventListener("pointerup",e.pointerUp),t.removeEventListener("pointercancel",e.pointerUp),t.removeEventListener("wheel",e.wheel),t.removeEventListener("dblclick",e.doubleClick),t.removeEventListener("contextmenu",e.contextMenu),t.removeEventListener("webglcontextlost",e.contextLost),t.removeEventListener("webglcontextrestored",e.contextRestored)}function Al(t,e,n){const r=t.getBoundingClientRect(),i=Math.max(1,r.width||t.clientWidth||1),o=Math.max(1,r.height||t.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));(t.width!==a||t.height!==l)&&(t.width=a,t.height=l),n.setViewport(i,o),e.viewport(0,0,a,l)}const An=.35,Mn=.5,Ml=256,Tn=[{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,Cl=5,vl=0,Pl=1,Il=-100,_l=100,Fl=2e3;function Qt(t){return t*Math.PI/180}function Bt(t,e){return!t||!e?t===e:t.buffer===e.buffer&&t.byteOffset===e.byteOffset&&t.byteLength===e.byteLength}function Cn(t){return t.map(e=>({zoom:e.zoom,size:e.size}))}function Or(t){if(!t)return Cn(Tn);const e=new Map;for(const[n,r]of Object.entries(t)){const i=Number(n),o=Number(r);!Number.isFinite(i)||!Number.isFinite(o)||o<=0||e.set(i,o)}return e.size===0?Cn(Tn):Array.from(e.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function Ll(t,e){if(t===e)return!0;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n].zoom!==e[n].zoom||t[n].size!==e[n].size)return!1;return!0}function Dl(t,e){if(!Number.isFinite(t))return e[0]?.size??Mn;if(e.length===0)return Mn;if(e.length===1||t<=e[0].zoom)return e[0].size;for(let s=1;s<e.length;s+=1){const a=e[s-1],l=e[s];if(t>l.zoom)continue;const u=Math.max(1e-6,l.zoom-a.zoom),f=_((t-a.zoom)/u,0,1);return a.size+(l.size-a.size)*f}const n=e[e.length-1],r=e[e.length-2],i=Math.max(1e-6,n.zoom-r.zoom),o=(n.size-r.size)/i;return n.size+(t-n.zoom)*o}function Wr(t){return typeof t!="number"||!Number.isFinite(t)?1:_(t,Tl,Cl)}function Yr(t){return typeof t!="number"||!Number.isFinite(t)?0:_(t,vl,Pl)}function an(t){return typeof t!="number"||!Number.isFinite(t)?0:_(t,Il,_l)}function Xr(t){const e=an(t?.brightness),n=an(t?.contrast),r=an(t?.saturation);return{brightness:e/200,contrast:n/100,saturation:r/100}}function Yn(t){return t}function ln(t){return typeof t!="number"||!Number.isFinite(t)?0:_(t,0,Fl)}function kt(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?null:Math.max(1e-6,t)}function cn(t){return typeof t=="function"?t:Yn}function zi(t,e,n){const r=t.getBoundingClientRect(),i=e-r.left-r.width*.5,o=n-r.top-r.height*.5;return Math.atan2(o,i)}function Oi(t,e){if(e.pointerId!==null&&t.hasPointerCapture(e.pointerId))try{t.releasePointerCapture(e.pointerId)}catch{}e.dragging=!1,e.mode="none",e.rotateLastAngleRad=null,e.pointerId=null,t.classList.remove("dragging")}function Nl(t){const{event:e,canvas:n,state:r,config:i,cancelViewAnimation:o}=t,s=i.ctrlDragRotate&&(e.ctrlKey||e.metaKey);(e.button===0||s&&e.button===2)&&(o(),s&&e.preventDefault(),r.dragging=!0,r.mode=s?"rotate":"pan",r.pointerId=e.pointerId,r.lastPointerX=e.clientX,r.lastPointerY=e.clientY,r.rotateLastAngleRad=r.mode==="rotate"?zi(n,e.clientX,e.clientY):null,n.classList.add("dragging"),n.setPointerCapture(e.pointerId))}function Bl(t){const{event:e,canvas:n,state:r,config:i,camera:o,clampViewState:s,emitViewState:a,requestRender:l}=t;if(!r.dragging||e.pointerId!==r.pointerId)return;const u=e.clientX-r.lastPointerX,f=e.clientY-r.lastPointerY;if(r.lastPointerX=e.clientX,r.lastPointerY=e.clientY,r.mode==="rotate"){const c=zi(n,e.clientX,e.clientY),h=r.rotateLastAngleRad;if(r.rotateLastAngleRad=c,h!==null){const d=c-h,m=Math.atan2(Math.sin(d),Math.cos(d)),g=i.rotationDragSensitivityDegPerPixel/An,y=o.getViewState();o.setViewState({rotationDeg:y.rotationDeg-m*180/Math.PI*g})}}else{const c=o.getViewState(),h=Math.max(1e-6,c.zoom),d=Qt(c.rotationDeg),m=Math.cos(d),g=Math.sin(d),y=(u*m-f*g)/h,b=(u*g+f*m)/h;o.setViewState({offsetX:c.offsetX-y,offsetY:c.offsetY-b})}s(),a(),l()}function kl(t,e,n){t.pointerId===n.pointerId&&Oi(e,n)}function Ul(t){const{event:e,canvas:n,onZoomBy:r}=t;e.preventDefault();const i=n.getBoundingClientRect(),o=e.clientX-i.left,s=e.clientY-i.top,a=e.deltaY<0?1.12:.89;r(a,o,s)}const zl=4;function Ol(t){const{event:e,canvas:n,snapState:r,onSnapZoom:i}=t;e.preventDefault();const o=e.deltaY<0?"in":e.deltaY>0?"out":null;if(o&&r.blockedDirection)if(o!==r.blockedDirection)r.blockedDirection=null,r.accumulatedDelta=0;else return;if(r.accumulatedDelta!==0&&e.deltaY!==0&&Math.sign(r.accumulatedDelta)!==Math.sign(e.deltaY)&&(r.accumulatedDelta=0),r.accumulatedDelta+=e.deltaY,Math.abs(r.accumulatedDelta)<zl)return;const s=n.getBoundingClientRect(),a=e.clientX-s.left,l=e.clientY-s.top,u=r.accumulatedDelta>0?"out":"in";if(r.accumulatedDelta=0,!i(u,a,l)){r.blockedDirection=u;return}r.blockedDirection=null}function Wl(t){const{event:e,canvas:n,onZoomBy:r}=t,i=n.getBoundingClientRect(),o=e.clientX-i.left,s=e.clientY-i.top;r(e.shiftKey?.8:1.25,o,s)}function Yl(t,e){(e||t.ctrlKey||t.metaKey)&&t.preventDefault()}function jt(t){const e=t.getViewCorners();let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[s,a]of e)s<n&&(n=s),s>i&&(i=s),a<r&&(r=a),a>o&&(o=a);return[n,r,i,o]}function Yt(t,e,n=.2,r=.2){const i=jt(t),o=Math.max(1e-6,i[2]-i[0]),s=Math.max(1e-6,i[3]-i[1]),a=o*n,l=s*r,[u,f]=t.getCenter(),c=o*.5,h=s*.5,d=c-a,m=e.width-c+a,g=h-l,y=e.height-h+l,b=d<=m?_(u,d,m):e.width*.5,x=g<=y?_(f,g,y):e.height*.5;t.setCenter(b,x)}function Xl(t,e){const n=Math.max(1e-6,t.getViewState().zoom),r=e.maxTierZoom+Math.log2(n);return _(Math.floor(r),0,e.maxTierZoom)}function Vl(t,e){return!(t[2]<=e[0]||t[0]>=e[2]||t[3]<=e[1]||t[1]>=e[3])}function Wi(t,e,n){const r=jt(t),i=Math.pow(2,e.maxTierZoom-n),o=Math.ceil(e.width/i),s=Math.ceil(e.height/i),a=Math.max(1,Math.ceil(o/e.tileSize)),l=Math.max(1,Math.ceil(s/e.tileSize)),u=r[0],f=r[1],c=r[2],h=r[3],d=_(Math.floor(u/i/e.tileSize),0,a-1),m=_(Math.floor((c-1)/i/e.tileSize),0,a-1),g=_(Math.floor(f/i/e.tileSize),0,l-1),y=_(Math.floor((h-1)/i/e.tileSize),0,l-1);if(d>m||g>y)return[];const b=(u+c)*.5/i/e.tileSize,x=(f+h)*.5/i/e.tileSize,A=[];for(let w=g;w<=y;w+=1)for(let T=d;T<=m;T+=1){const M=T*e.tileSize*i,z=w*e.tileSize*i,L=Math.min((T+1)*e.tileSize,o)*i,V=Math.min((w+1)*e.tileSize,s)*i,H=T-b,W=w-x;A.push({key:`${n}/${T}/${w}`,tier:n,x:T,y:w,bounds:[M,z,L,V],distance2:H*H+W*W,url:Wn(e,n,T,w)})}return A.sort((w,T)=>w.distance2-T.distance2),A}function Gl(t,e){const n=Xl(t,e);return{tier:n,visible:Wi(t,e,n)}}function Hl(t){t.interactionLocked||Nl({event:t.event,canvas:t.canvas,state:t.state,config:{ctrlDragRotate:t.ctrlDragRotate,rotationDragSensitivityDegPerPixel:t.rotationDragSensitivityDegPerPixel},cancelViewAnimation:t.cancelViewAnimation})}function ql(t){t.interactionLocked||Bl({event:t.event,canvas:t.canvas,state:t.state,config:{ctrlDragRotate:t.ctrlDragRotate,rotationDragSensitivityDegPerPixel:t.rotationDragSensitivityDegPerPixel},camera:t.camera,clampViewState:()=>Yt(t.camera,t.source,t.panExtentX,t.panExtentY),emitViewState:t.emitViewState,requestRender:t.requestRender})}function Zl(t){t.interactionLocked||kl(t.event,t.canvas,t.state)}function $l(t){t.interactionLocked||Wl({event:t.event,canvas:t.canvas,onZoomBy:t.onZoomBy})}function Kl(t){Yl(t.event,t.state.dragging)}function jl(t,e){Oi(t,e)}function Ql(t){return{pointerDown:e=>Hl({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,state:t.state,ctrlDragRotate:t.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:t.getRotationDragSensitivityDegPerPixel(),cancelViewAnimation:t.cancelViewAnimation}),pointerMove:e=>ql({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,state:t.state,ctrlDragRotate:t.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:t.getRotationDragSensitivityDegPerPixel(),camera:t.camera,source:t.source,panExtentX:t.getPanExtentX(),panExtentY:t.getPanExtentY(),emitViewState:t.emitViewState,requestRender:t.requestRender}),pointerUp:e=>Zl({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,state:t.state}),wheel:e=>{if(t.getInteractionLocked()){e.preventDefault();return}if(t.getUseZoomSnaps?.()&&t.onSnapZoom&&t.zoomSnapState){Ol({event:e,canvas:t.canvas,snapState:t.zoomSnapState,onSnapZoom:t.onSnapZoom});return}Ul({event:e,canvas:t.canvas,onZoomBy:t.zoomBy})},doubleClick:e=>$l({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,onZoomBy:t.zoomBy}),contextMenu:e=>Kl({event:e,canvas:t.canvas,state:t.state})}}function Jl(t){const{gl:e,cache:n,maxCacheTiles:r}=t;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;e.deleteTexture(s.texture),n.delete(o)}}function ec(t,e){if(t.isContextLost())return null;const n=t.createTexture();return n?(t.bindTexture(t.TEXTURE_2D,n),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,1),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),t.bindTexture(t.TEXTURE_2D,null),n):null}function tc(t){const{gl:e,cache:n,tile:r,bitmap:i,frameSerial:o,maxCacheTiles:s,destroyed:a,contextLost:l,requestRender:u}=t;if(a||l||e.isContextLost()){i.close();return}if(n.has(r.key)){i.close();return}const f=ec(e,i);i.close(),f&&(n.set(r.key,{key:r.key,texture:f,bounds:r.bounds,tier:r.tier,lastUsed:o}),Jl({gl:e,cache:n,maxCacheTiles:s}),u())}function nc(t,e){for(const[,n]of e)t.deleteTexture(n.texture)}function rc(t){const{event:e,destroyed:n,contextLost:r,cancelViewAnimation:i,cancelDrag:o,tileScheduler:s,cache:a,onContextLost:l}=t;if(e.preventDefault(),n||r)return{handled:!1,frame:t.frame};let u=t.frame;return u!==null&&(cancelAnimationFrame(u),u=null),i(),o(),s.clear(),a.clear(),l?.(),{handled:!0,frame:u}}function ic(t){if(t.destroyed)return{didDestroy:!1,frame:t.frame};let e=t.frame;return e!==null&&(cancelAnimationFrame(e),e=null),t.cancelViewAnimation(),t.resizeObserver.disconnect(),t.removeCanvasEventListeners(),t.cancelDrag(),t.tileScheduler.destroy(),!t.contextLost&&!t.gl.isContextLost()&&(nc(t.gl,t.cache),t.gl.deleteBuffer(t.tileProgram.vbo),t.gl.deleteVertexArray(t.tileProgram.vao),t.gl.deleteProgram(t.tileProgram.program),t.gl.deleteBuffer(t.pointProgram.posBuffer),t.gl.deleteBuffer(t.pointProgram.termBuffer),t.gl.deleteBuffer(t.pointProgram.fillModeBuffer),t.gl.deleteBuffer(t.pointProgram.indexBuffer),t.gl.deleteTexture(t.pointProgram.paletteTexture),t.gl.deleteVertexArray(t.pointProgram.vao),t.gl.deleteProgram(t.pointProgram.program)),t.cache.clear(),{didDestroy:!0,frame:e}}function oc(t,e){if(e<=0||t.length===0)return new Uint32Array(0);let n=t.length;for(let o=0;o<t.length;o+=1)t[o]<e||(n-=1);if(n===t.length)return t;if(n<=0)return new Uint32Array(0);const r=new Uint32Array(n);let i=0;for(let o=0;o<t.length;o+=1){const s=t[o];s>=e||(r[i]=s,i+=1)}return r}function sc(t,e){return e<=0?new Uint8Array(0):t.length<e?new Uint8Array(e):t.subarray(0,e)}function ac(t,e,n,r,i){if(!i||i.length===0)return{...t,lastPointPalette:null};const o=new Uint8Array(i);if(r||e.isContextLost())return{...t,lastPointPalette:o};const s=Math.max(1,Math.floor(o.length/4));return e.bindTexture(e.TEXTURE_2D,n.paletteTexture),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,s,1,0,e.RGBA,e.UNSIGNED_BYTE,o),e.bindTexture(e.TEXTURE_2D,null),{...t,lastPointPalette:o,pointPaletteSize:s}}function lc(t,e,n,r,i){if(!i||!i.count||!i.positions||!i.paletteIndices)return{...t,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?oc(i.drawIndices,a):null,d=t.lastPointData,m=d?.fillModes instanceof Uint8Array,g=t.pointBuffersDirty||!d||d.count!==a||!Bt(d.positions,l)||!Bt(d.paletteIndices,u)||m!==s||s&&(!d?.fillModes||!Bt(d.fillModes,f)),y=t.pointBuffersDirty||c&&(!d?.drawIndices||!Bt(d.drawIndices,h))||!c&&!!d?.drawIndices,b={...t,lastPointData:{count:a,positions:l,paletteIndices:u,fillModes:f,drawIndices:c?h??void 0:void 0}};if(r||e.isContextLost())return b;const x=b.lastPointData;if(!x)return b;if(g){e.bindBuffer(e.ARRAY_BUFFER,n.posBuffer),e.bufferData(e.ARRAY_BUFFER,x.positions,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,n.termBuffer),e.bufferData(e.ARRAY_BUFFER,x.paletteIndices,e.STATIC_DRAW);const A=sc(b.zeroFillModes,a);e.bindBuffer(e.ARRAY_BUFFER,n.fillModeBuffer),e.bufferData(e.ARRAY_BUFFER,x.fillModes??A,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,null),b.zeroFillModes=A}return c&&y&&(e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n.indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,h??new Uint32Array(0),e.DYNAMIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),b.usePointIndices=c,b.pointCount=c?h?.length??0:x.count,(g||y)&&(b.pointBuffersDirty=!1),b}function cc(t){const{gl:e,camera:n,source:r,cache:i,frameSerial:o,tileProgram:s,pointProgram:a,imageColorSettings:l,pointCount:u,usePointIndices:f,pointPaletteSize:c,pointStrokeScale:h,pointInnerFillOpacity:d,pointSizePx:m,tileScheduler:g,getVisibleTiles:y,getVisibleTilesForTier:b,getViewBounds:x,intersectsBounds:A}=t;e.clearColor(.03,.06,.1,1),e.clear(e.COLOR_BUFFER_BIT);const{tier:w,visible:T}=y(),M=x(),z=new Set(T.map(O=>O.key));e.useProgram(s.program),e.bindVertexArray(s.vao),e.uniformMatrix3fv(s.uCamera,!1,n.getMatrix()),e.uniform1i(s.uTexture,0),e.uniform1f(s.uBrightness,l.brightness),e.uniform1f(s.uContrast,l.contrast),e.uniform1f(s.uSaturation,l.saturation);const L=[];for(const[,O]of i)z.has(O.key)||A(O.bounds,M)&&L.push(O);L.sort((O,N)=>O.tier-N.tier);for(const O of L)O.lastUsed=o,e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,O.texture),e.uniform4f(s.uBounds,O.bounds[0],O.bounds[1],O.bounds[2],O.bounds[3]),e.drawArrays(e.TRIANGLE_STRIP,0,4);let V=0;const H=[];for(const O of T){const N=i.get(O.key);if(!N){H.push(O);continue}N.lastUsed=o,e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,N.texture),e.uniform4f(s.uBounds,N.bounds[0],N.bounds[1],N.bounds[2],N.bounds[3]),e.drawArrays(e.TRIANGLE_STRIP,0,4),V+=1}const W=H.slice(),D=1e6,C=[];w>0&&C.push(w-1),w<r.maxTierZoom&&C.push(w+1);for(const O of C){const N=b(O);for(const Z of N)i.has(Z.key)||(Z.distance2+=D,W.push(Z))}g.schedule(W),e.bindTexture(e.TEXTURE_2D,null),e.bindVertexArray(null);let Y=0;return u>0&&(e.enable(e.BLEND),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA),e.useProgram(a.program),e.bindVertexArray(a.vao),e.uniformMatrix3fv(a.uCamera,!1,n.getMatrix()),e.uniform1f(a.uPointSize,m),e.uniform1f(a.uPointStrokeScale,h),e.uniform1f(a.uPointInnerFillAlpha,d),e.uniform1f(a.uPaletteSize,c),e.uniform1i(a.uPalette,1),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,a.paletteTexture),f?e.drawElements(e.POINTS,u,e.UNSIGNED_INT,0):e.drawArrays(e.POINTS,0,u),e.bindTexture(e.TEXTURE_2D,null),e.bindVertexArray(null),Y=u),{tier:w,visible:T.length,rendered:V,points:Y,fallback:L.length,cacheHits:V,cacheMisses:H.length,drawCalls:L.length+V+(Y>0?1:0)}}function Vr(t){const r=pt(t,`#version 300 es
|
|
135
135
|
precision highp float;
|
|
136
136
|
in vec2 aUnit;
|
|
137
137
|
in vec2 aUv;
|
|
@@ -176,7 +176,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
176
176
|
|
|
177
177
|
color.rgb = clamp(color.rgb + uBrightness, vec3(0.0), vec3(1.0));
|
|
178
178
|
outColor = color;
|
|
179
|
-
}`),i=Fe(t,r,"uCamera"),o=Fe(t,r,"uBounds"),s=Fe(t,r,"uTexture"),a=Fe(t,r,"uBrightness"),l=Fe(t,r,"uContrast"),u=Fe(t,r,"uSaturation"),f=t.createVertexArray(),c=t.createBuffer();if(!f||!c)throw new Error("buffer allocation failed");t.bindVertexArray(f),t.bindBuffer(t.ARRAY_BUFFER,c),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,0,1,0,1,0,0,1,0,1,1,1,1,1]),t.STATIC_DRAW);const h=t.getAttribLocation(r,"aUnit"),d=t.getAttribLocation(r,"aUv");if(h<0||d<0)throw new Error("tile attribute lookup failed");return t.enableVertexAttribArray(h),t.enableVertexAttribArray(d),t.vertexAttribPointer(h,2,t.FLOAT,!1,16,0),t.vertexAttribPointer(d,2,t.FLOAT,!1,16,8),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null),{program:r,vao:f,vbo:c,uCamera:i,uBounds:o,uTexture:s,uBrightness:a,uContrast:l,uSaturation:u}}function Gr(t){const r=
|
|
179
|
+
}`),i=Fe(t,r,"uCamera"),o=Fe(t,r,"uBounds"),s=Fe(t,r,"uTexture"),a=Fe(t,r,"uBrightness"),l=Fe(t,r,"uContrast"),u=Fe(t,r,"uSaturation"),f=t.createVertexArray(),c=t.createBuffer();if(!f||!c)throw new Error("buffer allocation failed");t.bindVertexArray(f),t.bindBuffer(t.ARRAY_BUFFER,c),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,0,1,0,1,0,0,1,0,1,1,1,1,1]),t.STATIC_DRAW);const h=t.getAttribLocation(r,"aUnit"),d=t.getAttribLocation(r,"aUv");if(h<0||d<0)throw new Error("tile attribute lookup failed");return t.enableVertexAttribArray(h),t.enableVertexAttribArray(d),t.vertexAttribPointer(h,2,t.FLOAT,!1,16,0),t.vertexAttribPointer(d,2,t.FLOAT,!1,16,8),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null),{program:r,vao:f,vbo:c,uCamera:i,uBounds:o,uTexture:s,uBrightness:a,uContrast:l,uSaturation:u}}function Gr(t){const r=pt(t,`#version 300 es
|
|
180
180
|
precision highp float;
|
|
181
181
|
in vec2 aPosition;
|
|
182
182
|
in uint aTerm;
|
|
@@ -229,6 +229,6 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
229
229
|
// Premultiplied alpha output: inner fill is black, so it only contributes alpha.
|
|
230
230
|
outColor = vec4(color.rgb * ringAlpha, alpha);
|
|
231
231
|
}
|
|
232
|
-
}`),i=Fe(t,r,"uCamera"),o=Fe(t,r,"uPointSize"),s=Fe(t,r,"uPointStrokeScale"),a=Fe(t,r,"uPointInnerFillAlpha"),l=Fe(t,r,"uPalette"),u=Fe(t,r,"uPaletteSize"),f=t.createVertexArray(),c=t.createBuffer(),h=t.createBuffer(),d=t.createBuffer(),m=t.createBuffer(),g=t.createTexture();if(!f||!c||!h||!d||!m||!g)throw new Error("point buffer allocation failed");t.bindVertexArray(f),t.bindBuffer(t.ARRAY_BUFFER,c),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const y=t.getAttribLocation(r,"aPosition");if(y<0)throw new Error("point position attribute not found");t.enableVertexAttribArray(y),t.vertexAttribPointer(y,2,t.FLOAT,!1,0,0),t.bindBuffer(t.ARRAY_BUFFER,h),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const b=t.getAttribLocation(r,"aTerm");if(b<0)throw new Error("point term attribute not found");t.enableVertexAttribArray(b),t.vertexAttribIPointer(b,1,t.UNSIGNED_SHORT,0,0),t.bindBuffer(t.ARRAY_BUFFER,d),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const x=t.getAttribLocation(r,"aFillMode");if(x<0)throw new Error("point fill mode attribute not found");return t.enableVertexAttribArray(x),t.vertexAttribIPointer(x,1,t.UNSIGNED_BYTE,0,0),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,m),t.bufferData(t.ELEMENT_ARRAY_BUFFER,0,t.DYNAMIC_DRAW),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null),t.bindTexture(t.TEXTURE_2D,g),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,new Uint8Array([160,160,160,255])),t.bindTexture(t.TEXTURE_2D,null),{program:r,vao:f,posBuffer:c,termBuffer:h,fillModeBuffer:d,indexBuffer:m,paletteTexture:g,uCamera:i,uPointSize:o,uPointStrokeScale:s,uPointInnerFillAlpha:a,uPalette:l,uPaletteSize:u}}function Yi(t){t.animation=null,t.frame!==null&&(cancelAnimationFrame(t.frame),t.frame=null)}function uc(t){const{state:e,camera:n,target:r,durationMs:i,easing:o,onUpdate:s}=t,a=n.getViewState();Yi(e),e.animation={startMs:ye(),durationMs:Math.max(0,i),from:a,to:r,easing:o};const l=()=>{const u=e.animation;if(!u)return;const f=Math.max(0,ye()-u.startMs),c=u.durationMs<=0?1:I(f/u.durationMs,0,1);let h=c;try{h=u.easing(c)}catch{h=c}if(Number.isFinite(h)||(h=c),h=I(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){e.animation=null,e.frame=null;return}e.frame=requestAnimationFrame(l)};e.frame=requestAnimationFrame(l)}function fc(t){const e=Math.max(t*.5,1e-6),n=Math.max(1,t*8);return{minZoom:e,maxZoom:Math.max(e,n)}}function hc(t,e,n){const r=fc(t);let i=e??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 dc(t,e,n,r,i){const o=t.getViewState(),s={zoom:typeof r.zoom=="number"&&Number.isFinite(r.zoom)?I(r.zoom,e,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};t.setViewState(s),i();const a=t.getViewState();return t.setViewState(o),a}function Hr(t,e,n,r,i){const o=Math.min(e/t.width,n/t.height),s=Number.isFinite(o)&&o>0?o:1,a=I(s,r,i),l=e/a,u=n/a;return{fitZoom:s,target:{zoom:a,offsetX:(t.width-l)*.5,offsetY:(t.height-u)*.5,rotationDeg:0}}}function mc(t,e,n,r,i,o){const s=t.getViewState(),a=I(s.zoom*r,e,n);if(a===s.zoom)return null;const[l,u]=t.screenToWorld(i,o),f=t.getViewportSize(),c=i-f.width*.5,h=o-f.height*.5,d=jt(s.rotationDeg),m=Math.cos(d),g=Math.sin(d),y=c/a*m-h/a*g,b=c/a*g+h/a*m,x=l-y,M=u-b;return{zoom:a,offsetX:x-f.width/(2*a),offsetY:M-f.height/(2*a)}}function gc(t,e,n,r,i,o){const s=t.getViewState(),a=I(r,e,n);if(a===s.zoom)return null;const[l,u]=t.screenToWorld(i,o),f=t.getViewportSize(),c=i-f.width*.5,h=o-f.height*.5,d=jt(s.rotationDeg),m=Math.cos(d),g=Math.sin(d),y=c/a*m-h/a*g,b=c/a*g+h/a*m,x=l-y,M=u-b;return{zoom:a,offsetX:x-f.width/(2*a),offsetY:M-f.height/(2*a)}}const pc=250;function qr(t,e){if(!t||t.length===0)return[];if(!e||e<=0)return[];const n=10/e;return t.map(r=>r/n).filter(r=>Number.isFinite(r)&&r>0).sort((r,i)=>r-i)}function yc(t,e,n,r){if(t.length===0)return null;const i=Math.max(e*.005,1e-8);if(n==="in"){for(const o of t)if(o>e+i)return{type:"snap",zoom:o};return null}for(let o=t.length-1;o>=0;o--)if(t[o]<e-i)return{type:"snap",zoom:t[o]};return r&&e<=t[0]+i?{type:"fit"}:null}function bc(t,e,n,r,i){const o=t.camera.getViewState(),[s,a]=t.camera.screenToWorld(n,r),l=t.camera.getViewportSize(),u=I(e,t.minZoom,t.maxZoom);if(u===o.zoom)return;const f=jt(o.rotationDeg),c=Math.cos(f),h=Math.sin(f),d=n-l.width*.5,m=r-l.height*.5;t.cancelViewAnimation();const g=x=>{const M=d/x*c-m/x*h,w=d/x*h+m/x*c;return{offsetX:s-M-l.width/(2*x),offsetY:a-w-l.height/(2*x)}},y=g(u);t.viewAnimationState.animation={startMs:ye(),durationMs:Math.max(0,i),from:o,to:{zoom:u,offsetX:y.offsetX,offsetY:y.offsetY,rotationDeg:o.rotationDeg},easing:Yn};const b=()=>{const x=t.viewAnimationState.animation;if(!x)return;const M=Math.max(0,ye()-x.startMs),w=I(M/i,0,1),T=I(w*w*(3-2*w),0,1),A=o.zoom+(u-o.zoom)*T,{offsetX:k,offsetY:L}=g(A);t.camera.setViewState({zoom:A,offsetX:k,offsetY:L,rotationDeg:o.rotationDeg});const W=w>=1;W&&(t.clampViewState(),t.viewAnimationState.animation=null,t.viewAnimationState.frame=null),t.onViewStateChange(t.camera.getViewState()),t.requestRender(),W||(t.viewAnimationState.frame=requestAnimationFrame(b))};t.viewAnimationState.frame=requestAnimationFrame(b)}class Xi{constructor(e,n,r={}){S(this,"canvas");S(this,"source");S(this,"gl");S(this,"camera",new $r);S(this,"onViewStateChange");S(this,"onStats");S(this,"onTileError");S(this,"onContextLost");S(this,"onContextRestored");S(this,"resizeObserver");S(this,"tileProgram");S(this,"pointProgram");S(this,"tileScheduler");S(this,"authToken");S(this,"destroyed",!1);S(this,"contextLost",!1);S(this,"frame",null);S(this,"frameSerial",0);S(this,"interactionState",{dragging:!1,mode:"none",rotateLastAngleRad:null,pointerId:null,lastPointerX:0,lastPointerY:0});S(this,"interactionLocked",!1);S(this,"ctrlDragRotate",!0);S(this,"rotationDragSensitivityDegPerPixel",An);S(this,"maxCacheTiles");S(this,"fitZoom",1);S(this,"minZoom",1e-6);S(this,"maxZoom",1);S(this,"minZoomOverride",null);S(this,"maxZoomOverride",null);S(this,"viewTransitionDurationMs",0);S(this,"viewTransitionEasing",Yn);S(this,"viewAnimationState",{animation:null,frame:null});S(this,"pointCount",0);S(this,"usePointIndices",!1);S(this,"pointBuffersDirty",!0);S(this,"pointPaletteSize",1);S(this,"pointSizeStops",Cn(Tn));S(this,"pointStrokeScale",1);S(this,"pointInnerFillOpacity",0);S(this,"imageColorSettings",{brightness:0,contrast:0,saturation:0});S(this,"lastPointData",null);S(this,"lastPointPalette",null);S(this,"zeroFillModes",new Uint8Array(0));S(this,"cache",new Map);S(this,"zoomSnaps",[]);S(this,"zoomSnapFitAsMin",!1);S(this,"zoomSnapState",{accumulatedDelta:0,lastSnapTimeMs:0,blockedDirection:null});S(this,"boundPointerDown");S(this,"boundPointerMove");S(this,"boundPointerUp");S(this,"boundWheel");S(this,"boundDoubleClick");S(this,"boundContextMenu");S(this,"boundContextLost");S(this,"boundContextRestored");this.canvas=e,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):An,this.pointSizeStops=Or(r.pointSizeByZoom),this.pointStrokeScale=Wr(r.pointStrokeScale),this.pointInnerFillOpacity=Yr(r.pointInnerFillOpacity),this.imageColorSettings=Xr(r.imageColorSettings),this.minZoomOverride=Bt(r.minZoom),this.maxZoomOverride=Bt(r.maxZoom),this.viewTransitionDurationMs=ln(r.viewTransition?.duration),this.viewTransitionEasing=cn(r.viewTransition?.easing),this.zoomSnaps=qr(r.zoomSnaps,this.source.mpp),this.zoomSnapFitAsMin=!!r.zoomSnapFitAsMin;const i=e.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=Vr(this.gl),this.pointProgram=Gr(this.gl),this.tileScheduler=new Ui({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)=>tc({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(e);const o=Ql({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),Rl(e,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 e=hc(this.fitZoom,this.minZoomOverride,this.maxZoomOverride);this.minZoom=e.minZoom,this.maxZoom=e.maxZoom}resolveTargetViewState(e){return dc(this.camera,this.minZoom,this.maxZoom,e,()=>Wt(this.camera,this.source))}cancelViewAnimation(){Yi(this.viewAnimationState)}startViewAnimation(e,n,r){uc({state:this.viewAnimationState,camera:this.camera,target:e,durationMs:n,easing:r,onUpdate:()=>{Wt(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(e){this.pointCount=e.pointCount,this.usePointIndices=e.usePointIndices,this.pointBuffersDirty=e.pointBuffersDirty,this.lastPointData=e.lastPointData,this.zeroFillModes=e.zeroFillModes,this.lastPointPalette=e.lastPointPalette,this.pointPaletteSize=e.pointPaletteSize}applyViewStateAndRender(e,n=!0){n&&this.cancelViewAnimation(),this.camera.setViewState(e),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}setAuthToken(e){this.authToken=String(e??""),this.tileScheduler.setAuthToken(this.authToken)}setZoomRange(e,n){const r=Bt(e),i=Bt(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();pn(s,o)||this.applyViewStateAndRender(o)}setViewTransition(e){this.viewTransitionDurationMs=ln(e?.duration),this.viewTransitionEasing=cn(e?.easing)}setViewState(e,n){const r=this.resolveTargetViewState(e),i=this.camera.getViewState();if(pn(i,r))return;const o=ln(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}}getRegionLabelAutoLiftCapZoom(){const e=this.zoomSnaps.filter(n=>n>=this.minZoom&&n<=this.maxZoom);return e.length>0?e[e.length-1]:this.maxZoom}isViewAnimating(){return this.viewAnimationState.animation!==null}setPointPalette(e){const n=ac(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,e);this.applyPointBufferRuntime(n),!(!e||e.length===0)&&this.requestRender()}setPointData(e){const n=lc(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,e);this.applyPointBufferRuntime(n),this.requestRender()}setInteractionLock(e){const n=!!e;this.interactionLocked!==n&&(this.interactionLocked=n,n&&this.cancelDrag())}setPointSizeByZoom(e){const n=Or(e);Ll(this.pointSizeStops,n)||(this.pointSizeStops=n,this.requestRender())}setPointStrokeScale(e){const n=Wr(e);this.pointStrokeScale!==n&&(this.pointStrokeScale=n,this.requestRender())}setPointInnerFillOpacity(e){const n=Yr(e);this.pointInnerFillOpacity!==n&&(this.pointInnerFillOpacity=n,this.requestRender())}setImageColorSettings(e){const n=Xr(e),r=this.imageColorSettings;r.brightness===n.brightness&&r.contrast===n.contrast&&r.saturation===n.saturation||(this.imageColorSettings=n,this.requestRender())}cancelDrag(){jl(this.canvas,this.interactionState)}screenToWorld(e,n){const r=this.canvas.getBoundingClientRect(),i=e-r.left,o=n-r.top;return this.camera.screenToWorld(i,o)}worldToScreen(e,n){return this.camera.worldToScreen(e,n)}setViewCenter(e,n,r){if(!Number.isFinite(e)||!Number.isFinite(n))return;const i=this.camera.getViewState(),o=Math.max(1e-6,i.zoom),s=this.camera.getViewportSize();this.setViewState({offsetX:e-s.width/(2*o),offsetY:n-s.height/(2*o)},r)}getViewCorners(){return this.camera.getViewCorners()}getViewBounds(){return Kt(this.camera)}resetRotation(e){const n=this.camera.getViewState();Math.abs(n.rotationDeg)<1e-6||this.setViewState({rotationDeg:0},e)}getPointSizeByZoom(){const e=Math.max(1e-6,this.camera.getViewState().zoom),n=this.source.maxTierZoom+Math.log2(e),r=Dl(n,this.pointSizeStops);return I(r,Mn,Ml)}fitToImage(e){const n=this.canvas.getBoundingClientRect(),r=Math.max(1,n.width||1),i=Math.max(1,n.height||1),o=Hr(this.source,r,i,this.minZoom,this.maxZoom);this.fitZoom=o.fitZoom,this.applyZoomBounds(),this.setViewState(o.target,e)}zoomBy(e,n,r,i){const o=mc(this.camera,this.minZoom,this.maxZoom,e,n,r);o&&this.setViewState(o,i)}zoomTo(e,n,r,i){const o=gc(this.camera,this.minZoom,this.maxZoom,e,n,r);o&&this.setViewState(o,i)}setZoomSnaps(e,n){this.zoomSnaps=qr(e,this.source.mpp),this.zoomSnapFitAsMin=!!n}getZoomPivotAnimationContext(){return{camera:this.camera,viewAnimationState:this.viewAnimationState,minZoom:this.minZoom,maxZoom:this.maxZoom,cancelViewAnimation:()=>this.cancelViewAnimation(),clampViewState:()=>Wt(this.camera,this.source),onViewStateChange:e=>this.onViewStateChange?.(e),requestRender:()=>this.requestRender()}}handleSnapZoom(e,n,r){const i=this.viewAnimationState.animation,o=i?i.to.zoom:this.camera.getViewState().zoom,s=this.zoomSnaps.filter(f=>f>=this.minZoom&&f<=this.maxZoom),a=yc(s,o,e,this.zoomSnapFitAsMin);if(!a)return!1;let l;if(a.type==="fit"){const f=this.canvas.getBoundingClientRect(),c=Math.max(1,f.width||1),h=Math.max(1,f.height||1),d=Hr(this.source,c,h,this.minZoom,this.maxZoom);this.fitZoom=d.fitZoom,this.applyZoomBounds(),l=d.target.zoom}else l=a.zoom;const u=Math.max(Math.abs(l)*.005,1e-8);if(i){if((i.to.zoom>i.from.zoom+u?"in":i.to.zoom<i.from.zoom-u?"out":null)===e&&Math.abs(i.to.zoom-l)<=u)return!1}else if(Math.abs(o-l)<=u)return!1;return bc(this.getZoomPivotAnimationContext(),l,n,r,pc),!0}render(){if(this.destroyed||this.contextLost||this.gl.isContextLost())return;const e=this.onStats?ye():0;this.frameSerial+=1;const n=cc({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:()=>Gl(this.camera,this.source),getVisibleTilesForTier:r=>Wi(this.camera,this.source,r),getViewBounds:()=>Kt(this.camera),intersectsBounds:Vl});if(this.onStats){const r=this.tileScheduler.getSnapshot();this.onStats({tier:n.tier,visible:n.visible,rendered:n.rendered,points:n.points,fallback:n.fallback,cache:this.cache.size,inflight:r.inflight,queued:r.queued,retries:r.retries,failed:r.failed,aborted:r.aborted,cacheHits:n.cacheHits,cacheMisses:n.cacheMisses,drawCalls:n.drawCalls,frameMs:ye()-e})}}requestRender(){this.frame!==null||this.destroyed||this.contextLost||this.gl.isContextLost()||(this.frame=requestAnimationFrame(()=>{this.frame=null,this.render()}))}resize(){Al(this.canvas,this.gl,this.camera),this.requestRender()}onWebGlContextLost(e){const n=rc({event:e,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(e){this.destroyed||(this.contextLost=!1,this.cache.clear(),this.tileProgram=Vr(this.gl),this.pointProgram=Gr(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 e=ic({destroyed:this.destroyed,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),resizeObserver:this.resizeObserver,removeCanvasEventListeners:()=>El(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});e.didDestroy&&(this.destroyed=!0,this.frame=e.frame)}}const xc=[];function wc({source:t,viewState:e,onViewStateChange:n,onStats:r,onTileError:i,onContextLost:o,onContextRestored:s,imageColorSettings:a=null,fitNonce:l=0,rotationResetNonce:u=0,authToken:f="",ctrlDragRotate:c=!0,minZoom:h,maxZoom:d,viewTransition:m,zoomSnaps:g,zoomSnapFitAsMin:y,onPointerWorldMove:b,debugOverlay:x=!1,debugOverlayStyle:M,className:w,style:T,children:A}){const k=p.useRef(null),L=p.useRef(null),W=p.useRef(null),D=p.useRef(null),G=p.useRef(null),U=p.useRef(null),v=p.useRef(xc),Y=p.useRef(!1),B=p.useRef(new Set),z=p.useRef(new Set),Z=p.useRef(n),ae=p.useRef(r),te=p.useRef(i),Te=p.useRef(o),Se=p.useRef(s),[Ce,P]=p.useState(0),[C,H]=p.useState(null),he=p.useRef(x);p.useEffect(()=>{Z.current=n},[n]),p.useEffect(()=>{ae.current=r},[r]),p.useEffect(()=>{te.current=i},[i]),p.useEffect(()=>{Te.current=o},[o]),p.useEffect(()=>{Se.current=s},[s]),p.useEffect(()=>{he.current=x,x||H(null)},[x]);const J=p.useMemo(()=>({position:"relative",width:"100%",height:"100%",...T}),[T]),le=p.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)",...M}),[M]),ce=p.useCallback(O=>{ae.current?.(O),he.current&&H(O)},[]),ge=p.useMemo(()=>C?[`tier ${C.tier} | frame ${C.frameMs?.toFixed(2)??"-"} ms | drawCalls ${C.drawCalls??"-"}`,`tiles visible ${C.visible} | rendered ${C.rendered} | fallback ${C.fallback}`,`cache size ${C.cache} | hit ${C.cacheHits??"-"} | miss ${C.cacheMisses??"-"}`,`queue inflight ${C.inflight} | queued ${C.queued??"-"} | retries ${C.retries??"-"} | failed ${C.failed??"-"} | aborted ${C.aborted??"-"}`,`points ${C.points}`].join(`
|
|
233
|
-
`):"stats: waiting for first frame...",[C]),oe=p.useCallback(()=>{const O=W.current;if(!O)return;const q=O.getContext("2d");if(!q)return;const _=Math.max(1,window.devicePixelRatio||1),V=O.getBoundingClientRect(),j=Math.max(1,Math.round(V.width*_)),ie=Math.max(1,Math.round(V.height*_));(O.width!==j||O.height!==ie)&&(O.width=j,O.height=ie);const se=V.width,ve=V.height;q.setTransform(1,0,0,1,0,0),q.clearRect(0,0,O.width,O.height),q.setTransform(_,0,0,_,0,0);const ke=v.current;for(let Ge=0;Ge<ke.length;Ge+=1)q.save(),ke[Ge].draw(q,se,ve),q.restore()},[]),re=p.useCallback(()=>{Y.current||(Y.current=!0,requestAnimationFrame(()=>{Y.current=!1,oe()}))},[oe]),be=p.useCallback((O,q,_)=>{const V=v.current.filter(j=>j.id!==O);V.push({id:O,priority:q,draw:_}),V.sort((j,ie)=>j.priority-ie.priority),v.current=V,re()},[re]),de=p.useCallback(O=>{v.current=v.current.filter(q=>q.id!==O),re()},[re]),X=p.useCallback((O,q)=>{q?B.current.add(O):B.current.delete(O),D.current?.setInteractionLock(B.current.size>0)},[]),K=p.useCallback(()=>B.current.size>0,[]),$=p.useCallback((O,q)=>{const _=D.current;return _?_n(_.worldToScreen(O,q)):null},[]),ee=p.useCallback((O,q)=>{const _=D.current;if(!_)return null;const V=_.screenToWorld(O,q);if(!Array.isArray(V)||V.length<2)return null;const j=Number(V[0]),ie=Number(V[1]);return!Number.isFinite(j)||!Number.isFinite(ie)?null:[j,ie]},[]),ne=p.useCallback(O=>(z.current.add(O),()=>{z.current.delete(O)}),[]),ue=p.useCallback(O=>{Z.current?.(O);const q=z.current;if(q.size>0){const _=Array.from(q);for(let V=0;V<_.length;V+=1)_[V](O)}G.current?.(),U.current?.(),re()},[re]);p.useEffect(()=>{const O=L.current;if(!O||!t)return;const q=new Xi(O,t,{onViewStateChange:ue,onStats:ce,onTileError:_=>{te.current?.(_)},onContextLost:()=>{Te.current?.()},onContextRestored:()=>{Se.current?.()},authToken:f,imageColorSettings:a,ctrlDragRotate:c,minZoom:h,maxZoom:d,viewTransition:m,zoomSnaps:g,zoomSnapFitAsMin:y});return D.current=q,P(_=>_+1),e&&q.setViewState(e),q.setInteractionLock(B.current.size>0),()=>{q.destroy(),D.current=null}},[t,ce,c,ue]),p.useEffect(()=>{D.current?.setAuthToken(f)},[f]),p.useEffect(()=>{const O=D.current;!O||!e||O.isViewAnimating()||O.setViewState(e)},[e]),p.useEffect(()=>{D.current?.fitToImage()},[l]),p.useEffect(()=>{D.current?.resetRotation()},[u]),p.useEffect(()=>{D.current?.setZoomRange(h,d)},[h,d]),p.useEffect(()=>{D.current?.setViewTransition(m)},[m]),p.useEffect(()=>{D.current?.setZoomSnaps(g,y)},[g,y]),p.useEffect(()=>{D.current?.setImageColorSettings(a)},[a]),p.useEffect(()=>{const O=W.current;if(!O)return;G.current=re,re();const q=new ResizeObserver(()=>re());return q.observe(O),()=>{q.disconnect(),G.current===re&&(G.current=null)}},[re]);const Re=p.useMemo(()=>({source:t,rendererRef:D,rendererSerial:Ce,canvasRef:L,containerRef:k,drawInvalidateRef:G,overviewInvalidateRef:U,worldToScreen:$,screenToWorld:ee,registerDrawCallback:be,unregisterDrawCallback:de,requestOverlayRedraw:re,registerViewStateListener:ne,setInteractionLock:X,isInteractionLocked:K}),[t,Ce,$,ee,be,de,re,ne,X,K]),xe=p.useRef(b);p.useEffect(()=>{xe.current=b},[b]);const we=p.useCallback(O=>{const q=xe.current;if(!q)return;const _=ee(O.clientX,O.clientY),V=!!_&&_[0]>=0&&_[1]>=0&&!!t&&_[0]<=t.width&&_[1]<=t.height;q({coordinate:_,clientX:O.clientX,clientY:O.clientY,insideImage:V})},[ee,t]),pe=p.useCallback(()=>{xe.current?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1})},[]);return Ye.jsx(Gs,{value:Re,children:Ye.jsxs("div",{ref:k,className:w,style:J,onPointerMove:b?we:void 0,onPointerLeave:b?pe:void 0,children:[Ye.jsx("canvas",{ref:L,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none"}}),Ye.jsx("canvas",{ref:W,className:"wsi-overlay-canvas",style:{position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",pointerEvents:"none",touchAction:"none"}}),A,x&&Ye.jsx("pre",{"data-open-plant-debug-overlay":!0,style:le,children:ge})]})})}function Sc(t){const e=[];for(let n=0;n<t.length;n+=1){const r=t[n],i=ut([ct(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)||e.push({regionId:r.id??n,regionIndex:n,polygons:i,area:Math.max(1e-6,o),minX:s,minY:a,maxX:l,maxY:u})}return e}const Rc=128,un=[];function at(t,e,n,r,i){if(i<=1||n<=e)return 0;const o=(t-e)/r;return!Number.isFinite(o)||o<=0?0:o>=i-1?i-1:Math.floor(o)}function Ec(t){if(t.length===0)return null;let e=1/0,n=1/0,r=-1/0,i=-1/0;for(const f of t)f.minX<e&&(e=f.minX),f.minY<n&&(n=f.minY),f.maxX>r&&(r=f.maxX),f.maxY>i&&(i=f.maxY);if(!Number.isFinite(e)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i))return null;const o=Math.ceil(Math.sqrt(t.length*2)),s=Math.max(1,Math.min(Rc,o)),a=r>e?(r-e)/s:1,l=i>n?(i-n)/s:1,u=Array.from({length:s*s},()=>[]);for(let f=0;f<t.length;f+=1){const c=t[f],h=at(c.minX,e,r,a,s),d=at(c.maxX,e,r,a,s),m=at(c.minY,n,i,l,s),g=at(c.maxY,n,i,l,s);for(let y=m;y<=g;y+=1)for(let b=h;b<=d;b+=1)u[y*s+b].push(f)}return{minX:e,minY:n,maxX:r,maxY:i,gridSize:s,cellWidth:a,cellHeight:l,buckets:u}}function Ac(t,e,n){if(!t||e<t.minX||e>t.maxX||n<t.minY||n>t.maxY)return un;const r=at(e,t.minX,t.maxX,t.cellWidth,t.gridSize),i=at(n,t.minY,t.maxY,t.cellHeight,t.gridSize);return t.buckets[i*t.gridSize+r]??un}function Mc(t,e){if(Array.isArray(e)){const n=e[t];if(typeof n=="string"&&n.length>0)return n}if(e instanceof Map){const n=e.get(t);if(typeof n=="string"&&n.length>0)return n}return String(t)}function Tc(t,e,n={}){const r=Math.max(0,Math.min(Math.floor(t?.count??0),Math.floor((t?.positions?.length??0)/2),t?.paletteIndices?.length??0,t?.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER));let i=null;if(t?.drawIndices instanceof Uint32Array){const d=t.drawIndices;let m=d.length;for(let g=0;g<d.length;g+=1)d[g]<r||(m-=1);if(m===d.length)i=d;else if(m>0){const g=new Uint32Array(m);let y=0;for(let b=0;b<d.length;b+=1){const x=d[b];x>=r||(g[y]=x,y+=1)}i=g}else i=new Uint32Array(0)}const o=i?i.length:r,s=Sc(e??[]);if(!t||o===0||s.length===0)return{groups:[],inputPointCount:o,pointsInsideAnyRegion:0,unmatchedPointCount:o};const a=new Map,l=new Map,u=Ec(s);let f=0;for(let d=0;d<o;d+=1){const m=i?i[d]:d,g=t.positions[m*2],y=t.positions[m*2+1];if(!Number.isFinite(g)||!Number.isFinite(y))continue;let b=null;const x=Ac(u,g,y);if(x.length===0)continue;for(const T of x){const A=s[T];let k=!1;for(const L of A.polygons)if(ti(g,y,L)){k=!0;break}k&&(!b||A.area<b.area)&&(b=A)}if(!b)continue;f+=1;const M=t.paletteIndices[m]??0,w=a.get(b.regionIndex)??new Map;w.set(M,(w.get(M)??0)+1),a.set(b.regionIndex,w),l.set(b.regionIndex,(l.get(b.regionIndex)??0)+1)}const c=n.includeEmptyRegions??!1,h=[];for(const d of s){const m=l.get(d.regionIndex)??0;if(!c&&m<=0)continue;const g=a.get(d.regionIndex)??new Map,y=Array.from(g.entries()).map(([b,x])=>({termId:Mc(b,n.paletteIndexToTermId),paletteIndex:b,count:x})).sort((b,x)=>x.count-b.count||b.paletteIndex-x.paletteIndex);h.push({regionId:d.regionId,regionIndex:d.regionIndex,totalCount:m,termCounts:y})}return{groups:h,inputPointCount:o,pointsInsideAnyRegion:f,unmatchedPointCount:Math.max(0,o-f)}}function Cc(t){return t.replace(/^\s*SRID\s*=\s*\d+\s*;\s*/i,"")}function vc(t){return t>="A"&&t<="Z"||t>="a"&&t<="z"}function Pc(t){return t>="0"&&t<="9"}function Zr(t){return t==="+"||t==="-"||t==="."||Pc(t)}class Ic{constructor(e){S(this,"text");S(this,"index",0);this.text=Cc(e.trim())}parse(){if(!this.text)return null;const e=this.readWord();if(!e)return null;const n=e.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=Vi(i);return s?{type:"Polygon",coordinates:s}:null}const o=Fc(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 e=this.index;for(;!this.isEof()&&vc(this.currentChar());)this.index+=1;return this.index===e?null:this.text.slice(e,this.index)}peekWord(){const e=this.index,n=this.readWord();return this.index=e,n}consumeWordIf(e){const n=this.index,r=this.readWord();return!r||r.toUpperCase()!==e.toUpperCase()?(this.index=n,!1):!0}parseNestedList(){if(this.skipWhitespace(),this.currentChar()!=="(")throw new Error("Expected '('");this.index+=1;const e=[];for(;;){this.skipWhitespace(),this.currentChar()==="("?e.push(this.parseNestedList()):e.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 e}parseCoordinateTuple(){this.skipWhitespace();const e=[];for(;;){this.skipWhitespace();const n=this.currentChar();if(!n||!Zr(n))break;const r=this.readNumber();if(r===null)break;e.push(r),this.skipWhitespace();const i=this.currentChar();if(!i||i===","||i===")")break;if(!Zr(i))throw new Error("Invalid coordinate")}if(e.length<2)throw new Error("Coordinate requires at least x y");return[e[0],e[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 _c(t){return Array.isArray(t)&&t.length>=2&&typeof t[0]=="number"&&Number.isFinite(t[0])&&typeof t[1]=="number"&&Number.isFinite(t[1])}function Vi(t){if(!Array.isArray(t))return null;const e=[];for(const n of t){if(!Array.isArray(n))return null;const r=[];for(const i of n){if(!_c(i))return null;r.push([i[0],i[1]])}e.push(r)}return e}function Fc(t){if(!Array.isArray(t))return null;const e=[];for(const n of t){const r=Vi(n);if(!r)return null;e.push(r)}return e}function Lc(t){return typeof t!="string"?null:new Ic(t).parse()}exports.DEFAULT_POINT_COLOR=Pn;exports.DrawLayer=di;exports.DrawingLayer=Hs;exports.HeatmapLayer=Ta;exports.M1TileRenderer=Kr;exports.OverlayLayer=va;exports.OverviewMap=Da;exports.PatchLayer=Ba;exports.PointLayer=al;exports.RegionLayer=xl;exports.TileScheduler=Ui;exports.TileViewerCanvas=wl;exports.WsiTileRenderer=Xi;exports.WsiViewer=wc;exports.__heatmapLayerInternals=Ca;exports.buildPointSpatialIndexAsync=ki;exports.buildTermPalette=Io;exports.calcScaleLength=vo;exports.calcScaleResolution=In;exports.clamp=I;exports.closeRing=Le;exports.computeRoiPointGroups=Tc;exports.createCircle=yn;exports.createRectangle=qt;exports.createSpatialIndex=gi;exports.filterPointDataByPolygons=wt;exports.filterPointDataByPolygonsHybrid=Li;exports.filterPointDataByPolygonsInWorker=Ni;exports.filterPointIndicesByPolygons=Ii;exports.filterPointIndicesByPolygonsInWorker=Ha;exports.getWebGpuCapabilities=Xa;exports.hexToRgba=ni;exports.isSameViewState=pn;exports.lookupCellIndex=Bi;exports.normalizeImageInfo=Ia;exports.parseWkt=Lc;exports.prefilterPointsByBoundsWebGpu=Fi;exports.terminatePointHitIndexWorker=nl;exports.terminateRoiClipWorker=Ga;exports.toBearerToken=Po;exports.toRoiGeometry=ct;exports.toTileUrl=Wn;exports.useViewerContext=rt;
|
|
232
|
+
}`),i=Fe(t,r,"uCamera"),o=Fe(t,r,"uPointSize"),s=Fe(t,r,"uPointStrokeScale"),a=Fe(t,r,"uPointInnerFillAlpha"),l=Fe(t,r,"uPalette"),u=Fe(t,r,"uPaletteSize"),f=t.createVertexArray(),c=t.createBuffer(),h=t.createBuffer(),d=t.createBuffer(),m=t.createBuffer(),g=t.createTexture();if(!f||!c||!h||!d||!m||!g)throw new Error("point buffer allocation failed");t.bindVertexArray(f),t.bindBuffer(t.ARRAY_BUFFER,c),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const y=t.getAttribLocation(r,"aPosition");if(y<0)throw new Error("point position attribute not found");t.enableVertexAttribArray(y),t.vertexAttribPointer(y,2,t.FLOAT,!1,0,0),t.bindBuffer(t.ARRAY_BUFFER,h),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const b=t.getAttribLocation(r,"aTerm");if(b<0)throw new Error("point term attribute not found");t.enableVertexAttribArray(b),t.vertexAttribIPointer(b,1,t.UNSIGNED_SHORT,0,0),t.bindBuffer(t.ARRAY_BUFFER,d),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const x=t.getAttribLocation(r,"aFillMode");if(x<0)throw new Error("point fill mode attribute not found");return t.enableVertexAttribArray(x),t.vertexAttribIPointer(x,1,t.UNSIGNED_BYTE,0,0),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,m),t.bufferData(t.ELEMENT_ARRAY_BUFFER,0,t.DYNAMIC_DRAW),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null),t.bindTexture(t.TEXTURE_2D,g),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,new Uint8Array([160,160,160,255])),t.bindTexture(t.TEXTURE_2D,null),{program:r,vao:f,posBuffer:c,termBuffer:h,fillModeBuffer:d,indexBuffer:m,paletteTexture:g,uCamera:i,uPointSize:o,uPointStrokeScale:s,uPointInnerFillAlpha:a,uPalette:l,uPaletteSize:u}}function Yi(t){t.animation=null,t.frame!==null&&(cancelAnimationFrame(t.frame),t.frame=null)}function uc(t){const{state:e,camera:n,target:r,durationMs:i,easing:o,onUpdate:s}=t,a=n.getViewState();Yi(e),e.animation={startMs:be(),durationMs:Math.max(0,i),from:a,to:r,easing:o};const l=()=>{const u=e.animation;if(!u)return;const f=Math.max(0,be()-u.startMs),c=u.durationMs<=0?1:_(f/u.durationMs,0,1);let h=c;try{h=u.easing(c)}catch{h=c}if(Number.isFinite(h)||(h=c),h=_(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){e.animation=null,e.frame=null;return}e.frame=requestAnimationFrame(l)};e.frame=requestAnimationFrame(l)}function fc(t){const e=Math.max(t*.5,1e-6),n=Math.max(1,t*8);return{minZoom:e,maxZoom:Math.max(e,n)}}function hc(t,e,n){const r=fc(t);let i=e??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 dc(t,e,n,r,i){const o=t.getViewState(),s={zoom:typeof r.zoom=="number"&&Number.isFinite(r.zoom)?_(r.zoom,e,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};t.setViewState(s),i();const a=t.getViewState();return t.setViewState(o),a}function Hr(t,e,n,r,i){const o=Math.min(e/t.width,n/t.height),s=Number.isFinite(o)&&o>0?o:1,a=_(s,r,i),l=e/a,u=n/a;return{fitZoom:s,target:{zoom:a,offsetX:(t.width-l)*.5,offsetY:(t.height-u)*.5,rotationDeg:0}}}function mc(t,e,n,r,i,o){const s=t.getViewState(),a=_(s.zoom*r,e,n);if(a===s.zoom)return null;const[l,u]=t.screenToWorld(i,o),f=t.getViewportSize(),c=i-f.width*.5,h=o-f.height*.5,d=Qt(s.rotationDeg),m=Math.cos(d),g=Math.sin(d),y=c/a*m-h/a*g,b=c/a*g+h/a*m,x=l-y,A=u-b;return{zoom:a,offsetX:x-f.width/(2*a),offsetY:A-f.height/(2*a)}}function gc(t,e,n,r,i,o){const s=t.getViewState(),a=_(r,e,n);if(a===s.zoom)return null;const[l,u]=t.screenToWorld(i,o),f=t.getViewportSize(),c=i-f.width*.5,h=o-f.height*.5,d=Qt(s.rotationDeg),m=Math.cos(d),g=Math.sin(d),y=c/a*m-h/a*g,b=c/a*g+h/a*m,x=l-y,A=u-b;return{zoom:a,offsetX:x-f.width/(2*a),offsetY:A-f.height/(2*a)}}const pc=250;function qr(t,e){if(!t||t.length===0)return[];if(!e||e<=0)return[];const n=10/e;return t.map(r=>r/n).filter(r=>Number.isFinite(r)&&r>0).sort((r,i)=>r-i)}function yc(t,e,n,r){if(t.length===0)return null;const i=Math.max(e*.005,1e-8);if(n==="in"){for(const o of t)if(o>e+i)return{type:"snap",zoom:o};return null}for(let o=t.length-1;o>=0;o--)if(t[o]<e-i)return{type:"snap",zoom:t[o]};return r&&e<=t[0]+i?{type:"fit"}:null}function bc(t,e,n,r,i){const o=t.camera.getViewState(),[s,a]=t.camera.screenToWorld(n,r),l=t.camera.getViewportSize(),u=_(e,t.minZoom,t.maxZoom);if(u===o.zoom)return;const f=Qt(o.rotationDeg),c=Math.cos(f),h=Math.sin(f),d=n-l.width*.5,m=r-l.height*.5;t.cancelViewAnimation();const g=x=>{const A=d/x*c-m/x*h,w=d/x*h+m/x*c;return{offsetX:s-A-l.width/(2*x),offsetY:a-w-l.height/(2*x)}},y=g(u);t.viewAnimationState.animation={startMs:be(),durationMs:Math.max(0,i),from:o,to:{zoom:u,offsetX:y.offsetX,offsetY:y.offsetY,rotationDeg:o.rotationDeg},easing:Yn};const b=()=>{const x=t.viewAnimationState.animation;if(!x)return;const A=Math.max(0,be()-x.startMs),w=_(A/i,0,1),T=_(w*w*(3-2*w),0,1),M=o.zoom+(u-o.zoom)*T,{offsetX:z,offsetY:L}=g(M);t.camera.setViewState({zoom:M,offsetX:z,offsetY:L,rotationDeg:o.rotationDeg});const V=w>=1;V&&(t.clampViewState(),t.viewAnimationState.animation=null,t.viewAnimationState.frame=null),t.onViewStateChange(t.camera.getViewState()),t.requestRender(),V||(t.viewAnimationState.frame=requestAnimationFrame(b))};t.viewAnimationState.frame=requestAnimationFrame(b)}class Xi{constructor(e,n,r={}){S(this,"canvas");S(this,"source");S(this,"gl");S(this,"camera",new $r);S(this,"onViewStateChange");S(this,"onStats");S(this,"onTileError");S(this,"onContextLost");S(this,"onContextRestored");S(this,"resizeObserver");S(this,"tileProgram");S(this,"pointProgram");S(this,"tileScheduler");S(this,"authToken");S(this,"destroyed",!1);S(this,"contextLost",!1);S(this,"frame",null);S(this,"frameSerial",0);S(this,"interactionState",{dragging:!1,mode:"none",rotateLastAngleRad:null,pointerId:null,lastPointerX:0,lastPointerY:0});S(this,"interactionLocked",!1);S(this,"ctrlDragRotate",!0);S(this,"rotationDragSensitivityDegPerPixel",An);S(this,"maxCacheTiles");S(this,"fitZoom",1);S(this,"minZoom",1e-6);S(this,"maxZoom",1);S(this,"minZoomOverride",null);S(this,"maxZoomOverride",null);S(this,"viewTransitionDurationMs",0);S(this,"viewTransitionEasing",Yn);S(this,"viewAnimationState",{animation:null,frame:null});S(this,"pointCount",0);S(this,"usePointIndices",!1);S(this,"pointBuffersDirty",!0);S(this,"pointPaletteSize",1);S(this,"pointSizeStops",Cn(Tn));S(this,"pointStrokeScale",1);S(this,"pointInnerFillOpacity",0);S(this,"imageColorSettings",{brightness:0,contrast:0,saturation:0});S(this,"lastPointData",null);S(this,"lastPointPalette",null);S(this,"zeroFillModes",new Uint8Array(0));S(this,"cache",new Map);S(this,"zoomSnaps",[]);S(this,"zoomSnapFitAsMin",!1);S(this,"zoomSnapState",{accumulatedDelta:0,lastSnapTimeMs:0,blockedDirection:null});S(this,"panExtentX",.2);S(this,"panExtentY",.2);S(this,"boundPointerDown");S(this,"boundPointerMove");S(this,"boundPointerUp");S(this,"boundWheel");S(this,"boundDoubleClick");S(this,"boundContextMenu");S(this,"boundContextLost");S(this,"boundContextRestored");this.canvas=e,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):An,this.pointSizeStops=Or(r.pointSizeByZoom),this.pointStrokeScale=Wr(r.pointStrokeScale),this.pointInnerFillOpacity=Yr(r.pointInnerFillOpacity),this.imageColorSettings=Xr(r.imageColorSettings),this.minZoomOverride=kt(r.minZoom),this.maxZoomOverride=kt(r.maxZoom),this.viewTransitionDurationMs=ln(r.viewTransition?.duration),this.viewTransitionEasing=cn(r.viewTransition?.easing),this.zoomSnaps=qr(r.zoomSnaps,this.source.mpp),this.zoomSnapFitAsMin=!!r.zoomSnapFitAsMin,this.applyPanExtent(r.panExtent);const i=e.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=Vr(this.gl),this.pointProgram=Gr(this.gl),this.tileScheduler=new Ui({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)=>tc({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(e);const o=Ql({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(),getPanExtentX:()=>this.panExtentX,getPanExtentY:()=>this.panExtentY,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),El(e,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 e=hc(this.fitZoom,this.minZoomOverride,this.maxZoomOverride);this.minZoom=e.minZoom,this.maxZoom=e.maxZoom}resolveTargetViewState(e){return dc(this.camera,this.minZoom,this.maxZoom,e,()=>Yt(this.camera,this.source,this.panExtentX,this.panExtentY))}cancelViewAnimation(){Yi(this.viewAnimationState)}startViewAnimation(e,n,r){uc({state:this.viewAnimationState,camera:this.camera,target:e,durationMs:n,easing:r,onUpdate:()=>{Yt(this.camera,this.source,this.panExtentX,this.panExtentY),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(e){this.pointCount=e.pointCount,this.usePointIndices=e.usePointIndices,this.pointBuffersDirty=e.pointBuffersDirty,this.lastPointData=e.lastPointData,this.zeroFillModes=e.zeroFillModes,this.lastPointPalette=e.lastPointPalette,this.pointPaletteSize=e.pointPaletteSize}applyViewStateAndRender(e,n=!0){n&&this.cancelViewAnimation(),this.camera.setViewState(e),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}setAuthToken(e){this.authToken=String(e??""),this.tileScheduler.setAuthToken(this.authToken)}setZoomRange(e,n){const r=kt(e),i=kt(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();pn(s,o)||this.applyViewStateAndRender(o)}setViewTransition(e){this.viewTransitionDurationMs=ln(e?.duration),this.viewTransitionEasing=cn(e?.easing)}setViewState(e,n){const r=this.resolveTargetViewState(e),i=this.camera.getViewState();if(pn(i,r))return;const o=ln(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}}getRegionLabelAutoLiftCapZoom(){const e=this.zoomSnaps.filter(n=>n>=this.minZoom&&n<=this.maxZoom);return e.length>0?e[e.length-1]:this.maxZoom}isViewAnimating(){return this.viewAnimationState.animation!==null}setPointPalette(e){const n=ac(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,e);this.applyPointBufferRuntime(n),!(!e||e.length===0)&&this.requestRender()}setPointData(e){const n=lc(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,e);this.applyPointBufferRuntime(n),this.requestRender()}setInteractionLock(e){const n=!!e;this.interactionLocked!==n&&(this.interactionLocked=n,n&&this.cancelDrag())}setPointSizeByZoom(e){const n=Or(e);Ll(this.pointSizeStops,n)||(this.pointSizeStops=n,this.requestRender())}setPointStrokeScale(e){const n=Wr(e);this.pointStrokeScale!==n&&(this.pointStrokeScale=n,this.requestRender())}setPointInnerFillOpacity(e){const n=Yr(e);this.pointInnerFillOpacity!==n&&(this.pointInnerFillOpacity=n,this.requestRender())}setImageColorSettings(e){const n=Xr(e),r=this.imageColorSettings;r.brightness===n.brightness&&r.contrast===n.contrast&&r.saturation===n.saturation||(this.imageColorSettings=n,this.requestRender())}cancelDrag(){jl(this.canvas,this.interactionState)}screenToWorld(e,n){const r=this.canvas.getBoundingClientRect(),i=e-r.left,o=n-r.top;return this.camera.screenToWorld(i,o)}worldToScreen(e,n){return this.camera.worldToScreen(e,n)}setViewCenter(e,n,r){if(!Number.isFinite(e)||!Number.isFinite(n))return;const i=this.camera.getViewState(),o=Math.max(1e-6,i.zoom),s=this.camera.getViewportSize();this.setViewState({offsetX:e-s.width/(2*o),offsetY:n-s.height/(2*o)},r)}getViewCorners(){return this.camera.getViewCorners()}getViewBounds(){return jt(this.camera)}resetRotation(e){const n=this.camera.getViewState();Math.abs(n.rotationDeg)<1e-6||this.setViewState({rotationDeg:0},e)}getPointSizeByZoom(){const e=Math.max(1e-6,this.camera.getViewState().zoom),n=this.source.maxTierZoom+Math.log2(e),r=Dl(n,this.pointSizeStops);return _(r,Mn,Ml)}fitToImage(e){const n=this.canvas.getBoundingClientRect(),r=Math.max(1,n.width||1),i=Math.max(1,n.height||1),o=Hr(this.source,r,i,this.minZoom,this.maxZoom);this.fitZoom=o.fitZoom,this.applyZoomBounds(),this.setViewState(o.target,e)}zoomBy(e,n,r,i){const o=mc(this.camera,this.minZoom,this.maxZoom,e,n,r);o&&this.setViewState(o,i)}zoomTo(e,n,r,i){const o=gc(this.camera,this.minZoom,this.maxZoom,e,n,r);o&&this.setViewState(o,i)}setZoomSnaps(e,n){this.zoomSnaps=qr(e,this.source.mpp),this.zoomSnapFitAsMin=!!n}setPanExtent(e){this.applyPanExtent(e)}applyPanExtent(e){typeof e=="number"&&Number.isFinite(e)?(this.panExtentX=Math.max(0,e),this.panExtentY=Math.max(0,e)):e!=null&&typeof e=="object"?(this.panExtentX=typeof e.x=="number"&&Number.isFinite(e.x)?Math.max(0,e.x):.2,this.panExtentY=typeof e.y=="number"&&Number.isFinite(e.y)?Math.max(0,e.y):.2):(this.panExtentX=.2,this.panExtentY=.2)}getZoomPivotAnimationContext(){return{camera:this.camera,viewAnimationState:this.viewAnimationState,minZoom:this.minZoom,maxZoom:this.maxZoom,cancelViewAnimation:()=>this.cancelViewAnimation(),clampViewState:()=>Yt(this.camera,this.source,this.panExtentX,this.panExtentY),onViewStateChange:e=>this.onViewStateChange?.(e),requestRender:()=>this.requestRender()}}handleSnapZoom(e,n,r){const i=this.viewAnimationState.animation,o=i?i.to.zoom:this.camera.getViewState().zoom,s=this.zoomSnaps.filter(f=>f>=this.minZoom&&f<=this.maxZoom),a=yc(s,o,e,this.zoomSnapFitAsMin);if(!a)return!1;let l;if(a.type==="fit"){const f=this.canvas.getBoundingClientRect(),c=Math.max(1,f.width||1),h=Math.max(1,f.height||1),d=Hr(this.source,c,h,this.minZoom,this.maxZoom);this.fitZoom=d.fitZoom,this.applyZoomBounds(),l=d.target.zoom}else l=a.zoom;const u=Math.max(Math.abs(l)*.005,1e-8);if(i){if((i.to.zoom>i.from.zoom+u?"in":i.to.zoom<i.from.zoom-u?"out":null)===e&&Math.abs(i.to.zoom-l)<=u)return!1}else if(Math.abs(o-l)<=u)return!1;return bc(this.getZoomPivotAnimationContext(),l,n,r,pc),!0}render(){if(this.destroyed||this.contextLost||this.gl.isContextLost())return;const e=this.onStats?be():0;this.frameSerial+=1;const n=cc({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:()=>Gl(this.camera,this.source),getVisibleTilesForTier:r=>Wi(this.camera,this.source,r),getViewBounds:()=>jt(this.camera),intersectsBounds:Vl});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()-e})}}requestRender(){this.frame!==null||this.destroyed||this.contextLost||this.gl.isContextLost()||(this.frame=requestAnimationFrame(()=>{this.frame=null,this.render()}))}resize(){Al(this.canvas,this.gl,this.camera),this.requestRender()}onWebGlContextLost(e){const n=rc({event:e,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(e){this.destroyed||(this.contextLost=!1,this.cache.clear(),this.tileProgram=Vr(this.gl),this.pointProgram=Gr(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 e=ic({destroyed:this.destroyed,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),resizeObserver:this.resizeObserver,removeCanvasEventListeners:()=>Rl(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});e.didDestroy&&(this.destroyed=!0,this.frame=e.frame)}}const xc=[];function wc({source:t,viewState:e,onViewStateChange:n,onStats:r,onTileError:i,onContextLost:o,onContextRestored:s,imageColorSettings:a=null,fitNonce:l=0,rotationResetNonce:u=0,authToken:f="",ctrlDragRotate:c=!0,minZoom:h,maxZoom:d,viewTransition:m,zoomSnaps:g,zoomSnapFitAsMin:y,panExtent:b,onPointerWorldMove:x,debugOverlay:A=!1,debugOverlayStyle:w,className:T,style:M,children:z}){const L=p.useRef(null),V=p.useRef(null),H=p.useRef(null),W=p.useRef(null),D=p.useRef(null),C=p.useRef(null),Y=p.useRef(xc),O=p.useRef(!1),N=p.useRef(new Set),Z=p.useRef(new Set),oe=p.useRef(n),ne=p.useRef(r),Me=p.useRef(i),we=p.useRef(o),Te=p.useRef(s),[v,I]=p.useState(0),[B,fe]=p.useState(null),Q=p.useRef(A);p.useEffect(()=>{oe.current=n},[n]),p.useEffect(()=>{ne.current=r},[r]),p.useEffect(()=>{Me.current=i},[i]),p.useEffect(()=>{we.current=o},[o]),p.useEffect(()=>{Te.current=s},[s]),p.useEffect(()=>{Q.current=A,A||fe(null)},[A]);const se=p.useMemo(()=>({position:"relative",width:"100%",height:"100%",...M}),[M]),le=p.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)",...w}),[w]),de=p.useCallback(U=>{ne.current?.(U),Q.current&&fe(U)},[]),ae=p.useMemo(()=>B?[`tier ${B.tier} | frame ${B.frameMs?.toFixed(2)??"-"} ms | drawCalls ${B.drawCalls??"-"}`,`tiles visible ${B.visible} | rendered ${B.rendered} | fallback ${B.fallback}`,`cache size ${B.cache} | hit ${B.cacheHits??"-"} | miss ${B.cacheMisses??"-"}`,`queue inflight ${B.inflight} | queued ${B.queued??"-"} | retries ${B.retries??"-"} | failed ${B.failed??"-"} | aborted ${B.aborted??"-"}`,`points ${B.points}`].join(`
|
|
233
|
+
`):"stats: waiting for first frame...",[B]),ge=p.useCallback(()=>{const U=H.current;if(!U)return;const P=U.getContext("2d");if(!P)return;const X=Math.max(1,window.devicePixelRatio||1),G=U.getBoundingClientRect(),te=Math.max(1,Math.round(G.width*X)),ee=Math.max(1,Math.round(G.height*X));(U.width!==te||U.height!==ee)&&(U.width=te,U.height=ee);const Ce=G.width,Ue=G.height;P.setTransform(1,0,0,1,0,0),P.clearRect(0,0,U.width,U.height),P.setTransform(X,0,0,X,0,0);const Ze=Y.current;for(let tt=0;tt<Ze.length;tt+=1)P.save(),Ze[tt].draw(P,Ce,Ue),P.restore()},[]),ie=p.useCallback(()=>{O.current||(O.current=!0,requestAnimationFrame(()=>{O.current=!1,ge()}))},[ge]),he=p.useCallback((U,P,X)=>{const G=Y.current.filter(te=>te.id!==U);G.push({id:U,priority:P,draw:X}),G.sort((te,ee)=>te.priority-ee.priority),Y.current=G,ie()},[ie]),q=p.useCallback(U=>{Y.current=Y.current.filter(P=>P.id!==U),ie()},[ie]),K=p.useCallback((U,P)=>{P?N.current.add(U):N.current.delete(U),W.current?.setInteractionLock(N.current.size>0)},[]),$=p.useCallback(()=>N.current.size>0,[]),re=p.useCallback((U,P)=>{const X=W.current;return X?_n(X.worldToScreen(U,P)):null},[]),J=p.useCallback((U,P)=>{const X=W.current;if(!X)return null;const G=X.screenToWorld(U,P);if(!Array.isArray(G)||G.length<2)return null;const te=Number(G[0]),ee=Number(G[1]);return!Number.isFinite(te)||!Number.isFinite(ee)?null:[te,ee]},[]),ce=p.useCallback(U=>(Z.current.add(U),()=>{Z.current.delete(U)}),[]),xe=p.useCallback(U=>{oe.current?.(U);const P=Z.current;if(P.size>0){const X=Array.from(P);for(let G=0;G<X.length;G+=1)X[G](U)}D.current?.(),C.current?.(),ie()},[ie]);p.useEffect(()=>{const U=V.current;if(!U||!t)return;const P=new Xi(U,t,{onViewStateChange:xe,onStats:de,onTileError:X=>{Me.current?.(X)},onContextLost:()=>{we.current?.()},onContextRestored:()=>{Te.current?.()},authToken:f,imageColorSettings:a,ctrlDragRotate:c,minZoom:h,maxZoom:d,viewTransition:m,zoomSnaps:g,zoomSnapFitAsMin:y,panExtent:b});return W.current=P,I(X=>X+1),e&&P.setViewState(e),P.setInteractionLock(N.current.size>0),()=>{P.destroy(),W.current=null}},[t,de,c,xe]),p.useEffect(()=>{W.current?.setAuthToken(f)},[f]),p.useEffect(()=>{const U=W.current;!U||!e||U.isViewAnimating()||U.setViewState(e)},[e]),p.useEffect(()=>{W.current?.fitToImage()},[l]),p.useEffect(()=>{W.current?.resetRotation()},[u]),p.useEffect(()=>{W.current?.setZoomRange(h,d)},[h,d]),p.useEffect(()=>{W.current?.setViewTransition(m)},[m]),p.useEffect(()=>{W.current?.setZoomSnaps(g,y)},[g,y]),p.useEffect(()=>{W.current?.setPanExtent(b)},[b]),p.useEffect(()=>{W.current?.setImageColorSettings(a)},[a]),p.useEffect(()=>{const U=H.current;if(!U)return;D.current=ie,ie();const P=new ResizeObserver(()=>ie());return P.observe(U),()=>{P.disconnect(),D.current===ie&&(D.current=null)}},[ie]);const Ee=p.useMemo(()=>({source:t,rendererRef:W,rendererSerial:v,canvasRef:V,containerRef:L,drawInvalidateRef:D,overviewInvalidateRef:C,worldToScreen:re,screenToWorld:J,registerDrawCallback:he,unregisterDrawCallback:q,requestOverlayRedraw:ie,registerViewStateListener:ce,setInteractionLock:K,isInteractionLocked:$}),[t,v,re,J,he,q,ie,ce,K,$]),pe=p.useRef(x);p.useEffect(()=>{pe.current=x},[x]);const ye=p.useCallback(U=>{const P=pe.current;if(!P)return;const X=J(U.clientX,U.clientY),G=!!X&&X[0]>=0&&X[1]>=0&&!!t&&X[0]<=t.width&&X[1]<=t.height;P({coordinate:X,clientX:U.clientX,clientY:U.clientY,insideImage:G})},[J,t]),ve=p.useCallback(()=>{pe.current?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1})},[]);return Ye.jsx(Gs,{value:Ee,children:Ye.jsxs("div",{ref:L,className:T,style:se,onPointerMove:x?ye:void 0,onPointerLeave:x?ve:void 0,children:[Ye.jsx("canvas",{ref:V,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none"}}),Ye.jsx("canvas",{ref:H,className:"wsi-overlay-canvas",style:{position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",pointerEvents:"none",touchAction:"none"}}),z,A&&Ye.jsx("pre",{"data-open-plant-debug-overlay":!0,style:le,children:ae})]})})}function Sc(t){const e=[];for(let n=0;n<t.length;n+=1){const r=t[n],i=ft([ut(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)||e.push({regionId:r.id??n,regionIndex:n,polygons:i,area:Math.max(1e-6,o),minX:s,minY:a,maxX:l,maxY:u})}return e}const Ec=128,un=[];function lt(t,e,n,r,i){if(i<=1||n<=e)return 0;const o=(t-e)/r;return!Number.isFinite(o)||o<=0?0:o>=i-1?i-1:Math.floor(o)}function Rc(t){if(t.length===0)return null;let e=1/0,n=1/0,r=-1/0,i=-1/0;for(const f of t)f.minX<e&&(e=f.minX),f.minY<n&&(n=f.minY),f.maxX>r&&(r=f.maxX),f.maxY>i&&(i=f.maxY);if(!Number.isFinite(e)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i))return null;const o=Math.ceil(Math.sqrt(t.length*2)),s=Math.max(1,Math.min(Ec,o)),a=r>e?(r-e)/s:1,l=i>n?(i-n)/s:1,u=Array.from({length:s*s},()=>[]);for(let f=0;f<t.length;f+=1){const c=t[f],h=lt(c.minX,e,r,a,s),d=lt(c.maxX,e,r,a,s),m=lt(c.minY,n,i,l,s),g=lt(c.maxY,n,i,l,s);for(let y=m;y<=g;y+=1)for(let b=h;b<=d;b+=1)u[y*s+b].push(f)}return{minX:e,minY:n,maxX:r,maxY:i,gridSize:s,cellWidth:a,cellHeight:l,buckets:u}}function Ac(t,e,n){if(!t||e<t.minX||e>t.maxX||n<t.minY||n>t.maxY)return un;const r=lt(e,t.minX,t.maxX,t.cellWidth,t.gridSize),i=lt(n,t.minY,t.maxY,t.cellHeight,t.gridSize);return t.buckets[i*t.gridSize+r]??un}function Mc(t,e){if(Array.isArray(e)){const n=e[t];if(typeof n=="string"&&n.length>0)return n}if(e instanceof Map){const n=e.get(t);if(typeof n=="string"&&n.length>0)return n}return String(t)}function Tc(t,e,n={}){const r=Math.max(0,Math.min(Math.floor(t?.count??0),Math.floor((t?.positions?.length??0)/2),t?.paletteIndices?.length??0,t?.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER));let i=null;if(t?.drawIndices instanceof Uint32Array){const d=t.drawIndices;let m=d.length;for(let g=0;g<d.length;g+=1)d[g]<r||(m-=1);if(m===d.length)i=d;else if(m>0){const g=new Uint32Array(m);let y=0;for(let b=0;b<d.length;b+=1){const x=d[b];x>=r||(g[y]=x,y+=1)}i=g}else i=new Uint32Array(0)}const o=i?i.length:r,s=Sc(e??[]);if(!t||o===0||s.length===0)return{groups:[],inputPointCount:o,pointsInsideAnyRegion:0,unmatchedPointCount:o};const a=new Map,l=new Map,u=Rc(s);let f=0;for(let d=0;d<o;d+=1){const m=i?i[d]:d,g=t.positions[m*2],y=t.positions[m*2+1];if(!Number.isFinite(g)||!Number.isFinite(y))continue;let b=null;const x=Ac(u,g,y);if(x.length===0)continue;for(const T of x){const M=s[T];let z=!1;for(const L of M.polygons)if(ti(g,y,L)){z=!0;break}z&&(!b||M.area<b.area)&&(b=M)}if(!b)continue;f+=1;const A=t.paletteIndices[m]??0,w=a.get(b.regionIndex)??new Map;w.set(A,(w.get(A)??0)+1),a.set(b.regionIndex,w),l.set(b.regionIndex,(l.get(b.regionIndex)??0)+1)}const c=n.includeEmptyRegions??!1,h=[];for(const d of s){const m=l.get(d.regionIndex)??0;if(!c&&m<=0)continue;const g=a.get(d.regionIndex)??new Map,y=Array.from(g.entries()).map(([b,x])=>({termId:Mc(b,n.paletteIndexToTermId),paletteIndex:b,count:x})).sort((b,x)=>x.count-b.count||b.paletteIndex-x.paletteIndex);h.push({regionId:d.regionId,regionIndex:d.regionIndex,totalCount:m,termCounts:y})}return{groups:h,inputPointCount:o,pointsInsideAnyRegion:f,unmatchedPointCount:Math.max(0,o-f)}}function Cc(t){return t.replace(/^\s*SRID\s*=\s*\d+\s*;\s*/i,"")}function vc(t){return t>="A"&&t<="Z"||t>="a"&&t<="z"}function Pc(t){return t>="0"&&t<="9"}function Zr(t){return t==="+"||t==="-"||t==="."||Pc(t)}class Ic{constructor(e){S(this,"text");S(this,"index",0);this.text=Cc(e.trim())}parse(){if(!this.text)return null;const e=this.readWord();if(!e)return null;const n=e.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=Vi(i);return s?{type:"Polygon",coordinates:s}:null}const o=Fc(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 e=this.index;for(;!this.isEof()&&vc(this.currentChar());)this.index+=1;return this.index===e?null:this.text.slice(e,this.index)}peekWord(){const e=this.index,n=this.readWord();return this.index=e,n}consumeWordIf(e){const n=this.index,r=this.readWord();return!r||r.toUpperCase()!==e.toUpperCase()?(this.index=n,!1):!0}parseNestedList(){if(this.skipWhitespace(),this.currentChar()!=="(")throw new Error("Expected '('");this.index+=1;const e=[];for(;;){this.skipWhitespace(),this.currentChar()==="("?e.push(this.parseNestedList()):e.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 e}parseCoordinateTuple(){this.skipWhitespace();const e=[];for(;;){this.skipWhitespace();const n=this.currentChar();if(!n||!Zr(n))break;const r=this.readNumber();if(r===null)break;e.push(r),this.skipWhitespace();const i=this.currentChar();if(!i||i===","||i===")")break;if(!Zr(i))throw new Error("Invalid coordinate")}if(e.length<2)throw new Error("Coordinate requires at least x y");return[e[0],e[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 _c(t){return Array.isArray(t)&&t.length>=2&&typeof t[0]=="number"&&Number.isFinite(t[0])&&typeof t[1]=="number"&&Number.isFinite(t[1])}function Vi(t){if(!Array.isArray(t))return null;const e=[];for(const n of t){if(!Array.isArray(n))return null;const r=[];for(const i of n){if(!_c(i))return null;r.push([i[0],i[1]])}e.push(r)}return e}function Fc(t){if(!Array.isArray(t))return null;const e=[];for(const n of t){const r=Vi(n);if(!r)return null;e.push(r)}return e}function Lc(t){return typeof t!="string"?null:new Ic(t).parse()}exports.DEFAULT_POINT_COLOR=Pn;exports.DrawLayer=di;exports.DrawingLayer=Hs;exports.HeatmapLayer=Ta;exports.M1TileRenderer=Kr;exports.OverlayLayer=va;exports.OverviewMap=Da;exports.PatchLayer=Ba;exports.PointLayer=al;exports.RegionLayer=xl;exports.TileScheduler=Ui;exports.TileViewerCanvas=wl;exports.WsiTileRenderer=Xi;exports.WsiViewer=wc;exports.__heatmapLayerInternals=Ca;exports.buildPointSpatialIndexAsync=ki;exports.buildTermPalette=Io;exports.calcScaleLength=vo;exports.calcScaleResolution=In;exports.clamp=_;exports.closeRing=Le;exports.computeRoiPointGroups=Tc;exports.createCircle=yn;exports.createRectangle=Zt;exports.createSpatialIndex=gi;exports.filterPointDataByPolygons=St;exports.filterPointDataByPolygonsHybrid=Li;exports.filterPointDataByPolygonsInWorker=Ni;exports.filterPointIndicesByPolygons=Ii;exports.filterPointIndicesByPolygonsInWorker=Ha;exports.getWebGpuCapabilities=Xa;exports.hexToRgba=ni;exports.isSameViewState=pn;exports.lookupCellIndex=Bi;exports.normalizeImageInfo=Ia;exports.parseWkt=Lc;exports.prefilterPointsByBoundsWebGpu=Fi;exports.terminatePointHitIndexWorker=nl;exports.terminateRoiClipWorker=Ga;exports.toBearerToken=Po;exports.toRoiGeometry=ut;exports.toTileUrl=Wn;exports.useViewerContext=it;
|
|
234
234
|
//# sourceMappingURL=index.cjs.map
|