open-plant 1.3.3 → 1.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +7 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1504 -1500
- package/dist/index.js.map +1 -1
- package/dist/types/index.d.ts +1 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/react/draw-layer-label.d.ts +3 -3
- package/dist/types/react/draw-layer-label.d.ts.map +1 -1
- package/dist/types/react/draw-layer-types.d.ts +2 -0
- package/dist/types/react/draw-layer-types.d.ts.map +1 -1
- package/dist/types/react/draw-layer.d.ts +2 -2
- package/dist/types/react/draw-layer.d.ts.map +1 -1
- package/dist/types/react/wsi-region-hit-utils.d.ts +2 -2
- package/dist/types/react/wsi-region-hit-utils.d.ts.map +1 -1
- package/dist/types/react/wsi-viewer-canvas.d.ts +3 -2
- package/dist/types/react/wsi-viewer-canvas.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var Ri=Object.defineProperty;var Ci=(e,t,n)=>t in e?Ri(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var S=(e,t,n)=>Ci(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ze=require("react/jsx-runtime"),d=require("react");var gt=typeof document<"u"?document.currentScript:null;function tr(e,t,n){const r=e.createShader(t);if(!r)throw new Error("Failed to create shader.");if(e.shaderSource(r,n),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS)){const o=e.getShaderInfoLog(r)??"unknown shader error";throw e.deleteShader(r),new Error(o)}return r}function Pn(e,t,n){const r=tr(e,e.VERTEX_SHADER,t),i=tr(e,e.FRAGMENT_SHADER,n),o=e.createProgram();if(!o)throw e.deleteShader(r),e.deleteShader(i),new Error("Failed to create program.");if(e.attachShader(o,r),e.attachShader(o,i),e.linkProgram(o),e.deleteShader(r),e.deleteShader(i),!e.getProgramParameter(o,e.LINK_STATUS)){const a=e.getProgramInfoLog(o)??"unknown link error";throw e.deleteProgram(o),new Error(a)}return o}function Pe(e,t,n){const r=e.getUniformLocation(t,n);if(!r)throw new Error(`Failed to get uniform location: ${n}`);return r}function Pi(e){const t=e.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,stencil:!1,preserveDrawingBuffer:!1,powerPreference:"high-performance"});if(!t)throw new Error("WebGL2 is not available.");return t}function un(e){return e*Math.PI/180}class Er{constructor(){S(this,"viewportWidth",1);S(this,"viewportHeight",1);S(this,"viewState",{offsetX:0,offsetY:0,zoom:1,rotationDeg:0})}setViewport(t,n){this.viewportWidth=Math.max(1,t),this.viewportHeight=Math.max(1,n)}getViewportSize(){return{width:this.viewportWidth,height:this.viewportHeight}}setViewState(t){t.offsetX!==void 0&&(this.viewState.offsetX=t.offsetX),t.offsetY!==void 0&&(this.viewState.offsetY=t.offsetY),t.zoom!==void 0&&(this.viewState.zoom=Math.max(1e-4,t.zoom)),typeof t.rotationDeg=="number"&&Number.isFinite(t.rotationDeg)&&(this.viewState.rotationDeg=t.rotationDeg)}getViewState(){return{...this.viewState}}getCenter(){const t=Math.max(1e-6,this.viewState.zoom);return[this.viewState.offsetX+this.viewportWidth/(2*t),this.viewState.offsetY+this.viewportHeight/(2*t)]}setCenter(t,n){const r=Math.max(1e-6,this.viewState.zoom);this.viewState.offsetX=t-this.viewportWidth/(2*r),this.viewState.offsetY=n-this.viewportHeight/(2*r)}screenToWorld(t,n){const r=Math.max(1e-6,this.viewState.zoom),[i,o]=this.getCenter(),s=this.viewState.rotationDeg??0,a=(t-this.viewportWidth*.5)/r,c=(n-this.viewportHeight*.5)/r,u=un(s),l=Math.cos(u),h=Math.sin(u);return[i+a*l-c*h,o+a*h+c*l]}worldToScreen(t,n){const r=Math.max(1e-6,this.viewState.zoom),[i,o]=this.getCenter(),s=this.viewState.rotationDeg??0,a=t-i,c=n-o,u=un(s),l=Math.cos(u),h=Math.sin(u),f=a*l+c*h,y=-a*h+c*l;return[this.viewportWidth*.5+f*r,this.viewportHeight*.5+y*r]}getViewCorners(){const t=this.viewportWidth,n=this.viewportHeight;return[this.screenToWorld(0,0),this.screenToWorld(t,0),this.screenToWorld(t,n),this.screenToWorld(0,n)]}getMatrix(){const t=Math.max(1e-6,this.viewState.zoom),n=this.viewState.rotationDeg??0;if(n===0){const b=this.viewportWidth/t,x=this.viewportHeight/t,w=2/b,A=-2/x,E=-1-this.viewState.offsetX*w,X=1-this.viewState.offsetY*A;return new Float32Array([w,0,0,0,A,0,E,X,1])}const[r,i]=this.getCenter(),o=un(n),s=Math.cos(o),a=Math.sin(o),c=2*t*s/this.viewportWidth,u=2*t*a/this.viewportWidth,l=2*t*a/this.viewportHeight,h=-2*t*s/this.viewportHeight,f=-(c*r+u*i),y=-(l*r+h*i);return new Float32Array([c,l,0,u,h,0,f,y,1])}}const Ii=`#version 300 es
|
|
2
2
|
precision highp float;
|
|
3
3
|
|
|
4
4
|
in vec2 aUnit;
|
|
@@ -18,7 +18,7 @@ void main() {
|
|
|
18
18
|
gl_Position = vec4(clip.xy, 0.0, 1.0);
|
|
19
19
|
vUv = aUv;
|
|
20
20
|
}
|
|
21
|
-
`,
|
|
21
|
+
`,Ei=`#version 300 es
|
|
22
22
|
precision highp float;
|
|
23
23
|
|
|
24
24
|
in vec2 vUv;
|
|
@@ -29,7 +29,7 @@ out vec4 outColor;
|
|
|
29
29
|
void main() {
|
|
30
30
|
outColor = texture(uTexture, vUv);
|
|
31
31
|
}
|
|
32
|
-
`;class Er{constructor(t){S(this,"canvas");S(this,"gl");S(this,"camera",new Ir);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=t.canvas,this.imageWidth=Math.max(1,t.imageWidth),this.imageHeight=Math.max(1,t.imageHeight),this.clearColor=t.clearColor??[.03,.05,.08,1],this.gl=Ci(this.canvas),this.program=Cn(this.gl,Pi,Ii);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=Ee(this.gl,this.program,"uCamera"),this.uBoundsLocation=Ee(this.gl,this.program,"uBounds"),this.uTextureLocation=Ee(this.gl,this.program,"uTexture"),t.initialViewState&&(this.controlledViewState=!0,this.camera.setViewState(t.initialViewState)),this.resizeObserver=new ResizeObserver(()=>{this.resize()}),this.resizeObserver.observe(this.canvas),this.resize()}async setTiles(t){if(this.destroyed)return;const n=++this.loadVersion,r=await Promise.all(t.map(async i=>await this.loadTile(i,n)));if(this.destroyed||n!==this.loadVersion){for(const i of r)i&&this.gl.deleteTexture(i.texture);return}this.disposeTiles(this.tiles),this.tiles=r.filter(i=>i!==null),this.requestRender()}setViewState(t){this.controlledViewState=!0,this.camera.setViewState(t),this.requestRender()}getViewState(){return this.camera.getViewState()}destroy(){this.destroyed||(this.destroyed=!0,this.loadVersion+=1,this.frameId!==null&&(cancelAnimationFrame(this.frameId),this.frameId=null),this.resizeObserver.disconnect(),this.disposeTiles(this.tiles),this.tiles=[],this.gl.deleteBuffer(this.quadBuffer),this.gl.deleteVertexArray(this.vao),this.gl.deleteProgram(this.program))}async loadTile(t,n){try{const r=await fetch(t.url);if(!r.ok)throw new Error(`Tile fetch failed: ${r.status} ${r.statusText}`);const i=await r.blob(),o=await createImageBitmap(i);if(this.destroyed||n!==this.loadVersion)return o.close(),null;const s=this.gl.createTexture();if(!s)throw o.close(),new Error("Failed to create tile texture.");return this.gl.bindTexture(this.gl.TEXTURE_2D,s),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,1),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),this.gl.bindTexture(this.gl.TEXTURE_2D,null),o.close(),{id:t.id,bounds:t.bounds,texture:s}}catch(r){return console.error(`[M1TileRenderer] tile load failed: ${t.id}`,r),null}}resize(){if(this.destroyed)return;const t=this.canvas.getBoundingClientRect(),n=Math.max(1,t.width||this.canvas.clientWidth||1),r=Math.max(1,t.height||this.canvas.clientHeight||1),i=Math.max(1,window.devicePixelRatio||1),o=Math.max(1,Math.round(n*i)),s=Math.max(1,Math.round(r*i));(this.canvas.width!==o||this.canvas.height!==s)&&(this.canvas.width=o,this.canvas.height=s),this.camera.setViewport(n,r),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),!this.fitted&&!this.controlledViewState&&(this.fitToImage(),this.fitted=!0),this.requestRender()}fitToImage(){const t=this.camera.getViewportSize(),n=Math.min(t.width/this.imageWidth,t.height/this.imageHeight),r=Number.isFinite(n)&&n>0?n:1,i=t.width/r,o=t.height/r,s=(this.imageWidth-i)*.5,a=(this.imageHeight-o)*.5;this.camera.setViewState({zoom:r,offsetX:s,offsetY:a})}requestRender(){this.frameId!==null||this.destroyed||(this.frameId=requestAnimationFrame(()=>{this.frameId=null,this.render()}))}render(){if(!this.destroyed){this.gl.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.useProgram(this.program),this.gl.bindVertexArray(this.vao),this.gl.uniformMatrix3fv(this.uCameraLocation,!1,this.camera.getMatrix()),this.gl.uniform1i(this.uTextureLocation,0);for(const t of this.tiles)this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,t.texture),this.gl.uniform4f(this.uBoundsLocation,t.bounds[0],t.bounds[1],t.bounds[2],t.bounds[3]),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindVertexArray(null)}}disposeTiles(t){for(const n of t)this.gl.deleteTexture(n.texture)}}function Pt(e){return e??null}function tr(e){return typeof e=="number"&&Number.isFinite(e)}function Ei(e){return Array.isArray(e)&&e.length>=2&&tr(e[0])&&tr(e[1])}function vr(e){return Array.isArray(e)&&e.length>0&&e.every(t=>Ei(t))}function _r(e){return Array.isArray(e)&&e.length>0&&e.every(t=>vr(t))}function vi(e){return Array.isArray(e)&&e.length>0&&e.every(t=>_r(t))}function ke(e){if(!Array.isArray(e)||e.length<3)return[];const t=[];for(const i of e){if(!Array.isArray(i)||i.length<2)continue;const o=Number(i[0]),s=Number(i[1]);if(!Number.isFinite(o)||!Number.isFinite(s))continue;const a=t[t.length-1];a&&a[0]===o&&a[1]===s||t.push([o,s])}if(t.length<3)return[];const n=t[0],r=t[t.length-1];return(n[0]!==r[0]||n[1]!==r[1])&&t.push([n[0],n[1]]),t.length>=4?t:[]}function At(e){if(!Array.isArray(e)||e.length<4)return 0;let t=0;for(let n=0;n<e.length-1;n+=1){const r=e[n],i=e[n+1];t+=r[0]*i[1]-i[0]*r[1]}return t*.5}function un(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const o of e){const s=ke(o);s.length>=4&&t.push(s)}if(t.length===0)return[];if(t.length===1)return[t[0]];let n=0,r=0;for(let o=0;o<t.length;o+=1){const s=Math.abs(At(t[o]));s<=r||(r=s,n=o)}const i=[t[n]];for(let o=0;o<t.length;o+=1)o!==n&&i.push(t[o]);return i}function Fr(e){if(!e)return[];if(vr(e)){const t=un([e]);return t.length>0?[t]:[]}if(_r(e)){const t=un(e);return t.length>0?[t]:[]}if(vi(e)){const t=[];for(const n of e){const r=un(n);r.length>0&&t.push(r)}return t}return[]}function nr(e,t,n){let r=!1;for(let i=0,o=n.length-1;i<n.length;o=i,i+=1){const s=n[i][0],a=n[i][1],c=n[o][0],u=n[o][1];a>t!=u>t&&e<(c-s)*(t-a)/(u-a||Number.EPSILON)+s&&(r=!r)}return r}function It(e){const t=[];for(const n of e??[]){const r=Fr(n);for(const i of r){const o=i[0];if(!o||o.length<4)continue;let s=1/0,a=1/0,c=-1/0,u=-1/0;for(const[h,f]of o)h<s&&(s=h),h>c&&(c=h),f<a&&(a=f),f>u&&(u=f);if(!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(c)||!Number.isFinite(u))continue;let l=Math.abs(At(o));for(let h=1;h<i.length;h+=1)l-=Math.abs(At(i[h]));t.push({outer:o,holes:i.slice(1),minX:s,minY:a,maxX:c,maxY:u,area:Math.max(1e-6,l)})}}return t}function Br(e,t,n){if(e<n.minX||e>n.maxX||t<n.minY||t>n.maxY||!nr(e,t,n.outer))return!1;for(const r of n.holes)if(nr(e,t,r))return!1;return!0}function Kt(e,t,n){for(const r of n)if(Br(e,t,r))return!0;return!1}const Pn=[160,160,160,255];function k(e,t,n){return Math.max(t,Math.min(n,e))}function In(e,t,n){const r=Number(e),i=Number(t),o=Number(n);return!Number.isFinite(r)||r<=0?1:!Number.isFinite(i)||!Number.isFinite(o)?r:Math.pow(2,i-o)*r}function _i(e,t,n){let i=100*In(e,t,n);if(Number(e)){let o="μm";return i>1e3&&(i/=1e3,o="mm"),`${i.toPrecision(3)} ${o}`}return`${Math.round(i*1e3)/1e3} pixels`}function fe(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function ct(e){const t=e.fillModes instanceof Uint8Array?e.fillModes.length:Number.MAX_SAFE_INTEGER;return Math.max(0,Math.min(Math.floor(e.count??0),Math.floor((e.positions?.length??0)/2),e.paletteIndices?.length??0,t))}function pn(e,t){return!e&&!t?!0:!e||!t?!1:Math.abs((e.zoom??0)-(t.zoom??0))<1e-6&&Math.abs((e.offsetX??0)-(t.offsetX??0))<1e-6&&Math.abs((e.offsetY??0)-(t.offsetY??0))<1e-6&&Math.abs((e.rotationDeg??0)-(t.rotationDeg??0))<1e-6}function Fi(e){const t=String(e??"").trim();if(!t)return"";if(/^bearer\s+/i.test(t)){const n=t.replace(/^bearer\s+/i,"").trim();return n?`Bearer ${n}`:""}return`Bearer ${t}`}function Ur(e){const n=String(e??"").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 Bi(e){const t=[[...Pn]],n=new Map;for(const i of e??[]){const o=String(i?.termId??"");!o||n.has(o)||(n.set(o,t.length),t.push(Ur(i?.termColor)))}const r=new Uint8Array(t.length*4);for(let i=0;i<t.length;i+=1)r[i*4]=t[i][0],r[i*4+1]=t[i][1],r[i*4+2]=t[i][2],r[i*4+3]=t[i][3];return{colors:r,termToPaletteIndex:n}}const Ui=.1,Li=4e6,Di=4096,ki=64,Ni=1,zi=4,Lr=1e-6,Oi=24;function Wi(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const n of e){if(!Array.isArray(n)||n.length<2)continue;const r=Number(n[0]),i=Number(n[1]);if(!Number.isFinite(r)||!Number.isFinite(i))continue;const o=t[t.length-1];o&&Math.abs(o[0]-r)<1e-9&&Math.abs(o[1]-i)<1e-9||t.push([r,i])}return t}function Yi(e,t,n){if(t<=Lr||n<8)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([e[0]+Math.cos(o)*t,e[1]+Math.sin(o)*t])}return ke(r)}function ln(e,t){if(!e.length)return[];let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,c]of e)a<n&&(n=a),a>i&&(i=a),c<r&&(r=c),c>o&&(o=c);if(!Number.isFinite(n)||!Number.isFinite(r))return[];const s=Math.max(t,1);return ke([[n-s,r-s],[i+s,r-s],[i+s,o+s],[n-s,o+s]])}function Xi(e,t){let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,c]of e)a<n&&(n=a),a>i&&(i=a),c<r&&(r=c),c>o&&(o=c);const s=Math.max(t,1);return[n-s,r-s,i+s,o+s]}function Vi(e,t,n){const r=Math.max(Ui,Number(n.minRasterStep)||0),i=Math.max(32768,Math.floor(n.maxRasterPixels||Li)),o=Math.max(256,Math.floor(n.maxRasterSize||Di)),s=Math.max(.001,e[2]-e[0]),a=Math.max(.001,e[3]-e[1]);let c=Math.max(r,Number.EPSILON),u=3,l=Math.ceil(s/c)+u*2+1,h=Math.ceil(a/c)+u*2+1;for(;(l>o||h>o||l*h>i)&&(c*=1.15,l=Math.ceil(s/c)+u*2+1,h=Math.ceil(a/c)+u*2+1,!(c>Math.max(s,a))););return l=Math.max(8,l),h=Math.max(8,h),{minX:e[0],minY:e[1],step:c,padding:u,width:l,height:h}}function Gi(e,t){if(typeof OffscreenCanvas<"u"){const r=new OffscreenCanvas(e,t).getContext("2d",{willReadFrequently:!0});if(r)return r}if(typeof document<"u"){const n=document.createElement("canvas");return n.width=e,n.height=t,n.getContext("2d",{willReadFrequently:!0})}return null}function qi(e,t){return[(e[0]-t.minX)/t.step+t.padding,(e[1]-t.minY)/t.step+t.padding]}function Hi(e,t,n){const r=Gi(n.width,n.height);if(!r)return new Uint8Array(0);r.clearRect(0,0,n.width,n.height),r.fillStyle="#ffffff",r.strokeStyle="#ffffff",r.lineCap="round",r.lineJoin="round",r.lineWidth=t*2/n.step;const i=e.map(a=>qi(a,n));if(i.length<=1){const a=i[0];if(!a)return new Uint8Array(0);r.beginPath(),r.arc(a[0],a[1],t/n.step,0,Math.PI*2),r.fill()}else{r.beginPath(),r.moveTo(i[0][0],i[0][1]);for(let a=1;a<i.length;a+=1)r.lineTo(i[a][0],i[a][1]);r.stroke()}const o=r.getImageData(0,0,n.width,n.height),s=new Uint8Array(n.width*n.height);for(let a=0;a<s.length;a+=1)s[a]=o.data[a*4+3]>=Oi?1:0;return s}function $i(e,t,n){const r=[],i=t+1,o=(a,c)=>c*i+a,s=(a,c)=>a>=0&&c>=0&&a<t&&c<n&&e[c*t+a]>0;for(let a=0;a<n;a+=1)for(let c=0;c<t;c+=1)s(c,a)&&(s(c,a-1)||r.push({start:o(c,a),end:o(c+1,a),dir:0}),s(c+1,a)||r.push({start:o(c+1,a),end:o(c+1,a+1),dir:1}),s(c,a+1)||r.push({start:o(c+1,a+1),end:o(c,a+1),dir:2}),s(c-1,a)||r.push({start:o(c,a+1),end:o(c,a),dir:3}));return r}function Zi(e,t){const n=(t-e+4)%4;return n===1?0:n===0?1:n===3?2:3}function Ki(e){if(!e.length)return[];const t=new Map;for(let i=0;i<e.length;i+=1){const o=t.get(e[i].start);o?o.push(i):t.set(e[i].start,[i])}const n=new Uint8Array(e.length),r=[];for(let i=0;i<e.length;i+=1){if(n[i])continue;const o=e[i],s=o.start;let a=o.end,c=o.dir;const u=[o.start,o.end];n[i]=1;let l=0;const h=e.length*3;for(;a!==s&&l<h;){const f=t.get(a);if(!f||f.length===0)break;let y=-1,b=1/0;for(const w of f){if(n[w])continue;const A=e[w],I=Zi(c,A.dir);I<b&&(b=I,y=w)}if(y<0)break;n[y]=1;const x=e[y];a=x.end,c=x.dir,u.push(a),l+=1}u.length>=4&&u[0]===u[u.length-1]&&r.push(u)}return r}function ji(e,t,n){const r=t+1,i=[];for(const o of e){const s=o%r,a=Math.floor(o/r);i.push([n.minX+(s-n.padding)*n.step,n.minY+(a-n.padding)*n.step])}return ke(i)}function Ji(e,t=1e-9){const n=ke(e);if(n.length<5)return n;const r=[n[0]];for(let i=1;i<n.length-1;i+=1){const o=r[r.length-1],s=n[i],a=n[i+1],c=(s[0]-o[0])*(a[1]-s[1])-(s[1]-o[1])*(a[0]-s[0]);Math.abs(c)<=t||r.push(s)}return r.push(r[0]),ke(r)}function Qi(e,t,n){const r=n[0]-t[0],i=n[1]-t[1],o=r*r+i*i;if(o<=1e-12){const h=e[0]-t[0],f=e[1]-t[1];return h*h+f*f}const s=k(((e[0]-t[0])*r+(e[1]-t[1])*i)/o,0,1),a=t[0]+r*s,c=t[1]+i*s,u=e[0]-a,l=e[1]-c;return u*u+l*l}function eo(e,t){if(e.length<=2||t<=0)return e.slice();const n=new Uint8Array(e.length);n[0]=1,n[e.length-1]=1;const r=t*t,i=[[0,e.length-1]];for(;i.length>0;){const s=i.pop();if(!s)break;const[a,c]=s;if(c-a<=1)continue;let u=0,l=-1;for(let h=a+1;h<c;h+=1){const f=Qi(e[h],e[a],e[c]);f>u&&(u=f,l=h)}l>=0&&u>r&&(n[l]=1,i.push([a,l],[l,c]))}const o=[];for(let s=0;s<e.length;s+=1)n[s]&&o.push(e[s]);return o}function to(e,t){const n=ke(e);if(n.length<5||t<=0)return n;const r=n.slice(0,-1),i=eo(r,t);return i.length<3?n:ke(i)}function no(e,t){let n=ke(e);if(t<=0||n.length<5)return n;for(let r=0;r<t;r+=1){const i=n.slice(0,-1);if(i.length<3)break;const o=[];for(let s=0;s<i.length;s+=1){const a=i[s],c=i[(s+1)%i.length];o.push([a[0]*.75+c[0]*.25,a[1]*.75+c[1]*.25],[a[0]*.25+c[0]*.75,a[1]*.25+c[1]*.75])}n=ke(o)}return n}function wt(e,t){return t?ke(e.map(([n,r])=>[k(n,t[0],t[2]),k(r,t[1],t[3])])):e}function ro(e,t){const n=Wi(e),r=Math.max(Lr,Number(t.radius)||0);if(n.length===0||!Number.isFinite(r))return[];const i=Math.max(12,Math.floor(t.circleSides||ki));if(n.length===1)return wt(Yi(n[0],r,i),t.clipBounds);const o=Xi(n,r),s=Vi(o,r,t),a=Hi(n,r,s);if(!a.length)return wt(ln(n,r),t.clipBounds);const c=$i(a,s.width,s.height),u=Ki(c);if(!u.length)return wt(ln(n,r),t.clipBounds);let l=[],h=0;for(const x of u){const w=ji(x,s.width,s),A=Math.abs(At(w));A<=h||(h=A,l=w)}if(!l.length)return wt(ln(n,r),t.clipBounds);const f=typeof t.simplifyTolerance=="number"&&Number.isFinite(t.simplifyTolerance)?Math.max(0,t.simplifyTolerance):s.step*.2,y=typeof t.smoothingPasses=="number"&&Number.isFinite(t.smoothingPasses)?Math.round(k(t.smoothingPasses,0,zi)):Ni,b=to(no(Ji(l,s.step*.001),y),f);return wt(b,t.clipBounds)}const Tt=[],rr=[],Je={color:"#ff4d4f",width:2,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},io={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},oo="rgba(23, 23, 25, 0.1)",so=6,ze={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},Qe={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},ir={x:16,y:-24},ao=20,or=1e-6,sr="transparent",co=3,uo=2,Dr=96,lo=1,ar=1e3,kr=2,Nr=2,fo=4096,ho=.2,mo=1.12,go=.89,po=32,bo="#000000",yo=.1,wo="#FFCF00",So="#FF0000",xo=1.5,cr=[2,2],Mo=1,Ao=.25,To=4,Ro=1,Co=0,Po=4,Io=.05,Eo=256,ur=1.5;function jt(e,t,n){return[k(e[0],0,t),k(e[1],0,n)]}function Jt(e){if(!Array.isArray(e)||e.length<2)return null;const t=Number(e[0]),n=Number(e[1]);return!Number.isFinite(t)||!Number.isFinite(n)?null:[t,n]}const at=Jt;function Fe(e){return ke(e)}function $t(e){return Math.abs(At(Fe(e)))}function lr(e){if(!Array.isArray(e)||e.length===0)return[0,0,0,0];let t=1/0,n=1/0,r=-1/0,i=-1/0;for(const[o,s]of e)o<t&&(t=o),o>r&&(r=o),s<n&&(n=s),s>i&&(i=s);return[t,n,r,i]}function bn(e,t,n=!1){if(t.length!==0){e.moveTo(t[0][0],t[0][1]);for(let r=1;r<t.length;r+=1)e.lineTo(t[r][0],t[r][1]);n&&e.closePath()}}function Ye(e,t,n,r=!1,i=!1,o="rgba(255, 77, 79, 0.16)"){t.length!==0&&(e.beginPath(),bn(e,t,r),i&&r&&(e.fillStyle=o,e.fill()),e.strokeStyle=n.color,e.lineWidth=n.width,e.lineJoin=n.lineJoin,e.lineCap=n.lineCap,e.shadowColor=n.shadowColor,e.shadowBlur=n.shadowBlur,e.shadowOffsetX=n.shadowOffsetX,e.shadowOffsetY=n.shadowOffsetY,e.setLineDash(n.lineDash),e.stroke(),e.setLineDash(Tt),e.shadowColor="rgba(0, 0, 0, 0)",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0)}function zr(e){const t=Array.isArray(e?.lineDash)?e.lineDash.filter(s=>Number.isFinite(s)&&s>=0):Tt,n=typeof e?.width=="number"&&Number.isFinite(e.width)?Math.max(0,e.width):Je.width,r=typeof e?.shadowBlur=="number"&&Number.isFinite(e.shadowBlur)?Math.max(0,e.shadowBlur):Je.shadowBlur,i=typeof e?.shadowOffsetX=="number"&&Number.isFinite(e.shadowOffsetX)?e.shadowOffsetX:Je.shadowOffsetX,o=typeof e?.shadowOffsetY=="number"&&Number.isFinite(e.shadowOffsetY)?e.shadowOffsetY:Je.shadowOffsetY;return{color:e?.color||Je.color,width:n,lineDash:t.length?t:Tt,lineJoin:e?.lineJoin||Je.lineJoin,lineCap:e?.lineCap||Je.lineCap,shadowColor:e?.shadowColor||Je.shadowColor,shadowBlur:r,shadowOffsetX:i,shadowOffsetY:o}}function St(e,t){return t?zr({color:t.color??e.color,width:t.width??e.width,lineDash:t.lineDash??e.lineDash,lineJoin:t.lineJoin??e.lineJoin,lineCap:t.lineCap??e.lineCap,shadowColor:t.shadowColor??e.shadowColor,shadowBlur:t.shadowBlur??e.shadowBlur,shadowOffsetX:t.shadowOffsetX??e.shadowOffsetX,shadowOffsetY:t.shadowOffsetY??e.shadowOffsetY}):e}function fr(e,t){return e==null||t===null||t===void 0?!1:String(e)===String(t)}function dr(e){return typeof e=="number"&&Number.isFinite(e)}function vo(e){return Array.isArray(e)&&e.length>=2&&dr(e[0])&&dr(e[1])}function _o(e){return Array.isArray(e)&&e.length>=2&&e.every(t=>vo(t))}function Or(e,t){if(!(!Array.isArray(e)||e.length===0)){if(_o(e)){t.push(e.map(([n,r])=>[n,r]));return}for(const n of e)Or(n,t)}}function hr(e,t){const n=[];Or(e,n);const r=[];for(const i of n){if(i.length<2)continue;const o=t?Fe(i):i;o.length>=(t?4:2)&&r.push(o)}return r}function Mt(e,t){return typeof e!="number"||!Number.isFinite(e)||e<=0?t:e}function Fo(e,t){return typeof e!="number"||!Number.isFinite(e)?t:k(e,0,1)}function Wr(e,t,n,r,i,o){const s=Math.max(0,Math.min(o,r*.5,i*.5));e.beginPath(),e.moveTo(t+s,n),e.lineTo(t+r-s,n),e.quadraticCurveTo(t+r,n,t+r,n+s),e.lineTo(t+r,n+i-s),e.quadraticCurveTo(t+r,n+i,t+r-s,n+i),e.lineTo(t+s,n+i),e.quadraticCurveTo(t,n+i,t,n+i-s),e.lineTo(t,n+s),e.quadraticCurveTo(t,n,t+s,n),e.closePath()}function Bo(e){const t=e[0];return Array.isArray(t)&&Array.isArray(t[0])}function Qt(e,t,n){if(!e||!t)return[];if(n){const r=n.worldToScreen(e[0],e[1]),i=n.worldToScreen(t[0],t[1]);if(r&&i){const o=[[r[0],r[1]],[i[0],r[1]],[i[0],i[1]],[r[0],i[1]]],s=[];for(const a of o){const c=n.screenToWorld(a);if(!c)return Qt(e,t);s.push(c)}return Fe(s)}}return Fe([[e[0],e[1]],[t[0],e[1]],[t[0],t[1]],[e[0],t[1]]])}function yn(e,t,n=Dr){if(!e||!t)return[];const r=(e[0]+t[0])*.5,i=(e[1]+t[1])*.5,o=Math.hypot(t[0]-e[0],t[1]-e[1])*.5;if(o<1)return[];const s=[];for(let a=0;a<=n;a+=1){const c=a/n*Math.PI*2;s.push([r+Math.cos(c)*o,i+Math.sin(c)*o])}return Fe(s)}function mr(e){const t=Fr(Pt(e));if(t.length===0)return[];const n=[];for(const r of t){const i=r[0];if(!i||i.length<4)continue;const o=i.map(([a,c])=>[a,c]),s=[];for(let a=1;a<r.length;a+=1){const c=r[a];!c||c.length<4||s.push(c.map(([u,l])=>[u,l]))}n.push({outer:o,holes:s})}return n}function Uo(e){if(!Array.isArray(e))return cr;const t=e.filter(n=>Number.isFinite(n)&&n>=0);return t.length>0?t:cr}function Lo(e){return typeof e!="number"||!Number.isFinite(e)?Mo:k(e,Ao,To)}function Do(e){return typeof e!="number"||!Number.isFinite(e)?Ro:Math.round(k(e,Co,Po))}function ko(e){const t=Mt(e?.radius,po),n=Mt(e?.cursorLineWidth,xo),r=Lo(e?.edgeDetail),i=Do(e?.edgeSmoothing);return{radius:t,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:e?.clickSelectRoi===!0,fillColor:e?.fillColor||bo,fillOpacity:Fo(e?.fillOpacity,yo),cursorColor:e?.cursorColor||wo,cursorActiveColor:e?.cursorActiveColor||So,cursorLineWidth:n,cursorLineDash:Uo(e?.cursorLineDash)}}function No(e,t,n){if(!t.isDrawing||t.screenPoints.length===0)return;const r=t.screenPoints;if(r.length===0)return;const i=n.radius;if(!(!Number.isFinite(i)||i<=0)){if(e.save(),e.globalAlpha=n.fillOpacity,e.fillStyle=n.fillColor,e.strokeStyle=n.fillColor,e.lineCap="round",e.lineJoin="round",e.lineWidth=i*2,r.length===1)e.beginPath(),e.arc(r[0][0],r[0][1],i,0,Math.PI*2),e.fill();else{e.beginPath(),e.moveTo(r[0][0],r[0][1]);for(let o=1;o<r.length;o+=1)e.lineTo(r[o][0],r[o][1]);e.stroke()}e.restore()}}function zo(e,t,n,r){const i=t.cursor;if(!i)return;const o=t.cursorScreen??at(n?.worldToScreen(i[0],i[1])??[]);if(!o)return;const s=r.radius;!Number.isFinite(s)||s<=0||(e.save(),e.beginPath(),e.arc(o[0],o[1],s,0,Math.PI*2),e.strokeStyle=t.isDrawing?r.cursorActiveColor:r.cursorColor,e.lineWidth=r.cursorLineWidth,e.setLineDash(r.cursorLineDash),e.stroke(),e.setLineDash(Tt),e.restore())}const Oo=.58,Wo=4096,Yo=.5;let Nt=null;const zt=new Map;function Xo(){if(Nt)return Nt;if(typeof document>"u")return null;const t=document.createElement("canvas").getContext("2d");return t?(Nt=t,Nt):null}function En(e,t){const n=`${t.fontWeight}|${t.fontSize}|${t.fontFamily}|${e}`,r=zt.get(n);if(r!==void 0)return r;const i=e.length*t.fontSize*Oo,o=Xo();let s=i;if(o){o.font=`${t.fontWeight} ${t.fontSize}px ${t.fontFamily}`;const a=o.measureText(e).width;Number.isFinite(a)&&a>=0&&(s=a)}return zt.size>Wo&&zt.clear(),zt.set(n,s),s}function Vo(e){if(!e.length)return null;let t=1/0;for(const i of e)i[1]<t&&(t=i[1]);if(!Number.isFinite(t))return null;let n=1/0,r=-1/0;for(const i of e)Math.abs(i[1]-t)>Yo||(i[0]<n&&(n=i[0]),i[0]>r&&(r=i[0]));return!Number.isFinite(n)||!Number.isFinite(r)?null:[(n+r)*.5,t]}function Yr(e){let t=null;for(const n of e){const r=Vo(n.outer);r&&(!t||r[1]<t[1]||r[1]===t[1]&&r[0]<t[0])&&(t=r)}return t}function vn(e){const t=typeof e?.paddingX=="number"&&Number.isFinite(e.paddingX)?Math.max(0,e.paddingX):ze.paddingX,n=typeof e?.paddingY=="number"&&Number.isFinite(e.paddingY)?Math.max(0,e.paddingY):ze.paddingY,r=typeof e?.fontSize=="number"&&Number.isFinite(e.fontSize)?Math.max(8,e.fontSize):ze.fontSize,i=typeof e?.borderWidth=="number"&&Number.isFinite(e.borderWidth)?Math.max(0,e.borderWidth):ze.borderWidth,o=typeof e?.offsetY=="number"&&Number.isFinite(e.offsetY)?e.offsetY:ze.offsetY,s=typeof e?.borderRadius=="number"&&Number.isFinite(e.borderRadius)?Math.max(0,e.borderRadius):ze.borderRadius;return{fontFamily:e?.fontFamily||ze.fontFamily,fontSize:r,fontWeight:e?.fontWeight||ze.fontWeight,textColor:e?.textColor||ze.textColor,backgroundColor:e?.backgroundColor||ze.backgroundColor,borderColor:e?.borderColor||ze.borderColor,borderWidth:i,paddingX:t,paddingY:n,offsetY:o,borderRadius:s}}function Xr(e,t){return t?vn({fontFamily:t.fontFamily??e.fontFamily,fontSize:t.fontSize??e.fontSize,fontWeight:t.fontWeight??e.fontWeight,textColor:t.textColor??e.textColor,backgroundColor:t.backgroundColor??e.backgroundColor,borderColor:t.borderColor??e.borderColor,borderWidth:t.borderWidth??e.borderWidth,paddingX:t.paddingX??e.paddingX,paddingY:t.paddingY??e.paddingY,offsetY:t.offsetY??e.offsetY,borderRadius:t.borderRadius??e.borderRadius}):e}function Vr(e,t,n){if(!e||!n)return 0;const r=Number(n.minZoom),i=Number(n.maxZoom);return!Number.isFinite(r)||!Number.isFinite(i)||i-r<=or||!Number.isFinite(t)?0:t>=i-or?ao:0}function Go(e){const t=typeof e?.fontSize=="number"&&Number.isFinite(e.fontSize)?Math.max(8,e.fontSize):Qe.fontSize,n=typeof e?.borderRadius=="number"&&Number.isFinite(e.borderRadius)?Math.max(0,e.borderRadius):Qe.borderRadius,r=typeof e?.paddingX=="number"&&Number.isFinite(e.paddingX)?Math.max(0,e.paddingX):Qe.paddingX,i=typeof e?.paddingY=="number"&&Number.isFinite(e.paddingY)?Math.max(0,e.paddingY):Qe.paddingY;return{fontFamily:e?.fontFamily||Qe.fontFamily,fontSize:t,fontWeight:e?.fontWeight||Qe.fontWeight,textColor:e?.textColor||Qe.textColor,backgroundColor:e?.backgroundColor||Qe.backgroundColor,borderRadius:n,paddingX:r,paddingY:i}}function qo(e){const t=typeof e?.x=="number"&&Number.isFinite(e.x)?e.x:ir.x,n=typeof e?.y=="number"&&Number.isFinite(e.y)?e.y:ir.y;return{x:t,y:n}}function Ho(e){return Number.isFinite(e)?`${Math.max(0,e).toFixed(3)} mm²`:"0.000 mm²"}function $o(e){const t=typeof e?.format=="function"?e.format:Ho,n=qo(e?.cursorOffset);return{enabled:e?.enabled===!0,format:t,style:Go(e?.style),cursorOffsetX:n.x,cursorOffsetY:n.y}}function Zo(e,t,n,r,i,o,s=!0){const a=t.trim();if(!a)return;e.save(),e.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,e.textAlign="center",e.textBaseline="middle";const u=En(a,o)+o.paddingX*2,l=o.fontSize+o.paddingY*2,h=n[0],f=n[1]-o.offsetY,y=s?k(h,u*.5+1,r-u*.5-1):h,b=s?k(f,l*.5+1,i-l*.5-1):f,x=y-u*.5,w=b-l*.5;e.fillStyle=o.backgroundColor,e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,Wr(e,x,w,u,l,o.borderRadius),e.fill(),o.borderWidth>0&&e.stroke(),e.fillStyle=o.textColor,e.fillText(a,y,b+.5),e.restore()}function Ko(e,t,n,r,i,o,s,a){const c=t.trim();if(!c)return;e.save(),e.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,e.textAlign="center",e.textBaseline="middle";const l=En(c,o)+o.paddingX*2,h=o.fontSize+o.paddingY*2,f=k(n[0]+s,l*.5+1,r-l*.5-1),y=k(n[1]+a,h*.5+1,i-h*.5-1),b=f-l*.5,x=y-h*.5;e.fillStyle=o.backgroundColor,Wr(e,b,x,l,h,o.borderRadius),e.fill(),e.fillStyle=o.textColor,e.fillText(c,f,y+.5),e.restore()}function jo(e,t,n,r){if(!(t.length<4||n.length===0)){e.save(),e.beginPath(),bn(e,t,!0);for(const i of n)i.length<4||bn(e,i,!0);e.fillStyle=r,e.fill("evenodd"),e.restore()}}function Jo(e){const{ctx:t,overlayShapes:n,imageOuterRing:r,worldToScreenPoints:i,baseStrokeStyle:o,onInvertedFillDebug:s}=e,a=!!globalThis.__OPEN_PLANT_DEBUG_OVERLAY__;for(let c=0;c<n.length;c+=1){const u=n[c];if(!u?.coordinates?.length||u.visible===!1)continue;const l=u.closed??Bo(u.coordinates),h=hr(u.coordinates,l);if(u.invertedFill?.fillColor){const y=[],b=hr(u.coordinates,!0);for(const x of b){const w=i(x);w.length>=4&&y.push(w)}a&&s&&s({id:u.id??c,outerRingPoints:r.length,sourceRingCount:b.length,holeRingCount:y.length,fillColor:u.invertedFill.fillColor}),jo(t,r,y,u.invertedFill.fillColor)}if(h.length===0)continue;const f=St(o,u.stroke??u.strokeStyle);for(const y of h){const b=i(y);b.length<2||Ye(t,b,f,l,u.fill??!1)}}}function Ot(e){return e==="stamp-rectangle"||e==="stamp-circle"||e==="stamp-rectangle-4096px"||e==="stamp-rectangle-2mm2"||e==="stamp-circle-2mm2"||e==="stamp-circle-hpf-0.2mm2"}function Qo(e){return{rectangleAreaMm2:Mt(e?.rectangleAreaMm2,kr),circleAreaMm2:Mt(e?.circleAreaMm2,Nr),rectanglePixelSize:Mt(e?.rectanglePixelSize,fo)}}const gr=1e3;function es(e){return e*gr*gr}function pr(e,t,n){if(!e||!Number.isFinite(t)||t<=0)return[];if(n){const r=n.worldToScreen(e[0],e[1]),i=n.worldToScreen(e[0]+t,e[1]);if(r&&i){const o=Math.hypot(i[0]-r[0],i[1]-r[1]),s=[[r[0]-o,r[1]-o],[r[0]+o,r[1]-o],[r[0]+o,r[1]+o],[r[0]-o,r[1]+o]],a=[];for(const c of s){const u=n.screenToWorld(c);if(!u)throw new Error("Failed to create rectangle");a.push(u)}return Fe(a)}}return Fe([[e[0]-t,e[1]-t],[e[0]+t,e[1]-t],[e[0]+t,e[1]+t],[e[0]-t,e[1]+t]])}function ts(e,t,n=Dr){if(!e||!Number.isFinite(t)||t<=0)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([e[0]+Math.cos(o)*t,e[1]+Math.sin(o)*t])}return Fe(r)}function ns(e){const{stampTool:t,center:n,resolvedStampOptions:r,imageWidth:i,imageHeight:o,micronsToWorldPixels:s,getRectangleProjection:a}=e;if(!n)return[];if(t==="stamp-rectangle-4096px"){const h=r.rectanglePixelSize*.5;return pr(n,h,a()).map(f=>jt(f,i,o))}let c=0;if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"?c=t==="stamp-rectangle-2mm2"?kr:r.rectangleAreaMm2:(t==="stamp-circle"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2")&&(c=t==="stamp-circle-hpf-0.2mm2"?ho:t==="stamp-circle-2mm2"?Nr:r.circleAreaMm2),!Number.isFinite(c)||c<=0)return[];const u=es(c);let l=[];if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"){const h=s(Math.sqrt(u)*.5);l=pr(n,h,a())}else if(t==="stamp-circle"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2"){const h=s(Math.sqrt(u/Math.PI));l=ts(n,h)}return l.length?l.map(h=>jt(h,i,o)):[]}function rs(e){return{color:oo,width:so,lineDash:Tt,lineJoin:e.lineJoin,lineCap:e.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function is(e){if(typeof e!="string")return sr;const t=e.trim();return t.length>0?t:sr}function br(e){return Array.isArray(e)&&e.length>=4&&$t(e)>lo}function Gr({tool:e,imageWidth:t,imageHeight:n,imageMpp:r,imageZoom:i,stampOptions:o,brushOptions:s,projectorRef:a,onBrushTap:c,onDrawComplete:u,onPatchComplete:l,enabled:h,viewStateSignal:f,persistedRegions:y,patchRegions:b,persistedPolygons:x,drawFillColor:w,regionStrokeStyle:A,regionStrokeHoverStyle:I,regionStrokeActiveStyle:X,patchStrokeStyle:R,resolveRegionStrokeStyle:_,resolveRegionLabelStyle:H,overlayShapes:ae,hoveredRegionId:te=null,activeRegionId:ne=null,regionLabelStyle:ce,drawAreaTooltip:he,autoLiftRegionLabelAtMaxZoom:Pe=!1,clampRegionLabelToViewport:B=!0,regionLabelAutoLiftOffsetPx:U,invalidateRef:z,className:D,style:J}){const be=d.useRef(null),Me=d.useRef(!1),Xe=d.useRef(new Map),Be=d.useRef(e),ye=d.useRef({isDrawing:!1,pointerId:null,start:null,current:null,cursor:null,cursorScreen:null,points:[],screenPoints:[],stampCenter:null}),M=h??e!=="cursor",E=d.useMemo(()=>y&&y.length>0?y:!x||x.length===0?rr:x.map((m,g)=>({id:g,coordinates:m})),[y,x]),O=d.useMemo(()=>b??rr,[b]),oe=d.useMemo(()=>{const m=[];for(let g=0;g<E.length;g+=1){const T=E[g],P=mr(T.coordinates);P.length!==0&&m.push({region:T,regionIndex:g,regionKey:T.id??g,polygons:P})}return m},[E]),j=d.useMemo(()=>{const m=[];for(let g=0;g<O.length;g+=1){const T=O[g],P=mr(T.coordinates);P.length!==0&&m.push({region:T,regionIndex:g,regionKey:T.id??g,polygons:P})}return m},[O]),Q=d.useMemo(()=>zr(A),[A]),Ae=d.useMemo(()=>St(Q,I),[Q,I]),ge=d.useMemo(()=>St(Q,X),[Q,X]),Z=d.useMemo(()=>St(io,R),[R]),re=d.useMemo(()=>is(w),[w]),pe=d.useMemo(()=>vn(ce),[ce]),G=d.useMemo(()=>$o(he),[he]),me=d.useMemo(()=>Qo(o),[o]),K=d.useMemo(()=>ko(s),[s]),we=d.useMemo(()=>({position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",touchAction:"none",pointerEvents:M?"auto":"none",cursor:M?e==="brush"?"none":"crosshair":"default",...J}),[M,e,J]),ee=d.useCallback(()=>{const m=be.current;if(!m)return;const g=m.getBoundingClientRect(),T=Math.max(1,window.devicePixelRatio||1),P=Math.max(1,Math.round(g.width*T)),v=Math.max(1,Math.round(g.height*T));(m.width!==P||m.height!==v)&&(m.width=P,m.height=v)},[]),le=d.useCallback(m=>{const g=a.current;if(!g||m.length===0)return[];const T=new Array(m.length);for(let P=0;P<m.length;P+=1){const v=at(g.worldToScreen(m[P][0],m[P][1]));if(!v)return[];T[P]=v}return T},[a]),Ue=d.useCallback(m=>{const g=a.current,T=be.current;if(!g||!T)return null;const P=T.getBoundingClientRect(),v=at(g.screenToWorld(P.left+m[0],P.top+m[1]));return v?jt(v,t,n):null},[a,t,n]),Te=d.useCallback(()=>{const m=a.current,g=m?.getViewState?.().rotationDeg??0;if(!(Math.abs(g%360)<.01||!m))return{worldToScreen:(T,P)=>at(m.worldToScreen(T,P)),screenToWorld:Ue}},[a,Ue]),Ve=d.useCallback(m=>{if(!Number.isFinite(m)||m<=0)return 0;const g=typeof r=="number"&&Number.isFinite(r)&&r>0?r:1,T=typeof i=="number"&&Number.isFinite(i)?i:0,P=a.current?.getViewState?.().zoom,v=typeof P=="number"&&Number.isFinite(P)&&P>0?P:1,de=T+Math.log2(v),V=Math.max(1e-9,In(g,T,de));return m/V/v},[r,i,a]),xe=d.useCallback((m,g)=>ns({stampTool:m,center:g,resolvedStampOptions:me,imageWidth:t,imageHeight:n,micronsToWorldPixels:Ve,getRectangleProjection:Te}),[Ve,t,n,me,Te]),Le=d.useCallback(()=>{const m=ye.current;return Ot(e)?xe(e,m.stampCenter):e==="brush"?[]:m.isDrawing?e==="freehand"?m.points:e==="rectangle"?Qt(m.start,m.current,Te()):e==="circular"?yn(m.start,m.current):[]:[]},[e,xe,Te]),ut=d.useCallback(()=>{ee();const m=be.current;if(!m)return;const g=m.getContext("2d");if(!g)return;const T=Math.max(1,window.devicePixelRatio||1),P=m.width/T,v=m.height/T;if(g.setTransform(1,0,0,1,0,0),g.clearRect(0,0,m.width,m.height),g.setTransform(T,0,0,T,0,0),oe.length>0)for(const V of oe){const{region:se,polygons:q,regionIndex:ie,regionKey:Se}=V,Ie=fr(ne,Se)?"active":fr(te,Se)?"hover":"default";let De=Ie==="active"?ge:Ie==="hover"?Ae:Q;if(_){const qe=_({region:se,regionId:Se,regionIndex:ie,state:Ie});De=St(De,qe||void 0)}const nt=Ie==="default"?null:rs(De);for(const qe of q){const bt=le(qe.outer);bt.length>=4&&(nt&&Ye(g,bt,nt,!0,!1),Ye(g,bt,De,!0,!1));for(const yt of qe.holes){const He=le(yt);He.length>=4&&(nt&&Ye(g,He,nt,!0,!1),Ye(g,He,De,!0,!1))}}}if(j.length>0)for(const V of j)for(const se of V.polygons){const q=le(se.outer);q.length>=4&&Ye(g,q,Z,!0,!1);for(const ie of se.holes){const Se=le(ie);Se.length>=4&&Ye(g,Se,Z,!0,!1)}}if(Array.isArray(ae)&&ae.length>0){const V=le(Fe([[0,0],[t,0],[t,n],[0,n]]));Jo({ctx:g,overlayShapes:ae,imageOuterRing:V,worldToScreenPoints:le,baseStrokeStyle:Q,onInvertedFillDebug:globalThis.__OPEN_PLANT_DEBUG_OVERLAY__?se=>{const q=String(se.id),ie=`${se.outerRingPoints}|${se.sourceRingCount}|${se.holeRingCount}|${se.fillColor}`;Xe.current.get(q)!==ie&&(Xe.current.set(q,ie),console.debug("[open-plant] invertedFill",se))}:void 0})}const de=Le();if(M){if(e==="brush")No(g,ye.current,K),zo(g,ye.current,a.current,K);else if(de.length>0)if(e==="freehand"){const V=le(de);V.length>=2&&Ye(g,V,Q,!1,!1),V.length>=3&&Ye(g,le(Fe(de)),Q,!0,!0,re)}else{const V=le(de);V.length>=4&&Ye(g,V,Q,!0,!0,re)}}if(oe.length>0){const V=Math.max(1e-6,a.current?.getViewState?.().zoom??1),se=typeof U=="number"&&Number.isFinite(U)?Math.max(0,U):Vr(Pe,V,a.current?.getZoomRange?.());for(const q of oe){if(!q.region.label)continue;const ie=Yr(q.polygons);if(!ie)continue;const Se=at(a.current?.worldToScreen(ie[0],ie[1])??[]);if(!Se)continue;let Ie=Xr(pe,H?.({region:q.region,regionId:q.regionKey,regionIndex:q.regionIndex,zoom:V}));se>0&&(Ie={...Ie,offsetY:Ie.offsetY+se}),Zo(g,q.region.label,Se,P,v,Ie,B)}}if(G.enabled&&M&&(e==="freehand"||e==="rectangle"||e==="circular")){const V=ye.current;if(V.isDrawing){const se=e==="freehand"?Fe(de):de;if(se.length>=4){const q=$t(se),ie=typeof r=="number"&&Number.isFinite(r)&&r>0?r:0,Se=ie>0?q*ie*ie/(ar*ar):0,Ie=G.format(Se),De=V.cursorScreen??(V.current?at(a.current?.worldToScreen(V.current[0],V.current[1])??[]):null);De&&Ko(g,Ie,De,P,v,G.style,G.cursorOffsetX,G.cursorOffsetY)}}}},[M,e,Le,ee,le,t,n,a,oe,ae,te,ne,Q,Ae,ge,re,j,Z,_,H,pe,G,Pe,B,U,r,K]),Y=d.useCallback(()=>{Me.current||(Me.current=!0,requestAnimationFrame(()=>{Me.current=!1,ut()}))},[ut]),W=d.useCallback((m=!1)=>{const g=ye.current,T=be.current;T&&g.pointerId!==null&&T.hasPointerCapture(g.pointerId)&&T.releasePointerCapture(g.pointerId),g.isDrawing=!1,g.pointerId=null,g.start=null,g.current=null,g.points=[],g.screenPoints=[],g.stampCenter=null,m||(g.cursor=null,g.cursorScreen=null)},[]),Re=d.useCallback(m=>{const g=a.current;if(!g||t<=0||n<=0)return null;const T=at(g.screenToWorld(m.clientX,m.clientY));return T?jt(T,t,n):null},[a,t,n]),ue=d.useCallback(m=>{const g=be.current;if(!g)return null;const T=g.getBoundingClientRect(),P=k(m.clientX-T.left,0,T.width),v=k(m.clientY-T.top,0,T.height);return!Number.isFinite(P)||!Number.isFinite(v)?null:[P,v]},[]),Ce=d.useCallback(()=>{const m=ye.current;if(!m.isDrawing){W(!0),Y();return}let g=[];if(e==="freehand")m.points.length>=co&&(g=Fe(m.points));else if(e==="rectangle")g=Qt(m.start,m.current,Te());else if(e==="circular")g=yn(m.start,m.current);else if(e==="brush"){const T=m.points[m.points.length-1]??m.current??m.start;if(K.clickSelectRoi&&T&&m.points.length<=1&&c?.(T)){W(!0),Y();return}const P=K.edgeDetail,v=Math.max(Io,K.radius*2/(Eo*P)),de=m.screenPoints.length>0?m.screenPoints:le(m.points),V=ro(de,{radius:K.radius,minRasterStep:v,circleSides:Math.max(24,Math.round(64*P)),simplifyTolerance:v*.25,smoothingPasses:K.edgeSmoothing}),se=[];for(const q of V){const ie=Ue(q);ie&&se.push(ie)}g=Fe(se)}(e==="freehand"||e==="rectangle"||e==="circular"||e==="brush")&&br(g)&&u&&u({tool:e,intent:e==="brush"?"brush":"roi",coordinates:g,bbox:lr(g),areaPx:$t(g)}),W(!0),Y()},[e,u,W,Y,le,Ue,Te,K.radius,K.edgeDetail,K.edgeSmoothing,K.clickSelectRoi,c]),pt=d.useCallback((m,g)=>{const T=xe(m,g);if(!br(T))return;const P=m==="stamp-rectangle-4096px"?"patch":"roi",v={tool:m,intent:P,coordinates:T,bbox:lr(T),areaPx:$t(T)};u?.(v),P==="patch"&&l&&l(v)},[xe,u,l]),et=d.useCallback((m,g,T)=>{const P=ur*ur,v=m.screenPoints[m.screenPoints.length-1];if(!v){m.points.push(g),m.screenPoints.push(T),m.current=g;return}const de=T[0]-v[0],V=T[1]-v[1];de*de+V*V>=P?(m.points.push(g),m.screenPoints.push(T)):(m.points[m.points.length-1]=g,m.screenPoints[m.screenPoints.length-1]=T),m.current=g},[]),Et=d.useCallback(m=>{if(!M||e==="cursor"||m.button!==0)return;const g=Re(m);if(!g)return;const T=ue(m);if(!T)return;if(m.preventDefault(),m.stopPropagation(),Ot(e)){const de=ye.current;de.stampCenter=g,pt(e,g),Y();return}const P=be.current;P&&P.setPointerCapture(m.pointerId);const v=ye.current;v.isDrawing=!0,v.pointerId=m.pointerId,v.start=g,v.current=g,v.cursor=g,v.cursorScreen=T,v.points=e==="freehand"||e==="brush"?[g]:[],v.screenPoints=e==="brush"?[T]:[],Y()},[M,e,Re,ue,pt,Y]),tt=d.useCallback(m=>{if(!M||e==="cursor")return;const g=Re(m);if(!g)return;const T=ue(m);if(!T)return;const P=ye.current;if(P.cursor=g,P.cursorScreen=T,Ot(e)){P.stampCenter=g,m.preventDefault(),m.stopPropagation(),Y();return}if(e==="brush"){if(!P.isDrawing||P.pointerId!==m.pointerId){Y();return}m.preventDefault(),m.stopPropagation(),et(P,g,T),Y();return}if(!(!P.isDrawing||P.pointerId!==m.pointerId)){if(m.preventDefault(),m.stopPropagation(),e==="freehand"){const v=a.current,de=Math.max(1e-6,v?.getViewState?.().zoom??1),V=uo/de,se=V*V,q=P.points[P.points.length-1];if(!q)P.points.push(g);else{const ie=g[0]-q[0],Se=g[1]-q[1];ie*ie+Se*Se>=se&&P.points.push(g)}}else P.current=g;Y()}},[M,e,Re,ue,Y,a,et]),vt=d.useCallback(m=>{const g=ye.current;if(!g.isDrawing||g.pointerId!==m.pointerId)return;m.preventDefault(),m.stopPropagation();const T=Re(m),P=ue(m);T&&(g.cursor=T,P&&(g.cursorScreen=P),e==="brush"?P&&et(g,T,P):g.current=T);const v=be.current;v&&v.hasPointerCapture(m.pointerId)&&v.releasePointerCapture(m.pointerId),Ce()},[Ce,Re,ue,e,et]),_t=d.useCallback(()=>{const m=ye.current;let g=!1;e==="brush"&&!m.isDrawing&&m.cursor&&(m.cursor=null,m.cursorScreen=null,g=!0),Ot(e)&&m.stampCenter&&(m.stampCenter=null,g=!0),g&&Y()},[e,Y]);return d.useEffect(()=>{ee(),Y();const m=be.current;if(!m)return;const g=new ResizeObserver(()=>{ee(),Y()});return g.observe(m),()=>{g.disconnect()}},[ee,Y]),d.useEffect(()=>{M||W(),Y()},[M,Y,W]),d.useEffect(()=>{Be.current!==e&&(Be.current=e,W(),Y())},[e,W,Y]),d.useEffect(()=>{Y()},[f,E,ae,Y]),d.useEffect(()=>{if(z)return z.current=Y,()=>{z.current===Y&&(z.current=null)}},[z,Y]),d.useEffect(()=>{if(!M)return;const m=g=>{g.key==="Escape"&&(W(),Y())};return window.addEventListener("keydown",m),()=>{window.removeEventListener("keydown",m)}},[M,W,Y]),Oe.jsx("canvas",{ref:be,className:D,style:we,onPointerDown:Et,onPointerMove:tt,onPointerUp:vt,onPointerCancel:vt,onPointerLeave:_t,onContextMenu:m=>{M&&m.preventDefault()},onWheel:m=>{if(!M)return;const g=be.current,T=a.current;if(!g||typeof T?.zoomBy!="function")return;m.preventDefault(),m.stopPropagation();const P=g.getBoundingClientRect(),v=m.clientX-P.left,de=m.clientY-P.top;T.zoomBy(m.deltaY<0?mo:go,v,de),Y()}})}function yr(e){return String(e??"").replace(/\/+$/,"")}function qr(e){const t=String(e??"");return t.startsWith("/")?t:`/${t}`}function os(e){const t=yr(e);if(!t)return"";if(/\/TileGroup\d+$/i.test(t))return t;let n=null;try{n=new URL(t)}catch{n=null}if(n){const r=`${n.protocol}//${n.host}`,i=yr(n.pathname||"");return/\/ims$/i.test(i)?`${r}${i}`:/\/tiles$/i.test(i)?`${r}${i}`:`${r}${i}/tiles`}return/\/ims$/i.test(t)?"/ims":/\/tiles$/i.test(t)?`${t}`:`${t}/tiles`}function ss(e,t){const n=e?.imsInfo??{},r=!!e?.imsInfo,i=Number(n.width??e?.width??0),o=Number(n.height??e?.height??0),s=Number(n.tileSize??e?.tileSize??0),a=Number(n.zoom??e?.zoom??0),c=String(n.path??e?.path??""),u=Number(n.mpp??e?.mpp??0);if(!i||!o||!s||!c)throw new Error("Incomplete image metadata: width/height/tileSize/path required");const l=Array.isArray(e?.terms)?e.terms.map(b=>({termId:String(b?.termId??""),termName:String(b?.termName??""),termColor:String(b?.termColor??"")})):[],h=qr(c),f=os(t),y=r?(b,x,w)=>`${f}${h}/${b}/${w}_${x}.webp`:void 0;return{id:e?._id||"unknown",name:e?.name||"unknown",width:i,height:o,mpp:Number.isFinite(u)&&u>0?u:void 0,tileSize:s,maxTierZoom:Number.isFinite(a)?Math.max(0,Math.floor(a)):0,tilePath:c,tileBaseUrl:t,terms:l,tileUrlBuilder:y}}function _n(e,t,n,r){if(e.tileUrlBuilder)return e.tileUrlBuilder(t,n,r);const i=qr(e.tilePath);return`${e.tileBaseUrl}${i}/${t}/${r}_${n}.webp`}const _e={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:"#171719",viewportBorderStyle:"dash",viewportFillColor:"transparent",interactive:!0,showThumbnail:!0,maxThumbnailTiles:16};function wr(e,t,n,r){const i=t.length;if(i===4){for(let o=0;o<i;o+=1){const s=t[o],a=t[(o+1)%i],c=Math.hypot(a[0]-s[0],a[1]-s[1]);if(c<1e-6)continue;const u=Math.max(1,Math.round((c+r)/(n+r))),l=u*n+(u-1)*r,h=c/Math.max(1e-6,l),f=n*h,y=r*h;e.beginPath(),e.moveTo(s[0],s[1]),e.lineTo(a[0],a[1]),e.setLineDash([f,y]),e.lineDashOffset=0,e.stroke()}e.setLineDash([]),e.lineDashOffset=0}}function mt(e,t,n=1){return typeof e!="number"||!Number.isFinite(e)?t:Math.max(n,e)}function Wt(e){return Array.isArray(e)&&e.length===4&&Number.isFinite(e[0])&&Number.isFinite(e[1])&&Number.isFinite(e[2])&&Number.isFinite(e[3])}const as={position:"absolute",top:4,right:4,zIndex:1,width:18,height:18,borderRadius:999,border:"1px solid rgba(255,255,255,0.4)",background:"rgba(16, 17, 19, 0.85)",color:"#fff",fontSize:12,lineHeight:1,cursor:"pointer",padding:0,display:"flex",alignItems:"center",justifyContent:"center"};function Hr({source:e,projectorRef:t,authToken:n="",options:r,invalidateRef:i,className:o,style:s}){const a=d.useRef(null),c=d.useRef(null),u=d.useRef(null),l=d.useRef({active:!1,pointerId:null}),h=d.useRef(null),f=d.useRef(!1),y=mt(r?.width,_e.width,64),b=mt(r?.height,_e.height,48),x=d.useMemo(()=>{const M=Math.max(1,e.width),E=Math.max(1,e.height),O=M/E,oe=y/b;let j,Q;return O>oe?(j=y,Q=y/O):(Q=b,j=b*O),{x:(y-j)/2,y:(b-Q)/2,w:j,h:Q}},[e.width,e.height,y,b]),w=mt(r?.margin,_e.margin,0),A=mt(r?.borderRadius,_e.borderRadius,0),I=mt(r?.borderWidth,_e.borderWidth,0),X=Math.max(1,Math.round(mt(r?.maxThumbnailTiles,_e.maxThumbnailTiles,1))),R=r?.backgroundColor||_e.backgroundColor,_=r?.borderColor||_e.borderColor,H=r?.viewportBorderColor||_e.viewportBorderColor,ae=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:_e.viewportBorderStyle,te=r?.viewportFillColor??_e.viewportFillColor,ne=r?.interactive??_e.interactive,ce=r?.showThumbnail??_e.showThumbnail,he=r?.position||_e.position,Pe=r?.onClose,B=r?.closeIcon,U=r?.closeButtonStyle,z=d.useMemo(()=>{const M={};return he==="top-left"||he==="bottom-left"?M.left=w:M.right=w,he==="top-left"||he==="top-right"?M.top=w:M.bottom=w,{position:"absolute",...M,width:y,height:b,borderRadius:A,overflow:"hidden",zIndex:4,pointerEvents:ne?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[w,he,y,b,A,ne,s]),D=d.useCallback(()=>{const M=a.current;if(!M)return;const E=M.getContext("2d");if(!E)return;const O=y,oe=b,j=Math.max(1,window.devicePixelRatio||1),Q=Math.max(1,Math.round(O*j)),Ae=Math.max(1,Math.round(oe*j));(M.width!==Q||M.height!==Ae)&&(M.width=Q,M.height=Ae),E.setTransform(1,0,0,1,0,0),E.clearRect(0,0,M.width,M.height),E.setTransform(j,0,0,j,0,0),E.fillStyle=R,E.fillRect(0,0,O,oe);const{x:ge,y:Z,w:re,h:pe}=x,G=c.current;G&&E.drawImage(G,ge,Z,re,pe),E.strokeStyle=_,E.lineWidth=I,E.strokeRect(I*.5,I*.5,O-I,oe-I);const me=t.current,K=me?.getViewBounds?.(),we=me?.getViewCorners?.(),ee=Wt(K)?K:Wt(u.current)?u.current:null;if(!ee)return;u.current=ee;const le=re/Math.max(1,e.width),Ue=pe/Math.max(1,e.height),Te=Array.isArray(we)&&we.length>=4&&we.every(ue=>Array.isArray(ue)&&ue.length>=2&&Number.isFinite(ue[0])&&Number.isFinite(ue[1]))?we:null,Ve=ae==="dash";if(Te){const ue=Te.map(Ce=>[ge+Ce[0]*le,Z+Ce[1]*Ue]);E.save(),E.beginPath(),E.rect(ge,Z,re,pe),E.clip(),E.beginPath();for(let Ce=0;Ce<ue.length;Ce+=1)Ce===0?E.moveTo(ue[Ce][0],ue[Ce][1]):E.lineTo(ue[Ce][0],ue[Ce][1]);E.closePath(),E.fillStyle=te,E.fill(),E.strokeStyle=H,E.lineWidth=2.25,Ve?wr(E,ue,4,3):E.stroke(),E.restore();return}const xe=k(ge+ee[0]*le,ge,ge+re),Le=k(Z+ee[1]*Ue,Z,Z+pe),ut=k(ge+ee[2]*le,ge,ge+re),Y=k(Z+ee[3]*Ue,Z,Z+pe),W=Math.max(1,ut-xe),Re=Math.max(1,Y-Le);if(E.fillStyle=te,E.fillRect(xe,Le,W,Re),E.strokeStyle=H,E.lineWidth=2.25,Ve){const ue=[[xe+.5,Le+.5],[xe+.5+Math.max(1,W-1),Le+.5],[xe+.5+Math.max(1,W-1),Le+.5+Math.max(1,Re-1)],[xe+.5,Le+.5+Math.max(1,Re-1)]];wr(E,ue,4,3)}else E.strokeRect(xe+.5,Le+.5,Math.max(1,W-1),Math.max(1,Re-1))},[y,b,x,R,_,I,t,e.width,e.height,te,H,ae]),J=d.useCallback(()=>{f.current||(f.current=!0,h.current=requestAnimationFrame(()=>{f.current=!1,h.current=null,D()}))},[D]),be=d.useCallback((M,E)=>{const O=a.current;if(!O)return null;const oe=O.getBoundingClientRect();if(!oe.width||!oe.height)return null;const j=oe.width/y,Q=oe.height/b,Ae=x.x*j,ge=x.y*Q,Z=x.w*j,re=x.h*Q,pe=k((M-oe.left-Ae)/Z,0,1),G=k((E-oe.top-ge)/re,0,1);return[pe*e.width,G*e.height]},[e.width,e.height,y,b,x]),Me=d.useCallback((M,E)=>{const O=t.current;if(!O)return;if(O.setViewCenter){O.setViewCenter(M,E),J();return}const oe=O.getViewBounds?.(),j=Wt(oe)?oe:Wt(u.current)?u.current:null;if(!j)return;const Q=Math.max(1e-6,j[2]-j[0]),Ae=Math.max(1e-6,j[3]-j[1]);O.setViewState({offsetX:M-Q*.5,offsetY:E-Ae*.5}),J()},[t,J]),Xe=d.useCallback(M=>{if(!ne||M.button!==0)return;const E=a.current;if(!E)return;const O=be(M.clientX,M.clientY);O&&(M.preventDefault(),M.stopPropagation(),E.setPointerCapture(M.pointerId),l.current={active:!0,pointerId:M.pointerId},Me(O[0],O[1]))},[ne,be,Me]),Be=d.useCallback(M=>{const E=l.current;if(!E.active||E.pointerId!==M.pointerId)return;const O=be(M.clientX,M.clientY);O&&(M.preventDefault(),M.stopPropagation(),Me(O[0],O[1]))},[be,Me]),ye=d.useCallback(M=>{const E=l.current;if(!E.active||E.pointerId!==M.pointerId)return;const O=a.current;if(O&&O.hasPointerCapture(M.pointerId))try{O.releasePointerCapture(M.pointerId)}catch{}l.current={active:!1,pointerId:null},J()},[J]);return d.useEffect(()=>{let M=!1;c.current=null,J();const E=0,O=2**(e.maxTierZoom-E),oe=Math.ceil(e.width/O),j=Math.ceil(e.height/O),Q=Math.max(1,Math.ceil(oe/e.tileSize)),Ae=Math.max(1,Math.ceil(j/e.tileSize)),ge=Q*Ae;if(!ce||ge>X)return;const Z=document.createElement("canvas");Z.width=Math.max(1,Math.round(x.w)),Z.height=Math.max(1,Math.round(x.h));const re=Z.getContext("2d");if(!re)return;re.fillStyle=R,re.fillRect(0,0,Z.width,Z.height);const pe=[];for(let G=0;G<Ae;G+=1)for(let me=0;me<Q;me+=1){const K=me*e.tileSize*O,we=G*e.tileSize*O,ee=Math.min((me+1)*e.tileSize,oe)*O,le=Math.min((G+1)*e.tileSize,j)*O;pe.push({url:_n(e,E,me,G),bounds:[K,we,ee,le]})}return Promise.allSettled(pe.map(async G=>{const me=!!n,K=await fetch(G.url,{headers:me?{Authorization:n}:void 0});if(!K.ok)throw new Error(`HTTP ${K.status}`);const we=await createImageBitmap(await K.blob());return{tile:G,bitmap:we}})).then(G=>{if(M){for(const we of G)we.status==="fulfilled"&&we.value.bitmap.close();return}const me=Z.width/Math.max(1,e.width),K=Z.height/Math.max(1,e.height);for(const we of G){if(we.status!=="fulfilled")continue;const{tile:{bounds:ee},bitmap:le}=we.value,Ue=ee[0]*me,Te=ee[1]*K,Ve=Math.max(1,(ee[2]-ee[0])*me),xe=Math.max(1,(ee[3]-ee[1])*K);re.drawImage(le,Ue,Te,Ve,xe),le.close()}c.current=Z,J()}),()=>{M=!0}},[e,n,x,R,ce,X,J]),d.useEffect(()=>{J()},[J]),d.useEffect(()=>{if(i)return i.current=J,()=>{i.current===J&&(i.current=null)}},[i,J]),d.useEffect(()=>()=>{l.current={active:!1,pointerId:null},h.current!==null&&(cancelAnimationFrame(h.current),h.current=null),f.current=!1},[]),Oe.jsxs("div",{className:o,style:z,children:[Oe.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:Xe,onPointerMove:Be,onPointerUp:ye,onPointerCancel:ye,onContextMenu:M=>{M.preventDefault()},onWheel:M=>{M.preventDefault(),M.stopPropagation()}}),Pe&&Oe.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:M=>{M.stopPropagation(),Pe()},style:U?{...U}:{...as},children:B??"×"})]})}function cs({imageWidth:e,imageHeight:t,tiles:n,viewState:r,className:i,style:o}){const s=d.useRef(null),a=d.useRef(null),c=d.useMemo(()=>({width:"100%",height:"100%",display:"block",...o}),[o]);return d.useEffect(()=>{const u=s.current;if(!u)return;const l=new Er({canvas:u,imageWidth:e,imageHeight:t,initialViewState:r});return a.current=l,l.setTiles(n),()=>{l.destroy(),a.current=null}},[e,t]),d.useEffect(()=>{const u=a.current;u&&u.setTiles(n)},[n]),d.useEffect(()=>{const u=a.current;!u||!r||u.setViewState(r)},[r]),Oe.jsx("canvas",{ref:s,className:i,style:c})}function Rt(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return null;const n=It(t??[]);if(n.length===0){const b={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return e.fillModes instanceof Uint8Array&&(b.fillModes=new Uint8Array(0)),e.ids instanceof Uint32Array&&(b.ids=new Uint32Array(0)),b}const r=ct(e),i=e.positions,o=e.paletteIndices,s=e.fillModes instanceof Uint8Array&&e.fillModes.length>=r?e.fillModes:null,a=e.ids instanceof Uint32Array&&e.ids.length>=r?e.ids:null,c=new Float32Array(r*2),u=new Uint16Array(r),l=s?new Uint8Array(r):null,h=a?new Uint32Array(r):null;let f=0;for(let b=0;b<r;b+=1){const x=i[b*2],w=i[b*2+1];Kt(x,w,n)&&(c[f*2]=x,c[f*2+1]=w,u[f]=o[b],l&&(l[f]=s[b]),h&&(h[f]=a[b]),f+=1)}const y={count:f,positions:c.subarray(0,f*2),paletteIndices:u.subarray(0,f)};return l&&(y.fillModes=l.subarray(0,f)),h&&(y.ids=h.subarray(0,f)),y}function $r(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return new Uint32Array(0);const n=It(t??[]);if(n.length===0)return new Uint32Array(0);const r=ct(e);if(r===0)return new Uint32Array(0);const i=e.positions,o=new Uint32Array(r);let s=0;for(let a=0;a<r;a+=1){const c=i[a*2],u=i[a*2+1];Kt(c,u,n)&&(o[s]=a,s+=1)}return o.subarray(0,s)}let Yt=null;const us=`
|
|
32
|
+
`;class vr{constructor(t){S(this,"canvas");S(this,"gl");S(this,"camera",new Er);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=t.canvas,this.imageWidth=Math.max(1,t.imageWidth),this.imageHeight=Math.max(1,t.imageHeight),this.clearColor=t.clearColor??[.03,.05,.08,1],this.gl=Pi(this.canvas),this.program=Pn(this.gl,Ii,Ei);const n=this.gl.createVertexArray(),r=this.gl.createBuffer();if(!n||!r)throw new Error("Failed to create WebGL buffers.");this.vao=n,this.quadBuffer=r,this.gl.bindVertexArray(this.vao),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.quadBuffer);const i=new Float32Array([0,0,0,0,1,0,1,0,0,1,0,1,1,1,1,1]);this.gl.bufferData(this.gl.ARRAY_BUFFER,i,this.gl.STATIC_DRAW);const o=this.gl.getAttribLocation(this.program,"aUnit"),s=this.gl.getAttribLocation(this.program,"aUv");if(o<0||s<0)throw new Error("Failed to get attribute locations.");const a=4*Float32Array.BYTES_PER_ELEMENT;this.gl.enableVertexAttribArray(o),this.gl.vertexAttribPointer(o,2,this.gl.FLOAT,!1,a,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,a,2*Float32Array.BYTES_PER_ELEMENT),this.gl.bindVertexArray(null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.uCameraLocation=Pe(this.gl,this.program,"uCamera"),this.uBoundsLocation=Pe(this.gl,this.program,"uBounds"),this.uTextureLocation=Pe(this.gl,this.program,"uTexture"),t.initialViewState&&(this.controlledViewState=!0,this.camera.setViewState(t.initialViewState)),this.resizeObserver=new ResizeObserver(()=>{this.resize()}),this.resizeObserver.observe(this.canvas),this.resize()}async setTiles(t){if(this.destroyed)return;const n=++this.loadVersion,r=await Promise.all(t.map(async i=>await this.loadTile(i,n)));if(this.destroyed||n!==this.loadVersion){for(const i of r)i&&this.gl.deleteTexture(i.texture);return}this.disposeTiles(this.tiles),this.tiles=r.filter(i=>i!==null),this.requestRender()}setViewState(t){this.controlledViewState=!0,this.camera.setViewState(t),this.requestRender()}getViewState(){return this.camera.getViewState()}destroy(){this.destroyed||(this.destroyed=!0,this.loadVersion+=1,this.frameId!==null&&(cancelAnimationFrame(this.frameId),this.frameId=null),this.resizeObserver.disconnect(),this.disposeTiles(this.tiles),this.tiles=[],this.gl.deleteBuffer(this.quadBuffer),this.gl.deleteVertexArray(this.vao),this.gl.deleteProgram(this.program))}async loadTile(t,n){try{const r=await fetch(t.url);if(!r.ok)throw new Error(`Tile fetch failed: ${r.status} ${r.statusText}`);const i=await r.blob(),o=await createImageBitmap(i);if(this.destroyed||n!==this.loadVersion)return o.close(),null;const s=this.gl.createTexture();if(!s)throw o.close(),new Error("Failed to create tile texture.");return this.gl.bindTexture(this.gl.TEXTURE_2D,s),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,1),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),this.gl.bindTexture(this.gl.TEXTURE_2D,null),o.close(),{id:t.id,bounds:t.bounds,texture:s}}catch(r){return console.error(`[M1TileRenderer] tile load failed: ${t.id}`,r),null}}resize(){if(this.destroyed)return;const t=this.canvas.getBoundingClientRect(),n=Math.max(1,t.width||this.canvas.clientWidth||1),r=Math.max(1,t.height||this.canvas.clientHeight||1),i=Math.max(1,window.devicePixelRatio||1),o=Math.max(1,Math.round(n*i)),s=Math.max(1,Math.round(r*i));(this.canvas.width!==o||this.canvas.height!==s)&&(this.canvas.width=o,this.canvas.height=s),this.camera.setViewport(n,r),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),!this.fitted&&!this.controlledViewState&&(this.fitToImage(),this.fitted=!0),this.requestRender()}fitToImage(){const t=this.camera.getViewportSize(),n=Math.min(t.width/this.imageWidth,t.height/this.imageHeight),r=Number.isFinite(n)&&n>0?n:1,i=t.width/r,o=t.height/r,s=(this.imageWidth-i)*.5,a=(this.imageHeight-o)*.5;this.camera.setViewState({zoom:r,offsetX:s,offsetY:a})}requestRender(){this.frameId!==null||this.destroyed||(this.frameId=requestAnimationFrame(()=>{this.frameId=null,this.render()}))}render(){if(!this.destroyed){this.gl.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.useProgram(this.program),this.gl.bindVertexArray(this.vao),this.gl.uniformMatrix3fv(this.uCameraLocation,!1,this.camera.getMatrix()),this.gl.uniform1i(this.uTextureLocation,0);for(const t of this.tiles)this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,t.texture),this.gl.uniform4f(this.uBoundsLocation,t.bounds[0],t.bounds[1],t.bounds[2],t.bounds[3]),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindVertexArray(null)}}disposeTiles(t){for(const n of t)this.gl.deleteTexture(n.texture)}}function It(e){return e??null}function nr(e){return typeof e=="number"&&Number.isFinite(e)}function vi(e){return Array.isArray(e)&&e.length>=2&&nr(e[0])&&nr(e[1])}function _r(e){return Array.isArray(e)&&e.length>0&&e.every(t=>vi(t))}function Fr(e){return Array.isArray(e)&&e.length>0&&e.every(t=>_r(t))}function _i(e){return Array.isArray(e)&&e.length>0&&e.every(t=>Fr(t))}function Ue(e){if(!Array.isArray(e)||e.length<3)return[];const t=[];for(const i of e){if(!Array.isArray(i)||i.length<2)continue;const o=Number(i[0]),s=Number(i[1]);if(!Number.isFinite(o)||!Number.isFinite(s))continue;const a=t[t.length-1];a&&a[0]===o&&a[1]===s||t.push([o,s])}if(t.length<3)return[];const n=t[0],r=t[t.length-1];return(n[0]!==r[0]||n[1]!==r[1])&&t.push([n[0],n[1]]),t.length>=4?t:[]}function Tt(e){if(!Array.isArray(e)||e.length<4)return 0;let t=0;for(let n=0;n<e.length-1;n+=1){const r=e[n],i=e[n+1];t+=r[0]*i[1]-i[0]*r[1]}return t*.5}function ln(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const o of e){const s=Ue(o);s.length>=4&&t.push(s)}if(t.length===0)return[];if(t.length===1)return[t[0]];let n=0,r=0;for(let o=0;o<t.length;o+=1){const s=Math.abs(Tt(t[o]));s<=r||(r=s,n=o)}const i=[t[n]];for(let o=0;o<t.length;o+=1)o!==n&&i.push(t[o]);return i}function Br(e){if(!e)return[];if(_r(e)){const t=ln([e]);return t.length>0?[t]:[]}if(Fr(e)){const t=ln(e);return t.length>0?[t]:[]}if(_i(e)){const t=[];for(const n of e){const r=ln(n);r.length>0&&t.push(r)}return t}return[]}function rr(e,t,n){let r=!1;for(let i=0,o=n.length-1;i<n.length;o=i,i+=1){const s=n[i][0],a=n[i][1],c=n[o][0],u=n[o][1];a>t!=u>t&&e<(c-s)*(t-a)/(u-a||Number.EPSILON)+s&&(r=!r)}return r}function Et(e){const t=[];for(const n of e??[]){const r=Br(n);for(const i of r){const o=i[0];if(!o||o.length<4)continue;let s=1/0,a=1/0,c=-1/0,u=-1/0;for(const[h,f]of o)h<s&&(s=h),h>c&&(c=h),f<a&&(a=f),f>u&&(u=f);if(!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(c)||!Number.isFinite(u))continue;let l=Math.abs(Tt(o));for(let h=1;h<i.length;h+=1)l-=Math.abs(Tt(i[h]));t.push({outer:o,holes:i.slice(1),minX:s,minY:a,maxX:c,maxY:u,area:Math.max(1e-6,l)})}}return t}function Ur(e,t,n){if(e<n.minX||e>n.maxX||t<n.minY||t>n.maxY||!rr(e,t,n.outer))return!1;for(const r of n.holes)if(rr(e,t,r))return!1;return!0}function jt(e,t,n){for(const r of n)if(Ur(e,t,r))return!0;return!1}const In=[160,160,160,255];function k(e,t,n){return Math.max(t,Math.min(n,e))}function En(e,t,n){const r=Number(e),i=Number(t),o=Number(n);return!Number.isFinite(r)||r<=0?1:!Number.isFinite(i)||!Number.isFinite(o)?r:Math.pow(2,i-o)*r}function Fi(e,t,n){let i=100*En(e,t,n);if(Number(e)){let o="μm";return i>1e3&&(i/=1e3,o="mm"),`${i.toPrecision(3)} ${o}`}return`${Math.round(i*1e3)/1e3} pixels`}function fe(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function at(e){const t=e.fillModes instanceof Uint8Array?e.fillModes.length:Number.MAX_SAFE_INTEGER;return Math.max(0,Math.min(Math.floor(e.count??0),Math.floor((e.positions?.length??0)/2),e.paletteIndices?.length??0,t))}function bn(e,t){return!e&&!t?!0:!e||!t?!1:Math.abs((e.zoom??0)-(t.zoom??0))<1e-6&&Math.abs((e.offsetX??0)-(t.offsetX??0))<1e-6&&Math.abs((e.offsetY??0)-(t.offsetY??0))<1e-6&&Math.abs((e.rotationDeg??0)-(t.rotationDeg??0))<1e-6}function Bi(e){const t=String(e??"").trim();if(!t)return"";if(/^bearer\s+/i.test(t)){const n=t.replace(/^bearer\s+/i,"").trim();return n?`Bearer ${n}`:""}return`Bearer ${t}`}function Lr(e){const n=String(e??"").trim().match(/^#?([0-9a-fA-F]{6})$/);if(!n)return[...In];const r=Number.parseInt(n[1],16);return[r>>16&255,r>>8&255,r&255,255]}function Ui(e){const t=[[...In]],n=new Map;for(const i of e??[]){const o=String(i?.termId??"");!o||n.has(o)||(n.set(o,t.length),t.push(Lr(i?.termColor)))}const r=new Uint8Array(t.length*4);for(let i=0;i<t.length;i+=1)r[i*4]=t[i][0],r[i*4+1]=t[i][1],r[i*4+2]=t[i][2],r[i*4+3]=t[i][3];return{colors:r,termToPaletteIndex:n}}const Li=.1,Di=4e6,ki=4096,Ni=64,zi=1,Oi=4,Dr=1e-6,Wi=24;function Yi(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const n of e){if(!Array.isArray(n)||n.length<2)continue;const r=Number(n[0]),i=Number(n[1]);if(!Number.isFinite(r)||!Number.isFinite(i))continue;const o=t[t.length-1];o&&Math.abs(o[0]-r)<1e-9&&Math.abs(o[1]-i)<1e-9||t.push([r,i])}return t}function Xi(e,t,n){if(t<=Dr||n<8)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([e[0]+Math.cos(o)*t,e[1]+Math.sin(o)*t])}return Ue(r)}function fn(e,t){if(!e.length)return[];let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,c]of e)a<n&&(n=a),a>i&&(i=a),c<r&&(r=c),c>o&&(o=c);if(!Number.isFinite(n)||!Number.isFinite(r))return[];const s=Math.max(t,1);return Ue([[n-s,r-s],[i+s,r-s],[i+s,o+s],[n-s,o+s]])}function Vi(e,t){let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,c]of e)a<n&&(n=a),a>i&&(i=a),c<r&&(r=c),c>o&&(o=c);const s=Math.max(t,1);return[n-s,r-s,i+s,o+s]}function Gi(e,t,n){const r=Math.max(Li,Number(n.minRasterStep)||0),i=Math.max(32768,Math.floor(n.maxRasterPixels||Di)),o=Math.max(256,Math.floor(n.maxRasterSize||ki)),s=Math.max(.001,e[2]-e[0]),a=Math.max(.001,e[3]-e[1]);let c=Math.max(r,Number.EPSILON),u=3,l=Math.ceil(s/c)+u*2+1,h=Math.ceil(a/c)+u*2+1;for(;(l>o||h>o||l*h>i)&&(c*=1.15,l=Math.ceil(s/c)+u*2+1,h=Math.ceil(a/c)+u*2+1,!(c>Math.max(s,a))););return l=Math.max(8,l),h=Math.max(8,h),{minX:e[0],minY:e[1],step:c,padding:u,width:l,height:h}}function qi(e,t){if(typeof OffscreenCanvas<"u"){const r=new OffscreenCanvas(e,t).getContext("2d",{willReadFrequently:!0});if(r)return r}if(typeof document<"u"){const n=document.createElement("canvas");return n.width=e,n.height=t,n.getContext("2d",{willReadFrequently:!0})}return null}function Hi(e,t){return[(e[0]-t.minX)/t.step+t.padding,(e[1]-t.minY)/t.step+t.padding]}function $i(e,t,n){const r=qi(n.width,n.height);if(!r)return new Uint8Array(0);r.clearRect(0,0,n.width,n.height),r.fillStyle="#ffffff",r.strokeStyle="#ffffff",r.lineCap="round",r.lineJoin="round",r.lineWidth=t*2/n.step;const i=e.map(a=>Hi(a,n));if(i.length<=1){const a=i[0];if(!a)return new Uint8Array(0);r.beginPath(),r.arc(a[0],a[1],t/n.step,0,Math.PI*2),r.fill()}else{r.beginPath(),r.moveTo(i[0][0],i[0][1]);for(let a=1;a<i.length;a+=1)r.lineTo(i[a][0],i[a][1]);r.stroke()}const o=r.getImageData(0,0,n.width,n.height),s=new Uint8Array(n.width*n.height);for(let a=0;a<s.length;a+=1)s[a]=o.data[a*4+3]>=Wi?1:0;return s}function Zi(e,t,n){const r=[],i=t+1,o=(a,c)=>c*i+a,s=(a,c)=>a>=0&&c>=0&&a<t&&c<n&&e[c*t+a]>0;for(let a=0;a<n;a+=1)for(let c=0;c<t;c+=1)s(c,a)&&(s(c,a-1)||r.push({start:o(c,a),end:o(c+1,a),dir:0}),s(c+1,a)||r.push({start:o(c+1,a),end:o(c+1,a+1),dir:1}),s(c,a+1)||r.push({start:o(c+1,a+1),end:o(c,a+1),dir:2}),s(c-1,a)||r.push({start:o(c,a+1),end:o(c,a),dir:3}));return r}function Ki(e,t){const n=(t-e+4)%4;return n===1?0:n===0?1:n===3?2:3}function ji(e){if(!e.length)return[];const t=new Map;for(let i=0;i<e.length;i+=1){const o=t.get(e[i].start);o?o.push(i):t.set(e[i].start,[i])}const n=new Uint8Array(e.length),r=[];for(let i=0;i<e.length;i+=1){if(n[i])continue;const o=e[i],s=o.start;let a=o.end,c=o.dir;const u=[o.start,o.end];n[i]=1;let l=0;const h=e.length*3;for(;a!==s&&l<h;){const f=t.get(a);if(!f||f.length===0)break;let y=-1,b=1/0;for(const w of f){if(n[w])continue;const A=e[w],E=Ki(c,A.dir);E<b&&(b=E,y=w)}if(y<0)break;n[y]=1;const x=e[y];a=x.end,c=x.dir,u.push(a),l+=1}u.length>=4&&u[0]===u[u.length-1]&&r.push(u)}return r}function Ji(e,t,n){const r=t+1,i=[];for(const o of e){const s=o%r,a=Math.floor(o/r);i.push([n.minX+(s-n.padding)*n.step,n.minY+(a-n.padding)*n.step])}return Ue(i)}function Qi(e,t=1e-9){const n=Ue(e);if(n.length<5)return n;const r=[n[0]];for(let i=1;i<n.length-1;i+=1){const o=r[r.length-1],s=n[i],a=n[i+1],c=(s[0]-o[0])*(a[1]-s[1])-(s[1]-o[1])*(a[0]-s[0]);Math.abs(c)<=t||r.push(s)}return r.push(r[0]),Ue(r)}function eo(e,t,n){const r=n[0]-t[0],i=n[1]-t[1],o=r*r+i*i;if(o<=1e-12){const h=e[0]-t[0],f=e[1]-t[1];return h*h+f*f}const s=k(((e[0]-t[0])*r+(e[1]-t[1])*i)/o,0,1),a=t[0]+r*s,c=t[1]+i*s,u=e[0]-a,l=e[1]-c;return u*u+l*l}function to(e,t){if(e.length<=2||t<=0)return e.slice();const n=new Uint8Array(e.length);n[0]=1,n[e.length-1]=1;const r=t*t,i=[[0,e.length-1]];for(;i.length>0;){const s=i.pop();if(!s)break;const[a,c]=s;if(c-a<=1)continue;let u=0,l=-1;for(let h=a+1;h<c;h+=1){const f=eo(e[h],e[a],e[c]);f>u&&(u=f,l=h)}l>=0&&u>r&&(n[l]=1,i.push([a,l],[l,c]))}const o=[];for(let s=0;s<e.length;s+=1)n[s]&&o.push(e[s]);return o}function no(e,t){const n=Ue(e);if(n.length<5||t<=0)return n;const r=n.slice(0,-1),i=to(r,t);return i.length<3?n:Ue(i)}function ro(e,t){let n=Ue(e);if(t<=0||n.length<5)return n;for(let r=0;r<t;r+=1){const i=n.slice(0,-1);if(i.length<3)break;const o=[];for(let s=0;s<i.length;s+=1){const a=i[s],c=i[(s+1)%i.length];o.push([a[0]*.75+c[0]*.25,a[1]*.75+c[1]*.25],[a[0]*.25+c[0]*.75,a[1]*.25+c[1]*.75])}n=Ue(o)}return n}function St(e,t){return t?Ue(e.map(([n,r])=>[k(n,t[0],t[2]),k(r,t[1],t[3])])):e}function io(e,t){const n=Yi(e),r=Math.max(Dr,Number(t.radius)||0);if(n.length===0||!Number.isFinite(r))return[];const i=Math.max(12,Math.floor(t.circleSides||Ni));if(n.length===1)return St(Xi(n[0],r,i),t.clipBounds);const o=Vi(n,r),s=Gi(o,r,t),a=$i(n,r,s);if(!a.length)return St(fn(n,r),t.clipBounds);const c=Zi(a,s.width,s.height),u=ji(c);if(!u.length)return St(fn(n,r),t.clipBounds);let l=[],h=0;for(const x of u){const w=Ji(x,s.width,s),A=Math.abs(Tt(w));A<=h||(h=A,l=w)}if(!l.length)return St(fn(n,r),t.clipBounds);const f=typeof t.simplifyTolerance=="number"&&Number.isFinite(t.simplifyTolerance)?Math.max(0,t.simplifyTolerance):s.step*.2,y=typeof t.smoothingPasses=="number"&&Number.isFinite(t.smoothingPasses)?Math.round(k(t.smoothingPasses,0,Oi)):zi,b=no(ro(Qi(l,s.step*.001),y),f);return St(b,t.clipBounds)}const Rt=[],ir=[],je={color:"#ff4d4f",width:2,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},oo={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},so="rgba(23, 23, 25, 0.1)",ao=6,Ne={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},Je={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},or={x:16,y:-24},co=20,sr=1e-6,ar="transparent",uo=3,lo=2,kr=96,fo=1,cr=1e3,Nr=2,zr=2,ho=4096,mo=.2,go=1.12,po=.89,bo=32,yo="#000000",wo=.1,So="#FFCF00",xo="#FF0000",Mo=1.5,ur=[2,2],Ao=1,To=.25,Ro=4,Co=1,Po=0,Io=4,Eo=.05,vo=256,lr=1.5;function Jt(e,t,n){return[k(e[0],0,t),k(e[1],0,n)]}function Qt(e){if(!Array.isArray(e)||e.length<2)return null;const t=Number(e[0]),n=Number(e[1]);return!Number.isFinite(t)||!Number.isFinite(n)?null:[t,n]}const st=Qt;function _e(e){return Ue(e)}function Zt(e){return Math.abs(Tt(_e(e)))}function fr(e){if(!Array.isArray(e)||e.length===0)return[0,0,0,0];let t=1/0,n=1/0,r=-1/0,i=-1/0;for(const[o,s]of e)o<t&&(t=o),o>r&&(r=o),s<n&&(n=s),s>i&&(i=s);return[t,n,r,i]}function yn(e,t,n=!1){if(t.length!==0){e.moveTo(t[0][0],t[0][1]);for(let r=1;r<t.length;r+=1)e.lineTo(t[r][0],t[r][1]);n&&e.closePath()}}function Xe(e,t,n,r=!1,i=!1,o="rgba(255, 77, 79, 0.16)"){t.length!==0&&(e.beginPath(),yn(e,t,r),i&&r&&(e.fillStyle=o,e.fill()),e.strokeStyle=n.color,e.lineWidth=n.width,e.lineJoin=n.lineJoin,e.lineCap=n.lineCap,e.shadowColor=n.shadowColor,e.shadowBlur=n.shadowBlur,e.shadowOffsetX=n.shadowOffsetX,e.shadowOffsetY=n.shadowOffsetY,e.setLineDash(n.lineDash),e.stroke(),e.setLineDash(Rt),e.shadowColor="rgba(0, 0, 0, 0)",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0)}function Or(e){const t=Array.isArray(e?.lineDash)?e.lineDash.filter(s=>Number.isFinite(s)&&s>=0):Rt,n=typeof e?.width=="number"&&Number.isFinite(e.width)?Math.max(0,e.width):je.width,r=typeof e?.shadowBlur=="number"&&Number.isFinite(e.shadowBlur)?Math.max(0,e.shadowBlur):je.shadowBlur,i=typeof e?.shadowOffsetX=="number"&&Number.isFinite(e.shadowOffsetX)?e.shadowOffsetX:je.shadowOffsetX,o=typeof e?.shadowOffsetY=="number"&&Number.isFinite(e.shadowOffsetY)?e.shadowOffsetY:je.shadowOffsetY;return{color:e?.color||je.color,width:n,lineDash:t.length?t:Rt,lineJoin:e?.lineJoin||je.lineJoin,lineCap:e?.lineCap||je.lineCap,shadowColor:e?.shadowColor||je.shadowColor,shadowBlur:r,shadowOffsetX:i,shadowOffsetY:o}}function xt(e,t){return t?Or({color:t.color??e.color,width:t.width??e.width,lineDash:t.lineDash??e.lineDash,lineJoin:t.lineJoin??e.lineJoin,lineCap:t.lineCap??e.lineCap,shadowColor:t.shadowColor??e.shadowColor,shadowBlur:t.shadowBlur??e.shadowBlur,shadowOffsetX:t.shadowOffsetX??e.shadowOffsetX,shadowOffsetY:t.shadowOffsetY??e.shadowOffsetY}):e}function dr(e,t){return e==null||t===null||t===void 0?!1:String(e)===String(t)}function hr(e){return typeof e=="number"&&Number.isFinite(e)}function _o(e){return Array.isArray(e)&&e.length>=2&&hr(e[0])&&hr(e[1])}function Fo(e){return Array.isArray(e)&&e.length>=2&&e.every(t=>_o(t))}function Wr(e,t){if(!(!Array.isArray(e)||e.length===0)){if(Fo(e)){t.push(e.map(([n,r])=>[n,r]));return}for(const n of e)Wr(n,t)}}function mr(e,t){const n=[];Wr(e,n);const r=[];for(const i of n){if(i.length<2)continue;const o=t?_e(i):i;o.length>=(t?4:2)&&r.push(o)}return r}function At(e,t){return typeof e!="number"||!Number.isFinite(e)||e<=0?t:e}function Bo(e,t){return typeof e!="number"||!Number.isFinite(e)?t:k(e,0,1)}function Yr(e,t,n,r,i,o){const s=Math.max(0,Math.min(o,r*.5,i*.5));e.beginPath(),e.moveTo(t+s,n),e.lineTo(t+r-s,n),e.quadraticCurveTo(t+r,n,t+r,n+s),e.lineTo(t+r,n+i-s),e.quadraticCurveTo(t+r,n+i,t+r-s,n+i),e.lineTo(t+s,n+i),e.quadraticCurveTo(t,n+i,t,n+i-s),e.lineTo(t,n+s),e.quadraticCurveTo(t,n,t+s,n),e.closePath()}function Uo(e){const t=e[0];return Array.isArray(t)&&Array.isArray(t[0])}function en(e,t,n){if(!e||!t)return[];if(n){const r=n.worldToScreen(e[0],e[1]),i=n.worldToScreen(t[0],t[1]);if(r&&i){const o=[[r[0],r[1]],[i[0],r[1]],[i[0],i[1]],[r[0],i[1]]],s=[];for(const a of o){const c=n.screenToWorld(a);if(!c)return en(e,t);s.push(c)}return _e(s)}}return _e([[e[0],e[1]],[t[0],e[1]],[t[0],t[1]],[e[0],t[1]]])}function wn(e,t,n=kr){if(!e||!t)return[];const r=(e[0]+t[0])*.5,i=(e[1]+t[1])*.5,o=Math.hypot(t[0]-e[0],t[1]-e[1])*.5;if(o<1)return[];const s=[];for(let a=0;a<=n;a+=1){const c=a/n*Math.PI*2;s.push([r+Math.cos(c)*o,i+Math.sin(c)*o])}return _e(s)}function gr(e){const t=Br(It(e));if(t.length===0)return[];const n=[];for(const r of t){const i=r[0];if(!i||i.length<4)continue;const o=i.map(([a,c])=>[a,c]),s=[];for(let a=1;a<r.length;a+=1){const c=r[a];!c||c.length<4||s.push(c.map(([u,l])=>[u,l]))}n.push({outer:o,holes:s})}return n}function Lo(e){if(!Array.isArray(e))return ur;const t=e.filter(n=>Number.isFinite(n)&&n>=0);return t.length>0?t:ur}function Do(e){return typeof e!="number"||!Number.isFinite(e)?Ao:k(e,To,Ro)}function ko(e){return typeof e!="number"||!Number.isFinite(e)?Co:Math.round(k(e,Po,Io))}function No(e){const t=At(e?.radius,bo),n=At(e?.cursorLineWidth,Mo),r=Do(e?.edgeDetail),i=ko(e?.edgeSmoothing);return{radius:t,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:e?.clickSelectRoi===!0,fillColor:e?.fillColor||yo,fillOpacity:Bo(e?.fillOpacity,wo),cursorColor:e?.cursorColor||So,cursorActiveColor:e?.cursorActiveColor||xo,cursorLineWidth:n,cursorLineDash:Lo(e?.cursorLineDash)}}function zo(e,t,n){if(!t.isDrawing||t.screenPoints.length===0)return;const r=t.screenPoints;if(r.length===0)return;const i=n.radius;if(!(!Number.isFinite(i)||i<=0)){if(e.save(),e.globalAlpha=n.fillOpacity,e.fillStyle=n.fillColor,e.strokeStyle=n.fillColor,e.lineCap="round",e.lineJoin="round",e.lineWidth=i*2,r.length===1)e.beginPath(),e.arc(r[0][0],r[0][1],i,0,Math.PI*2),e.fill();else{e.beginPath(),e.moveTo(r[0][0],r[0][1]);for(let o=1;o<r.length;o+=1)e.lineTo(r[o][0],r[o][1]);e.stroke()}e.restore()}}function Oo(e,t,n,r){const i=t.cursor;if(!i)return;const o=t.cursorScreen??st(n?.worldToScreen(i[0],i[1])??[]);if(!o)return;const s=r.radius;!Number.isFinite(s)||s<=0||(e.save(),e.beginPath(),e.arc(o[0],o[1],s,0,Math.PI*2),e.strokeStyle=t.isDrawing?r.cursorActiveColor:r.cursorColor,e.lineWidth=r.cursorLineWidth,e.setLineDash(r.cursorLineDash),e.stroke(),e.setLineDash(Rt),e.restore())}const Wo=.58,Yo=4096,Xo=.5;let zt=null;const Ot=new Map;function Vo(){if(zt)return zt;if(typeof document>"u")return null;const t=document.createElement("canvas").getContext("2d");return t?(zt=t,zt):null}function vn(e,t){const n=`${t.fontWeight}|${t.fontSize}|${t.fontFamily}|${e}`,r=Ot.get(n);if(r!==void 0)return r;const i=e.length*t.fontSize*Wo,o=Vo();let s=i;if(o){o.font=`${t.fontWeight} ${t.fontSize}px ${t.fontFamily}`;const a=o.measureText(e).width;Number.isFinite(a)&&a>=0&&(s=a)}return Ot.size>Yo&&Ot.clear(),Ot.set(n,s),s}function Go(e,t="top-center"){if(!e.length)return null;let n=1/0;for(const o of e)o[1]<n&&(n=o[1]);if(!Number.isFinite(n))return null;let r=1/0,i=-1/0;for(const o of e)Math.abs(o[1]-n)>Xo||(o[0]<r&&(r=o[0]),o[0]>i&&(i=o[0]));return!Number.isFinite(r)||!Number.isFinite(i)?null:t==="top-center"?[(r+i)*.5,n]:[r,n]}function Xr(e,t="top-center"){let n=null;for(const r of e){const i=Go(r.outer,t);i&&(!n||i[1]<n[1]||i[1]===n[1]&&i[0]<n[0])&&(n=i)}return n}function _n(e){const t=typeof e?.paddingX=="number"&&Number.isFinite(e.paddingX)?Math.max(0,e.paddingX):Ne.paddingX,n=typeof e?.paddingY=="number"&&Number.isFinite(e.paddingY)?Math.max(0,e.paddingY):Ne.paddingY,r=typeof e?.fontSize=="number"&&Number.isFinite(e.fontSize)?Math.max(8,e.fontSize):Ne.fontSize,i=typeof e?.borderWidth=="number"&&Number.isFinite(e.borderWidth)?Math.max(0,e.borderWidth):Ne.borderWidth,o=typeof e?.offsetY=="number"&&Number.isFinite(e.offsetY)?e.offsetY:Ne.offsetY,s=typeof e?.borderRadius=="number"&&Number.isFinite(e.borderRadius)?Math.max(0,e.borderRadius):Ne.borderRadius;return{fontFamily:e?.fontFamily||Ne.fontFamily,fontSize:r,fontWeight:e?.fontWeight||Ne.fontWeight,textColor:e?.textColor||Ne.textColor,backgroundColor:e?.backgroundColor||Ne.backgroundColor,borderColor:e?.borderColor||Ne.borderColor,borderWidth:i,paddingX:t,paddingY:n,offsetY:o,borderRadius:s}}function Vr(e,t){return t?_n({fontFamily:t.fontFamily??e.fontFamily,fontSize:t.fontSize??e.fontSize,fontWeight:t.fontWeight??e.fontWeight,textColor:t.textColor??e.textColor,backgroundColor:t.backgroundColor??e.backgroundColor,borderColor:t.borderColor??e.borderColor,borderWidth:t.borderWidth??e.borderWidth,paddingX:t.paddingX??e.paddingX,paddingY:t.paddingY??e.paddingY,offsetY:t.offsetY??e.offsetY,borderRadius:t.borderRadius??e.borderRadius}):e}function Gr(e,t,n){if(!e||!n)return 0;const r=Number(n.minZoom),i=Number(n.maxZoom);return!Number.isFinite(r)||!Number.isFinite(i)||i-r<=sr||!Number.isFinite(t)?0:t>=i-sr?co:0}function qo(e){const t=typeof e?.fontSize=="number"&&Number.isFinite(e.fontSize)?Math.max(8,e.fontSize):Je.fontSize,n=typeof e?.borderRadius=="number"&&Number.isFinite(e.borderRadius)?Math.max(0,e.borderRadius):Je.borderRadius,r=typeof e?.paddingX=="number"&&Number.isFinite(e.paddingX)?Math.max(0,e.paddingX):Je.paddingX,i=typeof e?.paddingY=="number"&&Number.isFinite(e.paddingY)?Math.max(0,e.paddingY):Je.paddingY;return{fontFamily:e?.fontFamily||Je.fontFamily,fontSize:t,fontWeight:e?.fontWeight||Je.fontWeight,textColor:e?.textColor||Je.textColor,backgroundColor:e?.backgroundColor||Je.backgroundColor,borderRadius:n,paddingX:r,paddingY:i}}function Ho(e){const t=typeof e?.x=="number"&&Number.isFinite(e.x)?e.x:or.x,n=typeof e?.y=="number"&&Number.isFinite(e.y)?e.y:or.y;return{x:t,y:n}}function $o(e){return Number.isFinite(e)?`${Math.max(0,e).toFixed(3)} mm²`:"0.000 mm²"}function Zo(e){const t=typeof e?.format=="function"?e.format:$o,n=Ho(e?.cursorOffset);return{enabled:e?.enabled===!0,format:t,style:qo(e?.style),cursorOffsetX:n.x,cursorOffsetY:n.y}}function Ko(e,t,n,r,i,o,s=!0){const a=t.trim();if(!a)return;e.save(),e.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,e.textAlign="center",e.textBaseline="middle";const u=vn(a,o)+o.paddingX*2,l=o.fontSize+o.paddingY*2,h=n[0],f=n[1]-o.offsetY,y=s?k(h,u*.5+1,r-u*.5-1):h,b=s?k(f,l*.5+1,i-l*.5-1):f,x=y-u*.5,w=b-l*.5;e.fillStyle=o.backgroundColor,e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,Yr(e,x,w,u,l,o.borderRadius),e.fill(),o.borderWidth>0&&e.stroke(),e.fillStyle=o.textColor,e.fillText(a,y,b+.5),e.restore()}function jo(e,t,n,r,i,o,s,a){const c=t.trim();if(!c)return;e.save(),e.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,e.textAlign="center",e.textBaseline="middle";const l=vn(c,o)+o.paddingX*2,h=o.fontSize+o.paddingY*2,f=k(n[0]+s,l*.5+1,r-l*.5-1),y=k(n[1]+a,h*.5+1,i-h*.5-1),b=f-l*.5,x=y-h*.5;e.fillStyle=o.backgroundColor,Yr(e,b,x,l,h,o.borderRadius),e.fill(),e.fillStyle=o.textColor,e.fillText(c,f,y+.5),e.restore()}function Jo(e,t,n,r){if(!(t.length<4||n.length===0)){e.save(),e.beginPath(),yn(e,t,!0);for(const i of n)i.length<4||yn(e,i,!0);e.fillStyle=r,e.fill("evenodd"),e.restore()}}function Qo(e){const{ctx:t,overlayShapes:n,imageOuterRing:r,worldToScreenPoints:i,baseStrokeStyle:o,onInvertedFillDebug:s}=e,a=!!globalThis.__OPEN_PLANT_DEBUG_OVERLAY__;for(let c=0;c<n.length;c+=1){const u=n[c];if(!u?.coordinates?.length||u.visible===!1)continue;const l=u.closed??Uo(u.coordinates),h=mr(u.coordinates,l);if(u.invertedFill?.fillColor){const y=[],b=mr(u.coordinates,!0);for(const x of b){const w=i(x);w.length>=4&&y.push(w)}a&&s&&s({id:u.id??c,outerRingPoints:r.length,sourceRingCount:b.length,holeRingCount:y.length,fillColor:u.invertedFill.fillColor}),Jo(t,r,y,u.invertedFill.fillColor)}if(h.length===0)continue;const f=xt(o,u.stroke??u.strokeStyle);for(const y of h){const b=i(y);b.length<2||Xe(t,b,f,l,u.fill??!1)}}}function Wt(e){return e==="stamp-rectangle"||e==="stamp-circle"||e==="stamp-rectangle-4096px"||e==="stamp-rectangle-2mm2"||e==="stamp-circle-2mm2"||e==="stamp-circle-hpf-0.2mm2"}function es(e){return{rectangleAreaMm2:At(e?.rectangleAreaMm2,Nr),circleAreaMm2:At(e?.circleAreaMm2,zr),rectanglePixelSize:At(e?.rectanglePixelSize,ho)}}const pr=1e3;function ts(e){return e*pr*pr}function br(e,t,n){if(!e||!Number.isFinite(t)||t<=0)return[];if(n){const r=n.worldToScreen(e[0],e[1]),i=n.worldToScreen(e[0]+t,e[1]);if(r&&i){const o=Math.hypot(i[0]-r[0],i[1]-r[1]),s=[[r[0]-o,r[1]-o],[r[0]+o,r[1]-o],[r[0]+o,r[1]+o],[r[0]-o,r[1]+o]],a=[];for(const c of s){const u=n.screenToWorld(c);if(!u)throw new Error("Failed to create rectangle");a.push(u)}return _e(a)}}return _e([[e[0]-t,e[1]-t],[e[0]+t,e[1]-t],[e[0]+t,e[1]+t],[e[0]-t,e[1]+t]])}function ns(e,t,n=kr){if(!e||!Number.isFinite(t)||t<=0)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([e[0]+Math.cos(o)*t,e[1]+Math.sin(o)*t])}return _e(r)}function rs(e){const{stampTool:t,center:n,resolvedStampOptions:r,imageWidth:i,imageHeight:o,micronsToWorldPixels:s,getRectangleProjection:a}=e;if(!n)return[];if(t==="stamp-rectangle-4096px"){const h=r.rectanglePixelSize*.5;return br(n,h,a()).map(f=>Jt(f,i,o))}let c=0;if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"?c=t==="stamp-rectangle-2mm2"?Nr:r.rectangleAreaMm2:(t==="stamp-circle"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2")&&(c=t==="stamp-circle-hpf-0.2mm2"?mo:t==="stamp-circle-2mm2"?zr:r.circleAreaMm2),!Number.isFinite(c)||c<=0)return[];const u=ts(c);let l=[];if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"){const h=s(Math.sqrt(u)*.5);l=br(n,h,a())}else if(t==="stamp-circle"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2"){const h=s(Math.sqrt(u/Math.PI));l=ns(n,h)}return l.length?l.map(h=>Jt(h,i,o)):[]}function is(e){return{color:so,width:ao,lineDash:Rt,lineJoin:e.lineJoin,lineCap:e.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function os(e){if(typeof e!="string")return ar;const t=e.trim();return t.length>0?t:ar}function yr(e){return Array.isArray(e)&&e.length>=4&&Zt(e)>fo}function qr({tool:e,imageWidth:t,imageHeight:n,imageMpp:r,imageZoom:i,stampOptions:o,brushOptions:s,projectorRef:a,onBrushTap:c,onDrawComplete:u,onPatchComplete:l,enabled:h,viewStateSignal:f,persistedRegions:y,patchRegions:b,persistedPolygons:x,drawFillColor:w,regionStrokeStyle:A,regionStrokeHoverStyle:E,regionStrokeActiveStyle:X,patchStrokeStyle:R,resolveRegionStrokeStyle:_,resolveRegionLabelStyle:H,overlayShapes:se,hoveredRegionId:j=null,activeRegionId:J=null,regionLabelStyle:ae,drawAreaTooltip:ge,autoLiftRegionLabelAtMaxZoom:Te=!1,regionLabelAnchor:B="top-center",clampRegionLabelToViewport:D=!0,regionLabelAutoLiftOffsetPx:O,invalidateRef:U,className:Q,style:Le}){const ue=d.useRef(null),Oe=d.useRef(!1),Fe=d.useRef(new Map),We=d.useRef(e),C=d.useRef({isDrawing:!1,pointerId:null,start:null,current:null,cursor:null,cursorScreen:null,points:[],screenPoints:[],stampCenter:null}),M=h??e!=="cursor",z=d.useMemo(()=>y&&y.length>0?y:!x||x.length===0?ir:x.map((m,g)=>({id:g,coordinates:m})),[y,x]),ce=d.useMemo(()=>b??ir,[b]),$=d.useMemo(()=>{const m=[];for(let g=0;g<z.length;g+=1){const T=z[g],I=gr(T.coordinates);I.length!==0&&m.push({region:T,regionIndex:g,regionKey:T.id??g,polygons:I})}return m},[z]),le=d.useMemo(()=>{const m=[];for(let g=0;g<ce.length;g+=1){const T=ce[g],I=gr(T.coordinates);I.length!==0&&m.push({region:T,regionIndex:g,regionKey:T.id??g,polygons:I})}return m},[ce]),de=d.useMemo(()=>Or(A),[A]),ye=d.useMemo(()=>xt(de,E),[de,E]),ee=d.useMemo(()=>xt(de,X),[de,X]),he=d.useMemo(()=>xt(oo,R),[R]),re=d.useMemo(()=>os(w),[w]),ne=d.useMemo(()=>_n(ae),[ae]),K=d.useMemo(()=>Zo(ge),[ge]),xe=d.useMemo(()=>es(o),[o]),G=d.useMemo(()=>No(s),[s]),we=d.useMemo(()=>({position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",touchAction:"none",pointerEvents:M?"auto":"none",cursor:M?e==="brush"?"none":"crosshair":"default",...Le}),[M,e,Le]),pe=d.useCallback(()=>{const m=ue.current;if(!m)return;const g=m.getBoundingClientRect(),T=Math.max(1,window.devicePixelRatio||1),I=Math.max(1,Math.round(g.width*T)),v=Math.max(1,Math.round(g.height*T));(m.width!==I||m.height!==v)&&(m.width=I,m.height=v)},[]),Se=d.useCallback(m=>{const g=a.current;if(!g||m.length===0)return[];const T=new Array(m.length);for(let I=0;I<m.length;I+=1){const v=st(g.worldToScreen(m[I][0],m[I][1]));if(!v)return[];T[I]=v}return T},[a]),De=d.useCallback(m=>{const g=a.current,T=ue.current;if(!g||!T)return null;const I=T.getBoundingClientRect(),v=st(g.screenToWorld(I.left+m[0],I.top+m[1]));return v?Jt(v,t,n):null},[a,t,n]),Ae=d.useCallback(()=>{const m=a.current,g=m?.getViewState?.().rotationDeg??0;if(!(Math.abs(g%360)<.01||!m))return{worldToScreen:(T,I)=>st(m.worldToScreen(T,I)),screenToWorld:De}},[a,De]),Ie=d.useCallback(m=>{if(!Number.isFinite(m)||m<=0)return 0;const g=typeof r=="number"&&Number.isFinite(r)&&r>0?r:1,T=typeof i=="number"&&Number.isFinite(i)?i:0,I=a.current?.getViewState?.().zoom,v=typeof I=="number"&&Number.isFinite(I)&&I>0?I:1,me=T+Math.log2(v),V=Math.max(1e-9,En(g,T,me));return m/V/v},[r,i,a]),Re=d.useCallback((m,g)=>rs({stampTool:m,center:g,resolvedStampOptions:xe,imageWidth:t,imageHeight:n,micronsToWorldPixels:Ie,getRectangleProjection:Ae}),[Ie,t,n,xe,Ae]),ct=d.useCallback(()=>{const m=C.current;return Wt(e)?Re(e,m.stampCenter):e==="brush"?[]:m.isDrawing?e==="freehand"?m.points:e==="rectangle"?en(m.start,m.current,Ae()):e==="circular"?wn(m.start,m.current):[]:[]},[e,Re,Ae]),ut=d.useCallback(()=>{pe();const m=ue.current;if(!m)return;const g=m.getContext("2d");if(!g)return;const T=Math.max(1,window.devicePixelRatio||1),I=m.width/T,v=m.height/T;if(g.setTransform(1,0,0,1,0,0),g.clearRect(0,0,m.width,m.height),g.setTransform(T,0,0,T,0,0),$.length>0)for(const V of $){const{region:oe,polygons:q,regionIndex:te,regionKey:Me}=V,Ce=dr(J,Me)?"active":dr(j,Me)?"hover":"default";let Be=Ce==="active"?ee:Ce==="hover"?ye:de;if(_){const Ge=_({region:oe,regionId:Me,regionIndex:te,state:Ce});Be=xt(Be,Ge||void 0)}const tt=Ce==="default"?null:is(Be);for(const Ge of q){const yt=Se(Ge.outer);yt.length>=4&&(tt&&Xe(g,yt,tt,!0,!1),Xe(g,yt,Be,!0,!1));for(const wt of Ge.holes){const qe=Se(wt);qe.length>=4&&(tt&&Xe(g,qe,tt,!0,!1),Xe(g,qe,Be,!0,!1))}}}if(le.length>0)for(const V of le)for(const oe of V.polygons){const q=Se(oe.outer);q.length>=4&&Xe(g,q,he,!0,!1);for(const te of oe.holes){const Me=Se(te);Me.length>=4&&Xe(g,Me,he,!0,!1)}}if(Array.isArray(se)&&se.length>0){const V=Se(_e([[0,0],[t,0],[t,n],[0,n]]));Qo({ctx:g,overlayShapes:se,imageOuterRing:V,worldToScreenPoints:Se,baseStrokeStyle:de,onInvertedFillDebug:globalThis.__OPEN_PLANT_DEBUG_OVERLAY__?oe=>{const q=String(oe.id),te=`${oe.outerRingPoints}|${oe.sourceRingCount}|${oe.holeRingCount}|${oe.fillColor}`;Fe.current.get(q)!==te&&(Fe.current.set(q,te),console.debug("[open-plant] invertedFill",oe))}:void 0})}const me=ct();if(M){if(e==="brush")zo(g,C.current,G),Oo(g,C.current,a.current,G);else if(me.length>0)if(e==="freehand"){const V=Se(me);V.length>=2&&Xe(g,V,de,!1,!1),V.length>=3&&Xe(g,Se(_e(me)),de,!0,!0,re)}else{const V=Se(me);V.length>=4&&Xe(g,V,de,!0,!0,re)}}if($.length>0){const V=Math.max(1e-6,a.current?.getViewState?.().zoom??1),oe=typeof O=="number"&&Number.isFinite(O)?Math.max(0,O):Gr(Te,V,a.current?.getZoomRange?.());for(const q of $){if(!q.region.label)continue;const te=Xr(q.polygons,B);if(!te)continue;const Me=st(a.current?.worldToScreen(te[0],te[1])??[]);if(!Me)continue;let Ce=Vr(ne,H?.({region:q.region,regionId:q.regionKey,regionIndex:q.regionIndex,zoom:V}));oe>0&&(Ce={...Ce,offsetY:Ce.offsetY+oe}),Ko(g,q.region.label,Me,I,v,Ce,D)}}if(K.enabled&&M&&(e==="freehand"||e==="rectangle"||e==="circular")){const V=C.current;if(V.isDrawing){const oe=e==="freehand"?_e(me):me;if(oe.length>=4){const q=Zt(oe),te=typeof r=="number"&&Number.isFinite(r)&&r>0?r:0,Me=te>0?q*te*te/(cr*cr):0,Ce=K.format(Me),Be=V.cursorScreen??(V.current?st(a.current?.worldToScreen(V.current[0],V.current[1])??[]):null);Be&&jo(g,Ce,Be,I,v,K.style,K.cursorOffsetX,K.cursorOffsetY)}}}},[M,e,ct,pe,Se,t,n,a,$,se,j,J,de,ye,ee,re,le,he,_,H,ne,K,Te,B,D,O,r,G]),W=d.useCallback(()=>{Oe.current||(Oe.current=!0,requestAnimationFrame(()=>{Oe.current=!1,ut()}))},[ut]),Y=d.useCallback((m=!1)=>{const g=C.current,T=ue.current;T&&g.pointerId!==null&&T.hasPointerCapture(g.pointerId)&&T.releasePointerCapture(g.pointerId),g.isDrawing=!1,g.pointerId=null,g.start=null,g.current=null,g.points=[],g.screenPoints=[],g.stampCenter=null,m||(g.cursor=null,g.cursorScreen=null)},[]),ie=d.useCallback(m=>{const g=a.current;if(!g||t<=0||n<=0)return null;const T=st(g.screenToWorld(m.clientX,m.clientY));return T?Jt(T,t,n):null},[a,t,n]),be=d.useCallback(m=>{const g=ue.current;if(!g)return null;const T=g.getBoundingClientRect(),I=k(m.clientX-T.left,0,T.width),v=k(m.clientY-T.top,0,T.height);return!Number.isFinite(I)||!Number.isFinite(v)?null:[I,v]},[]),pt=d.useCallback(()=>{const m=C.current;if(!m.isDrawing){Y(!0),W();return}let g=[];if(e==="freehand")m.points.length>=uo&&(g=_e(m.points));else if(e==="rectangle")g=en(m.start,m.current,Ae());else if(e==="circular")g=wn(m.start,m.current);else if(e==="brush"){const T=m.points[m.points.length-1]??m.current??m.start;if(G.clickSelectRoi&&T&&m.points.length<=1&&c?.(T)){Y(!0),W();return}const I=G.edgeDetail,v=Math.max(Eo,G.radius*2/(vo*I)),me=m.screenPoints.length>0?m.screenPoints:Se(m.points),V=io(me,{radius:G.radius,minRasterStep:v,circleSides:Math.max(24,Math.round(64*I)),simplifyTolerance:v*.25,smoothingPasses:G.edgeSmoothing}),oe=[];for(const q of V){const te=De(q);te&&oe.push(te)}g=_e(oe)}(e==="freehand"||e==="rectangle"||e==="circular"||e==="brush")&&yr(g)&&u&&u({tool:e,intent:e==="brush"?"brush":"roi",coordinates:g,bbox:fr(g),areaPx:Zt(g)}),Y(!0),W()},[e,u,Y,W,Se,De,Ae,G.radius,G.edgeDetail,G.edgeSmoothing,G.clickSelectRoi,c]),bt=d.useCallback((m,g)=>{const T=Re(m,g);if(!yr(T))return;const I=m==="stamp-rectangle-4096px"?"patch":"roi",v={tool:m,intent:I,coordinates:T,bbox:fr(T),areaPx:Zt(T)};u?.(v),I==="patch"&&l&&l(v)},[Re,u,l]),Qe=d.useCallback((m,g,T)=>{const I=lr*lr,v=m.screenPoints[m.screenPoints.length-1];if(!v){m.points.push(g),m.screenPoints.push(T),m.current=g;return}const me=T[0]-v[0],V=T[1]-v[1];me*me+V*V>=I?(m.points.push(g),m.screenPoints.push(T)):(m.points[m.points.length-1]=g,m.screenPoints[m.screenPoints.length-1]=T),m.current=g},[]),vt=d.useCallback(m=>{if(!M||e==="cursor"||m.button!==0)return;const g=ie(m);if(!g)return;const T=be(m);if(!T)return;if(m.preventDefault(),m.stopPropagation(),Wt(e)){const me=C.current;me.stampCenter=g,bt(e,g),W();return}const I=ue.current;I&&I.setPointerCapture(m.pointerId);const v=C.current;v.isDrawing=!0,v.pointerId=m.pointerId,v.start=g,v.current=g,v.cursor=g,v.cursorScreen=T,v.points=e==="freehand"||e==="brush"?[g]:[],v.screenPoints=e==="brush"?[T]:[],W()},[M,e,ie,be,bt,W]),et=d.useCallback(m=>{if(!M||e==="cursor")return;const g=ie(m);if(!g)return;const T=be(m);if(!T)return;const I=C.current;if(I.cursor=g,I.cursorScreen=T,Wt(e)){I.stampCenter=g,m.preventDefault(),m.stopPropagation(),W();return}if(e==="brush"){if(!I.isDrawing||I.pointerId!==m.pointerId){W();return}m.preventDefault(),m.stopPropagation(),Qe(I,g,T),W();return}if(!(!I.isDrawing||I.pointerId!==m.pointerId)){if(m.preventDefault(),m.stopPropagation(),e==="freehand"){const v=a.current,me=Math.max(1e-6,v?.getViewState?.().zoom??1),V=lo/me,oe=V*V,q=I.points[I.points.length-1];if(!q)I.points.push(g);else{const te=g[0]-q[0],Me=g[1]-q[1];te*te+Me*Me>=oe&&I.points.push(g)}}else I.current=g;W()}},[M,e,ie,be,W,a,Qe]),_t=d.useCallback(m=>{const g=C.current;if(!g.isDrawing||g.pointerId!==m.pointerId)return;m.preventDefault(),m.stopPropagation();const T=ie(m),I=be(m);T&&(g.cursor=T,I&&(g.cursorScreen=I),e==="brush"?I&&Qe(g,T,I):g.current=T);const v=ue.current;v&&v.hasPointerCapture(m.pointerId)&&v.releasePointerCapture(m.pointerId),pt()},[pt,ie,be,e,Qe]),Ft=d.useCallback(()=>{const m=C.current;let g=!1;e==="brush"&&!m.isDrawing&&m.cursor&&(m.cursor=null,m.cursorScreen=null,g=!0),Wt(e)&&m.stampCenter&&(m.stampCenter=null,g=!0),g&&W()},[e,W]);return d.useEffect(()=>{pe(),W();const m=ue.current;if(!m)return;const g=new ResizeObserver(()=>{pe(),W()});return g.observe(m),()=>{g.disconnect()}},[pe,W]),d.useEffect(()=>{M||Y(),W()},[M,W,Y]),d.useEffect(()=>{We.current!==e&&(We.current=e,Y(),W())},[e,Y,W]),d.useEffect(()=>{W()},[f,z,se,W]),d.useEffect(()=>{if(U)return U.current=W,()=>{U.current===W&&(U.current=null)}},[U,W]),d.useEffect(()=>{if(!M)return;const m=g=>{g.key==="Escape"&&(Y(),W())};return window.addEventListener("keydown",m),()=>{window.removeEventListener("keydown",m)}},[M,Y,W]),ze.jsx("canvas",{ref:ue,className:Q,style:we,onPointerDown:vt,onPointerMove:et,onPointerUp:_t,onPointerCancel:_t,onPointerLeave:Ft,onContextMenu:m=>{M&&m.preventDefault()},onWheel:m=>{if(!M)return;const g=ue.current,T=a.current;if(!g||typeof T?.zoomBy!="function")return;m.preventDefault(),m.stopPropagation();const I=g.getBoundingClientRect(),v=m.clientX-I.left,me=m.clientY-I.top;T.zoomBy(m.deltaY<0?go:po,v,me),W()}})}function wr(e){return String(e??"").replace(/\/+$/,"")}function Hr(e){const t=String(e??"");return t.startsWith("/")?t:`/${t}`}function ss(e){const t=wr(e);if(!t)return"";if(/\/TileGroup\d+$/i.test(t))return t;let n=null;try{n=new URL(t)}catch{n=null}if(n){const r=`${n.protocol}//${n.host}`,i=wr(n.pathname||"");return/\/ims$/i.test(i)?`${r}${i}`:/\/tiles$/i.test(i)?`${r}${i}`:`${r}${i}/tiles`}return/\/ims$/i.test(t)?"/ims":/\/tiles$/i.test(t)?`${t}`:`${t}/tiles`}function as(e,t){const n=e?.imsInfo??{},r=!!e?.imsInfo,i=Number(n.width??e?.width??0),o=Number(n.height??e?.height??0),s=Number(n.tileSize??e?.tileSize??0),a=Number(n.zoom??e?.zoom??0),c=String(n.path??e?.path??""),u=Number(n.mpp??e?.mpp??0);if(!i||!o||!s||!c)throw new Error("Incomplete image metadata: width/height/tileSize/path required");const l=Array.isArray(e?.terms)?e.terms.map(b=>({termId:String(b?.termId??""),termName:String(b?.termName??""),termColor:String(b?.termColor??"")})):[],h=Hr(c),f=ss(t),y=r?(b,x,w)=>`${f}${h}/${b}/${w}_${x}.webp`:void 0;return{id:e?._id||"unknown",name:e?.name||"unknown",width:i,height:o,mpp:Number.isFinite(u)&&u>0?u:void 0,tileSize:s,maxTierZoom:Number.isFinite(a)?Math.max(0,Math.floor(a)):0,tilePath:c,tileBaseUrl:t,terms:l,tileUrlBuilder:y}}function Fn(e,t,n,r){if(e.tileUrlBuilder)return e.tileUrlBuilder(t,n,r);const i=Hr(e.tilePath);return`${e.tileBaseUrl}${i}/${t}/${r}_${n}.webp`}const ve={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:"#171719",viewportBorderStyle:"dash",viewportFillColor:"transparent",interactive:!0,showThumbnail:!0,maxThumbnailTiles:16};function Sr(e,t,n,r){const i=t.length;if(i===4){for(let o=0;o<i;o+=1){const s=t[o],a=t[(o+1)%i],c=Math.hypot(a[0]-s[0],a[1]-s[1]);if(c<1e-6)continue;const u=Math.max(1,Math.round((c+r)/(n+r))),l=u*n+(u-1)*r,h=c/Math.max(1e-6,l),f=n*h,y=r*h;e.beginPath(),e.moveTo(s[0],s[1]),e.lineTo(a[0],a[1]),e.setLineDash([f,y]),e.lineDashOffset=0,e.stroke()}e.setLineDash([]),e.lineDashOffset=0}}function mt(e,t,n=1){return typeof e!="number"||!Number.isFinite(e)?t:Math.max(n,e)}function Yt(e){return Array.isArray(e)&&e.length===4&&Number.isFinite(e[0])&&Number.isFinite(e[1])&&Number.isFinite(e[2])&&Number.isFinite(e[3])}const cs={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 $r({source:e,projectorRef:t,authToken:n="",options:r,invalidateRef:i,className:o,style:s}){const a=d.useRef(null),c=d.useRef(null),u=d.useRef(null),l=d.useRef({active:!1,pointerId:null}),h=d.useRef(null),f=d.useRef(!1),y=mt(r?.width,ve.width,64),b=mt(r?.height,ve.height,48),x=d.useMemo(()=>{const C=Math.max(1,e.width),M=Math.max(1,e.height),z=C/M,ce=y/b;let $,le;return z>ce?($=y,le=y/z):(le=b,$=b*z),{x:(y-$)/2,y:(b-le)/2,w:$,h:le}},[e.width,e.height,y,b]),w=mt(r?.margin,ve.margin,0),A=mt(r?.borderRadius,ve.borderRadius,0),E=mt(r?.borderWidth,ve.borderWidth,0),X=Math.max(1,Math.round(mt(r?.maxThumbnailTiles,ve.maxThumbnailTiles,1))),R=r?.backgroundColor||ve.backgroundColor,_=r?.borderColor||ve.borderColor,H=r?.viewportBorderColor||ve.viewportBorderColor,se=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:ve.viewportBorderStyle,j=r?.viewportFillColor??ve.viewportFillColor,J=r?.interactive??ve.interactive,ae=r?.showThumbnail??ve.showThumbnail,ge=r?.position||ve.position,Te=r?.onClose,B=r?.closeIcon,D=r?.closeButtonStyle,O=d.useMemo(()=>{const C={};return ge==="top-left"||ge==="bottom-left"?C.left=w:C.right=w,ge==="top-left"||ge==="top-right"?C.top=w:C.bottom=w,{position:"absolute",...C,width:y,height:b,borderRadius:A,overflow:"hidden",zIndex:4,pointerEvents:J?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[w,ge,y,b,A,J,s]),U=d.useCallback(()=>{const C=a.current;if(!C)return;const M=C.getContext("2d");if(!M)return;const z=y,ce=b,$=Math.max(1,window.devicePixelRatio||1),le=Math.max(1,Math.round(z*$)),de=Math.max(1,Math.round(ce*$));(C.width!==le||C.height!==de)&&(C.width=le,C.height=de),M.setTransform(1,0,0,1,0,0),M.clearRect(0,0,C.width,C.height),M.setTransform($,0,0,$,0,0),M.fillStyle=R,M.fillRect(0,0,z,ce);const{x:ye,y:ee,w:he,h:re}=x,ne=c.current;ne&&M.drawImage(ne,ye,ee,he,re),M.strokeStyle=_,M.lineWidth=E,M.strokeRect(E*.5,E*.5,z-E,ce-E);const K=t.current,xe=K?.getViewBounds?.(),G=K?.getViewCorners?.(),we=Yt(xe)?xe:Yt(u.current)?u.current:null;if(!we)return;u.current=we;const pe=he/Math.max(1,e.width),Se=re/Math.max(1,e.height),De=Array.isArray(G)&&G.length>=4&&G.every(ie=>Array.isArray(ie)&&ie.length>=2&&Number.isFinite(ie[0])&&Number.isFinite(ie[1]))?G:null,Ae=se==="dash";if(De){const ie=De.map(be=>[ye+be[0]*pe,ee+be[1]*Se]);M.save(),M.beginPath(),M.rect(ye,ee,he,re),M.clip(),M.beginPath();for(let be=0;be<ie.length;be+=1)be===0?M.moveTo(ie[be][0],ie[be][1]):M.lineTo(ie[be][0],ie[be][1]);M.closePath(),M.fillStyle=j,M.fill(),M.strokeStyle=H,M.lineWidth=2.25,Ae?Sr(M,ie,4,3):M.stroke(),M.restore();return}const Ie=k(ye+we[0]*pe,ye,ye+he),Re=k(ee+we[1]*Se,ee,ee+re),ct=k(ye+we[2]*pe,ye,ye+he),ut=k(ee+we[3]*Se,ee,ee+re),W=Math.max(1,ct-Ie),Y=Math.max(1,ut-Re);if(M.fillStyle=j,M.fillRect(Ie,Re,W,Y),M.strokeStyle=H,M.lineWidth=2.25,Ae){const ie=[[Ie+.5,Re+.5],[Ie+.5+Math.max(1,W-1),Re+.5],[Ie+.5+Math.max(1,W-1),Re+.5+Math.max(1,Y-1)],[Ie+.5,Re+.5+Math.max(1,Y-1)]];Sr(M,ie,4,3)}else M.strokeRect(Ie+.5,Re+.5,Math.max(1,W-1),Math.max(1,Y-1))},[y,b,x,R,_,E,t,e.width,e.height,j,H,se]),Q=d.useCallback(()=>{f.current||(f.current=!0,h.current=requestAnimationFrame(()=>{f.current=!1,h.current=null,U()}))},[U]),Le=d.useCallback((C,M)=>{const z=a.current;if(!z)return null;const ce=z.getBoundingClientRect();if(!ce.width||!ce.height)return null;const $=ce.width/y,le=ce.height/b,de=x.x*$,ye=x.y*le,ee=x.w*$,he=x.h*le,re=k((C-ce.left-de)/ee,0,1),ne=k((M-ce.top-ye)/he,0,1);return[re*e.width,ne*e.height]},[e.width,e.height,y,b,x]),ue=d.useCallback((C,M)=>{const z=t.current;if(!z)return;if(z.setViewCenter){z.setViewCenter(C,M),Q();return}const ce=z.getViewBounds?.(),$=Yt(ce)?ce:Yt(u.current)?u.current:null;if(!$)return;const le=Math.max(1e-6,$[2]-$[0]),de=Math.max(1e-6,$[3]-$[1]);z.setViewState({offsetX:C-le*.5,offsetY:M-de*.5}),Q()},[t,Q]),Oe=d.useCallback(C=>{if(!J||C.button!==0)return;const M=a.current;if(!M)return;const z=Le(C.clientX,C.clientY);z&&(C.preventDefault(),C.stopPropagation(),M.setPointerCapture(C.pointerId),l.current={active:!0,pointerId:C.pointerId},ue(z[0],z[1]))},[J,Le,ue]),Fe=d.useCallback(C=>{const M=l.current;if(!M.active||M.pointerId!==C.pointerId)return;const z=Le(C.clientX,C.clientY);z&&(C.preventDefault(),C.stopPropagation(),ue(z[0],z[1]))},[Le,ue]),We=d.useCallback(C=>{const M=l.current;if(!M.active||M.pointerId!==C.pointerId)return;const z=a.current;if(z&&z.hasPointerCapture(C.pointerId))try{z.releasePointerCapture(C.pointerId)}catch{}l.current={active:!1,pointerId:null},Q()},[Q]);return d.useEffect(()=>{let C=!1;c.current=null,Q();const M=0,z=2**(e.maxTierZoom-M),ce=Math.ceil(e.width/z),$=Math.ceil(e.height/z),le=Math.max(1,Math.ceil(ce/e.tileSize)),de=Math.max(1,Math.ceil($/e.tileSize)),ye=le*de;if(!ae||ye>X)return;const ee=document.createElement("canvas");ee.width=Math.max(1,Math.round(x.w)),ee.height=Math.max(1,Math.round(x.h));const he=ee.getContext("2d");if(!he)return;he.fillStyle=R,he.fillRect(0,0,ee.width,ee.height);const re=[];for(let ne=0;ne<de;ne+=1)for(let K=0;K<le;K+=1){const xe=K*e.tileSize*z,G=ne*e.tileSize*z,we=Math.min((K+1)*e.tileSize,ce)*z,pe=Math.min((ne+1)*e.tileSize,$)*z;re.push({url:Fn(e,M,K,ne),bounds:[xe,G,we,pe]})}return Promise.allSettled(re.map(async ne=>{const K=!!n,xe=await fetch(ne.url,{headers:K?{Authorization:n}:void 0});if(!xe.ok)throw new Error(`HTTP ${xe.status}`);const G=await createImageBitmap(await xe.blob());return{tile:ne,bitmap:G}})).then(ne=>{if(C){for(const G of ne)G.status==="fulfilled"&&G.value.bitmap.close();return}const K=ee.width/Math.max(1,e.width),xe=ee.height/Math.max(1,e.height);for(const G of ne){if(G.status!=="fulfilled")continue;const{tile:{bounds:we},bitmap:pe}=G.value,Se=we[0]*K,De=we[1]*xe,Ae=Math.max(1,(we[2]-we[0])*K),Ie=Math.max(1,(we[3]-we[1])*xe);he.drawImage(pe,Se,De,Ae,Ie),pe.close()}c.current=ee,Q()}),()=>{C=!0}},[e,n,x,R,ae,X,Q]),d.useEffect(()=>{Q()},[Q]),d.useEffect(()=>{if(i)return i.current=Q,()=>{i.current===Q&&(i.current=null)}},[i,Q]),d.useEffect(()=>()=>{l.current={active:!1,pointerId:null},h.current!==null&&(cancelAnimationFrame(h.current),h.current=null),f.current=!1},[]),ze.jsxs("div",{className:o,style:O,children:[ze.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:Oe,onPointerMove:Fe,onPointerUp:We,onPointerCancel:We,onContextMenu:C=>{C.preventDefault()},onWheel:C=>{C.preventDefault(),C.stopPropagation()}}),Te&&ze.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:C=>{C.stopPropagation(),Te()},style:D?{...D}:{...cs},children:B??"×"})]})}function us({imageWidth:e,imageHeight:t,tiles:n,viewState:r,className:i,style:o}){const s=d.useRef(null),a=d.useRef(null),c=d.useMemo(()=>({width:"100%",height:"100%",display:"block",...o}),[o]);return d.useEffect(()=>{const u=s.current;if(!u)return;const l=new vr({canvas:u,imageWidth:e,imageHeight:t,initialViewState:r});return a.current=l,l.setTiles(n),()=>{l.destroy(),a.current=null}},[e,t]),d.useEffect(()=>{const u=a.current;u&&u.setTiles(n)},[n]),d.useEffect(()=>{const u=a.current;!u||!r||u.setViewState(r)},[r]),ze.jsx("canvas",{ref:s,className:i,style:c})}function Ct(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return null;const n=Et(t??[]);if(n.length===0){const b={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return e.fillModes instanceof Uint8Array&&(b.fillModes=new Uint8Array(0)),e.ids instanceof Uint32Array&&(b.ids=new Uint32Array(0)),b}const r=at(e),i=e.positions,o=e.paletteIndices,s=e.fillModes instanceof Uint8Array&&e.fillModes.length>=r?e.fillModes:null,a=e.ids instanceof Uint32Array&&e.ids.length>=r?e.ids:null,c=new Float32Array(r*2),u=new Uint16Array(r),l=s?new Uint8Array(r):null,h=a?new Uint32Array(r):null;let f=0;for(let b=0;b<r;b+=1){const x=i[b*2],w=i[b*2+1];jt(x,w,n)&&(c[f*2]=x,c[f*2+1]=w,u[f]=o[b],l&&(l[f]=s[b]),h&&(h[f]=a[b]),f+=1)}const y={count:f,positions:c.subarray(0,f*2),paletteIndices:u.subarray(0,f)};return l&&(y.fillModes=l.subarray(0,f)),h&&(y.ids=h.subarray(0,f)),y}function Zr(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return new Uint32Array(0);const n=Et(t??[]);if(n.length===0)return new Uint32Array(0);const r=at(e);if(r===0)return new Uint32Array(0);const i=e.positions,o=new Uint32Array(r);let s=0;for(let a=0;a<r;a+=1){const c=i[a*2],u=i[a*2+1];jt(c,u,n)&&(o[s]=a,s+=1)}return o.subarray(0,s)}let Xt=null;const ls=`
|
|
33
33
|
struct Params {
|
|
34
34
|
pointCount: u32,
|
|
35
35
|
boundsCount: u32,
|
|
@@ -60,7 +60,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
60
60
|
}
|
|
61
61
|
outputMask[i] = inside;
|
|
62
62
|
}
|
|
63
|
-
`;function ls(){if(typeof navigator>"u")return!1;const e=navigator;return typeof e.gpu=="object"&&e.gpu!==null}function Zr(){if(!ls())return null;const t=navigator.gpu;if(!t||typeof t!="object")return null;const n=t;return typeof n.requestAdapter!="function"?null:n}const Xt=globalThis.GPUShaderStage?.COMPUTE??4,fn=globalThis.GPUBufferUsage?.STORAGE??128,Vt=globalThis.GPUBufferUsage?.COPY_DST??8,fs=globalThis.GPUBufferUsage?.COPY_SRC??4,ds=globalThis.GPUBufferUsage?.UNIFORM??64,hs=globalThis.GPUBufferUsage?.MAP_READ??1,ms=globalThis.GPUMapMode?.READ??1;async function gs(){const e=Zr();if(!e)return{supported:!1,features:[]};const t=await e.requestAdapter();return t?{supported:!0,adapterName:t.info?.description??t.info?.vendor??"unknown",features:Array.from(t.features),limits:{maxStorageBufferBindingSize:Number(t.limits.maxStorageBufferBindingSize),maxComputeInvocationsPerWorkgroup:Number(t.limits.maxComputeInvocationsPerWorkgroup),maxComputeWorkgroupSizeX:Number(t.limits.maxComputeWorkgroupSizeX)}}:{supported:!1,features:[]}}async function ps(){return Yt||(Yt=(async()=>{const e=Zr();if(!e)return null;const t=await e.requestAdapter();if(!t)return null;const n=await t.requestDevice(),r=n.createBindGroupLayout({entries:[{binding:0,visibility:Xt,buffer:{type:"read-only-storage"}},{binding:1,visibility:Xt,buffer:{type:"read-only-storage"}},{binding:2,visibility:Xt,buffer:{type:"storage"}},{binding:3,visibility:Xt,buffer:{type:"uniform"}}]}),i=n.createComputePipeline({layout:n.createPipelineLayout({bindGroupLayouts:[r]}),compute:{module:n.createShaderModule({code:us}),entryPoint:"main"}});return{device:n,pipeline:i,bindGroupLayout:r}})(),Yt)}function Gt(e,t){return Math.ceil(e/t)*t}async function Kr(e,t,n){const r=await ps();if(!r)return null;const i=Math.max(0,Math.floor(t)),o=Math.max(0,Math.floor(n.length/4));if(i===0||o===0)return new Uint32Array(0);const s=Math.min(i,Math.floor(e.length/2));if(s===0)return new Uint32Array(0);const a=s*2*Float32Array.BYTES_PER_ELEMENT,c=o*4*Float32Array.BYTES_PER_ELEMENT,u=s*Uint32Array.BYTES_PER_ELEMENT,l=Number(r.device.limits.maxStorageBufferBindingSize);if(a>l||c>l||u>l)return null;const h=r.device.createBuffer({size:Gt(a,4),usage:fn|Vt}),f=r.device.createBuffer({size:Gt(c,4),usage:fn|Vt}),y=r.device.createBuffer({size:Gt(u,4),usage:fn|fs}),b=r.device.createBuffer({size:16,usage:ds|Vt}),x=r.device.createBuffer({size:Gt(u,4),usage:Vt|hs});r.device.queue.writeBuffer(h,0,e.buffer,e.byteOffset,a),r.device.queue.writeBuffer(f,0,n.buffer,n.byteOffset,c),r.device.queue.writeBuffer(b,0,new Uint32Array([s,o,0,0]));const w=r.device.createBindGroup({layout:r.bindGroupLayout,entries:[{binding:0,resource:{buffer:h}},{binding:1,resource:{buffer:f}},{binding:2,resource:{buffer:y}},{binding:3,resource:{buffer:b}}]}),A=r.device.createCommandEncoder(),I=A.beginComputePass();I.setPipeline(r.pipeline),I.setBindGroup(0,w),I.dispatchWorkgroups(Math.ceil(s/256)),I.end(),A.copyBufferToBuffer(y,0,x,0,u),r.device.queue.submit([A.finish()]),await x.mapAsync(ms);const X=x.getMappedRange(),R=new Uint32Array(X.slice(0));return x.unmap(),h.destroy(),f.destroy(),y.destroy(),b.destroy(),x.destroy(),R}async function jr(e,t,n={}){const r=fe(),i=n.bridgeToDraw===!0;if(!e||!e.count||!e.positions||!e.paletteIndices)return{data:null,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}};const o=It(t??[]);if(o.length===0){const R={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return e.fillModes instanceof Uint8Array&&(R.fillModes=new Uint8Array(0)),e.ids instanceof Uint32Array&&(R.ids=new Uint32Array(0)),{data:R,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const s=ct(e),a=e.fillModes instanceof Uint8Array&&e.fillModes.length>=s?e.fillModes:null,c=e.ids instanceof Uint32Array&&e.ids.length>=s?e.ids:null;if(s===0){const R={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(R.fillModes=new Uint8Array(0)),c&&(R.ids=new Uint32Array(0)),{data:R,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const u=new Float32Array(o.length*4);for(let R=0;R<o.length;R+=1){const _=R*4,H=o[R];u[_]=H.minX,u[_+1]=H.minY,u[_+2]=H.maxX,u[_+3]=H.maxY}let l=null,h=!1;try{l=await Kr(e.positions,s,u),h=!!l}catch{l=null,h=!1}if(!l)return{data:Rt(e,t),meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!1,candidateCount:s,bridgedToDraw:!1}};let f=0;for(let R=0;R<s;R+=1)l[R]===1&&(f+=1);const y=new Uint32Array(f);if(f>0){let R=0;for(let _=0;_<s;_+=1)l[_]===1&&(y[R]=_,R+=1)}if(f===0){if(i){const _={count:s,positions:e.positions.subarray(0,s*2),paletteIndices:e.paletteIndices.subarray(0,s),drawIndices:new Uint32Array(0)};return a&&(_.fillModes=a.subarray(0,s)),c&&(_.ids=c.subarray(0,s)),{data:_,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!0}}}const R={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(R.fillModes=new Uint8Array(0)),c&&(R.ids=new Uint32Array(0)),{data:R,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const R=new Uint32Array(f);let _=0;for(let ae=0;ae<f;ae+=1){const te=y[ae]??0,ne=e.positions[te*2],ce=e.positions[te*2+1];Kt(ne,ce,o)&&(R[_]=te,_+=1)}const H={count:s,positions:e.positions.subarray(0,s*2),paletteIndices:e.paletteIndices.subarray(0,s),drawIndices:R.subarray(0,_)};return a&&(H.fillModes=a.subarray(0,s)),c&&(H.ids=c.subarray(0,s)),{data:H,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!0,candidateCount:f,bridgedToDraw:!0}}}const b=new Float32Array(f*2),x=new Uint16Array(f),w=a?new Uint8Array(f):null,A=c?new Uint32Array(f):null;let I=0;for(let R=0;R<f;R+=1){const _=y[R]??0,H=e.positions[_*2],ae=e.positions[_*2+1];Kt(H,ae,o)&&(b[I*2]=H,b[I*2+1]=ae,x[I]=e.paletteIndices[_],w&&(w[I]=a[_]),A&&(A[I]=c[_]),I+=1)}const X={count:I,positions:b.subarray(0,I*2),paletteIndices:x.subarray(0,I)};return w&&(X.fillModes=w.subarray(0,I)),A&&(X.ids=A.subarray(0,I)),{data:X,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!0,candidateCount:f,bridgedToDraw:!1}}}class Jr{constructor(t,n){S(this,"worker",null);S(this,"supported",!0);S(this,"requestId",1);S(this,"pendingById",new Map);S(this,"handleMessage",t=>{const n=t.data;if(!n)return;const r=this.pendingById.get(n.id);r&&(this.pendingById.delete(n.id),this.handlers.onResponse(n,r))});S(this,"handleError",()=>{this.supported=!1,this.teardownWorker("worker crashed")});this.createWorker=t,this.handlers=n}beginRequest(t){const n=this.getOrCreateWorker();if(!n)return null;const r=this.requestId++;return this.pendingById.set(r,t),{id:r,worker:n}}cancelRequest(t){const n=this.pendingById.get(t);if(n)return this.pendingById.delete(t),n}terminate(t="worker terminated"){this.teardownWorker(t)}getOrCreateWorker(){if(!this.supported)return null;if(this.worker)return this.worker;try{const t=this.createWorker();return t.addEventListener("message",this.handleMessage),t.addEventListener("error",this.handleError),this.worker=t,t}catch{return this.supported=!1,null}}teardownWorker(t){this.worker&&(this.worker.removeEventListener("message",this.handleMessage),this.worker.removeEventListener("error",this.handleError),this.worker.terminate(),this.worker=null);const n=new Error(t);for(const[,r]of this.pendingById)this.handlers.rejectPending(r,n);this.pendingById.clear()}}const Ct=new Jr(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/roi-clip-worker-BDVQwN2T.js").href:new URL("assets/roi-clip-worker-BDVQwN2T.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:gt&>.tagName.toUpperCase()==="SCRIPT"&>.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(e,t)=>{if(e.type==="roi-clip-failure"){t.reject(new Error(e.error||"worker clip failed"));return}if(e.type==="roi-clip-index-success"){if(t.kind!=="index"){t.reject(new Error("worker response mismatch: expected point data result"));return}const c=Math.max(0,Math.floor(e.count)),u=new Uint32Array(e.indices).subarray(0,c);t.resolve({indices:u,meta:{mode:"worker",durationMs:Number.isFinite(e.durationMs)?e.durationMs:fe()-t.startMs}});return}if(t.kind!=="data"){t.reject(new Error("worker response mismatch: expected index result"));return}const n=Math.max(0,Math.floor(e.count)),r=new Float32Array(e.positions),i=new Uint16Array(e.paletteIndices),o=e.fillModes?new Uint8Array(e.fillModes):null,s=e.ids?new Uint32Array(e.ids):null,a={count:n,positions:r.subarray(0,n*2),paletteIndices:i.subarray(0,n)};o&&(a.fillModes=o.subarray(0,n)),s&&(a.ids=s.subarray(0,n)),t.resolve({data:a,meta:{mode:"worker",durationMs:Number.isFinite(e.durationMs)?e.durationMs:fe()-t.startMs}})},rejectPending:(e,t)=>{e.reject(t)}});function bs(){Ct.terminate("worker terminated")}async function Qr(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return{data:null,meta:{mode:"worker",durationMs:0}};const n=ct(e),r=e.positions.slice(0,n*2),i=e.paletteIndices.slice(0,n),o=e.fillModes instanceof Uint8Array&&e.fillModes.length>=n?e.fillModes.slice(0,n):null,s=e.ids instanceof Uint32Array&&e.ids.length>=n?e.ids.slice(0,n):null;return new Promise((a,c)=>{const u=fe(),l=Ct.beginRequest({kind:"data",resolve:a,reject:c,startMs:u});if(!l){a({data:Rt(e,t),meta:{mode:"sync",durationMs:fe()-u}});return}const h={type:"roi-clip-request",id:l.id,count:n,positions:r.buffer,paletteIndices:i.buffer,fillModes:o?.buffer,ids:s?.buffer,polygons:t??[]},f=[r.buffer,i.buffer];o&&f.push(o.buffer),s&&f.push(s.buffer);try{l.worker.postMessage(h,f)}catch(y){const b=Ct.cancelRequest(l.id);b?b.reject(y):c(y)}})}async function ys(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return{indices:new Uint32Array(0),meta:{mode:"worker",durationMs:0}};const n=ct(e),r=e.positions.slice(0,n*2);return new Promise((i,o)=>{const s=fe(),a=Ct.beginRequest({kind:"index",resolve:i,reject:o,startMs:s});if(!a){i({indices:$r(e,t),meta:{mode:"sync",durationMs:fe()-s}});return}const c={type:"roi-clip-index-request",id:a.id,count:n,positions:r.buffer,polygons:t??[]};try{a.worker.postMessage(c,[r.buffer])}catch(u){const l=Ct.cancelRequest(a.id);l?l.reject(u):o(u)}})}const ws=24,Ss=1024,xs=4,Zt=-1;function xt(e,t,n){return(e*73856093^t*19349663)>>>0&n}function Ms(e,t,n){if(e<=0||t<=0||n<=0)return 256;const r=Math.max(1,e*t),o=Math.sqrt(r/Math.max(1,n))*xs;return Math.max(ws,Math.min(Ss,o))}function As(e,t){if(!(e instanceof Uint32Array)||e.length===0)return null;let n=!0;for(let o=0;o<e.length;o+=1)if(!(e[o]<t)){n=!1;break}if(n)return e;const r=new Uint32Array(e.length);let i=0;for(let o=0;o<e.length;o+=1)e[o]>=t||(r[i]=e[o],i+=1);return i>0?r.subarray(0,i):null}function Ts(e){const t=Math.max(0,Math.floor(e.count)),n=Math.floor(e.positions.length/2),r=Math.max(0,Math.min(t,n));if(r<=0)return null;const i=As(e.drawIndices??null,r),o=i?i.length:r;if(o===0)return null;const s=Ms(e.sourceWidth,e.sourceHeight,o),a=1/s,c=new Int32Array(o),u=new Int32Array(o);let l=0;if(i)for(let B=0;B<o;B+=1){const U=i[B],z=e.positions[U*2],D=e.positions[U*2+1];!Number.isFinite(z)||!Number.isFinite(D)||(c[l]=Math.floor(z*a),u[l]=Math.floor(D*a),l+=1)}else for(let B=0;B<r;B+=1){const U=e.positions[B*2],z=e.positions[B*2+1];!Number.isFinite(U)||!Number.isFinite(z)||(c[l]=Math.floor(U*a),u[l]=Math.floor(z*a),l+=1)}if(l===0)return null;let h=Math.min(l,Math.max(64,l>>>3));(!Number.isFinite(h)||h<=0)&&(h=l);let f=1;for(;f<h*2;)f<<=1;let y=f-1,b=new Int32Array(f*2),x=new Int32Array(f);b.fill(2147483647);let w=0;const A=new Int32Array(l);for(let B=0;B<l;B+=1){const U=c[B],z=u[B];let D=xt(U,z,y);for(;;){const J=b[D*2];if(J===2147483647){if(b[D*2]=U,b[D*2+1]=z,x[D]=1,A[B]=D,w+=1,w*4>f*3){const be=f;f<<=1,y=f-1;const Me=new Int32Array(f*2),Xe=new Int32Array(f);Me.fill(2147483647);for(let Be=0;Be<be;Be+=1){if(b[Be*2]===2147483647)continue;const ye=b[Be*2],M=b[Be*2+1];let E=xt(ye,M,y);for(;Me[E*2]!==2147483647;)E=E+1&y;Me[E*2]=ye,Me[E*2+1]=M,Xe[E]=x[Be]}for(b=Me,x=Xe,D=xt(U,z,y);b[D*2]!==U||b[D*2+1]!==z;)D=D+1&y;A[B]=D}break}if(J===U&&b[D*2+1]===z){x[D]+=1,A[B]=D;break}D=D+1&y}}const I=new Int32Array(w*2),X=new Uint32Array(w),R=new Uint32Array(w),_=new Int32Array(f);_.fill(Zt);let H=0,ae=0;for(let B=0;B<f;B+=1)b[B*2]!==2147483647&&(I[H*2]=b[B*2],I[H*2+1]=b[B*2+1],X[H]=ae,R[H]=x[B],_[B]=H,ae+=x[B],H+=1);const te=new Uint32Array(l),ne=new Uint32Array(w);if(ne.set(X),i)for(let B=0;B<l;B+=1){const U=_[A[B]];te[ne[U]]=i[B],ne[U]+=1}else{let B=0;for(let U=0;U<r;U+=1){const z=e.positions[U*2],D=e.positions[U*2+1];if(!Number.isFinite(z)||!Number.isFinite(D))continue;const J=_[A[B]];te[ne[J]]=U,ne[J]+=1,B+=1}}let ce=1;for(;ce<w*2;)ce<<=1;const he=ce-1,Pe=new Int32Array(ce);Pe.fill(Zt);for(let B=0;B<w;B+=1){const U=I[B*2],z=I[B*2+1];let D=xt(U,z,he);for(;Pe[D]!==Zt;)D=D+1&he;Pe[D]=B}return{cellSize:s,safeCount:r,cellCount:w,hashCapacity:ce,hashTable:Pe,cellKeys:I,cellOffsets:X,cellLengths:R,pointIndices:te}}function ei(e,t,n){const{hashTable:r,cellKeys:i,hashMask:o}=e;let s=xt(t,n,o);for(;;){const a=r[s];if(a===Zt)return-1;if(i[a*2]===t&&i[a*2+1]===n)return a;s=s+1&o}}function Rs(e,t){if(e.safeCount<=0||e.cellCount<=0)return null;const n=e.safeCount;return{cellSize:e.cellSize,safeCount:n,positions:t.positions.subarray(0,n*2),ids:t.ids instanceof Uint32Array&&t.ids.length>=n?t.ids.subarray(0,n):null,hashCapacity:e.hashCapacity,hashMask:e.hashCapacity-1,hashTable:new Int32Array(e.hashTable),cellKeys:new Int32Array(e.cellKeys),cellOffsets:new Uint32Array(e.cellOffsets),cellLengths:new Uint32Array(e.cellLengths),pointIndices:new Uint32Array(e.pointIndices)}}const wn=new Jr(()=>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:gt&>.tagName.toUpperCase()==="SCRIPT"&>.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(e,t)=>{if(e.type==="point-hit-index-failure"){t.reject(new Error(e.error||"worker index build failed"));return}t.resolve(Rs(e,t.pointData))},rejectPending:(e,t)=>{e.reject(t)}});function Cs(){wn.terminate("worker terminated")}function Ps(e,t){const n=ct(e);if(n<=0)return null;const r=e.positions.subarray(0,n*2),i=Ts({count:n,positions:r,drawIndices:e.drawIndices instanceof Uint32Array?e.drawIndices:null,sourceWidth:t?.width??0,sourceHeight:t?.height??0});return i?{cellSize:i.cellSize,safeCount:n,positions:r,ids:e.ids instanceof Uint32Array&&e.ids.length>=n?e.ids.subarray(0,n):null,hashCapacity:i.hashCapacity,hashMask:i.hashCapacity-1,hashTable:i.hashTable,cellKeys:i.cellKeys,cellOffsets:i.cellOffsets,cellLengths:i.cellLengths,pointIndices:i.pointIndices}:null}async function ti(e,t){if(!e||!e.positions||!e.paletteIndices)return null;const n=ct(e);return n<=0?null:new Promise((r,i)=>{const o={resolve:r,reject:i,pointData:e},s=wn.beginRequest(o);if(!s||!s.worker){r(Ps(e,t));return}const a=e.positions.slice(0,n*2),c=e.drawIndices instanceof Uint32Array&&e.drawIndices.length>0?e.drawIndices.slice():void 0,u={type:"point-hit-index-request",id:s.id,count:n,positions:a.buffer,drawIndices:c?.buffer,sourceWidth:t?.width??0,sourceHeight:t?.height??0},l=[a.buffer];c&&l.push(c.buffer);try{s.worker.postMessage(u,l)}catch(h){const f=wn.cancelRequest(s.id);f?f.reject(h):i(h)}})}function Is(e){const t=[];for(let n=0;n<e.length;n+=1){const r=e[n],i=It([Pt(r?.coordinates)]);if(i.length===0)continue;let o=0;for(const s of i)o+=s.area;t.push({regionId:r.id??n,regionIndex:n,polygons:i,area:Math.max(1e-6,o)})}return t}function Es(e,t){if(Array.isArray(t)){const n=t[e];if(typeof n=="string"&&n.length>0)return n}if(t instanceof Map){const n=t.get(e);if(typeof n=="string"&&n.length>0)return n}return String(e)}function ni(e,t,n={}){const r=Math.max(0,Math.min(Math.floor(e?.count??0),Math.floor((e?.positions?.length??0)/2),e?.paletteIndices?.length??0,e?.fillModes instanceof Uint8Array?e.fillModes.length:Number.MAX_SAFE_INTEGER));let i=null;if(e?.drawIndices instanceof Uint32Array){const f=e.drawIndices;let y=f.length;for(let b=0;b<f.length;b+=1)f[b]<r||(y-=1);if(y===f.length)i=f;else if(y>0){const b=new Uint32Array(y);let x=0;for(let w=0;w<f.length;w+=1){const A=f[w];A>=r||(b[x]=A,x+=1)}i=b}else i=new Uint32Array(0)}const o=i?i.length:r,s=Is(t??[]);if(!e||o===0||s.length===0)return{groups:[],inputPointCount:o,pointsInsideAnyRegion:0,unmatchedPointCount:o};const a=new Map,c=new Map;let u=0;for(let f=0;f<o;f+=1){const y=i?i[f]:f,b=e.positions[y*2],x=e.positions[y*2+1];let w=null;for(const X of s){let R=!1;for(const _ of X.polygons)if(Br(b,x,_)){R=!0;break}R&&(!w||X.area<w.area)&&(w=X)}if(!w)continue;u+=1;const A=e.paletteIndices[y]??0,I=a.get(w.regionIndex)??new Map;I.set(A,(I.get(A)??0)+1),a.set(w.regionIndex,I),c.set(w.regionIndex,(c.get(w.regionIndex)??0)+1)}const l=n.includeEmptyRegions??!1,h=[];for(const f of s){const y=c.get(f.regionIndex)??0;if(!l&&y<=0)continue;const b=a.get(f.regionIndex)??new Map,x=Array.from(b.entries()).map(([w,A])=>({termId:Es(w,n.paletteIndexToTermId),paletteIndex:w,count:A})).sort((w,A)=>A.count-w.count||w.paletteIndex-A.paletteIndex);h.push({regionId:f.regionId,regionIndex:f.regionIndex,totalCount:y,termCounts:x})}return{groups:h,inputPointCount:o,pointsInsideAnyRegion:u,unmatchedPointCount:Math.max(0,o-u)}}function vs(e,t){if(!t)return!1;try{const r=new URL(e,typeof window<"u"?window.location.href:void 0).hostname.toLowerCase();if(r.includes("amazonaws.com")||r.startsWith("s3.")||r.includes(".s3."))return!1}catch{}return!0}class ri{constructor(t){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(t.maxConcurrency??12)),this.maxRetries=Math.max(0,Math.floor(t.maxRetries??2)),this.retryBaseDelayMs=Math.max(10,Math.floor(t.retryBaseDelayMs??120)),this.retryMaxDelayMs=Math.max(this.retryBaseDelayMs,Math.floor(t.retryMaxDelayMs??1200)),this.authToken=t.authToken??"",this.onTileLoad=t.onTileLoad,this.onTileError=t.onTileError,this.onStateChange=t.onStateChange}setAuthToken(t){this.authToken=String(t??"")}schedule(t){if(this.destroyed)return;const n=new Set;for(const r of t)n.add(r.key);this.visibleKeys=n,this.dropInvisibleQueued(n),this.abortInvisibleInflight(n);for(const r of t){if(this.inflight.has(r.key)){const s=this.inflight.get(r.key);s&&(s.tile=r);continue}const i=this.queuedByKey.get(r.key);if(i){i.tile=r;continue}const o={tile:r,attempt:0,readyAt:fe()};this.queue.push(o),this.queuedByKey.set(r.key,o)}this.sortQueue(),this.pump(),this.emitStateChange()}clear(){this.clearPumpTimer(),this.visibleKeys.clear(),this.queue=[],this.queuedByKey.clear();for(const[,t]of this.inflight)t.controller.abort();this.inflight.clear(),this.emitStateChange()}destroy(){this.destroyed||(this.destroyed=!0,this.clear())}getInflightCount(){return this.inflight.size}getSnapshot(){return{inflight:this.inflight.size,queued:this.queue.length,aborted:this.abortedCount,retries:this.retryCount,failed:this.failedCount}}dropInvisibleQueued(t){if(this.queue.length===0)return;const n=[];for(const r of this.queue){if(!t.has(r.tile.key)){this.queuedByKey.delete(r.tile.key);continue}n.push(r)}this.queue=n}abortInvisibleInflight(t){for(const[n,r]of this.inflight)t.has(n)||(this.inflight.delete(n),this.abortedCount+=1,r.controller.abort())}sortQueue(){this.queue.sort((t,n)=>t.readyAt!==n.readyAt?t.readyAt-n.readyAt:t.tile.distance2!==n.tile.distance2?t.tile.distance2-n.tile.distance2:t.tile.tier!==n.tile.tier?n.tile.tier-t.tile.tier:t.tile.key.localeCompare(n.tile.key))}pump(){if(this.destroyed)return;for(this.clearPumpTimer();this.inflight.size<this.maxConcurrency;){const r=this.takeNextReadyQueueItem();if(!r)break;this.startFetch(r)}if(this.inflight.size>=this.maxConcurrency||this.queue.length===0)return;const t=this.queue[0]?.readyAt;if(typeof t!="number")return;const n=Math.max(0,t-fe());this.timerId=window.setTimeout(()=>{this.timerId=null,this.pump()},n)}takeNextReadyQueueItem(){if(this.queue.length===0)return null;const t=fe(),n=this.queue[0];return!n||n.readyAt>t?null:(this.queue.shift(),this.queuedByKey.delete(n.tile.key),n)}startFetch(t){const n=new AbortController,r={tile:t.tile,attempt:t.attempt,controller:n};this.inflight.set(t.tile.key,r),this.emitStateChange();const i=vs(t.tile.url,this.authToken);fetch(t.tile.url,{signal:n.signal,headers:i?{Authorization:this.authToken}:void 0}).then(o=>{if(!o.ok)throw new Error(`HTTP ${o.status}`);return o.blob()}).then(o=>createImageBitmap(o)).then(o=>{if(this.destroyed||n.signal.aborted){o.close();return}if(!this.visibleKeys.has(t.tile.key)){o.close();return}this.onTileLoad(t.tile,o)}).catch(o=>{if(n.signal.aborted||this.destroyed)return;if(t.attempt<this.maxRetries&&this.visibleKeys.has(t.tile.key)){this.retryCount+=1;const a=t.attempt+1,c=this.getRetryDelay(a),u={tile:t.tile,attempt:a,readyAt:fe()+c},l=this.queuedByKey.get(t.tile.key);l?(l.tile=u.tile,l.readyAt=Math.min(l.readyAt,u.readyAt),l.attempt=Math.max(l.attempt,u.attempt)):(this.queue.push(u),this.queuedByKey.set(u.tile.key,u)),this.sortQueue();return}this.failedCount+=1,this.onTileError?.(t.tile,o,t.attempt+1)}).finally(()=>{this.inflight.delete(t.tile.key),this.pump(),this.emitStateChange()})}getRetryDelay(t){const n=Math.max(0,t-1),r=Math.min(this.retryMaxDelayMs,this.retryBaseDelayMs*2**n),i=.85+Math.random()*.3;return Math.round(r*i)}clearPumpTimer(){this.timerId!==null&&(window.clearTimeout(this.timerId),this.timerId=null)}emitStateChange(){this.onStateChange?.(this.getSnapshot())}}function _s(e,t){e.addEventListener("pointerdown",t.pointerDown),e.addEventListener("pointermove",t.pointerMove),e.addEventListener("pointerup",t.pointerUp),e.addEventListener("pointercancel",t.pointerUp),e.addEventListener("wheel",t.wheel,{passive:!1}),e.addEventListener("dblclick",t.doubleClick),e.addEventListener("contextmenu",t.contextMenu),e.addEventListener("webglcontextlost",t.contextLost),e.addEventListener("webglcontextrestored",t.contextRestored)}function Fs(e,t){e.removeEventListener("pointerdown",t.pointerDown),e.removeEventListener("pointermove",t.pointerMove),e.removeEventListener("pointerup",t.pointerUp),e.removeEventListener("pointercancel",t.pointerUp),e.removeEventListener("wheel",t.wheel),e.removeEventListener("dblclick",t.doubleClick),e.removeEventListener("contextmenu",t.contextMenu),e.removeEventListener("webglcontextlost",t.contextLost),e.removeEventListener("webglcontextrestored",t.contextRestored)}function Bs(e,t,n){const r=e.getBoundingClientRect(),i=Math.max(1,r.width||e.clientWidth||1),o=Math.max(1,r.height||e.clientHeight||1),s=Math.max(1,window.devicePixelRatio||1),a=Math.max(1,Math.round(i*s)),c=Math.max(1,Math.round(o*s));(e.width!==a||e.height!==c)&&(e.width=a,e.height=c),n.setViewport(i,o),t.viewport(0,0,a,c)}const Sn=.35,xn=.5,Us=256,Mn=[{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}],Ls=.1,Ds=5,ks=0,Ns=1,zs=-100,Os=100,Ws=2e3;function ii(e){return e*Math.PI/180}function qt(e,t){return!e||!t?e===t:e.buffer===t.buffer&&e.byteOffset===t.byteOffset&&e.byteLength===t.byteLength}function An(e){return e.map(t=>({zoom:t.zoom,size:t.size}))}function Sr(e){if(!e)return An(Mn);const t=new Map;for(const[n,r]of Object.entries(e)){const i=Number(n),o=Number(r);!Number.isFinite(i)||!Number.isFinite(o)||o<=0||t.set(i,o)}return t.size===0?An(Mn):Array.from(t.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function Ys(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n].zoom!==t[n].zoom||e[n].size!==t[n].size)return!1;return!0}function Xs(e,t){if(!Number.isFinite(e))return t[0]?.size??xn;if(t.length===0)return xn;if(t.length===1||e<=t[0].zoom)return t[0].size;for(let s=1;s<t.length;s+=1){const a=t[s-1],c=t[s];if(e>c.zoom)continue;const u=Math.max(1e-6,c.zoom-a.zoom),l=k((e-a.zoom)/u,0,1);return a.size+(c.size-a.size)*l}const n=t[t.length-1],r=t[t.length-2],i=Math.max(1e-6,n.zoom-r.zoom),o=(n.size-r.size)/i;return n.size+(e-n.zoom)*o}function xr(e){return typeof e!="number"||!Number.isFinite(e)?1:k(e,Ls,Ds)}function Mr(e){return typeof e!="number"||!Number.isFinite(e)?0:k(e,ks,Ns)}function dn(e){return typeof e!="number"||!Number.isFinite(e)?0:k(e,zs,Os)}function Ar(e){const t=dn(e?.brightness),n=dn(e?.contrast),r=dn(e?.saturation);return{brightness:t/200,contrast:n/100,saturation:r/100}}function oi(e){return e}function hn(e){return typeof e!="number"||!Number.isFinite(e)?0:k(e,0,Ws)}function Ht(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:Math.max(1e-6,e)}function mn(e){return typeof e=="function"?e:oi}function si(e,t,n){const r=e.getBoundingClientRect(),i=t-r.left-r.width*.5,o=n-r.top-r.height*.5;return Math.atan2(o,i)}function ai(e,t){if(t.pointerId!==null&&e.hasPointerCapture(t.pointerId))try{e.releasePointerCapture(t.pointerId)}catch{}t.dragging=!1,t.mode="none",t.rotateLastAngleRad=null,t.pointerId=null,e.classList.remove("dragging")}function Vs(e){const{event:t,canvas:n,state:r,config:i,cancelViewAnimation:o}=e,s=i.ctrlDragRotate&&(t.ctrlKey||t.metaKey);(t.button===0||s&&t.button===2)&&(o(),s&&t.preventDefault(),r.dragging=!0,r.mode=s?"rotate":"pan",r.pointerId=t.pointerId,r.lastPointerX=t.clientX,r.lastPointerY=t.clientY,r.rotateLastAngleRad=r.mode==="rotate"?si(n,t.clientX,t.clientY):null,n.classList.add("dragging"),n.setPointerCapture(t.pointerId))}function Gs(e){const{event:t,canvas:n,state:r,config:i,camera:o,clampViewState:s,emitViewState:a,requestRender:c}=e;if(!r.dragging||t.pointerId!==r.pointerId)return;const u=t.clientX-r.lastPointerX,l=t.clientY-r.lastPointerY;if(r.lastPointerX=t.clientX,r.lastPointerY=t.clientY,r.mode==="rotate"){const h=si(n,t.clientX,t.clientY),f=r.rotateLastAngleRad;if(r.rotateLastAngleRad=h,f!==null){const y=h-f,b=Math.atan2(Math.sin(y),Math.cos(y)),x=i.rotationDragSensitivityDegPerPixel/Sn,w=o.getViewState();o.setViewState({rotationDeg:w.rotationDeg-b*180/Math.PI*x})}}else{const h=o.getViewState(),f=Math.max(1e-6,h.zoom),y=ii(h.rotationDeg),b=Math.cos(y),x=Math.sin(y),w=(u*b-l*x)/f,A=(u*x+l*b)/f;o.setViewState({offsetX:h.offsetX-w,offsetY:h.offsetY-A})}s(),a(),c()}function qs(e,t,n){e.pointerId===n.pointerId&&ai(t,n)}function Hs(e){const{event:t,canvas:n,onZoomBy:r}=e;t.preventDefault();const i=n.getBoundingClientRect(),o=t.clientX-i.left,s=t.clientY-i.top,a=t.deltaY<0?1.12:.89;r(a,o,s)}function $s(e){const{event:t,canvas:n,onZoomBy:r}=e,i=n.getBoundingClientRect(),o=t.clientX-i.left,s=t.clientY-i.top;r(t.shiftKey?.8:1.25,o,s)}function Zs(e,t){(t||e.ctrlKey||e.metaKey)&&e.preventDefault()}function Fn(e){const t=e.getViewCorners();let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[s,a]of t)s<n&&(n=s),s>i&&(i=s),a<r&&(r=a),a>o&&(o=a);return[n,r,i,o]}function Tn(e,t){const n=Fn(e),r=Math.max(1e-6,n[2]-n[0]),i=Math.max(1e-6,n[3]-n[1]),o=r*.2,s=i*.2,[a,c]=e.getCenter(),u=r*.5,l=i*.5,h=u-o,f=t.width-u+o,y=l-s,b=t.height-l+s,x=h<=f?k(a,h,f):t.width*.5,w=y<=b?k(c,y,b):t.height*.5;e.setCenter(x,w)}function Ks(e,t){const n=Math.max(1e-6,e.getViewState().zoom),r=t.maxTierZoom+Math.log2(n);return k(Math.floor(r),0,t.maxTierZoom)}function js(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function ci(e,t,n){const r=Fn(e),i=Math.pow(2,t.maxTierZoom-n),o=Math.ceil(t.width/i),s=Math.ceil(t.height/i),a=Math.max(1,Math.ceil(o/t.tileSize)),c=Math.max(1,Math.ceil(s/t.tileSize)),u=r[0],l=r[1],h=r[2],f=r[3],y=k(Math.floor(u/i/t.tileSize),0,a-1),b=k(Math.floor((h-1)/i/t.tileSize),0,a-1),x=k(Math.floor(l/i/t.tileSize),0,c-1),w=k(Math.floor((f-1)/i/t.tileSize),0,c-1);if(y>b||x>w)return[];const A=(u+h)*.5/i/t.tileSize,I=(l+f)*.5/i/t.tileSize,X=[];for(let R=x;R<=w;R+=1)for(let _=y;_<=b;_+=1){const H=_*t.tileSize*i,ae=R*t.tileSize*i,te=Math.min((_+1)*t.tileSize,o)*i,ne=Math.min((R+1)*t.tileSize,s)*i,ce=_-A,he=R-I;X.push({key:`${n}/${_}/${R}`,tier:n,x:_,y:R,bounds:[H,ae,te,ne],distance2:ce*ce+he*he,url:_n(t,n,_,R)})}return X.sort((R,_)=>R.distance2-_.distance2),X}function Js(e,t){const n=Ks(e,t);return{tier:n,visible:ci(e,t,n)}}function Qs(e){e.interactionLocked||Vs({event:e.event,canvas:e.canvas,state:e.state,config:{ctrlDragRotate:e.ctrlDragRotate,rotationDragSensitivityDegPerPixel:e.rotationDragSensitivityDegPerPixel},cancelViewAnimation:e.cancelViewAnimation})}function ea(e){e.interactionLocked||Gs({event:e.event,canvas:e.canvas,state:e.state,config:{ctrlDragRotate:e.ctrlDragRotate,rotationDragSensitivityDegPerPixel:e.rotationDragSensitivityDegPerPixel},camera:e.camera,clampViewState:()=>Tn(e.camera,e.source),emitViewState:e.emitViewState,requestRender:e.requestRender})}function ta(e){e.interactionLocked||qs(e.event,e.canvas,e.state)}function na(e){if(e.interactionLocked){e.event.preventDefault();return}Hs({event:e.event,canvas:e.canvas,onZoomBy:e.onZoomBy})}function ra(e){e.interactionLocked||$s({event:e.event,canvas:e.canvas,onZoomBy:e.onZoomBy})}function ia(e){Zs(e.event,e.state.dragging)}function oa(e,t){ai(e,t)}function sa(e){return{pointerDown:t=>Qs({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state,ctrlDragRotate:e.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:e.getRotationDragSensitivityDegPerPixel(),cancelViewAnimation:e.cancelViewAnimation}),pointerMove:t=>ea({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state,ctrlDragRotate:e.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:e.getRotationDragSensitivityDegPerPixel(),camera:e.camera,source:e.source,emitViewState:e.emitViewState,requestRender:e.requestRender}),pointerUp:t=>ta({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state}),wheel:t=>na({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,onZoomBy:e.zoomBy}),doubleClick:t=>ra({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,onZoomBy:e.zoomBy}),contextMenu:t=>ia({event:t,canvas:e.canvas,state:e.state})}}function aa(e){const{gl:t,cache:n,maxCacheTiles:r}=e;if(n.size<=r)return;const i=Array.from(n.entries());i.sort((s,a)=>s[1].lastUsed-a[1].lastUsed);const o=n.size-r;for(let s=0;s<o;s+=1){const[a,c]=i[s];t.deleteTexture(c.texture),n.delete(a)}}function ca(e,t){if(e.isContextLost())return null;const n=e.createTexture();return n?(e.bindTexture(e.TEXTURE_2D,n),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,1),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.bindTexture(e.TEXTURE_2D,null),n):null}function ua(e){const{gl:t,cache:n,tile:r,bitmap:i,frameSerial:o,maxCacheTiles:s,destroyed:a,contextLost:c,requestRender:u}=e;if(a||c||t.isContextLost()){i.close();return}if(n.has(r.key)){i.close();return}const l=ca(t,i);i.close(),l&&(n.set(r.key,{key:r.key,texture:l,bounds:r.bounds,tier:r.tier,lastUsed:o}),aa({gl:t,cache:n,maxCacheTiles:s}),u())}function la(e,t){for(const[,n]of t)e.deleteTexture(n.texture)}function fa(e){const{event:t,destroyed:n,contextLost:r,cancelViewAnimation:i,cancelDrag:o,tileScheduler:s,cache:a,onContextLost:c}=e;if(t.preventDefault(),n||r)return{handled:!1,frame:e.frame};let u=e.frame;return u!==null&&(cancelAnimationFrame(u),u=null),i(),o(),s.clear(),a.clear(),c?.(),{handled:!0,frame:u}}function da(e){if(e.destroyed)return{didDestroy:!1,frame:e.frame};let t=e.frame;return t!==null&&(cancelAnimationFrame(t),t=null),e.cancelViewAnimation(),e.resizeObserver.disconnect(),e.removeCanvasEventListeners(),e.cancelDrag(),e.tileScheduler.destroy(),!e.contextLost&&!e.gl.isContextLost()&&(la(e.gl,e.cache),e.gl.deleteBuffer(e.tileProgram.vbo),e.gl.deleteVertexArray(e.tileProgram.vao),e.gl.deleteProgram(e.tileProgram.program),e.gl.deleteBuffer(e.pointProgram.posBuffer),e.gl.deleteBuffer(e.pointProgram.termBuffer),e.gl.deleteBuffer(e.pointProgram.fillModeBuffer),e.gl.deleteBuffer(e.pointProgram.indexBuffer),e.gl.deleteTexture(e.pointProgram.paletteTexture),e.gl.deleteVertexArray(e.pointProgram.vao),e.gl.deleteProgram(e.pointProgram.program)),e.cache.clear(),{didDestroy:!0,frame:t}}function ha(e,t){if(t<=0||e.length===0)return new Uint32Array(0);let n=e.length;for(let o=0;o<e.length;o+=1)e[o]<t||(n-=1);if(n===e.length)return e;if(n<=0)return new Uint32Array(0);const r=new Uint32Array(n);let i=0;for(let o=0;o<e.length;o+=1){const s=e[o];s>=t||(r[i]=s,i+=1)}return r}function ma(e,t){return t<=0?new Uint8Array(0):e.length<t?new Uint8Array(t):e.subarray(0,t)}function ga(e,t,n,r,i){if(!i||i.length===0)return{...e,lastPointPalette:null};const o=new Uint8Array(i);if(r||t.isContextLost())return{...e,lastPointPalette:o};const s=Math.max(1,Math.floor(o.length/4));return t.bindTexture(t.TEXTURE_2D,n.paletteTexture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,s,1,0,t.RGBA,t.UNSIGNED_BYTE,o),t.bindTexture(t.TEXTURE_2D,null),{...e,lastPointPalette:o,pointPaletteSize:s}}function pa(e,t,n,r,i){if(!i||!i.count||!i.positions||!i.paletteIndices)return{...e,lastPointData:null,pointCount:0,usePointIndices:!1};const o=i.fillModes instanceof Uint8Array?i.fillModes:null,s=o!==null,a=Math.max(0,Math.min(i.count,Math.floor(i.positions.length/2),i.paletteIndices.length,s?o.length:Number.MAX_SAFE_INTEGER)),c=i.positions.subarray(0,a*2),u=i.paletteIndices.subarray(0,a),l=s?o.subarray(0,a):void 0,h=i.drawIndices instanceof Uint32Array,f=h?ha(i.drawIndices,a):null,y=e.lastPointData,b=y?.fillModes instanceof Uint8Array,x=e.pointBuffersDirty||!y||y.count!==a||!qt(y.positions,c)||!qt(y.paletteIndices,u)||b!==s||s&&(!y?.fillModes||!qt(y.fillModes,l)),w=e.pointBuffersDirty||h&&(!y?.drawIndices||!qt(y.drawIndices,f))||!h&&!!y?.drawIndices,A={...e,lastPointData:{count:a,positions:c,paletteIndices:u,fillModes:l,drawIndices:h?f??void 0:void 0}};if(r||t.isContextLost())return A;const I=A.lastPointData;if(!I)return A;if(x){t.bindBuffer(t.ARRAY_BUFFER,n.posBuffer),t.bufferData(t.ARRAY_BUFFER,I.positions,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,n.termBuffer),t.bufferData(t.ARRAY_BUFFER,I.paletteIndices,t.STATIC_DRAW);const X=ma(A.zeroFillModes,a);t.bindBuffer(t.ARRAY_BUFFER,n.fillModeBuffer),t.bufferData(t.ARRAY_BUFFER,I.fillModes??X,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,null),A.zeroFillModes=X}return h&&w&&(t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,n.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,f??new Uint32Array(0),t.DYNAMIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null)),A.usePointIndices=h,A.pointCount=h?f?.length??0:I.count,(x||w)&&(A.pointBuffersDirty=!1),A}function ba(e){const{gl:t,camera:n,source:r,cache:i,frameSerial:o,tileProgram:s,pointProgram:a,imageColorSettings:c,pointCount:u,usePointIndices:l,pointPaletteSize:h,pointStrokeScale:f,pointInnerFillOpacity:y,pointSizePx:b,tileScheduler:x,getVisibleTiles:w,getVisibleTilesForTier:A,getViewBounds:I,intersectsBounds:X}=e;t.clearColor(.03,.06,.1,1),t.clear(t.COLOR_BUFFER_BIT);const{tier:R,visible:_}=w(),H=I(),ae=new Set(_.map(z=>z.key));t.useProgram(s.program),t.bindVertexArray(s.vao),t.uniformMatrix3fv(s.uCamera,!1,n.getMatrix()),t.uniform1i(s.uTexture,0),t.uniform1f(s.uBrightness,c.brightness),t.uniform1f(s.uContrast,c.contrast),t.uniform1f(s.uSaturation,c.saturation);const te=[];for(const[,z]of i)ae.has(z.key)||X(z.bounds,H)&&te.push(z);te.sort((z,D)=>z.tier-D.tier);for(const z of te)z.lastUsed=o,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,z.texture),t.uniform4f(s.uBounds,z.bounds[0],z.bounds[1],z.bounds[2],z.bounds[3]),t.drawArrays(t.TRIANGLE_STRIP,0,4);let ne=0;const ce=[];for(const z of _){const D=i.get(z.key);if(!D){ce.push(z);continue}D.lastUsed=o,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,D.texture),t.uniform4f(s.uBounds,D.bounds[0],D.bounds[1],D.bounds[2],D.bounds[3]),t.drawArrays(t.TRIANGLE_STRIP,0,4),ne+=1}const he=ce.slice(),Pe=1e6,B=[];R>0&&B.push(R-1),R<r.maxTierZoom&&B.push(R+1);for(const z of B){const D=A(z);for(const J of D)i.has(J.key)||(J.distance2+=Pe,he.push(J))}x.schedule(he),t.bindTexture(t.TEXTURE_2D,null),t.bindVertexArray(null);let U=0;return u>0&&(t.enable(t.BLEND),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA),t.useProgram(a.program),t.bindVertexArray(a.vao),t.uniformMatrix3fv(a.uCamera,!1,n.getMatrix()),t.uniform1f(a.uPointSize,b),t.uniform1f(a.uPointStrokeScale,f),t.uniform1f(a.uPointInnerFillAlpha,y),t.uniform1f(a.uPaletteSize,h),t.uniform1i(a.uPalette,1),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,a.paletteTexture),l?t.drawElements(t.POINTS,u,t.UNSIGNED_INT,0):t.drawArrays(t.POINTS,0,u),t.bindTexture(t.TEXTURE_2D,null),t.bindVertexArray(null),U=u),{tier:R,visible:_.length,rendered:ne,points:U,fallback:te.length,cacheHits:ne,cacheMisses:ce.length,drawCalls:te.length+ne+(U>0?1:0)}}function Tr(e){const r=Cn(e,`#version 300 es
|
|
63
|
+
`;function fs(){if(typeof navigator>"u")return!1;const e=navigator;return typeof e.gpu=="object"&&e.gpu!==null}function Kr(){if(!fs())return null;const t=navigator.gpu;if(!t||typeof t!="object")return null;const n=t;return typeof n.requestAdapter!="function"?null:n}const Vt=globalThis.GPUShaderStage?.COMPUTE??4,dn=globalThis.GPUBufferUsage?.STORAGE??128,Gt=globalThis.GPUBufferUsage?.COPY_DST??8,ds=globalThis.GPUBufferUsage?.COPY_SRC??4,hs=globalThis.GPUBufferUsage?.UNIFORM??64,ms=globalThis.GPUBufferUsage?.MAP_READ??1,gs=globalThis.GPUMapMode?.READ??1;async function ps(){const e=Kr();if(!e)return{supported:!1,features:[]};const t=await e.requestAdapter();return t?{supported:!0,adapterName:t.info?.description??t.info?.vendor??"unknown",features:Array.from(t.features),limits:{maxStorageBufferBindingSize:Number(t.limits.maxStorageBufferBindingSize),maxComputeInvocationsPerWorkgroup:Number(t.limits.maxComputeInvocationsPerWorkgroup),maxComputeWorkgroupSizeX:Number(t.limits.maxComputeWorkgroupSizeX)}}:{supported:!1,features:[]}}async function bs(){return Xt||(Xt=(async()=>{const e=Kr();if(!e)return null;const t=await e.requestAdapter();if(!t)return null;const n=await t.requestDevice(),r=n.createBindGroupLayout({entries:[{binding:0,visibility:Vt,buffer:{type:"read-only-storage"}},{binding:1,visibility:Vt,buffer:{type:"read-only-storage"}},{binding:2,visibility:Vt,buffer:{type:"storage"}},{binding:3,visibility:Vt,buffer:{type:"uniform"}}]}),i=n.createComputePipeline({layout:n.createPipelineLayout({bindGroupLayouts:[r]}),compute:{module:n.createShaderModule({code:ls}),entryPoint:"main"}});return{device:n,pipeline:i,bindGroupLayout:r}})(),Xt)}function qt(e,t){return Math.ceil(e/t)*t}async function jr(e,t,n){const r=await bs();if(!r)return null;const i=Math.max(0,Math.floor(t)),o=Math.max(0,Math.floor(n.length/4));if(i===0||o===0)return new Uint32Array(0);const s=Math.min(i,Math.floor(e.length/2));if(s===0)return new Uint32Array(0);const a=s*2*Float32Array.BYTES_PER_ELEMENT,c=o*4*Float32Array.BYTES_PER_ELEMENT,u=s*Uint32Array.BYTES_PER_ELEMENT,l=Number(r.device.limits.maxStorageBufferBindingSize);if(a>l||c>l||u>l)return null;const h=r.device.createBuffer({size:qt(a,4),usage:dn|Gt}),f=r.device.createBuffer({size:qt(c,4),usage:dn|Gt}),y=r.device.createBuffer({size:qt(u,4),usage:dn|ds}),b=r.device.createBuffer({size:16,usage:hs|Gt}),x=r.device.createBuffer({size:qt(u,4),usage:Gt|ms});r.device.queue.writeBuffer(h,0,e.buffer,e.byteOffset,a),r.device.queue.writeBuffer(f,0,n.buffer,n.byteOffset,c),r.device.queue.writeBuffer(b,0,new Uint32Array([s,o,0,0]));const w=r.device.createBindGroup({layout:r.bindGroupLayout,entries:[{binding:0,resource:{buffer:h}},{binding:1,resource:{buffer:f}},{binding:2,resource:{buffer:y}},{binding:3,resource:{buffer:b}}]}),A=r.device.createCommandEncoder(),E=A.beginComputePass();E.setPipeline(r.pipeline),E.setBindGroup(0,w),E.dispatchWorkgroups(Math.ceil(s/256)),E.end(),A.copyBufferToBuffer(y,0,x,0,u),r.device.queue.submit([A.finish()]),await x.mapAsync(gs);const X=x.getMappedRange(),R=new Uint32Array(X.slice(0));return x.unmap(),h.destroy(),f.destroy(),y.destroy(),b.destroy(),x.destroy(),R}async function Jr(e,t,n={}){const r=fe(),i=n.bridgeToDraw===!0;if(!e||!e.count||!e.positions||!e.paletteIndices)return{data:null,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}};const o=Et(t??[]);if(o.length===0){const R={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return e.fillModes instanceof Uint8Array&&(R.fillModes=new Uint8Array(0)),e.ids instanceof Uint32Array&&(R.ids=new Uint32Array(0)),{data:R,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const s=at(e),a=e.fillModes instanceof Uint8Array&&e.fillModes.length>=s?e.fillModes:null,c=e.ids instanceof Uint32Array&&e.ids.length>=s?e.ids:null;if(s===0){const R={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(R.fillModes=new Uint8Array(0)),c&&(R.ids=new Uint32Array(0)),{data:R,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const u=new Float32Array(o.length*4);for(let R=0;R<o.length;R+=1){const _=R*4,H=o[R];u[_]=H.minX,u[_+1]=H.minY,u[_+2]=H.maxX,u[_+3]=H.maxY}let l=null,h=!1;try{l=await jr(e.positions,s,u),h=!!l}catch{l=null,h=!1}if(!l)return{data:Ct(e,t),meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!1,candidateCount:s,bridgedToDraw:!1}};let f=0;for(let R=0;R<s;R+=1)l[R]===1&&(f+=1);const y=new Uint32Array(f);if(f>0){let R=0;for(let _=0;_<s;_+=1)l[_]===1&&(y[R]=_,R+=1)}if(f===0){if(i){const _={count:s,positions:e.positions.subarray(0,s*2),paletteIndices:e.paletteIndices.subarray(0,s),drawIndices:new Uint32Array(0)};return a&&(_.fillModes=a.subarray(0,s)),c&&(_.ids=c.subarray(0,s)),{data:_,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!0}}}const R={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(R.fillModes=new Uint8Array(0)),c&&(R.ids=new Uint32Array(0)),{data:R,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const R=new Uint32Array(f);let _=0;for(let se=0;se<f;se+=1){const j=y[se]??0,J=e.positions[j*2],ae=e.positions[j*2+1];jt(J,ae,o)&&(R[_]=j,_+=1)}const H={count:s,positions:e.positions.subarray(0,s*2),paletteIndices:e.paletteIndices.subarray(0,s),drawIndices:R.subarray(0,_)};return a&&(H.fillModes=a.subarray(0,s)),c&&(H.ids=c.subarray(0,s)),{data:H,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!0,candidateCount:f,bridgedToDraw:!0}}}const b=new Float32Array(f*2),x=new Uint16Array(f),w=a?new Uint8Array(f):null,A=c?new Uint32Array(f):null;let E=0;for(let R=0;R<f;R+=1){const _=y[R]??0,H=e.positions[_*2],se=e.positions[_*2+1];jt(H,se,o)&&(b[E*2]=H,b[E*2+1]=se,x[E]=e.paletteIndices[_],w&&(w[E]=a[_]),A&&(A[E]=c[_]),E+=1)}const X={count:E,positions:b.subarray(0,E*2),paletteIndices:x.subarray(0,E)};return w&&(X.fillModes=w.subarray(0,E)),A&&(X.ids=A.subarray(0,E)),{data:X,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!0,candidateCount:f,bridgedToDraw:!1}}}class Qr{constructor(t,n){S(this,"worker",null);S(this,"supported",!0);S(this,"requestId",1);S(this,"pendingById",new Map);S(this,"handleMessage",t=>{const n=t.data;if(!n)return;const r=this.pendingById.get(n.id);r&&(this.pendingById.delete(n.id),this.handlers.onResponse(n,r))});S(this,"handleError",()=>{this.supported=!1,this.teardownWorker("worker crashed")});this.createWorker=t,this.handlers=n}beginRequest(t){const n=this.getOrCreateWorker();if(!n)return null;const r=this.requestId++;return this.pendingById.set(r,t),{id:r,worker:n}}cancelRequest(t){const n=this.pendingById.get(t);if(n)return this.pendingById.delete(t),n}terminate(t="worker terminated"){this.teardownWorker(t)}getOrCreateWorker(){if(!this.supported)return null;if(this.worker)return this.worker;try{const t=this.createWorker();return t.addEventListener("message",this.handleMessage),t.addEventListener("error",this.handleError),this.worker=t,t}catch{return this.supported=!1,null}}teardownWorker(t){this.worker&&(this.worker.removeEventListener("message",this.handleMessage),this.worker.removeEventListener("error",this.handleError),this.worker.terminate(),this.worker=null);const n=new Error(t);for(const[,r]of this.pendingById)this.handlers.rejectPending(r,n);this.pendingById.clear()}}const Pt=new Qr(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/roi-clip-worker-BDVQwN2T.js").href:new URL("assets/roi-clip-worker-BDVQwN2T.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:gt&>.tagName.toUpperCase()==="SCRIPT"&>.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(e,t)=>{if(e.type==="roi-clip-failure"){t.reject(new Error(e.error||"worker clip failed"));return}if(e.type==="roi-clip-index-success"){if(t.kind!=="index"){t.reject(new Error("worker response mismatch: expected point data result"));return}const c=Math.max(0,Math.floor(e.count)),u=new Uint32Array(e.indices).subarray(0,c);t.resolve({indices:u,meta:{mode:"worker",durationMs:Number.isFinite(e.durationMs)?e.durationMs:fe()-t.startMs}});return}if(t.kind!=="data"){t.reject(new Error("worker response mismatch: expected index result"));return}const n=Math.max(0,Math.floor(e.count)),r=new Float32Array(e.positions),i=new Uint16Array(e.paletteIndices),o=e.fillModes?new Uint8Array(e.fillModes):null,s=e.ids?new Uint32Array(e.ids):null,a={count:n,positions:r.subarray(0,n*2),paletteIndices:i.subarray(0,n)};o&&(a.fillModes=o.subarray(0,n)),s&&(a.ids=s.subarray(0,n)),t.resolve({data:a,meta:{mode:"worker",durationMs:Number.isFinite(e.durationMs)?e.durationMs:fe()-t.startMs}})},rejectPending:(e,t)=>{e.reject(t)}});function ys(){Pt.terminate("worker terminated")}async function ei(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return{data:null,meta:{mode:"worker",durationMs:0}};const n=at(e),r=e.positions.slice(0,n*2),i=e.paletteIndices.slice(0,n),o=e.fillModes instanceof Uint8Array&&e.fillModes.length>=n?e.fillModes.slice(0,n):null,s=e.ids instanceof Uint32Array&&e.ids.length>=n?e.ids.slice(0,n):null;return new Promise((a,c)=>{const u=fe(),l=Pt.beginRequest({kind:"data",resolve:a,reject:c,startMs:u});if(!l){a({data:Ct(e,t),meta:{mode:"sync",durationMs:fe()-u}});return}const h={type:"roi-clip-request",id:l.id,count:n,positions:r.buffer,paletteIndices:i.buffer,fillModes:o?.buffer,ids:s?.buffer,polygons:t??[]},f=[r.buffer,i.buffer];o&&f.push(o.buffer),s&&f.push(s.buffer);try{l.worker.postMessage(h,f)}catch(y){const b=Pt.cancelRequest(l.id);b?b.reject(y):c(y)}})}async function ws(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return{indices:new Uint32Array(0),meta:{mode:"worker",durationMs:0}};const n=at(e),r=e.positions.slice(0,n*2);return new Promise((i,o)=>{const s=fe(),a=Pt.beginRequest({kind:"index",resolve:i,reject:o,startMs:s});if(!a){i({indices:Zr(e,t),meta:{mode:"sync",durationMs:fe()-s}});return}const c={type:"roi-clip-index-request",id:a.id,count:n,positions:r.buffer,polygons:t??[]};try{a.worker.postMessage(c,[r.buffer])}catch(u){const l=Pt.cancelRequest(a.id);l?l.reject(u):o(u)}})}const Ss=24,xs=1024,Ms=4,Kt=-1;function Mt(e,t,n){return(e*73856093^t*19349663)>>>0&n}function As(e,t,n){if(e<=0||t<=0||n<=0)return 256;const r=Math.max(1,e*t),o=Math.sqrt(r/Math.max(1,n))*Ms;return Math.max(Ss,Math.min(xs,o))}function Ts(e,t){if(!(e instanceof Uint32Array)||e.length===0)return null;let n=!0;for(let o=0;o<e.length;o+=1)if(!(e[o]<t)){n=!1;break}if(n)return e;const r=new Uint32Array(e.length);let i=0;for(let o=0;o<e.length;o+=1)e[o]>=t||(r[i]=e[o],i+=1);return i>0?r.subarray(0,i):null}function Rs(e){const t=Math.max(0,Math.floor(e.count)),n=Math.floor(e.positions.length/2),r=Math.max(0,Math.min(t,n));if(r<=0)return null;const i=Ts(e.drawIndices??null,r),o=i?i.length:r;if(o===0)return null;const s=As(e.sourceWidth,e.sourceHeight,o),a=1/s,c=new Int32Array(o),u=new Int32Array(o);let l=0;if(i)for(let B=0;B<o;B+=1){const D=i[B],O=e.positions[D*2],U=e.positions[D*2+1];!Number.isFinite(O)||!Number.isFinite(U)||(c[l]=Math.floor(O*a),u[l]=Math.floor(U*a),l+=1)}else for(let B=0;B<r;B+=1){const D=e.positions[B*2],O=e.positions[B*2+1];!Number.isFinite(D)||!Number.isFinite(O)||(c[l]=Math.floor(D*a),u[l]=Math.floor(O*a),l+=1)}if(l===0)return null;let h=Math.min(l,Math.max(64,l>>>3));(!Number.isFinite(h)||h<=0)&&(h=l);let f=1;for(;f<h*2;)f<<=1;let y=f-1,b=new Int32Array(f*2),x=new Int32Array(f);b.fill(2147483647);let w=0;const A=new Int32Array(l);for(let B=0;B<l;B+=1){const D=c[B],O=u[B];let U=Mt(D,O,y);for(;;){const Q=b[U*2];if(Q===2147483647){if(b[U*2]=D,b[U*2+1]=O,x[U]=1,A[B]=U,w+=1,w*4>f*3){const Le=f;f<<=1,y=f-1;const ue=new Int32Array(f*2),Oe=new Int32Array(f);ue.fill(2147483647);for(let Fe=0;Fe<Le;Fe+=1){if(b[Fe*2]===2147483647)continue;const We=b[Fe*2],C=b[Fe*2+1];let M=Mt(We,C,y);for(;ue[M*2]!==2147483647;)M=M+1&y;ue[M*2]=We,ue[M*2+1]=C,Oe[M]=x[Fe]}for(b=ue,x=Oe,U=Mt(D,O,y);b[U*2]!==D||b[U*2+1]!==O;)U=U+1&y;A[B]=U}break}if(Q===D&&b[U*2+1]===O){x[U]+=1,A[B]=U;break}U=U+1&y}}const E=new Int32Array(w*2),X=new Uint32Array(w),R=new Uint32Array(w),_=new Int32Array(f);_.fill(Kt);let H=0,se=0;for(let B=0;B<f;B+=1)b[B*2]!==2147483647&&(E[H*2]=b[B*2],E[H*2+1]=b[B*2+1],X[H]=se,R[H]=x[B],_[B]=H,se+=x[B],H+=1);const j=new Uint32Array(l),J=new Uint32Array(w);if(J.set(X),i)for(let B=0;B<l;B+=1){const D=_[A[B]];j[J[D]]=i[B],J[D]+=1}else{let B=0;for(let D=0;D<r;D+=1){const O=e.positions[D*2],U=e.positions[D*2+1];if(!Number.isFinite(O)||!Number.isFinite(U))continue;const Q=_[A[B]];j[J[Q]]=D,J[Q]+=1,B+=1}}let ae=1;for(;ae<w*2;)ae<<=1;const ge=ae-1,Te=new Int32Array(ae);Te.fill(Kt);for(let B=0;B<w;B+=1){const D=E[B*2],O=E[B*2+1];let U=Mt(D,O,ge);for(;Te[U]!==Kt;)U=U+1≥Te[U]=B}return{cellSize:s,safeCount:r,cellCount:w,hashCapacity:ae,hashTable:Te,cellKeys:E,cellOffsets:X,cellLengths:R,pointIndices:j}}function ti(e,t,n){const{hashTable:r,cellKeys:i,hashMask:o}=e;let s=Mt(t,n,o);for(;;){const a=r[s];if(a===Kt)return-1;if(i[a*2]===t&&i[a*2+1]===n)return a;s=s+1&o}}function Cs(e,t){if(e.safeCount<=0||e.cellCount<=0)return null;const n=e.safeCount;return{cellSize:e.cellSize,safeCount:n,positions:t.positions.subarray(0,n*2),ids:t.ids instanceof Uint32Array&&t.ids.length>=n?t.ids.subarray(0,n):null,hashCapacity:e.hashCapacity,hashMask:e.hashCapacity-1,hashTable:new Int32Array(e.hashTable),cellKeys:new Int32Array(e.cellKeys),cellOffsets:new Uint32Array(e.cellOffsets),cellLengths:new Uint32Array(e.cellLengths),pointIndices:new Uint32Array(e.pointIndices)}}const Sn=new Qr(()=>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:gt&>.tagName.toUpperCase()==="SCRIPT"&>.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(e,t)=>{if(e.type==="point-hit-index-failure"){t.reject(new Error(e.error||"worker index build failed"));return}t.resolve(Cs(e,t.pointData))},rejectPending:(e,t)=>{e.reject(t)}});function Ps(){Sn.terminate("worker terminated")}function Is(e,t){const n=at(e);if(n<=0)return null;const r=e.positions.subarray(0,n*2),i=Rs({count:n,positions:r,drawIndices:e.drawIndices instanceof Uint32Array?e.drawIndices:null,sourceWidth:t?.width??0,sourceHeight:t?.height??0});return i?{cellSize:i.cellSize,safeCount:n,positions:r,ids:e.ids instanceof Uint32Array&&e.ids.length>=n?e.ids.subarray(0,n):null,hashCapacity:i.hashCapacity,hashMask:i.hashCapacity-1,hashTable:i.hashTable,cellKeys:i.cellKeys,cellOffsets:i.cellOffsets,cellLengths:i.cellLengths,pointIndices:i.pointIndices}:null}async function ni(e,t){if(!e||!e.positions||!e.paletteIndices)return null;const n=at(e);return n<=0?null:new Promise((r,i)=>{const o={resolve:r,reject:i,pointData:e},s=Sn.beginRequest(o);if(!s||!s.worker){r(Is(e,t));return}const a=e.positions.slice(0,n*2),c=e.drawIndices instanceof Uint32Array&&e.drawIndices.length>0?e.drawIndices.slice():void 0,u={type:"point-hit-index-request",id:s.id,count:n,positions:a.buffer,drawIndices:c?.buffer,sourceWidth:t?.width??0,sourceHeight:t?.height??0},l=[a.buffer];c&&l.push(c.buffer);try{s.worker.postMessage(u,l)}catch(h){const f=Sn.cancelRequest(s.id);f?f.reject(h):i(h)}})}function Es(e){const t=[];for(let n=0;n<e.length;n+=1){const r=e[n],i=Et([It(r?.coordinates)]);if(i.length===0)continue;let o=0;for(const s of i)o+=s.area;t.push({regionId:r.id??n,regionIndex:n,polygons:i,area:Math.max(1e-6,o)})}return t}function vs(e,t){if(Array.isArray(t)){const n=t[e];if(typeof n=="string"&&n.length>0)return n}if(t instanceof Map){const n=t.get(e);if(typeof n=="string"&&n.length>0)return n}return String(e)}function ri(e,t,n={}){const r=Math.max(0,Math.min(Math.floor(e?.count??0),Math.floor((e?.positions?.length??0)/2),e?.paletteIndices?.length??0,e?.fillModes instanceof Uint8Array?e.fillModes.length:Number.MAX_SAFE_INTEGER));let i=null;if(e?.drawIndices instanceof Uint32Array){const f=e.drawIndices;let y=f.length;for(let b=0;b<f.length;b+=1)f[b]<r||(y-=1);if(y===f.length)i=f;else if(y>0){const b=new Uint32Array(y);let x=0;for(let w=0;w<f.length;w+=1){const A=f[w];A>=r||(b[x]=A,x+=1)}i=b}else i=new Uint32Array(0)}const o=i?i.length:r,s=Es(t??[]);if(!e||o===0||s.length===0)return{groups:[],inputPointCount:o,pointsInsideAnyRegion:0,unmatchedPointCount:o};const a=new Map,c=new Map;let u=0;for(let f=0;f<o;f+=1){const y=i?i[f]:f,b=e.positions[y*2],x=e.positions[y*2+1];let w=null;for(const X of s){let R=!1;for(const _ of X.polygons)if(Ur(b,x,_)){R=!0;break}R&&(!w||X.area<w.area)&&(w=X)}if(!w)continue;u+=1;const A=e.paletteIndices[y]??0,E=a.get(w.regionIndex)??new Map;E.set(A,(E.get(A)??0)+1),a.set(w.regionIndex,E),c.set(w.regionIndex,(c.get(w.regionIndex)??0)+1)}const l=n.includeEmptyRegions??!1,h=[];for(const f of s){const y=c.get(f.regionIndex)??0;if(!l&&y<=0)continue;const b=a.get(f.regionIndex)??new Map,x=Array.from(b.entries()).map(([w,A])=>({termId:vs(w,n.paletteIndexToTermId),paletteIndex:w,count:A})).sort((w,A)=>A.count-w.count||w.paletteIndex-A.paletteIndex);h.push({regionId:f.regionId,regionIndex:f.regionIndex,totalCount:y,termCounts:x})}return{groups:h,inputPointCount:o,pointsInsideAnyRegion:u,unmatchedPointCount:Math.max(0,o-u)}}function _s(e,t){if(!t)return!1;try{const r=new URL(e,typeof window<"u"?window.location.href:void 0).hostname.toLowerCase();if(r.includes("amazonaws.com")||r.startsWith("s3.")||r.includes(".s3."))return!1}catch{}return!0}class ii{constructor(t){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(t.maxConcurrency??12)),this.maxRetries=Math.max(0,Math.floor(t.maxRetries??2)),this.retryBaseDelayMs=Math.max(10,Math.floor(t.retryBaseDelayMs??120)),this.retryMaxDelayMs=Math.max(this.retryBaseDelayMs,Math.floor(t.retryMaxDelayMs??1200)),this.authToken=t.authToken??"",this.onTileLoad=t.onTileLoad,this.onTileError=t.onTileError,this.onStateChange=t.onStateChange}setAuthToken(t){this.authToken=String(t??"")}schedule(t){if(this.destroyed)return;const n=new Set;for(const r of t)n.add(r.key);this.visibleKeys=n,this.dropInvisibleQueued(n),this.abortInvisibleInflight(n);for(const r of t){if(this.inflight.has(r.key)){const s=this.inflight.get(r.key);s&&(s.tile=r);continue}const i=this.queuedByKey.get(r.key);if(i){i.tile=r;continue}const o={tile:r,attempt:0,readyAt:fe()};this.queue.push(o),this.queuedByKey.set(r.key,o)}this.sortQueue(),this.pump(),this.emitStateChange()}clear(){this.clearPumpTimer(),this.visibleKeys.clear(),this.queue=[],this.queuedByKey.clear();for(const[,t]of this.inflight)t.controller.abort();this.inflight.clear(),this.emitStateChange()}destroy(){this.destroyed||(this.destroyed=!0,this.clear())}getInflightCount(){return this.inflight.size}getSnapshot(){return{inflight:this.inflight.size,queued:this.queue.length,aborted:this.abortedCount,retries:this.retryCount,failed:this.failedCount}}dropInvisibleQueued(t){if(this.queue.length===0)return;const n=[];for(const r of this.queue){if(!t.has(r.tile.key)){this.queuedByKey.delete(r.tile.key);continue}n.push(r)}this.queue=n}abortInvisibleInflight(t){for(const[n,r]of this.inflight)t.has(n)||(this.inflight.delete(n),this.abortedCount+=1,r.controller.abort())}sortQueue(){this.queue.sort((t,n)=>t.readyAt!==n.readyAt?t.readyAt-n.readyAt:t.tile.distance2!==n.tile.distance2?t.tile.distance2-n.tile.distance2:t.tile.tier!==n.tile.tier?n.tile.tier-t.tile.tier:t.tile.key.localeCompare(n.tile.key))}pump(){if(this.destroyed)return;for(this.clearPumpTimer();this.inflight.size<this.maxConcurrency;){const r=this.takeNextReadyQueueItem();if(!r)break;this.startFetch(r)}if(this.inflight.size>=this.maxConcurrency||this.queue.length===0)return;const t=this.queue[0]?.readyAt;if(typeof t!="number")return;const n=Math.max(0,t-fe());this.timerId=window.setTimeout(()=>{this.timerId=null,this.pump()},n)}takeNextReadyQueueItem(){if(this.queue.length===0)return null;const t=fe(),n=this.queue[0];return!n||n.readyAt>t?null:(this.queue.shift(),this.queuedByKey.delete(n.tile.key),n)}startFetch(t){const n=new AbortController,r={tile:t.tile,attempt:t.attempt,controller:n};this.inflight.set(t.tile.key,r),this.emitStateChange();const i=_s(t.tile.url,this.authToken);fetch(t.tile.url,{signal:n.signal,headers:i?{Authorization:this.authToken}:void 0}).then(o=>{if(!o.ok)throw new Error(`HTTP ${o.status}`);return o.blob()}).then(o=>createImageBitmap(o)).then(o=>{if(this.destroyed||n.signal.aborted){o.close();return}if(!this.visibleKeys.has(t.tile.key)){o.close();return}this.onTileLoad(t.tile,o)}).catch(o=>{if(n.signal.aborted||this.destroyed)return;if(t.attempt<this.maxRetries&&this.visibleKeys.has(t.tile.key)){this.retryCount+=1;const a=t.attempt+1,c=this.getRetryDelay(a),u={tile:t.tile,attempt:a,readyAt:fe()+c},l=this.queuedByKey.get(t.tile.key);l?(l.tile=u.tile,l.readyAt=Math.min(l.readyAt,u.readyAt),l.attempt=Math.max(l.attempt,u.attempt)):(this.queue.push(u),this.queuedByKey.set(u.tile.key,u)),this.sortQueue();return}this.failedCount+=1,this.onTileError?.(t.tile,o,t.attempt+1)}).finally(()=>{this.inflight.delete(t.tile.key),this.pump(),this.emitStateChange()})}getRetryDelay(t){const n=Math.max(0,t-1),r=Math.min(this.retryMaxDelayMs,this.retryBaseDelayMs*2**n),i=.85+Math.random()*.3;return Math.round(r*i)}clearPumpTimer(){this.timerId!==null&&(window.clearTimeout(this.timerId),this.timerId=null)}emitStateChange(){this.onStateChange?.(this.getSnapshot())}}function Fs(e,t){e.addEventListener("pointerdown",t.pointerDown),e.addEventListener("pointermove",t.pointerMove),e.addEventListener("pointerup",t.pointerUp),e.addEventListener("pointercancel",t.pointerUp),e.addEventListener("wheel",t.wheel,{passive:!1}),e.addEventListener("dblclick",t.doubleClick),e.addEventListener("contextmenu",t.contextMenu),e.addEventListener("webglcontextlost",t.contextLost),e.addEventListener("webglcontextrestored",t.contextRestored)}function Bs(e,t){e.removeEventListener("pointerdown",t.pointerDown),e.removeEventListener("pointermove",t.pointerMove),e.removeEventListener("pointerup",t.pointerUp),e.removeEventListener("pointercancel",t.pointerUp),e.removeEventListener("wheel",t.wheel),e.removeEventListener("dblclick",t.doubleClick),e.removeEventListener("contextmenu",t.contextMenu),e.removeEventListener("webglcontextlost",t.contextLost),e.removeEventListener("webglcontextrestored",t.contextRestored)}function Us(e,t,n){const r=e.getBoundingClientRect(),i=Math.max(1,r.width||e.clientWidth||1),o=Math.max(1,r.height||e.clientHeight||1),s=Math.max(1,window.devicePixelRatio||1),a=Math.max(1,Math.round(i*s)),c=Math.max(1,Math.round(o*s));(e.width!==a||e.height!==c)&&(e.width=a,e.height=c),n.setViewport(i,o),t.viewport(0,0,a,c)}const xn=.35,Mn=.5,Ls=256,An=[{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}],Ds=.1,ks=5,Ns=0,zs=1,Os=-100,Ws=100,Ys=2e3;function oi(e){return e*Math.PI/180}function Ht(e,t){return!e||!t?e===t:e.buffer===t.buffer&&e.byteOffset===t.byteOffset&&e.byteLength===t.byteLength}function Tn(e){return e.map(t=>({zoom:t.zoom,size:t.size}))}function xr(e){if(!e)return Tn(An);const t=new Map;for(const[n,r]of Object.entries(e)){const i=Number(n),o=Number(r);!Number.isFinite(i)||!Number.isFinite(o)||o<=0||t.set(i,o)}return t.size===0?Tn(An):Array.from(t.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function Xs(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n].zoom!==t[n].zoom||e[n].size!==t[n].size)return!1;return!0}function Vs(e,t){if(!Number.isFinite(e))return t[0]?.size??Mn;if(t.length===0)return Mn;if(t.length===1||e<=t[0].zoom)return t[0].size;for(let s=1;s<t.length;s+=1){const a=t[s-1],c=t[s];if(e>c.zoom)continue;const u=Math.max(1e-6,c.zoom-a.zoom),l=k((e-a.zoom)/u,0,1);return a.size+(c.size-a.size)*l}const n=t[t.length-1],r=t[t.length-2],i=Math.max(1e-6,n.zoom-r.zoom),o=(n.size-r.size)/i;return n.size+(e-n.zoom)*o}function Mr(e){return typeof e!="number"||!Number.isFinite(e)?1:k(e,Ds,ks)}function Ar(e){return typeof e!="number"||!Number.isFinite(e)?0:k(e,Ns,zs)}function hn(e){return typeof e!="number"||!Number.isFinite(e)?0:k(e,Os,Ws)}function Tr(e){const t=hn(e?.brightness),n=hn(e?.contrast),r=hn(e?.saturation);return{brightness:t/200,contrast:n/100,saturation:r/100}}function si(e){return e}function mn(e){return typeof e!="number"||!Number.isFinite(e)?0:k(e,0,Ys)}function $t(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:Math.max(1e-6,e)}function gn(e){return typeof e=="function"?e:si}function ai(e,t,n){const r=e.getBoundingClientRect(),i=t-r.left-r.width*.5,o=n-r.top-r.height*.5;return Math.atan2(o,i)}function ci(e,t){if(t.pointerId!==null&&e.hasPointerCapture(t.pointerId))try{e.releasePointerCapture(t.pointerId)}catch{}t.dragging=!1,t.mode="none",t.rotateLastAngleRad=null,t.pointerId=null,e.classList.remove("dragging")}function Gs(e){const{event:t,canvas:n,state:r,config:i,cancelViewAnimation:o}=e,s=i.ctrlDragRotate&&(t.ctrlKey||t.metaKey);(t.button===0||s&&t.button===2)&&(o(),s&&t.preventDefault(),r.dragging=!0,r.mode=s?"rotate":"pan",r.pointerId=t.pointerId,r.lastPointerX=t.clientX,r.lastPointerY=t.clientY,r.rotateLastAngleRad=r.mode==="rotate"?ai(n,t.clientX,t.clientY):null,n.classList.add("dragging"),n.setPointerCapture(t.pointerId))}function qs(e){const{event:t,canvas:n,state:r,config:i,camera:o,clampViewState:s,emitViewState:a,requestRender:c}=e;if(!r.dragging||t.pointerId!==r.pointerId)return;const u=t.clientX-r.lastPointerX,l=t.clientY-r.lastPointerY;if(r.lastPointerX=t.clientX,r.lastPointerY=t.clientY,r.mode==="rotate"){const h=ai(n,t.clientX,t.clientY),f=r.rotateLastAngleRad;if(r.rotateLastAngleRad=h,f!==null){const y=h-f,b=Math.atan2(Math.sin(y),Math.cos(y)),x=i.rotationDragSensitivityDegPerPixel/xn,w=o.getViewState();o.setViewState({rotationDeg:w.rotationDeg-b*180/Math.PI*x})}}else{const h=o.getViewState(),f=Math.max(1e-6,h.zoom),y=oi(h.rotationDeg),b=Math.cos(y),x=Math.sin(y),w=(u*b-l*x)/f,A=(u*x+l*b)/f;o.setViewState({offsetX:h.offsetX-w,offsetY:h.offsetY-A})}s(),a(),c()}function Hs(e,t,n){e.pointerId===n.pointerId&&ci(t,n)}function $s(e){const{event:t,canvas:n,onZoomBy:r}=e;t.preventDefault();const i=n.getBoundingClientRect(),o=t.clientX-i.left,s=t.clientY-i.top,a=t.deltaY<0?1.12:.89;r(a,o,s)}function Zs(e){const{event:t,canvas:n,onZoomBy:r}=e,i=n.getBoundingClientRect(),o=t.clientX-i.left,s=t.clientY-i.top;r(t.shiftKey?.8:1.25,o,s)}function Ks(e,t){(t||e.ctrlKey||e.metaKey)&&e.preventDefault()}function Bn(e){const t=e.getViewCorners();let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[s,a]of t)s<n&&(n=s),s>i&&(i=s),a<r&&(r=a),a>o&&(o=a);return[n,r,i,o]}function Rn(e,t){const n=Bn(e),r=Math.max(1e-6,n[2]-n[0]),i=Math.max(1e-6,n[3]-n[1]),o=r*.2,s=i*.2,[a,c]=e.getCenter(),u=r*.5,l=i*.5,h=u-o,f=t.width-u+o,y=l-s,b=t.height-l+s,x=h<=f?k(a,h,f):t.width*.5,w=y<=b?k(c,y,b):t.height*.5;e.setCenter(x,w)}function js(e,t){const n=Math.max(1e-6,e.getViewState().zoom),r=t.maxTierZoom+Math.log2(n);return k(Math.floor(r),0,t.maxTierZoom)}function Js(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function ui(e,t,n){const r=Bn(e),i=Math.pow(2,t.maxTierZoom-n),o=Math.ceil(t.width/i),s=Math.ceil(t.height/i),a=Math.max(1,Math.ceil(o/t.tileSize)),c=Math.max(1,Math.ceil(s/t.tileSize)),u=r[0],l=r[1],h=r[2],f=r[3],y=k(Math.floor(u/i/t.tileSize),0,a-1),b=k(Math.floor((h-1)/i/t.tileSize),0,a-1),x=k(Math.floor(l/i/t.tileSize),0,c-1),w=k(Math.floor((f-1)/i/t.tileSize),0,c-1);if(y>b||x>w)return[];const A=(u+h)*.5/i/t.tileSize,E=(l+f)*.5/i/t.tileSize,X=[];for(let R=x;R<=w;R+=1)for(let _=y;_<=b;_+=1){const H=_*t.tileSize*i,se=R*t.tileSize*i,j=Math.min((_+1)*t.tileSize,o)*i,J=Math.min((R+1)*t.tileSize,s)*i,ae=_-A,ge=R-E;X.push({key:`${n}/${_}/${R}`,tier:n,x:_,y:R,bounds:[H,se,j,J],distance2:ae*ae+ge*ge,url:Fn(t,n,_,R)})}return X.sort((R,_)=>R.distance2-_.distance2),X}function Qs(e,t){const n=js(e,t);return{tier:n,visible:ui(e,t,n)}}function ea(e){e.interactionLocked||Gs({event:e.event,canvas:e.canvas,state:e.state,config:{ctrlDragRotate:e.ctrlDragRotate,rotationDragSensitivityDegPerPixel:e.rotationDragSensitivityDegPerPixel},cancelViewAnimation:e.cancelViewAnimation})}function ta(e){e.interactionLocked||qs({event:e.event,canvas:e.canvas,state:e.state,config:{ctrlDragRotate:e.ctrlDragRotate,rotationDragSensitivityDegPerPixel:e.rotationDragSensitivityDegPerPixel},camera:e.camera,clampViewState:()=>Rn(e.camera,e.source),emitViewState:e.emitViewState,requestRender:e.requestRender})}function na(e){e.interactionLocked||Hs(e.event,e.canvas,e.state)}function ra(e){if(e.interactionLocked){e.event.preventDefault();return}$s({event:e.event,canvas:e.canvas,onZoomBy:e.onZoomBy})}function ia(e){e.interactionLocked||Zs({event:e.event,canvas:e.canvas,onZoomBy:e.onZoomBy})}function oa(e){Ks(e.event,e.state.dragging)}function sa(e,t){ci(e,t)}function aa(e){return{pointerDown:t=>ea({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state,ctrlDragRotate:e.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:e.getRotationDragSensitivityDegPerPixel(),cancelViewAnimation:e.cancelViewAnimation}),pointerMove:t=>ta({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state,ctrlDragRotate:e.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:e.getRotationDragSensitivityDegPerPixel(),camera:e.camera,source:e.source,emitViewState:e.emitViewState,requestRender:e.requestRender}),pointerUp:t=>na({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state}),wheel:t=>ra({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,onZoomBy:e.zoomBy}),doubleClick:t=>ia({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,onZoomBy:e.zoomBy}),contextMenu:t=>oa({event:t,canvas:e.canvas,state:e.state})}}function ca(e){const{gl:t,cache:n,maxCacheTiles:r}=e;if(n.size<=r)return;const i=Array.from(n.entries());i.sort((s,a)=>s[1].lastUsed-a[1].lastUsed);const o=n.size-r;for(let s=0;s<o;s+=1){const[a,c]=i[s];t.deleteTexture(c.texture),n.delete(a)}}function ua(e,t){if(e.isContextLost())return null;const n=e.createTexture();return n?(e.bindTexture(e.TEXTURE_2D,n),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,1),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.bindTexture(e.TEXTURE_2D,null),n):null}function la(e){const{gl:t,cache:n,tile:r,bitmap:i,frameSerial:o,maxCacheTiles:s,destroyed:a,contextLost:c,requestRender:u}=e;if(a||c||t.isContextLost()){i.close();return}if(n.has(r.key)){i.close();return}const l=ua(t,i);i.close(),l&&(n.set(r.key,{key:r.key,texture:l,bounds:r.bounds,tier:r.tier,lastUsed:o}),ca({gl:t,cache:n,maxCacheTiles:s}),u())}function fa(e,t){for(const[,n]of t)e.deleteTexture(n.texture)}function da(e){const{event:t,destroyed:n,contextLost:r,cancelViewAnimation:i,cancelDrag:o,tileScheduler:s,cache:a,onContextLost:c}=e;if(t.preventDefault(),n||r)return{handled:!1,frame:e.frame};let u=e.frame;return u!==null&&(cancelAnimationFrame(u),u=null),i(),o(),s.clear(),a.clear(),c?.(),{handled:!0,frame:u}}function ha(e){if(e.destroyed)return{didDestroy:!1,frame:e.frame};let t=e.frame;return t!==null&&(cancelAnimationFrame(t),t=null),e.cancelViewAnimation(),e.resizeObserver.disconnect(),e.removeCanvasEventListeners(),e.cancelDrag(),e.tileScheduler.destroy(),!e.contextLost&&!e.gl.isContextLost()&&(fa(e.gl,e.cache),e.gl.deleteBuffer(e.tileProgram.vbo),e.gl.deleteVertexArray(e.tileProgram.vao),e.gl.deleteProgram(e.tileProgram.program),e.gl.deleteBuffer(e.pointProgram.posBuffer),e.gl.deleteBuffer(e.pointProgram.termBuffer),e.gl.deleteBuffer(e.pointProgram.fillModeBuffer),e.gl.deleteBuffer(e.pointProgram.indexBuffer),e.gl.deleteTexture(e.pointProgram.paletteTexture),e.gl.deleteVertexArray(e.pointProgram.vao),e.gl.deleteProgram(e.pointProgram.program)),e.cache.clear(),{didDestroy:!0,frame:t}}function ma(e,t){if(t<=0||e.length===0)return new Uint32Array(0);let n=e.length;for(let o=0;o<e.length;o+=1)e[o]<t||(n-=1);if(n===e.length)return e;if(n<=0)return new Uint32Array(0);const r=new Uint32Array(n);let i=0;for(let o=0;o<e.length;o+=1){const s=e[o];s>=t||(r[i]=s,i+=1)}return r}function ga(e,t){return t<=0?new Uint8Array(0):e.length<t?new Uint8Array(t):e.subarray(0,t)}function pa(e,t,n,r,i){if(!i||i.length===0)return{...e,lastPointPalette:null};const o=new Uint8Array(i);if(r||t.isContextLost())return{...e,lastPointPalette:o};const s=Math.max(1,Math.floor(o.length/4));return t.bindTexture(t.TEXTURE_2D,n.paletteTexture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,s,1,0,t.RGBA,t.UNSIGNED_BYTE,o),t.bindTexture(t.TEXTURE_2D,null),{...e,lastPointPalette:o,pointPaletteSize:s}}function ba(e,t,n,r,i){if(!i||!i.count||!i.positions||!i.paletteIndices)return{...e,lastPointData:null,pointCount:0,usePointIndices:!1};const o=i.fillModes instanceof Uint8Array?i.fillModes:null,s=o!==null,a=Math.max(0,Math.min(i.count,Math.floor(i.positions.length/2),i.paletteIndices.length,s?o.length:Number.MAX_SAFE_INTEGER)),c=i.positions.subarray(0,a*2),u=i.paletteIndices.subarray(0,a),l=s?o.subarray(0,a):void 0,h=i.drawIndices instanceof Uint32Array,f=h?ma(i.drawIndices,a):null,y=e.lastPointData,b=y?.fillModes instanceof Uint8Array,x=e.pointBuffersDirty||!y||y.count!==a||!Ht(y.positions,c)||!Ht(y.paletteIndices,u)||b!==s||s&&(!y?.fillModes||!Ht(y.fillModes,l)),w=e.pointBuffersDirty||h&&(!y?.drawIndices||!Ht(y.drawIndices,f))||!h&&!!y?.drawIndices,A={...e,lastPointData:{count:a,positions:c,paletteIndices:u,fillModes:l,drawIndices:h?f??void 0:void 0}};if(r||t.isContextLost())return A;const E=A.lastPointData;if(!E)return A;if(x){t.bindBuffer(t.ARRAY_BUFFER,n.posBuffer),t.bufferData(t.ARRAY_BUFFER,E.positions,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,n.termBuffer),t.bufferData(t.ARRAY_BUFFER,E.paletteIndices,t.STATIC_DRAW);const X=ga(A.zeroFillModes,a);t.bindBuffer(t.ARRAY_BUFFER,n.fillModeBuffer),t.bufferData(t.ARRAY_BUFFER,E.fillModes??X,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,null),A.zeroFillModes=X}return h&&w&&(t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,n.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,f??new Uint32Array(0),t.DYNAMIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null)),A.usePointIndices=h,A.pointCount=h?f?.length??0:E.count,(x||w)&&(A.pointBuffersDirty=!1),A}function ya(e){const{gl:t,camera:n,source:r,cache:i,frameSerial:o,tileProgram:s,pointProgram:a,imageColorSettings:c,pointCount:u,usePointIndices:l,pointPaletteSize:h,pointStrokeScale:f,pointInnerFillOpacity:y,pointSizePx:b,tileScheduler:x,getVisibleTiles:w,getVisibleTilesForTier:A,getViewBounds:E,intersectsBounds:X}=e;t.clearColor(.03,.06,.1,1),t.clear(t.COLOR_BUFFER_BIT);const{tier:R,visible:_}=w(),H=E(),se=new Set(_.map(O=>O.key));t.useProgram(s.program),t.bindVertexArray(s.vao),t.uniformMatrix3fv(s.uCamera,!1,n.getMatrix()),t.uniform1i(s.uTexture,0),t.uniform1f(s.uBrightness,c.brightness),t.uniform1f(s.uContrast,c.contrast),t.uniform1f(s.uSaturation,c.saturation);const j=[];for(const[,O]of i)se.has(O.key)||X(O.bounds,H)&&j.push(O);j.sort((O,U)=>O.tier-U.tier);for(const O of j)O.lastUsed=o,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,O.texture),t.uniform4f(s.uBounds,O.bounds[0],O.bounds[1],O.bounds[2],O.bounds[3]),t.drawArrays(t.TRIANGLE_STRIP,0,4);let J=0;const ae=[];for(const O of _){const U=i.get(O.key);if(!U){ae.push(O);continue}U.lastUsed=o,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,U.texture),t.uniform4f(s.uBounds,U.bounds[0],U.bounds[1],U.bounds[2],U.bounds[3]),t.drawArrays(t.TRIANGLE_STRIP,0,4),J+=1}const ge=ae.slice(),Te=1e6,B=[];R>0&&B.push(R-1),R<r.maxTierZoom&&B.push(R+1);for(const O of B){const U=A(O);for(const Q of U)i.has(Q.key)||(Q.distance2+=Te,ge.push(Q))}x.schedule(ge),t.bindTexture(t.TEXTURE_2D,null),t.bindVertexArray(null);let D=0;return u>0&&(t.enable(t.BLEND),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA),t.useProgram(a.program),t.bindVertexArray(a.vao),t.uniformMatrix3fv(a.uCamera,!1,n.getMatrix()),t.uniform1f(a.uPointSize,b),t.uniform1f(a.uPointStrokeScale,f),t.uniform1f(a.uPointInnerFillAlpha,y),t.uniform1f(a.uPaletteSize,h),t.uniform1i(a.uPalette,1),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,a.paletteTexture),l?t.drawElements(t.POINTS,u,t.UNSIGNED_INT,0):t.drawArrays(t.POINTS,0,u),t.bindTexture(t.TEXTURE_2D,null),t.bindVertexArray(null),D=u),{tier:R,visible:_.length,rendered:J,points:D,fallback:j.length,cacheHits:J,cacheMisses:ae.length,drawCalls:j.length+J+(D>0?1:0)}}function Rr(e){const r=Pn(e,`#version 300 es
|
|
64
64
|
precision highp float;
|
|
65
65
|
in vec2 aUnit;
|
|
66
66
|
in vec2 aUv;
|
|
@@ -105,7 +105,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
105
105
|
|
|
106
106
|
color.rgb = clamp(color.rgb + uBrightness, vec3(0.0), vec3(1.0));
|
|
107
107
|
outColor = color;
|
|
108
|
-
}`),i=
|
|
108
|
+
}`),i=Pe(e,r,"uCamera"),o=Pe(e,r,"uBounds"),s=Pe(e,r,"uTexture"),a=Pe(e,r,"uBrightness"),c=Pe(e,r,"uContrast"),u=Pe(e,r,"uSaturation"),l=e.createVertexArray(),h=e.createBuffer();if(!l||!h)throw new Error("buffer allocation failed");e.bindVertexArray(l),e.bindBuffer(e.ARRAY_BUFFER,h),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,0,0,1,0,1,0,0,1,0,1,1,1,1,1]),e.STATIC_DRAW);const f=e.getAttribLocation(r,"aUnit"),y=e.getAttribLocation(r,"aUv");if(f<0||y<0)throw new Error("tile attribute lookup failed");return e.enableVertexAttribArray(f),e.enableVertexAttribArray(y),e.vertexAttribPointer(f,2,e.FLOAT,!1,16,0),e.vertexAttribPointer(y,2,e.FLOAT,!1,16,8),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),{program:r,vao:l,vbo:h,uCamera:i,uBounds:o,uTexture:s,uBrightness:a,uContrast:c,uSaturation:u}}function Cr(e){const r=Pn(e,`#version 300 es
|
|
109
109
|
precision highp float;
|
|
110
110
|
in vec2 aPosition;
|
|
111
111
|
in uint aTerm;
|
|
@@ -158,6 +158,6 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
158
158
|
// Premultiplied alpha output: inner fill is black, so it only contributes alpha.
|
|
159
159
|
outColor = vec4(color.rgb * ringAlpha, alpha);
|
|
160
160
|
}
|
|
161
|
-
}`),i=Ee(e,r,"uCamera"),o=Ee(e,r,"uPointSize"),s=Ee(e,r,"uPointStrokeScale"),a=Ee(e,r,"uPointInnerFillAlpha"),c=Ee(e,r,"uPalette"),u=Ee(e,r,"uPaletteSize"),l=e.createVertexArray(),h=e.createBuffer(),f=e.createBuffer(),y=e.createBuffer(),b=e.createBuffer(),x=e.createTexture();if(!l||!h||!f||!y||!b||!x)throw new Error("point buffer allocation failed");e.bindVertexArray(l),e.bindBuffer(e.ARRAY_BUFFER,h),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const w=e.getAttribLocation(r,"aPosition");if(w<0)throw new Error("point position attribute not found");e.enableVertexAttribArray(w),e.vertexAttribPointer(w,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,f),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const A=e.getAttribLocation(r,"aTerm");if(A<0)throw new Error("point term attribute not found");e.enableVertexAttribArray(A),e.vertexAttribIPointer(A,1,e.UNSIGNED_SHORT,0,0),e.bindBuffer(e.ARRAY_BUFFER,y),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const I=e.getAttribLocation(r,"aFillMode");if(I<0)throw new Error("point fill mode attribute not found");return e.enableVertexAttribArray(I),e.vertexAttribIPointer(I,1,e.UNSIGNED_BYTE,0,0),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,b),e.bufferData(e.ELEMENT_ARRAY_BUFFER,0,e.DYNAMIC_DRAW),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),e.bindTexture(e.TEXTURE_2D,x),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([160,160,160,255])),e.bindTexture(e.TEXTURE_2D,null),{program:r,vao:l,posBuffer:h,termBuffer:f,fillModeBuffer:y,indexBuffer:b,paletteTexture:x,uCamera:i,uPointSize:o,uPointStrokeScale:s,uPointInnerFillAlpha:a,uPalette:c,uPaletteSize:u}}function ui(e){e.animation=null,e.frame!==null&&(cancelAnimationFrame(e.frame),e.frame=null)}function ya(e){const{state:t,camera:n,target:r,durationMs:i,easing:o,onUpdate:s}=e,a=n.getViewState();ui(t),t.animation={startMs:fe(),durationMs:Math.max(0,i),from:a,to:r,easing:o};const c=()=>{const u=t.animation;if(!u)return;const l=Math.max(0,fe()-u.startMs),h=u.durationMs<=0?1:k(l/u.durationMs,0,1);let f=h;try{f=u.easing(h)}catch{f=h}if(Number.isFinite(f)||(f=h),f=k(f,0,1),n.setViewState({zoom:u.from.zoom+(u.to.zoom-u.from.zoom)*f,offsetX:u.from.offsetX+(u.to.offsetX-u.from.offsetX)*f,offsetY:u.from.offsetY+(u.to.offsetY-u.from.offsetY)*f,rotationDeg:u.from.rotationDeg+(u.to.rotationDeg-u.from.rotationDeg)*f}),s(),h>=1){t.animation=null,t.frame=null;return}t.frame=requestAnimationFrame(c)};t.frame=requestAnimationFrame(c)}function wa(e){const t=Math.max(e*.5,1e-6),n=Math.max(1,e*8);return{minZoom:t,maxZoom:Math.max(t,n)}}function Sa(e,t,n){const r=wa(e);let i=t??r.minZoom,o=n??r.maxZoom;return i=Math.max(1e-6,i),o=Math.max(1e-6,o),i>o&&(i=o),{minZoom:i,maxZoom:o}}function xa(e,t,n,r,i){const o=e.getViewState(),s={zoom:typeof r.zoom=="number"&&Number.isFinite(r.zoom)?k(r.zoom,t,n):o.zoom,offsetX:typeof r.offsetX=="number"&&Number.isFinite(r.offsetX)?r.offsetX:o.offsetX,offsetY:typeof r.offsetY=="number"&&Number.isFinite(r.offsetY)?r.offsetY:o.offsetY,rotationDeg:typeof r.rotationDeg=="number"&&Number.isFinite(r.rotationDeg)?r.rotationDeg:o.rotationDeg};e.setViewState(s),i();const a=e.getViewState();return e.setViewState(o),a}function Ma(e,t,n,r,i){const o=Math.min(t/e.width,n/e.height),s=Number.isFinite(o)&&o>0?o:1,a=k(s,r,i),c=t/a,u=n/a;return{fitZoom:s,target:{zoom:a,offsetX:(e.width-c)*.5,offsetY:(e.height-u)*.5,rotationDeg:0}}}function Aa(e,t,n,r,i,o){const s=e.getViewState(),a=k(s.zoom*r,t,n);if(a===s.zoom)return null;const[c,u]=e.screenToWorld(i,o),l=e.getViewportSize(),h=i-l.width*.5,f=o-l.height*.5,y=ii(s.rotationDeg),b=Math.cos(y),x=Math.sin(y),w=h/a*b-f/a*x,A=h/a*x+f/a*b,I=c-w,X=u-A;return{zoom:a,offsetX:I-l.width/(2*a),offsetY:X-l.height/(2*a)}}class li{constructor(t,n,r={}){S(this,"canvas");S(this,"source");S(this,"gl");S(this,"camera",new Ir);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",Sn);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",oi);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",An(Mn));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,"boundPointerDown");S(this,"boundPointerMove");S(this,"boundPointerUp");S(this,"boundWheel");S(this,"boundDoubleClick");S(this,"boundContextMenu");S(this,"boundContextLost");S(this,"boundContextRestored");this.canvas=t,this.source=n,this.onViewStateChange=r.onViewStateChange,this.onStats=r.onStats,this.onTileError=r.onTileError,this.onContextLost=r.onContextLost,this.onContextRestored=r.onContextRestored,this.authToken=r.authToken??"",this.maxCacheTiles=Math.max(32,Math.floor(r.maxCacheTiles??320)),this.ctrlDragRotate=r.ctrlDragRotate??!0,this.rotationDragSensitivityDegPerPixel=typeof r.rotationDragSensitivityDegPerPixel=="number"&&Number.isFinite(r.rotationDragSensitivityDegPerPixel)?Math.max(0,r.rotationDragSensitivityDegPerPixel):Sn,this.pointSizeStops=Sr(r.pointSizeByZoom),this.pointStrokeScale=xr(r.pointStrokeScale),this.pointInnerFillOpacity=Mr(r.pointInnerFillOpacity),this.imageColorSettings=Ar(r.imageColorSettings),this.minZoomOverride=Ht(r.minZoom),this.maxZoomOverride=Ht(r.maxZoom),this.viewTransitionDurationMs=hn(r.viewTransition?.duration),this.viewTransitionEasing=mn(r.viewTransition?.easing);const i=t.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,stencil:!1,powerPreference:"high-performance"});if(!i)throw new Error("WebGL2 not supported");this.gl=i,this.tileProgram=Tr(this.gl),this.pointProgram=Rr(this.gl),this.tileScheduler=new ri({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)=>ua({gl:this.gl,cache:this.cache,tile:s,bitmap:a,frameSerial:this.frameSerial,maxCacheTiles:this.maxCacheTiles,destroyed:this.destroyed,contextLost:this.contextLost,requestRender:()=>this.requestRender()}),onTileError:(s,a,c)=>{this.onTileError?.({tile:s,error:a,attemptCount:c}),console.warn("tile load failed",s.url,a)}}),this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(t);const o=sa({canvas:this.canvas,state:this.interactionState,getInteractionLocked:()=>this.interactionLocked,getCtrlDragRotate:()=>this.ctrlDragRotate,getRotationDragSensitivityDegPerPixel:()=>this.rotationDragSensitivityDegPerPixel,cancelViewAnimation:()=>this.cancelViewAnimation(),camera:this.camera,source:this.source,emitViewState:()=>this.onViewStateChange?.(this.camera.getViewState()),requestRender:()=>this.requestRender(),zoomBy:(s,a,c)=>this.zoomBy(s,a,c)});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),_s(t,this.getCanvasHandlers()),this.fitToImage({duration:0}),this.resize()}getCanvasHandlers(){return{pointerDown:this.boundPointerDown,pointerMove:this.boundPointerMove,pointerUp:this.boundPointerUp,wheel:this.boundWheel,doubleClick:this.boundDoubleClick,contextMenu:this.boundContextMenu,contextLost:this.boundContextLost,contextRestored:this.boundContextRestored}}applyZoomBounds(){const t=Sa(this.fitZoom,this.minZoomOverride,this.maxZoomOverride);this.minZoom=t.minZoom,this.maxZoom=t.maxZoom}resolveTargetViewState(t){return xa(this.camera,this.minZoom,this.maxZoom,t,()=>Tn(this.camera,this.source))}cancelViewAnimation(){ui(this.viewAnimationState)}startViewAnimation(t,n,r){ya({state:this.viewAnimationState,camera:this.camera,target:t,durationMs:n,easing:r,onUpdate:()=>{Tn(this.camera,this.source),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}})}getPointBufferRuntime(){return{pointCount:this.pointCount,usePointIndices:this.usePointIndices,pointBuffersDirty:this.pointBuffersDirty,lastPointData:this.lastPointData,zeroFillModes:this.zeroFillModes,lastPointPalette:this.lastPointPalette,pointPaletteSize:this.pointPaletteSize}}applyPointBufferRuntime(t){this.pointCount=t.pointCount,this.usePointIndices=t.usePointIndices,this.pointBuffersDirty=t.pointBuffersDirty,this.lastPointData=t.lastPointData,this.zeroFillModes=t.zeroFillModes,this.lastPointPalette=t.lastPointPalette,this.pointPaletteSize=t.pointPaletteSize}applyViewStateAndRender(t,n=!0){n&&this.cancelViewAnimation(),this.camera.setViewState(t),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}setAuthToken(t){this.authToken=String(t??""),this.tileScheduler.setAuthToken(this.authToken)}setZoomRange(t,n){const r=Ht(t),i=Ht(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(t){this.viewTransitionDurationMs=hn(t?.duration),this.viewTransitionEasing=mn(t?.easing)}setViewState(t,n){const r=this.resolveTargetViewState(t),i=this.camera.getViewState();if(pn(i,r))return;const o=hn(n?.duration??this.viewTransitionDurationMs),s=mn(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}}setPointPalette(t){const n=ga(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,t);this.applyPointBufferRuntime(n),!(!t||t.length===0)&&this.requestRender()}setPointData(t){const n=pa(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,t);this.applyPointBufferRuntime(n),this.requestRender()}setInteractionLock(t){const n=!!t;this.interactionLocked!==n&&(this.interactionLocked=n,n&&this.cancelDrag())}setPointSizeByZoom(t){const n=Sr(t);Ys(this.pointSizeStops,n)||(this.pointSizeStops=n,this.requestRender())}setPointStrokeScale(t){const n=xr(t);this.pointStrokeScale!==n&&(this.pointStrokeScale=n,this.requestRender())}setPointInnerFillOpacity(t){const n=Mr(t);this.pointInnerFillOpacity!==n&&(this.pointInnerFillOpacity=n,this.requestRender())}setImageColorSettings(t){const n=Ar(t),r=this.imageColorSettings;r.brightness===n.brightness&&r.contrast===n.contrast&&r.saturation===n.saturation||(this.imageColorSettings=n,this.requestRender())}cancelDrag(){oa(this.canvas,this.interactionState)}screenToWorld(t,n){const r=this.canvas.getBoundingClientRect(),i=t-r.left,o=n-r.top;return this.camera.screenToWorld(i,o)}worldToScreen(t,n){return this.camera.worldToScreen(t,n)}setViewCenter(t,n,r){if(!Number.isFinite(t)||!Number.isFinite(n))return;const i=this.camera.getViewState(),o=Math.max(1e-6,i.zoom),s=this.camera.getViewportSize();this.setViewState({offsetX:t-s.width/(2*o),offsetY:n-s.height/(2*o)},r)}getViewCorners(){return this.camera.getViewCorners()}resetRotation(t){const n=this.camera.getViewState();Math.abs(n.rotationDeg)<1e-6||this.setViewState({rotationDeg:0},t)}getPointSizeByZoom(){const t=Math.max(1e-6,this.camera.getViewState().zoom),n=this.source.maxTierZoom+Math.log2(t),r=Xs(n,this.pointSizeStops);return k(r,xn,Us)}fitToImage(t){const n=this.canvas.getBoundingClientRect(),r=Math.max(1,n.width||1),i=Math.max(1,n.height||1),o=Ma(this.source,r,i,this.minZoom,this.maxZoom);this.fitZoom=o.fitZoom,this.applyZoomBounds(),this.setViewState(o.target,t)}zoomBy(t,n,r,i){const o=Aa(this.camera,this.minZoom,this.maxZoom,t,n,r);o&&this.setViewState(o,i)}render(){if(this.destroyed||this.contextLost||this.gl.isContextLost())return;const t=this.onStats?fe():0;this.frameSerial+=1;const n=ba({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(),tileScheduler:this.tileScheduler,getVisibleTiles:()=>Js(this.camera,this.source),getVisibleTilesForTier:r=>ci(this.camera,this.source,r),getViewBounds:()=>Fn(this.camera),intersectsBounds:js});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:fe()-t})}}requestRender(){this.frame!==null||this.destroyed||this.contextLost||this.gl.isContextLost()||(this.frame=requestAnimationFrame(()=>{this.frame=null,this.render()}))}resize(){Bs(this.canvas,this.gl,this.camera),this.requestRender()}onWebGlContextLost(t){const n=fa({event:t,destroyed:this.destroyed,contextLost:this.contextLost,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,cache:this.cache,onContextLost:this.onContextLost});n.handled&&(this.frame=n.frame,this.contextLost=!0,this.pointBuffersDirty=!0)}onWebGlContextRestored(t){this.destroyed||(this.contextLost=!1,this.cache.clear(),this.tileProgram=Tr(this.gl),this.pointProgram=Rr(this.gl),this.pointBuffersDirty=!0,this.lastPointPalette&&this.lastPointPalette.length>0&&this.setPointPalette(this.lastPointPalette),this.lastPointData?this.setPointData(this.lastPointData):this.pointCount=0,this.resize(),this.requestRender(),this.onContextRestored?.())}destroy(){const t=da({destroyed:this.destroyed,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),resizeObserver:this.resizeObserver,removeCanvasEventListeners:()=>Fs(this.canvas,this.getCanvasHandlers()),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,contextLost:this.contextLost,gl:this.gl,cache:this.cache,tileProgram:this.tileProgram,pointProgram:this.pointProgram});t.didDestroy&&(this.destroyed=!0,this.frame=t.frame)}}const Ta=6;function Rn(e,t){return e.id??t}function Ra(e,t,n,r,i,o){const s=i-n,a=o-r,c=s*s+a*a;if(c<=1e-12){const b=e-n,x=t-r;return b*b+x*x}const u=k(((e-n)*s+(t-r)*a)/c,0,1),l=n+s*u,h=r+a*u,f=e-l,y=t-h;return f*f+y*y}function Cr(e,t,n,r){for(let i=1;i<n.length;i+=1){const o=n[i-1],s=n[i];if(Ra(e,t,o[0],o[1],s[0],s[1])<=r)return!0}return!1}function Ca(e,t,n,r){if(e<n.minX-r||e>n.maxX+r||t<n.minY-r||t>n.maxY+r)return!1;const i=r*r;if(Cr(e,t,n.outer,i))return!0;for(const o of n.holes)if(Cr(e,t,o,i))return!0;return!1}function Pa(e,t,n,r,i,o,s){if(!e.label||!e.labelAnchor)return!1;const a=Jt(n.worldToScreen(e.labelAnchor[0],e.labelAnchor[1]));if(!a)return!1;const u=En(e.label,r)+r.paddingX*2,l=r.fontSize+r.paddingY*2,h=a[0],f=a[1]-r.offsetY,y=s?k(h,u*.5+1,i-u*.5-1):h,b=s?k(f,l*.5+1,o-l*.5-1):f,x=y-u*.5,w=y+u*.5,A=b-l*.5,I=b+l*.5;return t[0]>=x&&t[0]<=w&&t[1]>=A&&t[1]<=I}function Ia(e){const t=[];for(let n=0;n<e.length;n+=1){const r=e[n],i=It([Pt(r?.coordinates)]);if(i.length===0)continue;const o=typeof r?.label=="string"?r.label.trim():"";t.push({region:r,regionIndex:n,regionId:Rn(r,n),polygons:i,label:o,labelAnchor:o?Yr(i):null})}return t}function Ea(e,t,n,r,i,o,s,a,c,u=!0){const l=e[0],h=e[1],f=Math.max(1e-6,r.getViewState().zoom),y=Math.max(0,s),b=Ta/f;for(let x=n.length-1;x>=0;x-=1){const w=n[x];for(const I of w.polygons)if(Ca(l,h,I,b))return{region:w.region,regionIndex:w.regionIndex,regionId:w.regionId};let A=Xr(i,o?.({region:w.region,regionId:w.regionId,regionIndex:w.regionIndex,zoom:f}));if(y>0&&(A={...A,offsetY:A.offsetY+y}),!!Pa(w,t,r,A,a,c,u))return{region:w.region,regionIndex:w.regionIndex,regionId:w.regionId}}return null}const gn=[],va=[],_a={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)},Fa=.65,Ba=4,Ua=180,Pr=20;function La(e){const t=k(e,0,1);return t*t*(3-2*t)}function Da({source:e,viewState:t,imageColorSettings:n=null,onViewStateChange:r,onStats:i,onTileError:o,onContextLost:s,onContextRestored:a,debugOverlay:c=!1,debugOverlayStyle:u,fitNonce:l=0,rotationResetNonce:h=0,authToken:f="",ctrlDragRotate:y=!0,pointData:b=null,pointPalette:x=null,pointSizeByZoom:w,pointStrokeScale:A,pointInnerFillOpacity:I,minZoom:X,maxZoom:R,viewTransition:_,roiRegions:H,roiPolygons:ae,clipPointsToRois:te=!1,clipMode:ne="worker",onClipStats:ce,onRoiPointGroups:he,roiPaletteIndexToTermId:Pe,interactionLock:B=!1,drawTool:U="cursor",stampOptions:z,brushOptions:D,drawFillColor:J,regionStrokeStyle:be,regionStrokeHoverStyle:Me,regionStrokeActiveStyle:Xe,patchStrokeStyle:Be,resolveRegionStrokeStyle:ye,resolveRegionLabelStyle:M,overlayShapes:E,customLayers:O,patchRegions:oe,regionLabelStyle:j,drawAreaTooltip:Q,autoLiftRegionLabelAtMaxZoom:Ae=!1,clampRegionLabelToViewport:ge=!0,onPointerWorldMove:Z,onPointHover:re,onPointClick:pe,onRegionHover:G,onRegionClick:me,activeRegionId:K,onActiveRegionChange:we,getCellByCoordinatesRef:ee,onDrawComplete:le,onPatchComplete:Ue,overviewMapConfig:Te,className:Ve,style:xe}){const Le=Te?.show??!1,ut=Te?.options,Y=d.useRef(null),W=d.useRef(null),Re=d.useRef(null),ue=d.useRef(null),Ce=d.useRef(r),pt=d.useRef(i),et=d.useRef(c),[Et,tt]=d.useState(null),[vt,_t]=d.useState(()=>K??null),m=K!==void 0,g=m?K??null:vt,[T,P]=d.useState(null),[v,de]=d.useState(null),[V,se]=d.useState(0),q=d.useRef(null),ie=d.useRef(null),Se=d.useRef(null),Ie=d.useRef(0),De=d.useRef({rafId:null,startMs:0,from:0,to:0}),nt=d.useRef(0),qe=H??gn,bt=oe??gn,yt=ae??va,He=(O?.length??0)>0,fi=d.useMemo(()=>({position:"relative",width:"100%",height:"100%",...xe}),[xe]),di=d.useMemo(()=>({position:"absolute",top:8,left:8,zIndex:7,margin:0,padding:"8px 10px",maxWidth:"min(420px, 80%)",pointerEvents:"none",whiteSpace:"pre-wrap",lineHeight:1.35,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:11,color:"#cde6ff",background:"rgba(6, 12, 20, 0.82)",border:"1px solid rgba(173, 216, 255, 0.28)",borderRadius:8,boxShadow:"0 8px 22px rgba(0,0,0,0.35)",...u}),[u]),We=d.useMemo(()=>qe.length>0?qe:yt.length===0?gn:yt.map((p,C)=>({id:C,coordinates:p})),[qe,yt]),$e=d.useMemo(()=>Ia(We),[We]),Bn=d.useMemo(()=>vn(j),[j]),lt=d.useCallback(p=>{const C=k(p,0,Pr);Math.abs(Ie.current-C)<1e-4||(Ie.current=C,se(C))},[]),rt=d.useCallback(()=>{const p=De.current;p.rafId!==null&&(cancelAnimationFrame(p.rafId),p.rafId=null)},[]),en=d.useCallback(p=>{const C=k(p,0,Pr),F=De.current,L=Ie.current;if(Math.abs(L-C)<1e-4){rt(),F.to=C,lt(C);return}rt(),F.startMs=performance.now(),F.from=L,F.to=C;const N=$=>{const ve=De.current,Ne=Math.max(0,$-ve.startMs),ht=k(Ne/Ua,0,1),tn=La(ht),nn=ve.from+(ve.to-ve.from)*tn;if(lt(nn),Re.current?.(),ht>=1){ve.rafId=null,lt(ve.to);return}ve.rafId=requestAnimationFrame(N)};F.rafId=requestAnimationFrame(N)},[lt,rt]),Ze=d.useCallback(p=>{const C=W.current;if(!C||typeof p!="number"||!Number.isFinite(p)){en(0);return}const F=Vr(Ae,p,C.getZoomRange());en(F)},[Ae,en]),it=d.useMemo(()=>We.map(p=>Pt(p.coordinates)).filter(p=>p!=null),[We]),[ot,Ft]=d.useState(b);d.useEffect(()=>{const p=++nt.current;let C=!1;if(!te)return Ft(b),()=>{C=!0};if(!b||!b.count||!b.positions||!b.paletteIndices)return Ft(null),()=>{C=!0};if(it.length===0)return Ft(_a),ce?.({mode:ne,durationMs:0,inputCount:b.count,outputCount:0,polygonCount:0}),()=>{C=!0};const F=(N,$)=>{if(C||p!==nt.current)return;const ve=b.count,Ne=N?.drawIndices?N.drawIndices.length:N?.count??0;Ft(N),ce?.({mode:$.mode,durationMs:$.durationMs,inputCount:ve,outputCount:Ne,polygonCount:it.length,usedWebGpu:$.usedWebGpu,candidateCount:$.candidateCount,bridgedToDraw:$.bridgedToDraw})};return(async()=>{if(ne==="sync"){const N=performance.now(),$=Rt(b,it);F($,{mode:"sync",durationMs:performance.now()-N});return}if(ne==="hybrid-webgpu"){const N=await jr(b,it,{bridgeToDraw:!0});F(N.data,{mode:N.meta.mode,durationMs:N.meta.durationMs,usedWebGpu:N.meta.usedWebGpu,candidateCount:N.meta.candidateCount,bridgedToDraw:N.meta.bridgedToDraw});return}try{const N=await Qr(b,it);F(N.data,{mode:N.meta.mode,durationMs:N.meta.durationMs})}catch{const N=performance.now(),$=Rt(b,it);F($,{mode:"sync",durationMs:performance.now()-N})}})(),()=>{C=!0}},[te,ne,b,it,ce]);const Un=!!(re||pe||ee),[Ge,Ln]=d.useState(null);d.useEffect(()=>{if(!Un||!ot){Ln(null);return}let p=!1;return ti(ot,e).then(C=>{p||Ln(C)}),()=>{p=!0}},[Un,ot,e]);const st=d.useCallback(p=>{const C=W.current;if(!C||!Ge)return null;const F=Number(p[0]),L=Number(p[1]);if(!Number.isFinite(F)||!Number.isFinite(L))return null;const N=Math.max(1e-6,C.getViewState().zoom),$=C.getPointSizeByZoom(),Ne=Math.max(Ba,$*Fa)/N;if(!Number.isFinite(Ne)||Ne<=0)return null;const{cellSize:ht,cellOffsets:tn,cellLengths:nn,pointIndices:wi,positions:Yn,safeCount:Si}=Ge,Xn=Math.floor(F/ht),Vn=Math.floor(L/ht),Lt=Math.max(1,Math.ceil(Ne/ht)),xi=Ne*Ne;let Dt=-1,Gn=xi,qn=0,Hn=0;for(let rn=Xn-Lt;rn<=Xn+Lt;rn+=1)for(let on=Vn-Lt;on<=Vn+Lt;on+=1){const sn=ei(Ge,rn,on);if(sn<0)continue;const $n=tn[sn],Ai=$n+nn[sn];for(let an=$n;an<Ai;an+=1){const kt=wi[an];if(kt>=Si)continue;const Zn=Yn[kt*2],Kn=Yn[kt*2+1],jn=Zn-F,Jn=Kn-L,Qn=jn*jn+Jn*Jn;Qn>Gn||(Gn=Qn,Dt=kt,qn=Zn,Hn=Kn)}}if(Dt<0)return null;const Mi=Ge.ids?Number(Ge.ids[Dt]):null;return{index:Dt,id:Mi,coordinate:[F,L],pointCoordinate:[qn,Hn]}},[Ge]),ft=d.useCallback((p,C)=>{if(!re)return;const F=p?.index??null,L=p?.id??null;ie.current===F&&Se.current===L||(ie.current=F,Se.current=L,re({index:F,id:L,coordinate:C,pointCoordinate:p?.pointCoordinate??null}))},[re]),Bt=d.useCallback((p,C)=>{if(!pe)return;const F=st(p);F&&pe({...F,button:C})},[pe,st]);d.useEffect(()=>{if(ee)return ee.current=st,()=>{ee.current===st&&(ee.current=null)}},[ee,st]),d.useEffect(()=>{m&&_t(K??null)},[m,K]);const Ke=d.useCallback(p=>{String(g)!==String(p)&&(m||_t(p),we?.(p))},[g,m,we]);d.useEffect(()=>{Ce.current=r},[r]),d.useEffect(()=>{pt.current=i},[i]),d.useEffect(()=>{et.current=c,c||de(null)},[c]),d.useEffect(()=>()=>{rt()},[rt]);const Dn=d.useCallback(p=>{pt.current?.(p),et.current&&de(p)},[]),hi=d.useMemo(()=>v?[`tier ${v.tier} | frame ${v.frameMs?.toFixed(2)??"-"} ms | drawCalls ${v.drawCalls??"-"}`,`tiles visible ${v.visible} | rendered ${v.rendered} | fallback ${v.fallback}`,`cache size ${v.cache} | hit ${v.cacheHits??"-"} | miss ${v.cacheMisses??"-"}`,`queue inflight ${v.inflight} | queued ${v.queued??"-"} | retries ${v.retries??"-"} | failed ${v.failed??"-"} | aborted ${v.aborted??"-"}`,`points ${v.points}`].join(`
|
|
162
|
-
`):"stats: waiting for first frame...",[v]);d.useEffect(()=>{!(g===null?!0:
|
|
161
|
+
}`),i=Pe(e,r,"uCamera"),o=Pe(e,r,"uPointSize"),s=Pe(e,r,"uPointStrokeScale"),a=Pe(e,r,"uPointInnerFillAlpha"),c=Pe(e,r,"uPalette"),u=Pe(e,r,"uPaletteSize"),l=e.createVertexArray(),h=e.createBuffer(),f=e.createBuffer(),y=e.createBuffer(),b=e.createBuffer(),x=e.createTexture();if(!l||!h||!f||!y||!b||!x)throw new Error("point buffer allocation failed");e.bindVertexArray(l),e.bindBuffer(e.ARRAY_BUFFER,h),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const w=e.getAttribLocation(r,"aPosition");if(w<0)throw new Error("point position attribute not found");e.enableVertexAttribArray(w),e.vertexAttribPointer(w,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,f),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const A=e.getAttribLocation(r,"aTerm");if(A<0)throw new Error("point term attribute not found");e.enableVertexAttribArray(A),e.vertexAttribIPointer(A,1,e.UNSIGNED_SHORT,0,0),e.bindBuffer(e.ARRAY_BUFFER,y),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const E=e.getAttribLocation(r,"aFillMode");if(E<0)throw new Error("point fill mode attribute not found");return e.enableVertexAttribArray(E),e.vertexAttribIPointer(E,1,e.UNSIGNED_BYTE,0,0),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,b),e.bufferData(e.ELEMENT_ARRAY_BUFFER,0,e.DYNAMIC_DRAW),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),e.bindTexture(e.TEXTURE_2D,x),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([160,160,160,255])),e.bindTexture(e.TEXTURE_2D,null),{program:r,vao:l,posBuffer:h,termBuffer:f,fillModeBuffer:y,indexBuffer:b,paletteTexture:x,uCamera:i,uPointSize:o,uPointStrokeScale:s,uPointInnerFillAlpha:a,uPalette:c,uPaletteSize:u}}function li(e){e.animation=null,e.frame!==null&&(cancelAnimationFrame(e.frame),e.frame=null)}function wa(e){const{state:t,camera:n,target:r,durationMs:i,easing:o,onUpdate:s}=e,a=n.getViewState();li(t),t.animation={startMs:fe(),durationMs:Math.max(0,i),from:a,to:r,easing:o};const c=()=>{const u=t.animation;if(!u)return;const l=Math.max(0,fe()-u.startMs),h=u.durationMs<=0?1:k(l/u.durationMs,0,1);let f=h;try{f=u.easing(h)}catch{f=h}if(Number.isFinite(f)||(f=h),f=k(f,0,1),n.setViewState({zoom:u.from.zoom+(u.to.zoom-u.from.zoom)*f,offsetX:u.from.offsetX+(u.to.offsetX-u.from.offsetX)*f,offsetY:u.from.offsetY+(u.to.offsetY-u.from.offsetY)*f,rotationDeg:u.from.rotationDeg+(u.to.rotationDeg-u.from.rotationDeg)*f}),s(),h>=1){t.animation=null,t.frame=null;return}t.frame=requestAnimationFrame(c)};t.frame=requestAnimationFrame(c)}function Sa(e){const t=Math.max(e*.5,1e-6),n=Math.max(1,e*8);return{minZoom:t,maxZoom:Math.max(t,n)}}function xa(e,t,n){const r=Sa(e);let i=t??r.minZoom,o=n??r.maxZoom;return i=Math.max(1e-6,i),o=Math.max(1e-6,o),i>o&&(i=o),{minZoom:i,maxZoom:o}}function Ma(e,t,n,r,i){const o=e.getViewState(),s={zoom:typeof r.zoom=="number"&&Number.isFinite(r.zoom)?k(r.zoom,t,n):o.zoom,offsetX:typeof r.offsetX=="number"&&Number.isFinite(r.offsetX)?r.offsetX:o.offsetX,offsetY:typeof r.offsetY=="number"&&Number.isFinite(r.offsetY)?r.offsetY:o.offsetY,rotationDeg:typeof r.rotationDeg=="number"&&Number.isFinite(r.rotationDeg)?r.rotationDeg:o.rotationDeg};e.setViewState(s),i();const a=e.getViewState();return e.setViewState(o),a}function Aa(e,t,n,r,i){const o=Math.min(t/e.width,n/e.height),s=Number.isFinite(o)&&o>0?o:1,a=k(s,r,i),c=t/a,u=n/a;return{fitZoom:s,target:{zoom:a,offsetX:(e.width-c)*.5,offsetY:(e.height-u)*.5,rotationDeg:0}}}function Ta(e,t,n,r,i,o){const s=e.getViewState(),a=k(s.zoom*r,t,n);if(a===s.zoom)return null;const[c,u]=e.screenToWorld(i,o),l=e.getViewportSize(),h=i-l.width*.5,f=o-l.height*.5,y=oi(s.rotationDeg),b=Math.cos(y),x=Math.sin(y),w=h/a*b-f/a*x,A=h/a*x+f/a*b,E=c-w,X=u-A;return{zoom:a,offsetX:E-l.width/(2*a),offsetY:X-l.height/(2*a)}}class fi{constructor(t,n,r={}){S(this,"canvas");S(this,"source");S(this,"gl");S(this,"camera",new Er);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",xn);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",si);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",Tn(An));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,"boundPointerDown");S(this,"boundPointerMove");S(this,"boundPointerUp");S(this,"boundWheel");S(this,"boundDoubleClick");S(this,"boundContextMenu");S(this,"boundContextLost");S(this,"boundContextRestored");this.canvas=t,this.source=n,this.onViewStateChange=r.onViewStateChange,this.onStats=r.onStats,this.onTileError=r.onTileError,this.onContextLost=r.onContextLost,this.onContextRestored=r.onContextRestored,this.authToken=r.authToken??"",this.maxCacheTiles=Math.max(32,Math.floor(r.maxCacheTiles??320)),this.ctrlDragRotate=r.ctrlDragRotate??!0,this.rotationDragSensitivityDegPerPixel=typeof r.rotationDragSensitivityDegPerPixel=="number"&&Number.isFinite(r.rotationDragSensitivityDegPerPixel)?Math.max(0,r.rotationDragSensitivityDegPerPixel):xn,this.pointSizeStops=xr(r.pointSizeByZoom),this.pointStrokeScale=Mr(r.pointStrokeScale),this.pointInnerFillOpacity=Ar(r.pointInnerFillOpacity),this.imageColorSettings=Tr(r.imageColorSettings),this.minZoomOverride=$t(r.minZoom),this.maxZoomOverride=$t(r.maxZoom),this.viewTransitionDurationMs=mn(r.viewTransition?.duration),this.viewTransitionEasing=gn(r.viewTransition?.easing);const i=t.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,stencil:!1,powerPreference:"high-performance"});if(!i)throw new Error("WebGL2 not supported");this.gl=i,this.tileProgram=Rr(this.gl),this.pointProgram=Cr(this.gl),this.tileScheduler=new ii({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)=>la({gl:this.gl,cache:this.cache,tile:s,bitmap:a,frameSerial:this.frameSerial,maxCacheTiles:this.maxCacheTiles,destroyed:this.destroyed,contextLost:this.contextLost,requestRender:()=>this.requestRender()}),onTileError:(s,a,c)=>{this.onTileError?.({tile:s,error:a,attemptCount:c}),console.warn("tile load failed",s.url,a)}}),this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(t);const o=aa({canvas:this.canvas,state:this.interactionState,getInteractionLocked:()=>this.interactionLocked,getCtrlDragRotate:()=>this.ctrlDragRotate,getRotationDragSensitivityDegPerPixel:()=>this.rotationDragSensitivityDegPerPixel,cancelViewAnimation:()=>this.cancelViewAnimation(),camera:this.camera,source:this.source,emitViewState:()=>this.onViewStateChange?.(this.camera.getViewState()),requestRender:()=>this.requestRender(),zoomBy:(s,a,c)=>this.zoomBy(s,a,c)});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),Fs(t,this.getCanvasHandlers()),this.fitToImage({duration:0}),this.resize()}getCanvasHandlers(){return{pointerDown:this.boundPointerDown,pointerMove:this.boundPointerMove,pointerUp:this.boundPointerUp,wheel:this.boundWheel,doubleClick:this.boundDoubleClick,contextMenu:this.boundContextMenu,contextLost:this.boundContextLost,contextRestored:this.boundContextRestored}}applyZoomBounds(){const t=xa(this.fitZoom,this.minZoomOverride,this.maxZoomOverride);this.minZoom=t.minZoom,this.maxZoom=t.maxZoom}resolveTargetViewState(t){return Ma(this.camera,this.minZoom,this.maxZoom,t,()=>Rn(this.camera,this.source))}cancelViewAnimation(){li(this.viewAnimationState)}startViewAnimation(t,n,r){wa({state:this.viewAnimationState,camera:this.camera,target:t,durationMs:n,easing:r,onUpdate:()=>{Rn(this.camera,this.source),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}})}getPointBufferRuntime(){return{pointCount:this.pointCount,usePointIndices:this.usePointIndices,pointBuffersDirty:this.pointBuffersDirty,lastPointData:this.lastPointData,zeroFillModes:this.zeroFillModes,lastPointPalette:this.lastPointPalette,pointPaletteSize:this.pointPaletteSize}}applyPointBufferRuntime(t){this.pointCount=t.pointCount,this.usePointIndices=t.usePointIndices,this.pointBuffersDirty=t.pointBuffersDirty,this.lastPointData=t.lastPointData,this.zeroFillModes=t.zeroFillModes,this.lastPointPalette=t.lastPointPalette,this.pointPaletteSize=t.pointPaletteSize}applyViewStateAndRender(t,n=!0){n&&this.cancelViewAnimation(),this.camera.setViewState(t),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}setAuthToken(t){this.authToken=String(t??""),this.tileScheduler.setAuthToken(this.authToken)}setZoomRange(t,n){const r=$t(t),i=$t(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();bn(s,o)||this.applyViewStateAndRender(o)}setViewTransition(t){this.viewTransitionDurationMs=mn(t?.duration),this.viewTransitionEasing=gn(t?.easing)}setViewState(t,n){const r=this.resolveTargetViewState(t),i=this.camera.getViewState();if(bn(i,r))return;const o=mn(n?.duration??this.viewTransitionDurationMs),s=gn(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}}setPointPalette(t){const n=pa(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,t);this.applyPointBufferRuntime(n),!(!t||t.length===0)&&this.requestRender()}setPointData(t){const n=ba(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,t);this.applyPointBufferRuntime(n),this.requestRender()}setInteractionLock(t){const n=!!t;this.interactionLocked!==n&&(this.interactionLocked=n,n&&this.cancelDrag())}setPointSizeByZoom(t){const n=xr(t);Xs(this.pointSizeStops,n)||(this.pointSizeStops=n,this.requestRender())}setPointStrokeScale(t){const n=Mr(t);this.pointStrokeScale!==n&&(this.pointStrokeScale=n,this.requestRender())}setPointInnerFillOpacity(t){const n=Ar(t);this.pointInnerFillOpacity!==n&&(this.pointInnerFillOpacity=n,this.requestRender())}setImageColorSettings(t){const n=Tr(t),r=this.imageColorSettings;r.brightness===n.brightness&&r.contrast===n.contrast&&r.saturation===n.saturation||(this.imageColorSettings=n,this.requestRender())}cancelDrag(){sa(this.canvas,this.interactionState)}screenToWorld(t,n){const r=this.canvas.getBoundingClientRect(),i=t-r.left,o=n-r.top;return this.camera.screenToWorld(i,o)}worldToScreen(t,n){return this.camera.worldToScreen(t,n)}setViewCenter(t,n,r){if(!Number.isFinite(t)||!Number.isFinite(n))return;const i=this.camera.getViewState(),o=Math.max(1e-6,i.zoom),s=this.camera.getViewportSize();this.setViewState({offsetX:t-s.width/(2*o),offsetY:n-s.height/(2*o)},r)}getViewCorners(){return this.camera.getViewCorners()}resetRotation(t){const n=this.camera.getViewState();Math.abs(n.rotationDeg)<1e-6||this.setViewState({rotationDeg:0},t)}getPointSizeByZoom(){const t=Math.max(1e-6,this.camera.getViewState().zoom),n=this.source.maxTierZoom+Math.log2(t),r=Vs(n,this.pointSizeStops);return k(r,Mn,Ls)}fitToImage(t){const n=this.canvas.getBoundingClientRect(),r=Math.max(1,n.width||1),i=Math.max(1,n.height||1),o=Aa(this.source,r,i,this.minZoom,this.maxZoom);this.fitZoom=o.fitZoom,this.applyZoomBounds(),this.setViewState(o.target,t)}zoomBy(t,n,r,i){const o=Ta(this.camera,this.minZoom,this.maxZoom,t,n,r);o&&this.setViewState(o,i)}render(){if(this.destroyed||this.contextLost||this.gl.isContextLost())return;const t=this.onStats?fe():0;this.frameSerial+=1;const n=ya({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(),tileScheduler:this.tileScheduler,getVisibleTiles:()=>Qs(this.camera,this.source),getVisibleTilesForTier:r=>ui(this.camera,this.source,r),getViewBounds:()=>Bn(this.camera),intersectsBounds:Js});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:fe()-t})}}requestRender(){this.frame!==null||this.destroyed||this.contextLost||this.gl.isContextLost()||(this.frame=requestAnimationFrame(()=>{this.frame=null,this.render()}))}resize(){Us(this.canvas,this.gl,this.camera),this.requestRender()}onWebGlContextLost(t){const n=da({event:t,destroyed:this.destroyed,contextLost:this.contextLost,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,cache:this.cache,onContextLost:this.onContextLost});n.handled&&(this.frame=n.frame,this.contextLost=!0,this.pointBuffersDirty=!0)}onWebGlContextRestored(t){this.destroyed||(this.contextLost=!1,this.cache.clear(),this.tileProgram=Rr(this.gl),this.pointProgram=Cr(this.gl),this.pointBuffersDirty=!0,this.lastPointPalette&&this.lastPointPalette.length>0&&this.setPointPalette(this.lastPointPalette),this.lastPointData?this.setPointData(this.lastPointData):this.pointCount=0,this.resize(),this.requestRender(),this.onContextRestored?.())}destroy(){const t=ha({destroyed:this.destroyed,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),resizeObserver:this.resizeObserver,removeCanvasEventListeners:()=>Bs(this.canvas,this.getCanvasHandlers()),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,contextLost:this.contextLost,gl:this.gl,cache:this.cache,tileProgram:this.tileProgram,pointProgram:this.pointProgram});t.didDestroy&&(this.destroyed=!0,this.frame=t.frame)}}const Ra=6;function Cn(e,t){return e.id??t}function Ca(e,t,n,r,i,o){const s=i-n,a=o-r,c=s*s+a*a;if(c<=1e-12){const b=e-n,x=t-r;return b*b+x*x}const u=k(((e-n)*s+(t-r)*a)/c,0,1),l=n+s*u,h=r+a*u,f=e-l,y=t-h;return f*f+y*y}function Pr(e,t,n,r){for(let i=1;i<n.length;i+=1){const o=n[i-1],s=n[i];if(Ca(e,t,o[0],o[1],s[0],s[1])<=r)return!0}return!1}function Pa(e,t,n,r){if(e<n.minX-r||e>n.maxX+r||t<n.minY-r||t>n.maxY+r)return!1;const i=r*r;if(Pr(e,t,n.outer,i))return!0;for(const o of n.holes)if(Pr(e,t,o,i))return!0;return!1}function Ia(e,t,n,r,i,o,s){if(!e.label||!e.labelAnchor)return!1;const a=Qt(n.worldToScreen(e.labelAnchor[0],e.labelAnchor[1]));if(!a)return!1;const u=vn(e.label,r)+r.paddingX*2,l=r.fontSize+r.paddingY*2,h=a[0],f=a[1]-r.offsetY,y=s?k(h,u*.5+1,i-u*.5-1):h,b=s?k(f,l*.5+1,o-l*.5-1):f,x=y-u*.5,w=y+u*.5,A=b-l*.5,E=b+l*.5;return t[0]>=x&&t[0]<=w&&t[1]>=A&&t[1]<=E}function Ea(e,t="top-center"){const n=[];for(let r=0;r<e.length;r+=1){const i=e[r],o=Et([It(i?.coordinates)]);if(o.length===0)continue;const s=typeof i?.label=="string"?i.label.trim():"";n.push({region:i,regionIndex:r,regionId:Cn(i,r),polygons:o,label:s,labelAnchor:s?Xr(o,t):null})}return n}function va(e,t,n,r,i,o,s,a,c,u=!0){const l=e[0],h=e[1],f=Math.max(1e-6,r.getViewState().zoom),y=Math.max(0,s),b=Ra/f;for(let x=n.length-1;x>=0;x-=1){const w=n[x];for(const E of w.polygons)if(Pa(l,h,E,b))return{region:w.region,regionIndex:w.regionIndex,regionId:w.regionId};let A=Vr(i,o?.({region:w.region,regionId:w.regionId,regionIndex:w.regionIndex,zoom:f}));if(y>0&&(A={...A,offsetY:A.offsetY+y}),!!Ia(w,t,r,A,a,c,u))return{region:w.region,regionIndex:w.regionIndex,regionId:w.regionId}}return null}const pn=[],_a=[],Fa={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)},Ba=.65,Ua=4,La=180,Ir=20;function Da(e){const t=k(e,0,1);return t*t*(3-2*t)}function ka({source:e,viewState:t,imageColorSettings:n=null,onViewStateChange:r,onStats:i,onTileError:o,onContextLost:s,onContextRestored:a,debugOverlay:c=!1,debugOverlayStyle:u,fitNonce:l=0,rotationResetNonce:h=0,authToken:f="",ctrlDragRotate:y=!0,pointData:b=null,pointPalette:x=null,pointSizeByZoom:w,pointStrokeScale:A,pointInnerFillOpacity:E,minZoom:X,maxZoom:R,viewTransition:_,roiRegions:H,roiPolygons:se,clipPointsToRois:j=!1,clipMode:J="worker",onClipStats:ae,onRoiPointGroups:ge,roiPaletteIndexToTermId:Te,interactionLock:B=!1,drawTool:D="cursor",stampOptions:O,brushOptions:U,drawFillColor:Q,regionStrokeStyle:Le,regionStrokeHoverStyle:ue,regionStrokeActiveStyle:Oe,patchStrokeStyle:Fe,resolveRegionStrokeStyle:We,resolveRegionLabelStyle:C,overlayShapes:M,customLayers:z,patchRegions:ce,regionLabelStyle:$,regionLabelAnchor:le="top-center",drawAreaTooltip:de,autoLiftRegionLabelAtMaxZoom:ye=!1,clampRegionLabelToViewport:ee=!0,onPointerWorldMove:he,onPointHover:re,onPointClick:ne,onRegionHover:K,onRegionClick:xe,activeRegionId:G,onActiveRegionChange:we,getCellByCoordinatesRef:pe,onDrawComplete:Se,onPatchComplete:De,overviewMapConfig:Ae,className:Ie,style:Re}){const ct=Ae?.show??!1,ut=Ae?.options,W=d.useRef(null),Y=d.useRef(null),ie=d.useRef(null),be=d.useRef(null),pt=d.useRef(r),bt=d.useRef(i),Qe=d.useRef(c),[vt,et]=d.useState(null),[_t,Ft]=d.useState(()=>G??null),m=G!==void 0,g=m?G??null:_t,[T,I]=d.useState(null),[v,me]=d.useState(null),[V,oe]=d.useState(0),q=d.useRef(null),te=d.useRef(null),Me=d.useRef(null),Ce=d.useRef(0),Be=d.useRef({rafId:null,startMs:0,from:0,to:0}),tt=d.useRef(0),Ge=H??pn,yt=ce??pn,wt=se??_a,qe=(z?.length??0)>0,di=d.useMemo(()=>({position:"relative",width:"100%",height:"100%",...Re}),[Re]),hi=d.useMemo(()=>({position:"absolute",top:8,left:8,zIndex:7,margin:0,padding:"8px 10px",maxWidth:"min(420px, 80%)",pointerEvents:"none",whiteSpace:"pre-wrap",lineHeight:1.35,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:11,color:"#cde6ff",background:"rgba(6, 12, 20, 0.82)",border:"1px solid rgba(173, 216, 255, 0.28)",borderRadius:8,boxShadow:"0 8px 22px rgba(0,0,0,0.35)",...u}),[u]),Ye=d.useMemo(()=>Ge.length>0?Ge:wt.length===0?pn:wt.map((p,P)=>({id:P,coordinates:p})),[Ge,wt]),He=d.useMemo(()=>Ea(Ye,le),[Ye,le]),Un=d.useMemo(()=>_n($),[$]),lt=d.useCallback(p=>{const P=k(p,0,Ir);Math.abs(Ce.current-P)<1e-4||(Ce.current=P,oe(P))},[]),nt=d.useCallback(()=>{const p=Be.current;p.rafId!==null&&(cancelAnimationFrame(p.rafId),p.rafId=null)},[]),tn=d.useCallback(p=>{const P=k(p,0,Ir),F=Be.current,L=Ce.current;if(Math.abs(L-P)<1e-4){nt(),F.to=P,lt(P);return}nt(),F.startMs=performance.now(),F.from=L,F.to=P;const N=Z=>{const Ee=Be.current,ke=Math.max(0,Z-Ee.startMs),ht=k(ke/La,0,1),nn=Da(ht),rn=Ee.from+(Ee.to-Ee.from)*nn;if(lt(rn),ie.current?.(),ht>=1){Ee.rafId=null,lt(Ee.to);return}Ee.rafId=requestAnimationFrame(N)};F.rafId=requestAnimationFrame(N)},[lt,nt]),$e=d.useCallback(p=>{const P=Y.current;if(!P||typeof p!="number"||!Number.isFinite(p)){tn(0);return}const F=Gr(ye,p,P.getZoomRange());tn(F)},[ye,tn]),rt=d.useMemo(()=>Ye.map(p=>It(p.coordinates)).filter(p=>p!=null),[Ye]),[it,Bt]=d.useState(b);d.useEffect(()=>{const p=++tt.current;let P=!1;if(!j)return Bt(b),()=>{P=!0};if(!b||!b.count||!b.positions||!b.paletteIndices)return Bt(null),()=>{P=!0};if(rt.length===0)return Bt(Fa),ae?.({mode:J,durationMs:0,inputCount:b.count,outputCount:0,polygonCount:0}),()=>{P=!0};const F=(N,Z)=>{if(P||p!==tt.current)return;const Ee=b.count,ke=N?.drawIndices?N.drawIndices.length:N?.count??0;Bt(N),ae?.({mode:Z.mode,durationMs:Z.durationMs,inputCount:Ee,outputCount:ke,polygonCount:rt.length,usedWebGpu:Z.usedWebGpu,candidateCount:Z.candidateCount,bridgedToDraw:Z.bridgedToDraw})};return(async()=>{if(J==="sync"){const N=performance.now(),Z=Ct(b,rt);F(Z,{mode:"sync",durationMs:performance.now()-N});return}if(J==="hybrid-webgpu"){const N=await Jr(b,rt,{bridgeToDraw:!0});F(N.data,{mode:N.meta.mode,durationMs:N.meta.durationMs,usedWebGpu:N.meta.usedWebGpu,candidateCount:N.meta.candidateCount,bridgedToDraw:N.meta.bridgedToDraw});return}try{const N=await ei(b,rt);F(N.data,{mode:N.meta.mode,durationMs:N.meta.durationMs})}catch{const N=performance.now(),Z=Ct(b,rt);F(Z,{mode:"sync",durationMs:performance.now()-N})}})(),()=>{P=!0}},[j,J,b,rt,ae]);const Ln=!!(re||ne||pe),[Ve,Dn]=d.useState(null);d.useEffect(()=>{if(!Ln||!it){Dn(null);return}let p=!1;return ni(it,e).then(P=>{p||Dn(P)}),()=>{p=!0}},[Ln,it,e]);const ot=d.useCallback(p=>{const P=Y.current;if(!P||!Ve)return null;const F=Number(p[0]),L=Number(p[1]);if(!Number.isFinite(F)||!Number.isFinite(L))return null;const N=Math.max(1e-6,P.getViewState().zoom),Z=P.getPointSizeByZoom(),ke=Math.max(Ua,Z*Ba)/N;if(!Number.isFinite(ke)||ke<=0)return null;const{cellSize:ht,cellOffsets:nn,cellLengths:rn,pointIndices:Si,positions:Xn,safeCount:xi}=Ve,Vn=Math.floor(F/ht),Gn=Math.floor(L/ht),Dt=Math.max(1,Math.ceil(ke/ht)),Mi=ke*ke;let kt=-1,qn=Mi,Hn=0,$n=0;for(let on=Vn-Dt;on<=Vn+Dt;on+=1)for(let sn=Gn-Dt;sn<=Gn+Dt;sn+=1){const an=ti(Ve,on,sn);if(an<0)continue;const Zn=nn[an],Ti=Zn+rn[an];for(let cn=Zn;cn<Ti;cn+=1){const Nt=Si[cn];if(Nt>=xi)continue;const Kn=Xn[Nt*2],jn=Xn[Nt*2+1],Jn=Kn-F,Qn=jn-L,er=Jn*Jn+Qn*Qn;er>qn||(qn=er,kt=Nt,Hn=Kn,$n=jn)}}if(kt<0)return null;const Ai=Ve.ids?Number(Ve.ids[kt]):null;return{index:kt,id:Ai,coordinate:[F,L],pointCoordinate:[Hn,$n]}},[Ve]),ft=d.useCallback((p,P)=>{if(!re)return;const F=p?.index??null,L=p?.id??null;te.current===F&&Me.current===L||(te.current=F,Me.current=L,re({index:F,id:L,coordinate:P,pointCoordinate:p?.pointCoordinate??null}))},[re]),Ut=d.useCallback((p,P)=>{if(!ne)return;const F=ot(p);F&&ne({...F,button:P})},[ne,ot]);d.useEffect(()=>{if(pe)return pe.current=ot,()=>{pe.current===ot&&(pe.current=null)}},[pe,ot]),d.useEffect(()=>{m&&Ft(G??null)},[m,G]);const Ze=d.useCallback(p=>{String(g)!==String(p)&&(m||Ft(p),we?.(p))},[g,m,we]);d.useEffect(()=>{pt.current=r},[r]),d.useEffect(()=>{bt.current=i},[i]),d.useEffect(()=>{Qe.current=c,c||me(null)},[c]),d.useEffect(()=>()=>{nt()},[nt]);const kn=d.useCallback(p=>{bt.current?.(p),Qe.current&&me(p)},[]),mi=d.useMemo(()=>v?[`tier ${v.tier} | frame ${v.frameMs?.toFixed(2)??"-"} ms | drawCalls ${v.drawCalls??"-"}`,`tiles visible ${v.visible} | rendered ${v.rendered} | fallback ${v.fallback}`,`cache size ${v.cache} | hit ${v.cacheHits??"-"} | miss ${v.cacheMisses??"-"}`,`queue inflight ${v.inflight} | queued ${v.queued??"-"} | retries ${v.retries??"-"} | failed ${v.failed??"-"} | aborted ${v.aborted??"-"}`,`points ${v.points}`].join(`
|
|
162
|
+
`):"stats: waiting for first frame...",[v]);d.useEffect(()=>{!(g===null?!0:Ye.some((L,N)=>String(Cn(L,N))===String(g)))&&g!==null&&Ze(null);const P=q.current;!(P===null?!0:Ye.some((L,N)=>String(Cn(L,N))===String(P)))&&P!==null&&(q.current=null,et(null),K?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[Ye,g,K,Ze]),d.useEffect(()=>{const p=te.current;p!==null&&(Ve&&p<Ve.safeCount||(te.current=null,Me.current=null,re?.({index:null,id:null,coordinate:null,pointCoordinate:null})))},[Ve,re]);const Nn=d.useCallback(p=>{$e(p.zoom),qe&&I(p);const P=pt.current;P&&P(p),ie.current?.(),be.current?.()},[qe,$e]);d.useEffect(()=>{const p=Y.current;p&&$e(p.getViewState().zoom)},[$e,X,R]),d.useEffect(()=>{D!=="cursor"&&q.current!==null&&(q.current=null,et(null),K?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[D,K]),d.useEffect(()=>{D!=="cursor"&&te.current!==null&&(te.current=null,Me.current=null,re?.({index:null,id:null,coordinate:null,pointCoordinate:null}))},[D,re]);const Ke=d.useCallback((p,P)=>{const F=Y.current;if(!F)return null;const L=F.screenToWorld(p,P);if(!Array.isArray(L)||L.length<2)return null;const N=Number(L[0]),Z=Number(L[1]);return!Number.isFinite(N)||!Number.isFinite(Z)?null:[N,Z]},[]),zn=d.useCallback((p,P)=>{const F=Y.current;if(!F)return null;const L=F.worldToScreen(p,P);return Qt(L)},[]),Lt=d.useCallback((p,P)=>{const F=W.current;if(!F)return null;const L=F.getBoundingClientRect();if(!Number.isFinite(L.width)||!Number.isFinite(L.height)||L.width<=0||L.height<=0)return null;const N=p-L.left,Z=P-L.top;return!Number.isFinite(N)||!Number.isFinite(Z)?null:{screenCoord:[N,Z],canvasWidth:Math.max(1,L.width),canvasHeight:Math.max(1,L.height)}},[]),dt=d.useCallback((p,P,F,L)=>{const N=Y.current;return N?va(p,P,He,N,Un,C,V,F,L,ee):null},[He,Un,C,V,ee]),On=d.useCallback(()=>{Y.current?.requestRender(),ie.current?.(),be.current?.()},[]),Wn=d.useMemo(()=>T??Y.current?.getViewState()??null,[T]),Yn=d.useMemo(()=>{if(!e)return null;const p=Wn;return p?{source:e,viewState:p,drawTool:D,interactionLock:B,worldToScreen:zn,screenToWorld:Ke,requestRedraw:On}:null},[e,Wn,D,B,zn,Ke,On]),gi=d.useCallback(p=>{const P=p.target===W.current,F=Ke(p.clientX,p.clientY);if(he){const ke=!!F&&F[0]>=0&&F[1]>=0&&!!e&&F[0]<=e.width&&F[1]<=e.height;he({coordinate:F,clientX:p.clientX,clientY:p.clientY,insideImage:ke})}if(D!=="cursor")return;if(!P){ft(null,null),q.current!==null&&(q.current=null,et(null),K?.({region:null,regionId:null,regionIndex:-1,coordinate:null}));return}if(!F){ft(null,null);return}if(re&&ft(ot(F),F),!He.length)return;const L=Lt(p.clientX,p.clientY);if(!L)return;const N=dt(F,L.screenCoord,L.canvasWidth,L.canvasHeight),Z=N?.regionId??null,Ee=q.current;String(Ee)!==String(Z)&&(q.current=Z,et(Z),K?.({region:N?.region??null,regionId:Z,regionIndex:N?.regionIndex??-1,coordinate:F}))},[D,He,Ke,K,he,e,ft,ot,re,Lt,dt]),pi=d.useCallback(()=>{he?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1}),ft(null,null),q.current!==null&&(q.current=null,et(null),K?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[K,he,ft]),bi=d.useCallback(p=>{if(D!=="cursor"||p.target!==W.current)return;const P=Ke(p.clientX,p.clientY);if(!P)return;if(Ut(P,p.button),!He.length){Ze(null);return}const F=Lt(p.clientX,p.clientY);if(!F)return;const L=dt(P,F.screenCoord,F.canvasWidth,F.canvasHeight);if(!L){Ze(null);return}const N=g!==null&&String(g)===String(L.regionId)?null:L.regionId;Ze(N),xe?.({region:L.region,regionId:L.regionId,regionIndex:L.regionIndex,coordinate:P})},[D,He,Ke,xe,g,Ze,Ut,Lt,dt]),yi=d.useCallback(p=>{if(D!=="brush"||U?.clickSelectRoi!==!0||!He.length)return!1;const P=Y.current,F=W.current;if(!P||!F)return!1;const L=F.getBoundingClientRect();if(L.width<=0||L.height<=0)return!1;const N=Qt(P.worldToScreen(p[0],p[1]));if(!N)return!1;const Z=dt(p,N,L.width,L.height);if(!Z)return!1;const Ee=g!==null&&String(g)===String(Z.regionId)?null:Z.regionId;return Ze(Ee),xe?.({region:Z.region,regionId:Z.regionId,regionIndex:Z.regionIndex,coordinate:p}),!0},[D,U?.clickSelectRoi,He,g,Ze,xe,dt]),wi=d.useCallback(p=>{if(!ne||D!=="cursor"||p.target!==W.current)return;p.preventDefault();const P=Ke(p.clientX,p.clientY);P&&Ut(P,p.button)},[D,Ke,Ut,ne]);return d.useEffect(()=>{const p=W.current;if(!p||!e)return;const P=new fi(p,e,{onViewStateChange:Nn,onStats:kn,onTileError:o,onContextLost:s,onContextRestored:a,authToken:f,imageColorSettings:n,ctrlDragRotate:y,pointSizeByZoom:w,pointStrokeScale:A,pointInnerFillOpacity:E,minZoom:X,maxZoom:R,viewTransition:_});return Y.current=P,t&&P.setViewState(t),$e(P.getViewState().zoom),P.setInteractionLock(B),qe&&I(P.getViewState()),()=>{nt(),lt(0),P.destroy(),Y.current=null}},[e,kn,o,s,a,f,y,Nn,qe,$e,nt,lt]),d.useEffect(()=>{const p=Y.current;!p||!t||p.setViewState(t)},[t]),d.useEffect(()=>{const p=Y.current;p&&p.fitToImage()},[l]),d.useEffect(()=>{const p=Y.current;p&&p.resetRotation()},[h]),d.useEffect(()=>{const p=Y.current;!p||!x||p.setPointPalette(x)},[x]),d.useEffect(()=>{const p=Y.current;p&&p.setPointSizeByZoom(w)},[w]),d.useEffect(()=>{const p=Y.current;p&&p.setPointStrokeScale(A)},[A]),d.useEffect(()=>{const p=Y.current;p&&p.setPointInnerFillOpacity(E)},[E]),d.useEffect(()=>{const p=Y.current;p&&(p.setZoomRange(X,R),$e(p.getViewState().zoom))},[X,R,$e]),d.useEffect(()=>{const p=Y.current;p&&p.setViewTransition(_)},[_]),d.useEffect(()=>{const p=Y.current;p&&p.setImageColorSettings(n)},[n]),d.useEffect(()=>{const p=Y.current;p&&p.setPointData(it)},[it]),d.useEffect(()=>{if(!ge)return;const P=ri(j?it:b,Ye,{paletteIndexToTermId:Te,includeEmptyRegions:!0});ge(P)},[ge,j,b,it,Ye,Te]),d.useEffect(()=>{const p=Y.current;p&&p.setInteractionLock(B)},[B]),ze.jsxs("div",{className:Ie,style:di,onPointerMove:gi,onPointerLeave:pi,onClick:bi,onContextMenu:wi,children:[ze.jsx("canvas",{ref:W,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none",cursor:D==="cursor"&&vt!==null?"pointer":B?"crosshair":"grab"}}),e&&Yn&&Array.isArray(z)&&z.length>0?z.map((p,P)=>ze.jsx("div",{className:p.className,style:{position:"absolute",inset:0,zIndex:p.zIndex??3,pointerEvents:p.pointerEvents??"none",...p.style},children:p.render(Yn)},p.id??P)):null,e?ze.jsx(qr,{tool:D,enabled:D!=="cursor",imageWidth:e.width,imageHeight:e.height,imageMpp:e.mpp,imageZoom:e.maxTierZoom,stampOptions:O,brushOptions:U,drawFillColor:Q,projectorRef:Y,onBrushTap:yi,viewStateSignal:t,persistedRegions:Ye,patchRegions:yt,regionStrokeStyle:Le,regionStrokeHoverStyle:ue,regionStrokeActiveStyle:Oe,patchStrokeStyle:Fe,resolveRegionStrokeStyle:We,resolveRegionLabelStyle:C,overlayShapes:M,hoveredRegionId:vt,activeRegionId:g,regionLabelStyle:$,regionLabelAnchor:le,drawAreaTooltip:de,autoLiftRegionLabelAtMaxZoom:ye,clampRegionLabelToViewport:ee,regionLabelAutoLiftOffsetPx:V,invalidateRef:ie,onDrawComplete:Se,onPatchComplete:De}):null,c?ze.jsx("pre",{"data-open-plant-debug-overlay":!0,style:hi,children:mi}):null,e&&ct&&ze.jsx($r,{source:e,projectorRef:Y,authToken:f,options:ut,invalidateRef:be,className:Ae?.className,style:Ae?.style})]})}exports.DEFAULT_POINT_COLOR=In;exports.DrawLayer=qr;exports.M1TileRenderer=vr;exports.OverviewMap=$r;exports.TileScheduler=ii;exports.TileViewerCanvas=us;exports.WsiTileRenderer=fi;exports.WsiViewerCanvas=ka;exports.buildPointSpatialIndexAsync=ni;exports.buildTermPalette=Ui;exports.calcScaleLength=Fi;exports.calcScaleResolution=En;exports.clamp=k;exports.closeRing=_e;exports.computeRoiPointGroups=ri;exports.createCircle=wn;exports.createRectangle=en;exports.filterPointDataByPolygons=Ct;exports.filterPointDataByPolygonsHybrid=Jr;exports.filterPointDataByPolygonsInWorker=ei;exports.filterPointIndicesByPolygons=Zr;exports.filterPointIndicesByPolygonsInWorker=ws;exports.getWebGpuCapabilities=ps;exports.hexToRgba=Lr;exports.isSameViewState=bn;exports.lookupCellIndex=ti;exports.normalizeImageInfo=as;exports.prefilterPointsByBoundsWebGpu=jr;exports.terminatePointHitIndexWorker=Ps;exports.terminateRoiClipWorker=ys;exports.toBearerToken=Bi;exports.toRoiGeometry=It;exports.toTileUrl=Fn;
|
|
163
163
|
//# sourceMappingURL=index.cjs.map
|