open-plant 1.3.1 → 1.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +17 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1739 -1721
- package/dist/index.js.map +1 -1
- package/dist/types/react/wsi-viewer-canvas.d.ts +2 -1
- package/dist/types/react/wsi-viewer-canvas.d.ts.map +1 -1
- package/dist/types/wsi/wsi-normalize.d.ts +1 -0
- package/dist/types/wsi/wsi-normalize.d.ts.map +1 -1
- package/dist/types/wsi/wsi-render-pass.d.ts +1 -0
- package/dist/types/wsi/wsi-render-pass.d.ts.map +1 -1
- package/dist/types/wsi/wsi-renderer-types.d.ts +2 -0
- package/dist/types/wsi/wsi-renderer-types.d.ts.map +1 -1
- package/dist/types/wsi/wsi-shaders.d.ts.map +1 -1
- package/dist/types/wsi/wsi-tile-renderer.d.ts +2 -0
- package/dist/types/wsi/wsi-tile-renderer.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var Ai=Object.defineProperty;var Ti=(e,t,n)=>t in e?Ai(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var S=(e,t,n)=>Ti(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const We=require("react/jsx-runtime"),h=require("react");var gt=typeof document<"u"?document.currentScript:null;function Qn(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 Rn(e,t,n){const r=Qn(e,e.VERTEX_SHADER,t),i=Qn(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 Ee(e,t,n){const r=e.getUniformLocation(t,n);if(!r)throw new Error(`Failed to get uniform location: ${n}`);return r}function Ri(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 an(e){return e*Math.PI/180}class Pr{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=an(s),l=Math.cos(u),d=Math.sin(u);return[i+a*l-c*d,o+a*d+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=an(s),l=Math.cos(u),d=Math.sin(u),f=a*l+c*d,y=-a*d+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,w=this.viewportHeight/t,x=2/b,R=-2/w,E=-1-this.viewState.offsetX*x,X=1-this.viewState.offsetY*R;return new Float32Array([x,0,0,0,R,0,E,X,1])}const[r,i]=this.getCenter(),o=an(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,d=-2*t*s/this.viewportHeight,f=-(c*r+u*i),y=-(l*r+d*i);return new Float32Array([c,l,0,u,d,0,f,y,1])}}const Ci=`#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
|
+
`,Pi=`#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 Pr{constructor(t){S(this,"canvas");S(this,"gl");S(this,"camera",new Cr);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=Ti(this.canvas),this.program=An(this.gl,Ri,Ai);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=Be(this.gl,this.program,"uCamera"),this.uBoundsLocation=Be(this.gl,this.program,"uBounds"),this.uTextureLocation=Be(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 Et(e){return e??null}function er(e){return typeof e=="number"&&Number.isFinite(e)}function Ci(e){return Array.isArray(e)&&e.length>=2&&er(e[0])&&er(e[1])}function Er(e){return Array.isArray(e)&&e.length>0&&e.every(t=>Ci(t))}function Ir(e){return Array.isArray(e)&&e.length>0&&e.every(t=>Er(t))}function Pi(e){return Array.isArray(e)&&e.length>0&&e.every(t=>Ir(t))}function De(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 Rt(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 cn(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const o of e){const s=De(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(Rt(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 vr(e){if(!e)return[];if(Er(e)){const t=cn([e]);return t.length>0?[t]:[]}if(Ir(e)){const t=cn(e);return t.length>0?[t]:[]}if(Pi(e)){const t=[];for(const n of e){const r=cn(n);r.length>0&&t.push(r)}return t}return[]}function tr(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=vr(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(Rt(o));for(let h=1;h<i.length;h+=1)l-=Math.abs(Rt(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 _r(e,t,n){if(e<n.minX||e>n.maxX||t<n.minY||t>n.maxY||!tr(e,t,n.outer))return!1;for(const r of n.holes)if(tr(e,t,r))return!1;return!0}function $t(e,t,n){for(const r of n)if(_r(e,t,r))return!0;return!1}const Cn=[160,160,160,255];function N(e,t,n){return Math.max(t,Math.min(n,e))}function Pn(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 Ei(e,t,n){let i=100*Pn(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 le(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function ut(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 gn(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 Ii(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 Fr(e){const n=String(e??"").trim().match(/^#?([0-9a-fA-F]{6})$/);if(!n)return[...Cn];const r=Number.parseInt(n[1],16);return[r>>16&255,r>>8&255,r&255,255]}function vi(e){const t=[[...Cn]],n=new Map;for(const i of e??[]){const o=String(i?.termId??"");!o||n.has(o)||(n.set(o,t.length),t.push(Fr(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 _i=.1,Fi=4e6,Bi=4096,Ui=64,Li=1,Di=4,Br=1e-6,ki=24;function Ni(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 zi(e,t,n){if(t<=Br||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 De(r)}function un(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 De([[n-s,r-s],[i+s,r-s],[i+s,o+s],[n-s,o+s]])}function Oi(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 Wi(e,t,n){const r=Math.max(_i,Number(n.minRasterStep)||0),i=Math.max(32768,Math.floor(n.maxRasterPixels||Fi)),o=Math.max(256,Math.floor(n.maxRasterSize||Bi)),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 Yi(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 Xi(e,t){return[(e[0]-t.minX)/t.step+t.padding,(e[1]-t.minY)/t.step+t.padding]}function Vi(e,t,n){const r=Yi(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=>Xi(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]>=ki?1:0;return s}function Gi(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 qi(e,t){const n=(t-e+4)%4;return n===1?0:n===0?1:n===3?2:3}function Hi(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 b=-1,g=1/0;for(const x of f){if(n[x])continue;const R=e[x],v=qi(c,R.dir);v<g&&(g=v,b=x)}if(b<0)break;n[b]=1;const y=e[b];a=y.end,c=y.dir,u.push(a),l+=1}u.length>=4&&u[0]===u[u.length-1]&&r.push(u)}return r}function $i(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 De(i)}function Zi(e,t=1e-9){const n=De(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]),De(r)}function Ki(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=N(((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 ji(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=Ki(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 Ji(e,t){const n=De(e);if(n.length<5||t<=0)return n;const r=n.slice(0,-1),i=ji(r,t);return i.length<3?n:De(i)}function Qi(e,t){let n=De(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=De(o)}return n}function St(e,t){return t?De(e.map(([n,r])=>[N(n,t[0],t[2]),N(r,t[1],t[3])])):e}function eo(e,t){const n=Ni(e),r=Math.max(Br,Number(t.radius)||0);if(n.length===0||!Number.isFinite(r))return[];const i=Math.max(12,Math.floor(t.circleSides||Ui));if(n.length===1)return St(zi(n[0],r,i),t.clipBounds);const o=Oi(n,r),s=Wi(o,r,t),a=Vi(n,r,s);if(!a.length)return St(un(n,r),t.clipBounds);const c=Gi(a,s.width,s.height),u=Hi(c);if(!u.length)return St(un(n,r),t.clipBounds);let l=[],h=0;for(const y of u){const x=$i(y,s.width,s),R=Math.abs(Rt(x));R<=h||(h=R,l=x)}if(!l.length)return St(un(n,r),t.clipBounds);const f=typeof t.simplifyTolerance=="number"&&Number.isFinite(t.simplifyTolerance)?Math.max(0,t.simplifyTolerance):s.step*.2,b=typeof t.smoothingPasses=="number"&&Number.isFinite(t.smoothingPasses)?Math.round(N(t.smoothingPasses,0,Di)):Li,g=Ji(Qi(Zi(l,s.step*.001),b),f);return St(g,t.clipBounds)}const At=[],nr=[],Je={color:"#ff4d4f",width:2,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},to={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},no="rgba(23, 23, 25, 0.1)",ro=6,Oe={fontFamily:"Pretendard, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:11,fontWeight:600,textColor:"#171719",backgroundColor:"#FFCC00",borderColor:"rgba(0, 0, 0, 0)",borderWidth:0,paddingX:8,paddingY:4,offsetY:10,borderRadius:4},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},rr={x:16,y:-24},io=20,ir=1e-6,or="transparent",oo=3,so=2,Ur=96,ao=1,sr=1e3,Lr=2,Dr=2,co=4096,uo=.2,lo=1.12,fo=.89,ho=32,mo="#000000",go=.1,po="#FFCF00",bo="#FF0000",wo=1.5,ar=[2,2],yo=1,So=.25,xo=4,Mo=1,To=0,Ro=4,Ao=.05,Co=256,cr=1.5;function Zt(e,t,n){return[N(e[0],0,t),N(e[1],0,n)]}function Kt(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 ct=Kt;function Ue(e){return De(e)}function qt(e){return Math.abs(Rt(Ue(e)))}function ur(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 pn(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 Ve(e,t,n,r=!1,i=!1,o="rgba(255, 77, 79, 0.16)"){t.length!==0&&(e.beginPath(),pn(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(At),e.shadowColor="rgba(0, 0, 0, 0)",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0)}function kr(e){const t=Array.isArray(e?.lineDash)?e.lineDash.filter(s=>Number.isFinite(s)&&s>=0):At,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:At,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?kr({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 lr(e,t){return e==null||t===null||t===void 0?!1:String(e)===String(t)}function fr(e){return typeof e=="number"&&Number.isFinite(e)}function Po(e){return Array.isArray(e)&&e.length>=2&&fr(e[0])&&fr(e[1])}function Eo(e){return Array.isArray(e)&&e.length>=2&&e.every(t=>Po(t))}function Nr(e,t){if(!(!Array.isArray(e)||e.length===0)){if(Eo(e)){t.push(e.map(([n,r])=>[n,r]));return}for(const n of e)Nr(n,t)}}function dr(e,t){const n=[];Nr(e,n);const r=[];for(const i of n){if(i.length<2)continue;const o=t?Ue(i):i;o.length>=(t?4:2)&&r.push(o)}return r}function Tt(e,t){return typeof e!="number"||!Number.isFinite(e)||e<=0?t:e}function Io(e,t){return typeof e!="number"||!Number.isFinite(e)?t:N(e,0,1)}function zr(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 vo(e){const t=e[0];return Array.isArray(t)&&Array.isArray(t[0])}function jt(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 jt(e,t);s.push(c)}return Ue(s)}}return Ue([[e[0],e[1]],[t[0],e[1]],[t[0],t[1]],[e[0],t[1]]])}function bn(e,t,n=Ur){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 Ue(s)}function hr(e){const t=vr(Et(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 _o(e){if(!Array.isArray(e))return ar;const t=e.filter(n=>Number.isFinite(n)&&n>=0);return t.length>0?t:ar}function Fo(e){return typeof e!="number"||!Number.isFinite(e)?yo:N(e,So,xo)}function Bo(e){return typeof e!="number"||!Number.isFinite(e)?Mo:Math.round(N(e,To,Ro))}function Uo(e){const t=Tt(e?.radius,ho),n=Tt(e?.cursorLineWidth,wo),r=Fo(e?.edgeDetail),i=Bo(e?.edgeSmoothing);return{radius:t,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:e?.clickSelectRoi===!0,fillColor:e?.fillColor||mo,fillOpacity:Io(e?.fillOpacity,go),cursorColor:e?.cursorColor||po,cursorActiveColor:e?.cursorActiveColor||bo,cursorLineWidth:n,cursorLineDash:_o(e?.cursorLineDash)}}function Lo(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 Do(e,t,n,r){const i=t.cursor;if(!i)return;const o=t.cursorScreen??ct(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(At),e.restore())}const ko=.58,No=4096,zo=.5;let Dt=null;const kt=new Map;function Oo(){if(Dt)return Dt;if(typeof document>"u")return null;const t=document.createElement("canvas").getContext("2d");return t?(Dt=t,Dt):null}function En(e,t){const n=`${t.fontWeight}|${t.fontSize}|${t.fontFamily}|${e}`,r=kt.get(n);if(r!==void 0)return r;const i=e.length*t.fontSize*ko,o=Oo();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 kt.size>No&&kt.clear(),kt.set(n,s),s}function Wo(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)>zo||(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 Or(e){let t=null;for(const n of e){const r=Wo(n.outer);r&&(!t||r[1]<t[1]||r[1]===t[1]&&r[0]<t[0])&&(t=r)}return t}function In(e){const t=typeof e?.paddingX=="number"&&Number.isFinite(e.paddingX)?Math.max(0,e.paddingX):Oe.paddingX,n=typeof e?.paddingY=="number"&&Number.isFinite(e.paddingY)?Math.max(0,e.paddingY):Oe.paddingY,r=typeof e?.fontSize=="number"&&Number.isFinite(e.fontSize)?Math.max(8,e.fontSize):Oe.fontSize,i=typeof e?.borderWidth=="number"&&Number.isFinite(e.borderWidth)?Math.max(0,e.borderWidth):Oe.borderWidth,o=typeof e?.offsetY=="number"&&Number.isFinite(e.offsetY)?e.offsetY:Oe.offsetY,s=typeof e?.borderRadius=="number"&&Number.isFinite(e.borderRadius)?Math.max(0,e.borderRadius):Oe.borderRadius;return{fontFamily:e?.fontFamily||Oe.fontFamily,fontSize:r,fontWeight:e?.fontWeight||Oe.fontWeight,textColor:e?.textColor||Oe.textColor,backgroundColor:e?.backgroundColor||Oe.backgroundColor,borderColor:e?.borderColor||Oe.borderColor,borderWidth:i,paddingX:t,paddingY:n,offsetY:o,borderRadius:s}}function Wr(e,t){return t?In({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 Yr(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<=ir||!Number.isFinite(t)?0:t>=i-ir?io:0}function Yo(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 Xo(e){const t=typeof e?.x=="number"&&Number.isFinite(e.x)?e.x:rr.x,n=typeof e?.y=="number"&&Number.isFinite(e.y)?e.y:rr.y;return{x:t,y:n}}function Vo(e){return Number.isFinite(e)?`${Math.max(0,e).toFixed(3)} mm²`:"0.000 mm²"}function Go(e){const t=typeof e?.format=="function"?e.format:Vo,n=Xo(e?.cursorOffset);return{enabled:e?.enabled===!0,format:t,style:Yo(e?.style),cursorOffsetX:n.x,cursorOffsetY:n.y}}function qo(e,t,n,r,i,o){const s=t.trim();if(!s)return;e.save(),e.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,e.textAlign="center",e.textBaseline="middle";const c=En(s,o)+o.paddingX*2,u=o.fontSize+o.paddingY*2,l=N(n[0],c*.5+1,r-c*.5-1),h=N(n[1]-o.offsetY,u*.5+1,i-u*.5-1),f=l-c*.5,b=h-u*.5;e.fillStyle=o.backgroundColor,e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,zr(e,f,b,c,u,o.borderRadius),e.fill(),o.borderWidth>0&&e.stroke(),e.fillStyle=o.textColor,e.fillText(s,l,h+.5),e.restore()}function Ho(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=N(n[0]+s,l*.5+1,r-l*.5-1),b=N(n[1]+a,h*.5+1,i-h*.5-1),g=f-l*.5,y=b-h*.5;e.fillStyle=o.backgroundColor,zr(e,g,y,l,h,o.borderRadius),e.fill(),e.fillStyle=o.textColor,e.fillText(c,f,b+.5),e.restore()}function $o(e,t,n,r){if(!(t.length<4||n.length===0)){e.save(),e.beginPath(),pn(e,t,!0);for(const i of n)i.length<4||pn(e,i,!0);e.fillStyle=r,e.fill("evenodd"),e.restore()}}function Zo(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??vo(u.coordinates),h=dr(u.coordinates,l);if(u.invertedFill?.fillColor){const b=[],g=dr(u.coordinates,!0);for(const y of g){const x=i(y);x.length>=4&&b.push(x)}a&&s&&s({id:u.id??c,outerRingPoints:r.length,sourceRingCount:g.length,holeRingCount:b.length,fillColor:u.invertedFill.fillColor}),$o(t,r,b,u.invertedFill.fillColor)}if(h.length===0)continue;const f=xt(o,u.stroke??u.strokeStyle);for(const b of h){const g=i(b);g.length<2||Ve(t,g,f,l,u.fill??!1)}}}function Nt(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 Ko(e){return{rectangleAreaMm2:Tt(e?.rectangleAreaMm2,Lr),circleAreaMm2:Tt(e?.circleAreaMm2,Dr),rectanglePixelSize:Tt(e?.rectanglePixelSize,co)}}const mr=1e3;function jo(e){return e*mr*mr}function gr(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 Ue(a)}}return Ue([[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 Jo(e,t,n=Ur){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 Ue(r)}function Qo(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 gr(n,h,a()).map(f=>Zt(f,i,o))}let c=0;if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"?c=t==="stamp-rectangle-2mm2"?Lr:r.rectangleAreaMm2:(t==="stamp-circle"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2")&&(c=t==="stamp-circle-hpf-0.2mm2"?uo:t==="stamp-circle-2mm2"?Dr:r.circleAreaMm2),!Number.isFinite(c)||c<=0)return[];const u=jo(c);let l=[];if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"){const h=s(Math.sqrt(u)*.5);l=gr(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=Jo(n,h)}return l.length?l.map(h=>Zt(h,i,o)):[]}function es(e){return{color:no,width:ro,lineDash:At,lineJoin:e.lineJoin,lineCap:e.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function ts(e){if(typeof e!="string")return or;const t=e.trim();return t.length>0?t:or}function pr(e){return Array.isArray(e)&&e.length>=4&&qt(e)>ao}function Xr({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:b,patchRegions:g,persistedPolygons:y,drawFillColor:x,regionStrokeStyle:R,regionStrokeHoverStyle:v,regionStrokeActiveStyle:O,patchStrokeStyle:P,resolveRegionStrokeStyle:U,resolveRegionLabelStyle:H,overlayShapes:$,hoveredRegionId:te=null,activeRegionId:ie=null,regionLabelStyle:ce,drawAreaTooltip:be,autoLiftRegionLabelAtMaxZoom:ge=!1,regionLabelAutoLiftOffsetPx:A,invalidateRef:B,className:Y,style:W}){const q=m.useRef(null),Le=m.useRef(!1),Ae=m.useRef(new Map),Ge=m.useRef(e),fe=m.useRef({isDrawing:!1,pointerId:null,start:null,current:null,cursor:null,cursorScreen:null,points:[],screenPoints:[],stampCenter:null}),ne=h??e!=="cursor",I=m.useMemo(()=>b&&b.length>0?b:!y||y.length===0?nr:y.map((d,w)=>({id:w,coordinates:d})),[b,y]),E=m.useMemo(()=>g??nr,[g]),z=m.useMemo(()=>{const d=[];for(let w=0;w<I.length;w+=1){const T=I[w],M=hr(T.coordinates);M.length!==0&&d.push({region:T,regionIndex:w,regionKey:T.id??w,polygons:M})}return d},[I]),re=m.useMemo(()=>{const d=[];for(let w=0;w<E.length;w+=1){const T=E[w],M=hr(T.coordinates);M.length!==0&&d.push({region:T,regionIndex:w,regionKey:T.id??w,polygons:M})}return d},[E]),X=m.useMemo(()=>kr(R),[R]),de=m.useMemo(()=>xt(X,v),[X,v]),ye=m.useMemo(()=>xt(X,O),[X,O]),ee=m.useMemo(()=>xt(to,P),[P]),Z=m.useMemo(()=>ts(x),[x]),oe=m.useMemo(()=>In(ce),[ce]),he=m.useMemo(()=>Go(be),[be]),se=m.useMemo(()=>Ko(o),[o]),J=m.useMemo(()=>Uo(s),[s]),pe=m.useMemo(()=>({position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",touchAction:"none",pointerEvents:ne?"auto":"none",cursor:ne?e==="brush"?"none":"crosshair":"default",...W}),[ne,e,W]),me=m.useCallback(()=>{const d=q.current;if(!d)return;const w=d.getBoundingClientRect(),T=Math.max(1,window.devicePixelRatio||1),M=Math.max(1,Math.round(w.width*T)),D=Math.max(1,Math.round(w.height*T));(d.width!==M||d.height!==D)&&(d.width=M,d.height=D)},[]),j=m.useCallback(d=>{const w=a.current;if(!w||d.length===0)return[];const T=new Array(d.length);for(let M=0;M<d.length;M+=1){const D=ct(w.worldToScreen(d[M][0],d[M][1]));if(!D)return[];T[M]=D}return T},[a]),Se=m.useCallback(d=>{const w=a.current,T=q.current;if(!w||!T)return null;const M=T.getBoundingClientRect(),D=ct(w.screenToWorld(M.left+d[0],M.top+d[1]));return D?Zt(D,t,n):null},[a,t,n]),Ee=m.useCallback(()=>{const d=a.current,w=d?.getViewState?.().rotationDeg??0;if(!(Math.abs(w%360)<.01||!d))return{worldToScreen:(T,M)=>ct(d.worldToScreen(T,M)),screenToWorld:Se}},[a,Se]),Ye=m.useCallback(d=>{if(!Number.isFinite(d)||d<=0)return 0;const w=typeof r=="number"&&Number.isFinite(r)&&r>0?r:1,T=typeof i=="number"&&Number.isFinite(i)?i:0,M=a.current?.getViewState?.().zoom,D=typeof M=="number"&&Number.isFinite(M)&&M>0?M:1,ue=T+Math.log2(D),G=Math.max(1e-9,Pn(w,T,ue));return d/G/D},[r,i,a]),ke=m.useCallback((d,w)=>Qo({stampTool:d,center:w,resolvedStampOptions:se,imageWidth:t,imageHeight:n,micronsToWorldPixels:Ye,getRectangleProjection:Ee}),[Ye,t,n,se,Ee]),Ie=m.useCallback(()=>{const d=fe.current;return Nt(e)?ke(e,d.stampCenter):e==="brush"?[]:d.isDrawing?e==="freehand"?d.points:e==="rectangle"?jt(d.start,d.current,Ee()):e==="circular"?bn(d.start,d.current):[]:[]},[e,ke,Ee]),xe=m.useCallback(()=>{me();const d=q.current;if(!d)return;const w=d.getContext("2d");if(!w)return;const T=Math.max(1,window.devicePixelRatio||1),M=d.width/T,D=d.height/T;if(w.setTransform(1,0,0,1,0,0),w.clearRect(0,0,d.width,d.height),w.setTransform(T,0,0,T,0,0),z.length>0)for(const G of z){const{region:V,polygons:Q,regionIndex:ae,regionKey:Me}=G,Pe=lr(ie,Me)?"active":lr(te,Me)?"hover":"default";let Ne=Pe==="active"?ye:Pe==="hover"?de:X;if(U){const lt=U({region:V,regionId:Me,regionIndex:ae,state:Pe});Ne=xt(Ne,lt||void 0)}const He=Pe==="default"?null:es(Ne);for(const lt of Q){const rt=j(lt.outer);rt.length>=4&&(He&&Ve(w,rt,He,!0,!1),Ve(w,rt,Ne,!0,!1));for(const ft of lt.holes){const yt=j(ft);yt.length>=4&&(He&&Ve(w,yt,He,!0,!1),Ve(w,yt,Ne,!0,!1))}}}if(re.length>0)for(const G of re)for(const V of G.polygons){const Q=j(V.outer);Q.length>=4&&Ve(w,Q,ee,!0,!1);for(const ae of V.holes){const Me=j(ae);Me.length>=4&&Ve(w,Me,ee,!0,!1)}}if(Array.isArray($)&&$.length>0){const G=j(Ue([[0,0],[t,0],[t,n],[0,n]]));Zo({ctx:w,overlayShapes:$,imageOuterRing:G,worldToScreenPoints:j,baseStrokeStyle:X,onInvertedFillDebug:globalThis.__OPEN_PLANT_DEBUG_OVERLAY__?V=>{const Q=String(V.id),ae=`${V.outerRingPoints}|${V.sourceRingCount}|${V.holeRingCount}|${V.fillColor}`;Ae.current.get(Q)!==ae&&(Ae.current.set(Q,ae),console.debug("[open-plant] invertedFill",V))}:void 0})}const ue=Ie();if(ne){if(e==="brush")Lo(w,fe.current,J),Do(w,fe.current,a.current,J);else if(ue.length>0)if(e==="freehand"){const G=j(ue);G.length>=2&&Ve(w,G,X,!1,!1),G.length>=3&&Ve(w,j(Ue(ue)),X,!0,!0,Z)}else{const G=j(ue);G.length>=4&&Ve(w,G,X,!0,!0,Z)}}if(z.length>0){const G=Math.max(1e-6,a.current?.getViewState?.().zoom??1),V=typeof A=="number"&&Number.isFinite(A)?Math.max(0,A):Yr(ge,G,a.current?.getZoomRange?.());for(const Q of z){if(!Q.region.label)continue;const ae=Or(Q.polygons);if(!ae)continue;const Me=ct(a.current?.worldToScreen(ae[0],ae[1])??[]);if(!Me)continue;let Pe=Wr(oe,H?.({region:Q.region,regionId:Q.regionKey,regionIndex:Q.regionIndex,zoom:G}));V>0&&(Pe={...Pe,offsetY:Pe.offsetY+V}),qo(w,Q.region.label,Me,M,D,Pe)}}if(he.enabled&&ne&&(e==="freehand"||e==="rectangle"||e==="circular")){const G=fe.current;if(G.isDrawing){const V=e==="freehand"?Ue(ue):ue;if(V.length>=4){const Q=qt(V),ae=typeof r=="number"&&Number.isFinite(r)&&r>0?r:0,Me=ae>0?Q*ae*ae/(sr*sr):0,Pe=he.format(Me),Ne=G.cursorScreen??(G.current?ct(a.current?.worldToScreen(G.current[0],G.current[1])??[]):null);Ne&&Ho(w,Pe,Ne,M,D,he.style,he.cursorOffsetX,he.cursorOffsetY)}}}},[ne,e,Ie,me,j,t,n,a,z,$,te,ie,X,de,ye,Z,re,ee,U,H,oe,he,ge,A,r,J]),_=m.useCallback(()=>{Le.current||(Le.current=!0,requestAnimationFrame(()=>{Le.current=!1,xe()}))},[xe]),Te=m.useCallback((d=!1)=>{const w=fe.current,T=q.current;T&&w.pointerId!==null&&T.hasPointerCapture(w.pointerId)&&T.releasePointerCapture(w.pointerId),w.isDrawing=!1,w.pointerId=null,w.start=null,w.current=null,w.points=[],w.screenPoints=[],w.stampCenter=null,d||(w.cursor=null,w.cursorScreen=null)},[]),Ce=m.useCallback(d=>{const w=a.current;if(!w||t<=0||n<=0)return null;const T=ct(w.screenToWorld(d.clientX,d.clientY));return T?Zt(T,t,n):null},[a,t,n]),ve=m.useCallback(d=>{const w=q.current;if(!w)return null;const T=w.getBoundingClientRect(),M=N(d.clientX-T.left,0,T.width),D=N(d.clientY-T.top,0,T.height);return!Number.isFinite(M)||!Number.isFinite(D)?null:[M,D]},[]),we=m.useCallback(()=>{const d=fe.current;if(!d.isDrawing){Te(!0),_();return}let w=[];if(e==="freehand")d.points.length>=oo&&(w=Ue(d.points));else if(e==="rectangle")w=jt(d.start,d.current,Ee());else if(e==="circular")w=bn(d.start,d.current);else if(e==="brush"){const T=d.points[d.points.length-1]??d.current??d.start;if(J.clickSelectRoi&&T&&d.points.length<=1&&c?.(T)){Te(!0),_();return}const M=J.edgeDetail,D=Math.max(Ao,J.radius*2/(Co*M)),ue=d.screenPoints.length>0?d.screenPoints:j(d.points),G=eo(ue,{radius:J.radius,minRasterStep:D,circleSides:Math.max(24,Math.round(64*M)),simplifyTolerance:D*.25,smoothingPasses:J.edgeSmoothing}),V=[];for(const Q of G){const ae=Se(Q);ae&&V.push(ae)}w=Ue(V)}(e==="freehand"||e==="rectangle"||e==="circular"||e==="brush")&&pr(w)&&u&&u({tool:e,intent:e==="brush"?"brush":"roi",coordinates:w,bbox:ur(w),areaPx:qt(w)}),Te(!0),_()},[e,u,Te,_,j,Se,Ee,J.radius,J.edgeDetail,J.edgeSmoothing,J.clickSelectRoi,c]),Re=m.useCallback((d,w)=>{const T=ke(d,w);if(!pr(T))return;const M=d==="stamp-rectangle-4096px"?"patch":"roi",D={tool:d,intent:M,coordinates:T,bbox:ur(T),areaPx:qt(T)};u?.(D),M==="patch"&&l&&l(D)},[ke,u,l]),et=m.useCallback((d,w,T)=>{const M=cr*cr,D=d.screenPoints[d.screenPoints.length-1];if(!D){d.points.push(w),d.screenPoints.push(T),d.current=w;return}const ue=T[0]-D[0],G=T[1]-D[1];ue*ue+G*G>=M?(d.points.push(w),d.screenPoints.push(T)):(d.points[d.points.length-1]=w,d.screenPoints[d.screenPoints.length-1]=T),d.current=w},[]),tt=m.useCallback(d=>{if(!ne||e==="cursor"||d.button!==0)return;const w=Ce(d);if(!w)return;const T=ve(d);if(!T)return;if(d.preventDefault(),d.stopPropagation(),Nt(e)){const ue=fe.current;ue.stampCenter=w,Re(e,w),_();return}const M=q.current;M&&M.setPointerCapture(d.pointerId);const D=fe.current;D.isDrawing=!0,D.pointerId=d.pointerId,D.start=w,D.current=w,D.cursor=w,D.cursorScreen=T,D.points=e==="freehand"||e==="brush"?[w]:[],D.screenPoints=e==="brush"?[T]:[],_()},[ne,e,Ce,ve,Re,_]),Jt=m.useCallback(d=>{if(!ne||e==="cursor")return;const w=Ce(d);if(!w)return;const T=ve(d);if(!T)return;const M=fe.current;if(M.cursor=w,M.cursorScreen=T,Nt(e)){M.stampCenter=w,d.preventDefault(),d.stopPropagation(),_();return}if(e==="brush"){if(!M.isDrawing||M.pointerId!==d.pointerId){_();return}d.preventDefault(),d.stopPropagation(),et(M,w,T),_();return}if(!(!M.isDrawing||M.pointerId!==d.pointerId)){if(d.preventDefault(),d.stopPropagation(),e==="freehand"){const D=a.current,ue=Math.max(1e-6,D?.getViewState?.().zoom??1),G=so/ue,V=G*G,Q=M.points[M.points.length-1];if(!Q)M.points.push(w);else{const ae=w[0]-Q[0],Me=w[1]-Q[1];ae*ae+Me*Me>=V&&M.points.push(w)}}else M.current=w;_()}},[ne,e,Ce,ve,_,a,et]),wt=m.useCallback(d=>{const w=fe.current;if(!w.isDrawing||w.pointerId!==d.pointerId)return;d.preventDefault(),d.stopPropagation();const T=Ce(d),M=ve(d);T&&(w.cursor=T,M&&(w.cursorScreen=M),e==="brush"?M&&et(w,T,M):w.current=T);const D=q.current;D&&D.hasPointerCapture(d.pointerId)&&D.releasePointerCapture(d.pointerId),we()},[we,Ce,ve,e,et]),nt=m.useCallback(()=>{const d=fe.current;let w=!1;e==="brush"&&!d.isDrawing&&d.cursor&&(d.cursor=null,d.cursorScreen=null,w=!0),Nt(e)&&d.stampCenter&&(d.stampCenter=null,w=!0),w&&_()},[e,_]);return m.useEffect(()=>{me(),_();const d=q.current;if(!d)return;const w=new ResizeObserver(()=>{me(),_()});return w.observe(d),()=>{w.disconnect()}},[me,_]),m.useEffect(()=>{ne||Te(),_()},[ne,_,Te]),m.useEffect(()=>{Ge.current!==e&&(Ge.current=e,Te(),_())},[e,Te,_]),m.useEffect(()=>{_()},[f,I,$,_]),m.useEffect(()=>{if(B)return B.current=_,()=>{B.current===_&&(B.current=null)}},[B,_]),m.useEffect(()=>{if(!ne)return;const d=w=>{w.key==="Escape"&&(Te(),_())};return window.addEventListener("keydown",d),()=>{window.removeEventListener("keydown",d)}},[ne,Te,_]),We.jsx("canvas",{ref:q,className:Y,style:pe,onPointerDown:tt,onPointerMove:Jt,onPointerUp:wt,onPointerCancel:wt,onPointerLeave:nt,onContextMenu:d=>{ne&&d.preventDefault()},onWheel:d=>{if(!ne)return;const w=q.current,T=a.current;if(!w||typeof T?.zoomBy!="function")return;d.preventDefault(),d.stopPropagation();const M=w.getBoundingClientRect(),D=d.clientX-M.left,ue=d.clientY-M.top;T.zoomBy(d.deltaY<0?lo:fo,D,ue),_()}})}function br(e){return String(e??"").replace(/\/+$/,"")}function Vr(e){const t=String(e??"");return t.startsWith("/")?t:`/${t}`}function ns(e){const t=br(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=br(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 rs(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(g=>({termId:String(g?.termId??""),termName:String(g?.termName??""),termColor:String(g?.termColor??"")})):[],h=Vr(c),f=ns(t),b=r?(g,y,x)=>`${f}${h}/${g}/${x}_${y}.webp`:void 0;return{id:e?._id||"unknown",name:e?.name||"unknown",width:i,height:o,mpp:Number.isFinite(u)&&u>0?u:void 0,tileSize:s,maxTierZoom:Number.isFinite(a)?Math.max(0,Math.floor(a)):0,tilePath:c,tileBaseUrl:t,terms:l,tileUrlBuilder:b}}function vn(e,t,n,r){if(e.tileUrlBuilder)return e.tileUrlBuilder(t,n,r);const i=Vr(e.tilePath);return`${e.tileBaseUrl}${i}/${t}/${r}_${n}.webp`}const Fe={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,b=r*h;e.beginPath(),e.moveTo(s[0],s[1]),e.lineTo(a[0],a[1]),e.setLineDash([f,b]),e.lineDashOffset=0,e.stroke()}e.setLineDash([]),e.lineDashOffset=0}}function pt(e,t,n=1){return typeof e!="number"||!Number.isFinite(e)?t:Math.max(n,e)}function zt(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 is={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 Gr({source:e,projectorRef:t,authToken:n="",options:r,invalidateRef:i,className:o,style:s}){const a=m.useRef(null),c=m.useRef(null),u=m.useRef(null),l=m.useRef({active:!1,pointerId:null}),h=m.useRef(null),f=m.useRef(!1),b=pt(r?.width,Fe.width,64),g=pt(r?.height,Fe.height,48),y=m.useMemo(()=>{const I=Math.max(1,e.width),E=Math.max(1,e.height),z=I/E,re=b/g;let X,de;return z>re?(X=b,de=b/z):(de=g,X=g*z),{x:(b-X)/2,y:(g-de)/2,w:X,h:de}},[e.width,e.height,b,g]),x=pt(r?.margin,Fe.margin,0),R=pt(r?.borderRadius,Fe.borderRadius,0),v=pt(r?.borderWidth,Fe.borderWidth,0),O=Math.max(1,Math.round(pt(r?.maxThumbnailTiles,Fe.maxThumbnailTiles,1))),P=r?.backgroundColor||Fe.backgroundColor,U=r?.borderColor||Fe.borderColor,H=r?.viewportBorderColor||Fe.viewportBorderColor,$=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:Fe.viewportBorderStyle,te=r?.viewportFillColor??Fe.viewportFillColor,ie=r?.interactive??Fe.interactive,ce=r?.showThumbnail??Fe.showThumbnail,be=r?.position||Fe.position,ge=r?.onClose,A=r?.closeIcon,B=r?.closeButtonStyle,Y=m.useMemo(()=>{const I={};return be==="top-left"||be==="bottom-left"?I.left=x:I.right=x,be==="top-left"||be==="top-right"?I.top=x:I.bottom=x,{position:"absolute",...I,width:b,height:g,borderRadius:R,overflow:"hidden",zIndex:4,pointerEvents:ie?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[x,be,b,g,R,ie,s]),W=m.useCallback(()=>{const I=a.current;if(!I)return;const E=I.getContext("2d");if(!E)return;const z=b,re=g,X=Math.max(1,window.devicePixelRatio||1),de=Math.max(1,Math.round(z*X)),ye=Math.max(1,Math.round(re*X));(I.width!==de||I.height!==ye)&&(I.width=de,I.height=ye),E.setTransform(1,0,0,1,0,0),E.clearRect(0,0,I.width,I.height),E.setTransform(X,0,0,X,0,0),E.fillStyle=P,E.fillRect(0,0,z,re);const{x:ee,y:Z,w:oe,h:he}=y,se=c.current;se&&E.drawImage(se,ee,Z,oe,he),E.strokeStyle=U,E.lineWidth=v,E.strokeRect(v*.5,v*.5,z-v,re-v);const J=t.current,pe=J?.getViewBounds?.(),me=J?.getViewCorners?.(),j=zt(pe)?pe:zt(u.current)?u.current:null;if(!j)return;u.current=j;const Se=oe/Math.max(1,e.width),Ee=he/Math.max(1,e.height),Ye=Array.isArray(me)&&me.length>=4&&me.every(we=>Array.isArray(we)&&we.length>=2&&Number.isFinite(we[0])&&Number.isFinite(we[1]))?me:null,ke=$==="dash";if(Ye){const we=Ye.map(Re=>[ee+Re[0]*Se,Z+Re[1]*Ee]);E.save(),E.beginPath(),E.rect(ee,Z,oe,he),E.clip(),E.beginPath();for(let Re=0;Re<we.length;Re+=1)Re===0?E.moveTo(we[Re][0],we[Re][1]):E.lineTo(we[Re][0],we[Re][1]);E.closePath(),E.fillStyle=te,E.fill(),E.strokeStyle=H,E.lineWidth=2.25,ke?wr(E,we,4,3):E.stroke(),E.restore();return}const Ie=N(ee+j[0]*Se,ee,ee+oe),xe=N(Z+j[1]*Ee,Z,Z+he),_=N(ee+j[2]*Se,ee,ee+oe),Te=N(Z+j[3]*Ee,Z,Z+he),Ce=Math.max(1,_-Ie),ve=Math.max(1,Te-xe);if(E.fillStyle=te,E.fillRect(Ie,xe,Ce,ve),E.strokeStyle=H,E.lineWidth=2.25,ke){const we=[[Ie+.5,xe+.5],[Ie+.5+Math.max(1,Ce-1),xe+.5],[Ie+.5+Math.max(1,Ce-1),xe+.5+Math.max(1,ve-1)],[Ie+.5,xe+.5+Math.max(1,ve-1)]];wr(E,we,4,3)}else E.strokeRect(Ie+.5,xe+.5,Math.max(1,Ce-1),Math.max(1,ve-1))},[b,g,y,P,U,v,t,e.width,e.height,te,H,$]),q=m.useCallback(()=>{f.current||(f.current=!0,h.current=requestAnimationFrame(()=>{f.current=!1,h.current=null,W()}))},[W]),Le=m.useCallback((I,E)=>{const z=a.current;if(!z)return null;const re=z.getBoundingClientRect();if(!re.width||!re.height)return null;const X=re.width/b,de=re.height/g,ye=y.x*X,ee=y.y*de,Z=y.w*X,oe=y.h*de,he=N((I-re.left-ye)/Z,0,1),se=N((E-re.top-ee)/oe,0,1);return[he*e.width,se*e.height]},[e.width,e.height,b,g,y]),Ae=m.useCallback((I,E)=>{const z=t.current;if(!z)return;if(z.setViewCenter){z.setViewCenter(I,E),q();return}const re=z.getViewBounds?.(),X=zt(re)?re:zt(u.current)?u.current:null;if(!X)return;const de=Math.max(1e-6,X[2]-X[0]),ye=Math.max(1e-6,X[3]-X[1]);z.setViewState({offsetX:I-de*.5,offsetY:E-ye*.5}),q()},[t,q]),Ge=m.useCallback(I=>{if(!ie||I.button!==0)return;const E=a.current;if(!E)return;const z=Le(I.clientX,I.clientY);z&&(I.preventDefault(),I.stopPropagation(),E.setPointerCapture(I.pointerId),l.current={active:!0,pointerId:I.pointerId},Ae(z[0],z[1]))},[ie,Le,Ae]),fe=m.useCallback(I=>{const E=l.current;if(!E.active||E.pointerId!==I.pointerId)return;const z=Le(I.clientX,I.clientY);z&&(I.preventDefault(),I.stopPropagation(),Ae(z[0],z[1]))},[Le,Ae]),ne=m.useCallback(I=>{const E=l.current;if(!E.active||E.pointerId!==I.pointerId)return;const z=a.current;if(z&&z.hasPointerCapture(I.pointerId))try{z.releasePointerCapture(I.pointerId)}catch{}l.current={active:!1,pointerId:null},q()},[q]);return m.useEffect(()=>{let I=!1;c.current=null,q();const E=0,z=2**(e.maxTierZoom-E),re=Math.ceil(e.width/z),X=Math.ceil(e.height/z),de=Math.max(1,Math.ceil(re/e.tileSize)),ye=Math.max(1,Math.ceil(X/e.tileSize)),ee=de*ye;if(!ce||ee>O)return;const Z=document.createElement("canvas");Z.width=Math.max(1,Math.round(y.w)),Z.height=Math.max(1,Math.round(y.h));const oe=Z.getContext("2d");if(!oe)return;oe.fillStyle=P,oe.fillRect(0,0,Z.width,Z.height);const he=[];for(let se=0;se<ye;se+=1)for(let J=0;J<de;J+=1){const pe=J*e.tileSize*z,me=se*e.tileSize*z,j=Math.min((J+1)*e.tileSize,re)*z,Se=Math.min((se+1)*e.tileSize,X)*z;he.push({url:vn(e,E,J,se),bounds:[pe,me,j,Se]})}return Promise.allSettled(he.map(async se=>{const J=!!n,pe=await fetch(se.url,{headers:J?{Authorization:n}:void 0});if(!pe.ok)throw new Error(`HTTP ${pe.status}`);const me=await createImageBitmap(await pe.blob());return{tile:se,bitmap:me}})).then(se=>{if(I){for(const me of se)me.status==="fulfilled"&&me.value.bitmap.close();return}const J=Z.width/Math.max(1,e.width),pe=Z.height/Math.max(1,e.height);for(const me of se){if(me.status!=="fulfilled")continue;const{tile:{bounds:j},bitmap:Se}=me.value,Ee=j[0]*J,Ye=j[1]*pe,ke=Math.max(1,(j[2]-j[0])*J),Ie=Math.max(1,(j[3]-j[1])*pe);oe.drawImage(Se,Ee,Ye,ke,Ie),Se.close()}c.current=Z,q()}),()=>{I=!0}},[e,n,y,P,ce,O,q]),m.useEffect(()=>{q()},[q]),m.useEffect(()=>{if(i)return i.current=q,()=>{i.current===q&&(i.current=null)}},[i,q]),m.useEffect(()=>()=>{l.current={active:!1,pointerId:null},h.current!==null&&(cancelAnimationFrame(h.current),h.current=null),f.current=!1},[]),We.jsxs("div",{className:o,style:Y,children:[We.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:Ge,onPointerMove:fe,onPointerUp:ne,onPointerCancel:ne,onContextMenu:I=>{I.preventDefault()},onWheel:I=>{I.preventDefault(),I.stopPropagation()}}),ge&&We.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:I=>{I.stopPropagation(),ge()},style:B?{...B}:{...is},children:A??"×"})]})}function os({imageWidth:e,imageHeight:t,tiles:n,viewState:r,className:i,style:o}){const s=m.useRef(null),a=m.useRef(null),c=m.useMemo(()=>({width:"100%",height:"100%",display:"block",...o}),[o]);return m.useEffect(()=>{const u=s.current;if(!u)return;const l=new Pr({canvas:u,imageWidth:e,imageHeight:t,initialViewState:r});return a.current=l,l.setTiles(n),()=>{l.destroy(),a.current=null}},[e,t]),m.useEffect(()=>{const u=a.current;u&&u.setTiles(n)},[n]),m.useEffect(()=>{const u=a.current;!u||!r||u.setViewState(r)},[r]),We.jsx("canvas",{ref:s,className:i,style:c})}function Ct(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return null;const n=It(t??[]);if(n.length===0){const g={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return e.fillModes instanceof Uint8Array&&(g.fillModes=new Uint8Array(0)),e.ids instanceof Uint32Array&&(g.ids=new Uint32Array(0)),g}const r=ut(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 g=0;g<r;g+=1){const y=i[g*2],x=i[g*2+1];$t(y,x,n)&&(c[f*2]=y,c[f*2+1]=x,u[f]=o[g],l&&(l[f]=s[g]),h&&(h[f]=a[g]),f+=1)}const b={count:f,positions:c.subarray(0,f*2),paletteIndices:u.subarray(0,f)};return l&&(b.fillModes=l.subarray(0,f)),h&&(b.ids=h.subarray(0,f)),b}function qr(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=ut(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];$t(c,u,n)&&(o[s]=a,s+=1)}return o.subarray(0,s)}let Ot=null;const ss=`
|
|
32
|
+
`;class Ir{constructor(t){S(this,"canvas");S(this,"gl");S(this,"camera",new Pr);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=Ri(this.canvas),this.program=Rn(this.gl,Ci,Pi);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 Ct(e){return e??null}function er(e){return typeof e=="number"&&Number.isFinite(e)}function Ii(e){return Array.isArray(e)&&e.length>=2&&er(e[0])&&er(e[1])}function Er(e){return Array.isArray(e)&&e.length>0&&e.every(t=>Ii(t))}function vr(e){return Array.isArray(e)&&e.length>0&&e.every(t=>Er(t))}function Ei(e){return Array.isArray(e)&&e.length>0&&e.every(t=>vr(t))}function Ne(e){if(!Array.isArray(e)||e.length<3)return[];const t=[];for(const i of e){if(!Array.isArray(i)||i.length<2)continue;const o=Number(i[0]),s=Number(i[1]);if(!Number.isFinite(o)||!Number.isFinite(s))continue;const a=t[t.length-1];a&&a[0]===o&&a[1]===s||t.push([o,s])}if(t.length<3)return[];const n=t[0],r=t[t.length-1];return(n[0]!==r[0]||n[1]!==r[1])&&t.push([n[0],n[1]]),t.length>=4?t:[]}function Mt(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 cn(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const o of e){const s=Ne(o);s.length>=4&&t.push(s)}if(t.length===0)return[];if(t.length===1)return[t[0]];let n=0,r=0;for(let o=0;o<t.length;o+=1){const s=Math.abs(Mt(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 _r(e){if(!e)return[];if(Er(e)){const t=cn([e]);return t.length>0?[t]:[]}if(vr(e)){const t=cn(e);return t.length>0?[t]:[]}if(Ei(e)){const t=[];for(const n of e){const r=cn(n);r.length>0&&t.push(r)}return t}return[]}function tr(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 Pt(e){const t=[];for(const n of e??[]){const r=_r(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[d,f]of o)d<s&&(s=d),d>c&&(c=d),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(Mt(o));for(let d=1;d<i.length;d+=1)l-=Math.abs(Mt(i[d]));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 Fr(e,t,n){if(e<n.minX||e>n.maxX||t<n.minY||t>n.maxY||!tr(e,t,n.outer))return!1;for(const r of n.holes)if(tr(e,t,r))return!1;return!0}function Zt(e,t,n){for(const r of n)if(Fr(e,t,r))return!0;return!1}const Cn=[160,160,160,255];function k(e,t,n){return Math.max(t,Math.min(n,e))}function Pn(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 vi(e,t,n){let i=100*Pn(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 ut(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 gn(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 _i(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 Br(e){const n=String(e??"").trim().match(/^#?([0-9a-fA-F]{6})$/);if(!n)return[...Cn];const r=Number.parseInt(n[1],16);return[r>>16&255,r>>8&255,r&255,255]}function Fi(e){const t=[[...Cn]],n=new Map;for(const i of e??[]){const o=String(i?.termId??"");!o||n.has(o)||(n.set(o,t.length),t.push(Br(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 Bi=.1,Li=4e6,Ui=4096,Di=64,ki=1,Ni=4,Lr=1e-6,zi=24;function Oi(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 Wi(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 Ne(r)}function un(e,t){if(!e.length)return[];let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,c]of e)a<n&&(n=a),a>i&&(i=a),c<r&&(r=c),c>o&&(o=c);if(!Number.isFinite(n)||!Number.isFinite(r))return[];const s=Math.max(t,1);return Ne([[n-s,r-s],[i+s,r-s],[i+s,o+s],[n-s,o+s]])}function Yi(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 Xi(e,t,n){const r=Math.max(Bi,Number(n.minRasterStep)||0),i=Math.max(32768,Math.floor(n.maxRasterPixels||Li)),o=Math.max(256,Math.floor(n.maxRasterSize||Ui)),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,d=Math.ceil(a/c)+u*2+1;for(;(l>o||d>o||l*d>i)&&(c*=1.15,l=Math.ceil(s/c)+u*2+1,d=Math.ceil(a/c)+u*2+1,!(c>Math.max(s,a))););return l=Math.max(8,l),d=Math.max(8,d),{minX:e[0],minY:e[1],step:c,padding:u,width:l,height:d}}function Vi(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 Gi(e,t){return[(e[0]-t.minX)/t.step+t.padding,(e[1]-t.minY)/t.step+t.padding]}function qi(e,t,n){const r=Vi(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=>Gi(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]>=zi?1:0;return s}function Hi(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 $i(e,t){const n=(t-e+4)%4;return n===1?0:n===0?1:n===3?2:3}function Zi(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 d=e.length*3;for(;a!==s&&l<d;){const f=t.get(a);if(!f||f.length===0)break;let y=-1,b=1/0;for(const x of f){if(n[x])continue;const R=e[x],E=$i(c,R.dir);E<b&&(b=E,y=x)}if(y<0)break;n[y]=1;const w=e[y];a=w.end,c=w.dir,u.push(a),l+=1}u.length>=4&&u[0]===u[u.length-1]&&r.push(u)}return r}function Ki(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 Ne(i)}function ji(e,t=1e-9){const n=Ne(e);if(n.length<5)return n;const r=[n[0]];for(let i=1;i<n.length-1;i+=1){const o=r[r.length-1],s=n[i],a=n[i+1],c=(s[0]-o[0])*(a[1]-s[1])-(s[1]-o[1])*(a[0]-s[0]);Math.abs(c)<=t||r.push(s)}return r.push(r[0]),Ne(r)}function Ji(e,t,n){const r=n[0]-t[0],i=n[1]-t[1],o=r*r+i*i;if(o<=1e-12){const d=e[0]-t[0],f=e[1]-t[1];return d*d+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 Qi(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 d=a+1;d<c;d+=1){const f=Ji(e[d],e[a],e[c]);f>u&&(u=f,l=d)}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 eo(e,t){const n=Ne(e);if(n.length<5||t<=0)return n;const r=n.slice(0,-1),i=Qi(r,t);return i.length<3?n:Ne(i)}function to(e,t){let n=Ne(e);if(t<=0||n.length<5)return n;for(let r=0;r<t;r+=1){const i=n.slice(0,-1);if(i.length<3)break;const o=[];for(let s=0;s<i.length;s+=1){const a=i[s],c=i[(s+1)%i.length];o.push([a[0]*.75+c[0]*.25,a[1]*.75+c[1]*.25],[a[0]*.25+c[0]*.75,a[1]*.25+c[1]*.75])}n=Ne(o)}return n}function yt(e,t){return t?Ne(e.map(([n,r])=>[k(n,t[0],t[2]),k(r,t[1],t[3])])):e}function no(e,t){const n=Oi(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||Di));if(n.length===1)return yt(Wi(n[0],r,i),t.clipBounds);const o=Yi(n,r),s=Xi(o,r,t),a=qi(n,r,s);if(!a.length)return yt(un(n,r),t.clipBounds);const c=Hi(a,s.width,s.height),u=Zi(c);if(!u.length)return yt(un(n,r),t.clipBounds);let l=[],d=0;for(const w of u){const x=Ki(w,s.width,s),R=Math.abs(Mt(x));R<=d||(d=R,l=x)}if(!l.length)return yt(un(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,Ni)):ki,b=eo(to(ji(l,s.step*.001),y),f);return yt(b,t.clipBounds)}const At=[],nr=[],Qe={color:"#ff4d4f",width:2,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},ro={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},io="rgba(23, 23, 25, 0.1)",oo=6,Oe={fontFamily:"Pretendard, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:11,fontWeight:600,textColor:"#171719",backgroundColor:"#FFCC00",borderColor:"rgba(0, 0, 0, 0)",borderWidth:0,paddingX:8,paddingY:4,offsetY:10,borderRadius:4},et={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},rr={x:16,y:-24},so=20,ir=1e-6,or="transparent",ao=3,co=2,Ur=96,uo=1,sr=1e3,Dr=2,kr=2,lo=4096,fo=.2,ho=1.12,mo=.89,go=32,po="#000000",bo=.1,yo="#FFCF00",wo="#FF0000",So=1.5,ar=[2,2],xo=1,Mo=.25,Ao=4,To=1,Ro=0,Co=4,Po=.05,Io=256,cr=1.5;function Kt(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 ct=jt;function Be(e){return Ne(e)}function Ht(e){return Math.abs(Mt(Be(e)))}function ur(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 pn(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(),pn(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(At),e.shadowColor="rgba(0, 0, 0, 0)",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0)}function Nr(e){const t=Array.isArray(e?.lineDash)?e.lineDash.filter(s=>Number.isFinite(s)&&s>=0):At,n=typeof e?.width=="number"&&Number.isFinite(e.width)?Math.max(0,e.width):Qe.width,r=typeof e?.shadowBlur=="number"&&Number.isFinite(e.shadowBlur)?Math.max(0,e.shadowBlur):Qe.shadowBlur,i=typeof e?.shadowOffsetX=="number"&&Number.isFinite(e.shadowOffsetX)?e.shadowOffsetX:Qe.shadowOffsetX,o=typeof e?.shadowOffsetY=="number"&&Number.isFinite(e.shadowOffsetY)?e.shadowOffsetY:Qe.shadowOffsetY;return{color:e?.color||Qe.color,width:n,lineDash:t.length?t:At,lineJoin:e?.lineJoin||Qe.lineJoin,lineCap:e?.lineCap||Qe.lineCap,shadowColor:e?.shadowColor||Qe.shadowColor,shadowBlur:r,shadowOffsetX:i,shadowOffsetY:o}}function wt(e,t){return t?Nr({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 lr(e,t){return e==null||t===null||t===void 0?!1:String(e)===String(t)}function fr(e){return typeof e=="number"&&Number.isFinite(e)}function Eo(e){return Array.isArray(e)&&e.length>=2&&fr(e[0])&&fr(e[1])}function vo(e){return Array.isArray(e)&&e.length>=2&&e.every(t=>Eo(t))}function zr(e,t){if(!(!Array.isArray(e)||e.length===0)){if(vo(e)){t.push(e.map(([n,r])=>[n,r]));return}for(const n of e)zr(n,t)}}function dr(e,t){const n=[];zr(e,n);const r=[];for(const i of n){if(i.length<2)continue;const o=t?Be(i):i;o.length>=(t?4:2)&&r.push(o)}return r}function xt(e,t){return typeof e!="number"||!Number.isFinite(e)||e<=0?t:e}function _o(e,t){return typeof e!="number"||!Number.isFinite(e)?t:k(e,0,1)}function Or(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 Fo(e){const t=e[0];return Array.isArray(t)&&Array.isArray(t[0])}function Jt(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 Jt(e,t);s.push(c)}return Be(s)}}return Be([[e[0],e[1]],[t[0],e[1]],[t[0],t[1]],[e[0],t[1]]])}function bn(e,t,n=Ur){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 Be(s)}function hr(e){const t=_r(Ct(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 Bo(e){if(!Array.isArray(e))return ar;const t=e.filter(n=>Number.isFinite(n)&&n>=0);return t.length>0?t:ar}function Lo(e){return typeof e!="number"||!Number.isFinite(e)?xo:k(e,Mo,Ao)}function Uo(e){return typeof e!="number"||!Number.isFinite(e)?To:Math.round(k(e,Ro,Co))}function Do(e){const t=xt(e?.radius,go),n=xt(e?.cursorLineWidth,So),r=Lo(e?.edgeDetail),i=Uo(e?.edgeSmoothing);return{radius:t,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:e?.clickSelectRoi===!0,fillColor:e?.fillColor||po,fillOpacity:_o(e?.fillOpacity,bo),cursorColor:e?.cursorColor||yo,cursorActiveColor:e?.cursorActiveColor||wo,cursorLineWidth:n,cursorLineDash:Bo(e?.cursorLineDash)}}function ko(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 No(e,t,n,r){const i=t.cursor;if(!i)return;const o=t.cursorScreen??ct(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(At),e.restore())}const zo=.58,Oo=4096,Wo=.5;let kt=null;const Nt=new Map;function Yo(){if(kt)return kt;if(typeof document>"u")return null;const t=document.createElement("canvas").getContext("2d");return t?(kt=t,kt):null}function In(e,t){const n=`${t.fontWeight}|${t.fontSize}|${t.fontFamily}|${e}`,r=Nt.get(n);if(r!==void 0)return r;const i=e.length*t.fontSize*zo,o=Yo();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 Nt.size>Oo&&Nt.clear(),Nt.set(n,s),s}function Xo(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)>Wo||(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 Wr(e){let t=null;for(const n of e){const r=Xo(n.outer);r&&(!t||r[1]<t[1]||r[1]===t[1]&&r[0]<t[0])&&(t=r)}return t}function En(e){const t=typeof e?.paddingX=="number"&&Number.isFinite(e.paddingX)?Math.max(0,e.paddingX):Oe.paddingX,n=typeof e?.paddingY=="number"&&Number.isFinite(e.paddingY)?Math.max(0,e.paddingY):Oe.paddingY,r=typeof e?.fontSize=="number"&&Number.isFinite(e.fontSize)?Math.max(8,e.fontSize):Oe.fontSize,i=typeof e?.borderWidth=="number"&&Number.isFinite(e.borderWidth)?Math.max(0,e.borderWidth):Oe.borderWidth,o=typeof e?.offsetY=="number"&&Number.isFinite(e.offsetY)?e.offsetY:Oe.offsetY,s=typeof e?.borderRadius=="number"&&Number.isFinite(e.borderRadius)?Math.max(0,e.borderRadius):Oe.borderRadius;return{fontFamily:e?.fontFamily||Oe.fontFamily,fontSize:r,fontWeight:e?.fontWeight||Oe.fontWeight,textColor:e?.textColor||Oe.textColor,backgroundColor:e?.backgroundColor||Oe.backgroundColor,borderColor:e?.borderColor||Oe.borderColor,borderWidth:i,paddingX:t,paddingY:n,offsetY:o,borderRadius:s}}function Yr(e,t){return t?En({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 Xr(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<=ir||!Number.isFinite(t)?0:t>=i-ir?so:0}function Vo(e){const t=typeof e?.fontSize=="number"&&Number.isFinite(e.fontSize)?Math.max(8,e.fontSize):et.fontSize,n=typeof e?.borderRadius=="number"&&Number.isFinite(e.borderRadius)?Math.max(0,e.borderRadius):et.borderRadius,r=typeof e?.paddingX=="number"&&Number.isFinite(e.paddingX)?Math.max(0,e.paddingX):et.paddingX,i=typeof e?.paddingY=="number"&&Number.isFinite(e.paddingY)?Math.max(0,e.paddingY):et.paddingY;return{fontFamily:e?.fontFamily||et.fontFamily,fontSize:t,fontWeight:e?.fontWeight||et.fontWeight,textColor:e?.textColor||et.textColor,backgroundColor:e?.backgroundColor||et.backgroundColor,borderRadius:n,paddingX:r,paddingY:i}}function Go(e){const t=typeof e?.x=="number"&&Number.isFinite(e.x)?e.x:rr.x,n=typeof e?.y=="number"&&Number.isFinite(e.y)?e.y:rr.y;return{x:t,y:n}}function qo(e){return Number.isFinite(e)?`${Math.max(0,e).toFixed(3)} mm²`:"0.000 mm²"}function Ho(e){const t=typeof e?.format=="function"?e.format:qo,n=Go(e?.cursorOffset);return{enabled:e?.enabled===!0,format:t,style:Vo(e?.style),cursorOffsetX:n.x,cursorOffsetY:n.y}}function $o(e,t,n,r,i,o){const s=t.trim();if(!s)return;e.save(),e.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,e.textAlign="center",e.textBaseline="middle";const c=In(s,o)+o.paddingX*2,u=o.fontSize+o.paddingY*2,l=k(n[0],c*.5+1,r-c*.5-1),d=k(n[1]-o.offsetY,u*.5+1,i-u*.5-1),f=l-c*.5,y=d-u*.5;e.fillStyle=o.backgroundColor,e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,Or(e,f,y,c,u,o.borderRadius),e.fill(),o.borderWidth>0&&e.stroke(),e.fillStyle=o.textColor,e.fillText(s,l,d+.5),e.restore()}function Zo(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=In(c,o)+o.paddingX*2,d=o.fontSize+o.paddingY*2,f=k(n[0]+s,l*.5+1,r-l*.5-1),y=k(n[1]+a,d*.5+1,i-d*.5-1),b=f-l*.5,w=y-d*.5;e.fillStyle=o.backgroundColor,Or(e,b,w,l,d,o.borderRadius),e.fill(),e.fillStyle=o.textColor,e.fillText(c,f,y+.5),e.restore()}function Ko(e,t,n,r){if(!(t.length<4||n.length===0)){e.save(),e.beginPath(),pn(e,t,!0);for(const i of n)i.length<4||pn(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??Fo(u.coordinates),d=dr(u.coordinates,l);if(u.invertedFill?.fillColor){const y=[],b=dr(u.coordinates,!0);for(const w of b){const x=i(w);x.length>=4&&y.push(x)}a&&s&&s({id:u.id??c,outerRingPoints:r.length,sourceRingCount:b.length,holeRingCount:y.length,fillColor:u.invertedFill.fillColor}),Ko(t,r,y,u.invertedFill.fillColor)}if(d.length===0)continue;const f=wt(o,u.stroke??u.strokeStyle);for(const y of d){const b=i(y);b.length<2||Xe(t,b,f,l,u.fill??!1)}}}function zt(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 Jo(e){return{rectangleAreaMm2:xt(e?.rectangleAreaMm2,Dr),circleAreaMm2:xt(e?.circleAreaMm2,kr),rectanglePixelSize:xt(e?.rectanglePixelSize,lo)}}const mr=1e3;function Qo(e){return e*mr*mr}function gr(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 Be(a)}}return Be([[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 es(e,t,n=Ur){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 Be(r)}function ts(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 d=r.rectanglePixelSize*.5;return gr(n,d,a()).map(f=>Kt(f,i,o))}let c=0;if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"?c=t==="stamp-rectangle-2mm2"?Dr:r.rectangleAreaMm2:(t==="stamp-circle"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2")&&(c=t==="stamp-circle-hpf-0.2mm2"?fo:t==="stamp-circle-2mm2"?kr:r.circleAreaMm2),!Number.isFinite(c)||c<=0)return[];const u=Qo(c);let l=[];if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"){const d=s(Math.sqrt(u)*.5);l=gr(n,d,a())}else if(t==="stamp-circle"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2"){const d=s(Math.sqrt(u/Math.PI));l=es(n,d)}return l.length?l.map(d=>Kt(d,i,o)):[]}function ns(e){return{color:io,width:oo,lineDash:At,lineJoin:e.lineJoin,lineCap:e.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function rs(e){if(typeof e!="string")return or;const t=e.trim();return t.length>0?t:or}function pr(e){return Array.isArray(e)&&e.length>=4&&Ht(e)>uo}function Vr({tool:e,imageWidth:t,imageHeight:n,imageMpp:r,imageZoom:i,stampOptions:o,brushOptions:s,projectorRef:a,onBrushTap:c,onDrawComplete:u,onPatchComplete:l,enabled:d,viewStateSignal:f,persistedRegions:y,patchRegions:b,persistedPolygons:w,drawFillColor:x,regionStrokeStyle:R,regionStrokeHoverStyle:E,regionStrokeActiveStyle:X,patchStrokeStyle:A,resolveRegionStrokeStyle:F,resolveRegionLabelStyle:K,overlayShapes:oe,hoveredRegionId:Q=null,activeRegionId:ee=null,regionLabelStyle:se,drawAreaTooltip:ge,autoLiftRegionLabelAtMaxZoom:Te=!1,regionLabelAutoLiftOffsetPx:_,invalidateRef:L,className:O,style:D}){const V=h.useRef(null),Le=h.useRef(!1),Re=h.useRef(new Map),Ve=h.useRef(e),de=h.useRef({isDrawing:!1,pointerId:null,start:null,current:null,cursor:null,cursorScreen:null,points:[],screenPoints:[],stampCenter:null}),ae=d??e!=="cursor",v=h.useMemo(()=>y&&y.length>0?y:!w||w.length===0?nr:w.map((m,g)=>({id:g,coordinates:m})),[y,w]),P=h.useMemo(()=>b??nr,[b]),N=h.useMemo(()=>{const m=[];for(let g=0;g<v.length;g+=1){const M=v[g],C=hr(M.coordinates);C.length!==0&&m.push({region:M,regionIndex:g,regionKey:M.id??g,polygons:C})}return m},[v]),ce=h.useMemo(()=>{const m=[];for(let g=0;g<P.length;g+=1){const M=P[g],C=hr(M.coordinates);C.length!==0&&m.push({region:M,regionIndex:g,regionKey:M.id??g,polygons:C})}return m},[P]),G=h.useMemo(()=>Nr(R),[R]),pe=h.useMemo(()=>wt(G,E),[G,E]),Se=h.useMemo(()=>wt(G,X),[G,X]),le=h.useMemo(()=>wt(ro,A),[A]),q=h.useMemo(()=>rs(x),[x]),he=h.useMemo(()=>En(se),[se]),te=h.useMemo(()=>Ho(ge),[ge]),ue=h.useMemo(()=>Jo(o),[o]),Z=h.useMemo(()=>Do(s),[s]),xe=h.useMemo(()=>({position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",touchAction:"none",pointerEvents:ae?"auto":"none",cursor:ae?e==="brush"?"none":"crosshair":"default",...D}),[ae,e,D]),ne=h.useCallback(()=>{const m=V.current;if(!m)return;const g=m.getBoundingClientRect(),M=Math.max(1,window.devicePixelRatio||1),C=Math.max(1,Math.round(g.width*M)),I=Math.max(1,Math.round(g.height*M));(m.width!==C||m.height!==I)&&(m.width=C,m.height=I)},[]),J=h.useCallback(m=>{const g=a.current;if(!g||m.length===0)return[];const M=new Array(m.length);for(let C=0;C<m.length;C+=1){const I=ct(g.worldToScreen(m[C][0],m[C][1]));if(!I)return[];M[C]=I}return M},[a]),Ce=h.useCallback(m=>{const g=a.current,M=V.current;if(!g||!M)return null;const C=M.getBoundingClientRect(),I=ct(g.screenToWorld(C.left+m[0],C.top+m[1]));return I?Kt(I,t,n):null},[a,t,n]),we=h.useCallback(()=>{const m=a.current,g=m?.getViewState?.().rotationDeg??0;if(!(Math.abs(g%360)<.01||!m))return{worldToScreen:(M,C)=>ct(m.worldToScreen(M,C)),screenToWorld:Ce}},[a,Ce]),Ge=h.useCallback(m=>{if(!Number.isFinite(m)||m<=0)return 0;const g=typeof r=="number"&&Number.isFinite(r)&&r>0?r:1,M=typeof i=="number"&&Number.isFinite(i)?i:0,C=a.current?.getViewState?.().zoom,I=typeof C=="number"&&Number.isFinite(C)&&C>0?C:1,me=M+Math.log2(I),H=Math.max(1e-9,Pn(g,M,me));return m/H/I},[r,i,a]),Ue=h.useCallback((m,g)=>ts({stampTool:m,center:g,resolvedStampOptions:ue,imageWidth:t,imageHeight:n,micronsToWorldPixels:Ge,getRectangleProjection:we}),[Ge,t,n,ue,we]),ve=h.useCallback(()=>{const m=de.current;return zt(e)?Ue(e,m.stampCenter):e==="brush"?[]:m.isDrawing?e==="freehand"?m.points:e==="rectangle"?Jt(m.start,m.current,we()):e==="circular"?bn(m.start,m.current):[]:[]},[e,Ue,we]),De=h.useCallback(()=>{ne();const m=V.current;if(!m)return;const g=m.getContext("2d");if(!g)return;const M=Math.max(1,window.devicePixelRatio||1),C=m.width/M,I=m.height/M;if(g.setTransform(1,0,0,1,0,0),g.clearRect(0,0,m.width,m.height),g.setTransform(M,0,0,M,0,0),N.length>0)for(const H of N){const{region:ie,polygons:$,regionIndex:re,regionKey:ye}=H,Ie=lr(ee,ye)?"active":lr(Q,ye)?"hover":"default";let ke=Ie==="active"?Se:Ie==="hover"?pe:G;if(F){const He=F({region:ie,regionId:ye,regionIndex:re,state:Ie});ke=wt(ke,He||void 0)}const rt=Ie==="default"?null:ns(ke);for(const He of $){const pt=J(He.outer);pt.length>=4&&(rt&&Xe(g,pt,rt,!0,!1),Xe(g,pt,ke,!0,!1));for(const bt of He.holes){const $e=J(bt);$e.length>=4&&(rt&&Xe(g,$e,rt,!0,!1),Xe(g,$e,ke,!0,!1))}}}if(ce.length>0)for(const H of ce)for(const ie of H.polygons){const $=J(ie.outer);$.length>=4&&Xe(g,$,le,!0,!1);for(const re of ie.holes){const ye=J(re);ye.length>=4&&Xe(g,ye,le,!0,!1)}}if(Array.isArray(oe)&&oe.length>0){const H=J(Be([[0,0],[t,0],[t,n],[0,n]]));jo({ctx:g,overlayShapes:oe,imageOuterRing:H,worldToScreenPoints:J,baseStrokeStyle:G,onInvertedFillDebug:globalThis.__OPEN_PLANT_DEBUG_OVERLAY__?ie=>{const $=String(ie.id),re=`${ie.outerRingPoints}|${ie.sourceRingCount}|${ie.holeRingCount}|${ie.fillColor}`;Re.current.get($)!==re&&(Re.current.set($,re),console.debug("[open-plant] invertedFill",ie))}:void 0})}const me=ve();if(ae){if(e==="brush")ko(g,de.current,Z),No(g,de.current,a.current,Z);else if(me.length>0)if(e==="freehand"){const H=J(me);H.length>=2&&Xe(g,H,G,!1,!1),H.length>=3&&Xe(g,J(Be(me)),G,!0,!0,q)}else{const H=J(me);H.length>=4&&Xe(g,H,G,!0,!0,q)}}if(N.length>0){const H=Math.max(1e-6,a.current?.getViewState?.().zoom??1),ie=typeof _=="number"&&Number.isFinite(_)?Math.max(0,_):Xr(Te,H,a.current?.getZoomRange?.());for(const $ of N){if(!$.region.label)continue;const re=Wr($.polygons);if(!re)continue;const ye=ct(a.current?.worldToScreen(re[0],re[1])??[]);if(!ye)continue;let Ie=Yr(he,K?.({region:$.region,regionId:$.regionKey,regionIndex:$.regionIndex,zoom:H}));ie>0&&(Ie={...Ie,offsetY:Ie.offsetY+ie}),$o(g,$.region.label,ye,C,I,Ie)}}if(te.enabled&&ae&&(e==="freehand"||e==="rectangle"||e==="circular")){const H=de.current;if(H.isDrawing){const ie=e==="freehand"?Be(me):me;if(ie.length>=4){const $=Ht(ie),re=typeof r=="number"&&Number.isFinite(r)&&r>0?r:0,ye=re>0?$*re*re/(sr*sr):0,Ie=te.format(ye),ke=H.cursorScreen??(H.current?ct(a.current?.worldToScreen(H.current[0],H.current[1])??[]):null);ke&&Zo(g,Ie,ke,C,I,te.style,te.cursorOffsetX,te.cursorOffsetY)}}}},[ae,e,ve,ne,J,t,n,a,N,oe,Q,ee,G,pe,Se,q,ce,le,F,K,he,te,Te,_,r,Z]),W=h.useCallback(()=>{Le.current||(Le.current=!0,requestAnimationFrame(()=>{Le.current=!1,De()}))},[De]),Y=h.useCallback((m=!1)=>{const g=de.current,M=V.current;M&&g.pointerId!==null&&M.hasPointerCapture(g.pointerId)&&M.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)},[]),Me=h.useCallback(m=>{const g=a.current;if(!g||t<=0||n<=0)return null;const M=ct(g.screenToWorld(m.clientX,m.clientY));return M?Kt(M,t,n):null},[a,t,n]),Pe=h.useCallback(m=>{const g=V.current;if(!g)return null;const M=g.getBoundingClientRect(),C=k(m.clientX-M.left,0,M.width),I=k(m.clientY-M.top,0,M.height);return!Number.isFinite(C)||!Number.isFinite(I)?null:[C,I]},[]),be=h.useCallback(()=>{const m=de.current;if(!m.isDrawing){Y(!0),W();return}let g=[];if(e==="freehand")m.points.length>=ao&&(g=Be(m.points));else if(e==="rectangle")g=Jt(m.start,m.current,we());else if(e==="circular")g=bn(m.start,m.current);else if(e==="brush"){const M=m.points[m.points.length-1]??m.current??m.start;if(Z.clickSelectRoi&&M&&m.points.length<=1&&c?.(M)){Y(!0),W();return}const C=Z.edgeDetail,I=Math.max(Po,Z.radius*2/(Io*C)),me=m.screenPoints.length>0?m.screenPoints:J(m.points),H=no(me,{radius:Z.radius,minRasterStep:I,circleSides:Math.max(24,Math.round(64*C)),simplifyTolerance:I*.25,smoothingPasses:Z.edgeSmoothing}),ie=[];for(const $ of H){const re=Ce($);re&&ie.push(re)}g=Be(ie)}(e==="freehand"||e==="rectangle"||e==="circular"||e==="brush")&&pr(g)&&u&&u({tool:e,intent:e==="brush"?"brush":"roi",coordinates:g,bbox:ur(g),areaPx:Ht(g)}),Y(!0),W()},[e,u,Y,W,J,Ce,we,Z.radius,Z.edgeDetail,Z.edgeSmoothing,Z.clickSelectRoi,c]),Ae=h.useCallback((m,g)=>{const M=Ue(m,g);if(!pr(M))return;const C=m==="stamp-rectangle-4096px"?"patch":"roi",I={tool:m,intent:C,coordinates:M,bbox:ur(M),areaPx:Ht(M)};u?.(I),C==="patch"&&l&&l(I)},[Ue,u,l]),tt=h.useCallback((m,g,M)=>{const C=cr*cr,I=m.screenPoints[m.screenPoints.length-1];if(!I){m.points.push(g),m.screenPoints.push(M),m.current=g;return}const me=M[0]-I[0],H=M[1]-I[1];me*me+H*H>=C?(m.points.push(g),m.screenPoints.push(M)):(m.points[m.points.length-1]=g,m.screenPoints[m.screenPoints.length-1]=M),m.current=g},[]),It=h.useCallback(m=>{if(!ae||e==="cursor"||m.button!==0)return;const g=Me(m);if(!g)return;const M=Pe(m);if(!M)return;if(m.preventDefault(),m.stopPropagation(),zt(e)){const me=de.current;me.stampCenter=g,Ae(e,g),W();return}const C=V.current;C&&C.setPointerCapture(m.pointerId);const I=de.current;I.isDrawing=!0,I.pointerId=m.pointerId,I.start=g,I.current=g,I.cursor=g,I.cursorScreen=M,I.points=e==="freehand"||e==="brush"?[g]:[],I.screenPoints=e==="brush"?[M]:[],W()},[ae,e,Me,Pe,Ae,W]),nt=h.useCallback(m=>{if(!ae||e==="cursor")return;const g=Me(m);if(!g)return;const M=Pe(m);if(!M)return;const C=de.current;if(C.cursor=g,C.cursorScreen=M,zt(e)){C.stampCenter=g,m.preventDefault(),m.stopPropagation(),W();return}if(e==="brush"){if(!C.isDrawing||C.pointerId!==m.pointerId){W();return}m.preventDefault(),m.stopPropagation(),tt(C,g,M),W();return}if(!(!C.isDrawing||C.pointerId!==m.pointerId)){if(m.preventDefault(),m.stopPropagation(),e==="freehand"){const I=a.current,me=Math.max(1e-6,I?.getViewState?.().zoom??1),H=co/me,ie=H*H,$=C.points[C.points.length-1];if(!$)C.points.push(g);else{const re=g[0]-$[0],ye=g[1]-$[1];re*re+ye*ye>=ie&&C.points.push(g)}}else C.current=g;W()}},[ae,e,Me,Pe,W,a,tt]),Et=h.useCallback(m=>{const g=de.current;if(!g.isDrawing||g.pointerId!==m.pointerId)return;m.preventDefault(),m.stopPropagation();const M=Me(m),C=Pe(m);M&&(g.cursor=M,C&&(g.cursorScreen=C),e==="brush"?C&&tt(g,M,C):g.current=M);const I=V.current;I&&I.hasPointerCapture(m.pointerId)&&I.releasePointerCapture(m.pointerId),be()},[be,Me,Pe,e,tt]),vt=h.useCallback(()=>{const m=de.current;let g=!1;e==="brush"&&!m.isDrawing&&m.cursor&&(m.cursor=null,m.cursorScreen=null,g=!0),zt(e)&&m.stampCenter&&(m.stampCenter=null,g=!0),g&&W()},[e,W]);return h.useEffect(()=>{ne(),W();const m=V.current;if(!m)return;const g=new ResizeObserver(()=>{ne(),W()});return g.observe(m),()=>{g.disconnect()}},[ne,W]),h.useEffect(()=>{ae||Y(),W()},[ae,W,Y]),h.useEffect(()=>{Ve.current!==e&&(Ve.current=e,Y(),W())},[e,Y,W]),h.useEffect(()=>{W()},[f,v,oe,W]),h.useEffect(()=>{if(L)return L.current=W,()=>{L.current===W&&(L.current=null)}},[L,W]),h.useEffect(()=>{if(!ae)return;const m=g=>{g.key==="Escape"&&(Y(),W())};return window.addEventListener("keydown",m),()=>{window.removeEventListener("keydown",m)}},[ae,Y,W]),We.jsx("canvas",{ref:V,className:O,style:xe,onPointerDown:It,onPointerMove:nt,onPointerUp:Et,onPointerCancel:Et,onPointerLeave:vt,onContextMenu:m=>{ae&&m.preventDefault()},onWheel:m=>{if(!ae)return;const g=V.current,M=a.current;if(!g||typeof M?.zoomBy!="function")return;m.preventDefault(),m.stopPropagation();const C=g.getBoundingClientRect(),I=m.clientX-C.left,me=m.clientY-C.top;M.zoomBy(m.deltaY<0?ho:mo,I,me),W()}})}function br(e){return String(e??"").replace(/\/+$/,"")}function Gr(e){const t=String(e??"");return t.startsWith("/")?t:`/${t}`}function is(e){const t=br(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=br(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 os(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??"")})):[],d=Gr(c),f=is(t),y=r?(b,w,x)=>`${f}${d}/${b}/${x}_${w}.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 vn(e,t,n,r){if(e.tileUrlBuilder)return e.tileUrlBuilder(t,n,r);const i=Gr(e.tilePath);return`${e.tileBaseUrl}${i}/${t}/${r}_${n}.webp`}const Fe={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 yr(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,d=c/Math.max(1e-6,l),f=n*d,y=r*d;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 Ot(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 ss={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 qr({source:e,projectorRef:t,authToken:n="",options:r,invalidateRef:i,className:o,style:s}){const a=h.useRef(null),c=h.useRef(null),u=h.useRef(null),l=h.useRef({active:!1,pointerId:null}),d=h.useRef(null),f=h.useRef(!1),y=mt(r?.width,Fe.width,64),b=mt(r?.height,Fe.height,48),w=h.useMemo(()=>{const v=Math.max(1,e.width),P=Math.max(1,e.height),N=v/P,ce=y/b;let G,pe;return N>ce?(G=y,pe=y/N):(pe=b,G=b*N),{x:(y-G)/2,y:(b-pe)/2,w:G,h:pe}},[e.width,e.height,y,b]),x=mt(r?.margin,Fe.margin,0),R=mt(r?.borderRadius,Fe.borderRadius,0),E=mt(r?.borderWidth,Fe.borderWidth,0),X=Math.max(1,Math.round(mt(r?.maxThumbnailTiles,Fe.maxThumbnailTiles,1))),A=r?.backgroundColor||Fe.backgroundColor,F=r?.borderColor||Fe.borderColor,K=r?.viewportBorderColor||Fe.viewportBorderColor,oe=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:Fe.viewportBorderStyle,Q=r?.viewportFillColor??Fe.viewportFillColor,ee=r?.interactive??Fe.interactive,se=r?.showThumbnail??Fe.showThumbnail,ge=r?.position||Fe.position,Te=r?.onClose,_=r?.closeIcon,L=r?.closeButtonStyle,O=h.useMemo(()=>{const v={};return ge==="top-left"||ge==="bottom-left"?v.left=x:v.right=x,ge==="top-left"||ge==="top-right"?v.top=x:v.bottom=x,{position:"absolute",...v,width:y,height:b,borderRadius:R,overflow:"hidden",zIndex:4,pointerEvents:ee?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[x,ge,y,b,R,ee,s]),D=h.useCallback(()=>{const v=a.current;if(!v)return;const P=v.getContext("2d");if(!P)return;const N=y,ce=b,G=Math.max(1,window.devicePixelRatio||1),pe=Math.max(1,Math.round(N*G)),Se=Math.max(1,Math.round(ce*G));(v.width!==pe||v.height!==Se)&&(v.width=pe,v.height=Se),P.setTransform(1,0,0,1,0,0),P.clearRect(0,0,v.width,v.height),P.setTransform(G,0,0,G,0,0),P.fillStyle=A,P.fillRect(0,0,N,ce);const{x:le,y:q,w:he,h:te}=w,ue=c.current;ue&&P.drawImage(ue,le,q,he,te),P.strokeStyle=F,P.lineWidth=E,P.strokeRect(E*.5,E*.5,N-E,ce-E);const Z=t.current,xe=Z?.getViewBounds?.(),ne=Z?.getViewCorners?.(),J=Ot(xe)?xe:Ot(u.current)?u.current:null;if(!J)return;u.current=J;const Ce=he/Math.max(1,e.width),we=te/Math.max(1,e.height),Ge=Array.isArray(ne)&&ne.length>=4&&ne.every(be=>Array.isArray(be)&&be.length>=2&&Number.isFinite(be[0])&&Number.isFinite(be[1]))?ne:null,Ue=oe==="dash";if(Ge){const be=Ge.map(Ae=>[le+Ae[0]*Ce,q+Ae[1]*we]);P.save(),P.beginPath(),P.rect(le,q,he,te),P.clip(),P.beginPath();for(let Ae=0;Ae<be.length;Ae+=1)Ae===0?P.moveTo(be[Ae][0],be[Ae][1]):P.lineTo(be[Ae][0],be[Ae][1]);P.closePath(),P.fillStyle=Q,P.fill(),P.strokeStyle=K,P.lineWidth=2.25,Ue?yr(P,be,4,3):P.stroke(),P.restore();return}const ve=k(le+J[0]*Ce,le,le+he),De=k(q+J[1]*we,q,q+te),W=k(le+J[2]*Ce,le,le+he),Y=k(q+J[3]*we,q,q+te),Me=Math.max(1,W-ve),Pe=Math.max(1,Y-De);if(P.fillStyle=Q,P.fillRect(ve,De,Me,Pe),P.strokeStyle=K,P.lineWidth=2.25,Ue){const be=[[ve+.5,De+.5],[ve+.5+Math.max(1,Me-1),De+.5],[ve+.5+Math.max(1,Me-1),De+.5+Math.max(1,Pe-1)],[ve+.5,De+.5+Math.max(1,Pe-1)]];yr(P,be,4,3)}else P.strokeRect(ve+.5,De+.5,Math.max(1,Me-1),Math.max(1,Pe-1))},[y,b,w,A,F,E,t,e.width,e.height,Q,K,oe]),V=h.useCallback(()=>{f.current||(f.current=!0,d.current=requestAnimationFrame(()=>{f.current=!1,d.current=null,D()}))},[D]),Le=h.useCallback((v,P)=>{const N=a.current;if(!N)return null;const ce=N.getBoundingClientRect();if(!ce.width||!ce.height)return null;const G=ce.width/y,pe=ce.height/b,Se=w.x*G,le=w.y*pe,q=w.w*G,he=w.h*pe,te=k((v-ce.left-Se)/q,0,1),ue=k((P-ce.top-le)/he,0,1);return[te*e.width,ue*e.height]},[e.width,e.height,y,b,w]),Re=h.useCallback((v,P)=>{const N=t.current;if(!N)return;if(N.setViewCenter){N.setViewCenter(v,P),V();return}const ce=N.getViewBounds?.(),G=Ot(ce)?ce:Ot(u.current)?u.current:null;if(!G)return;const pe=Math.max(1e-6,G[2]-G[0]),Se=Math.max(1e-6,G[3]-G[1]);N.setViewState({offsetX:v-pe*.5,offsetY:P-Se*.5}),V()},[t,V]),Ve=h.useCallback(v=>{if(!ee||v.button!==0)return;const P=a.current;if(!P)return;const N=Le(v.clientX,v.clientY);N&&(v.preventDefault(),v.stopPropagation(),P.setPointerCapture(v.pointerId),l.current={active:!0,pointerId:v.pointerId},Re(N[0],N[1]))},[ee,Le,Re]),de=h.useCallback(v=>{const P=l.current;if(!P.active||P.pointerId!==v.pointerId)return;const N=Le(v.clientX,v.clientY);N&&(v.preventDefault(),v.stopPropagation(),Re(N[0],N[1]))},[Le,Re]),ae=h.useCallback(v=>{const P=l.current;if(!P.active||P.pointerId!==v.pointerId)return;const N=a.current;if(N&&N.hasPointerCapture(v.pointerId))try{N.releasePointerCapture(v.pointerId)}catch{}l.current={active:!1,pointerId:null},V()},[V]);return h.useEffect(()=>{let v=!1;c.current=null,V();const P=0,N=2**(e.maxTierZoom-P),ce=Math.ceil(e.width/N),G=Math.ceil(e.height/N),pe=Math.max(1,Math.ceil(ce/e.tileSize)),Se=Math.max(1,Math.ceil(G/e.tileSize)),le=pe*Se;if(!se||le>X)return;const q=document.createElement("canvas");q.width=Math.max(1,Math.round(w.w)),q.height=Math.max(1,Math.round(w.h));const he=q.getContext("2d");if(!he)return;he.fillStyle=A,he.fillRect(0,0,q.width,q.height);const te=[];for(let ue=0;ue<Se;ue+=1)for(let Z=0;Z<pe;Z+=1){const xe=Z*e.tileSize*N,ne=ue*e.tileSize*N,J=Math.min((Z+1)*e.tileSize,ce)*N,Ce=Math.min((ue+1)*e.tileSize,G)*N;te.push({url:vn(e,P,Z,ue),bounds:[xe,ne,J,Ce]})}return Promise.allSettled(te.map(async ue=>{const Z=!!n,xe=await fetch(ue.url,{headers:Z?{Authorization:n}:void 0});if(!xe.ok)throw new Error(`HTTP ${xe.status}`);const ne=await createImageBitmap(await xe.blob());return{tile:ue,bitmap:ne}})).then(ue=>{if(v){for(const ne of ue)ne.status==="fulfilled"&&ne.value.bitmap.close();return}const Z=q.width/Math.max(1,e.width),xe=q.height/Math.max(1,e.height);for(const ne of ue){if(ne.status!=="fulfilled")continue;const{tile:{bounds:J},bitmap:Ce}=ne.value,we=J[0]*Z,Ge=J[1]*xe,Ue=Math.max(1,(J[2]-J[0])*Z),ve=Math.max(1,(J[3]-J[1])*xe);he.drawImage(Ce,we,Ge,Ue,ve),Ce.close()}c.current=q,V()}),()=>{v=!0}},[e,n,w,A,se,X,V]),h.useEffect(()=>{V()},[V]),h.useEffect(()=>{if(i)return i.current=V,()=>{i.current===V&&(i.current=null)}},[i,V]),h.useEffect(()=>()=>{l.current={active:!1,pointerId:null},d.current!==null&&(cancelAnimationFrame(d.current),d.current=null),f.current=!1},[]),We.jsxs("div",{className:o,style:O,children:[We.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:Ve,onPointerMove:de,onPointerUp:ae,onPointerCancel:ae,onContextMenu:v=>{v.preventDefault()},onWheel:v=>{v.preventDefault(),v.stopPropagation()}}),Te&&We.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:v=>{v.stopPropagation(),Te()},style:L?{...L}:{...ss},children:_??"×"})]})}function as({imageWidth:e,imageHeight:t,tiles:n,viewState:r,className:i,style:o}){const s=h.useRef(null),a=h.useRef(null),c=h.useMemo(()=>({width:"100%",height:"100%",display:"block",...o}),[o]);return h.useEffect(()=>{const u=s.current;if(!u)return;const l=new Ir({canvas:u,imageWidth:e,imageHeight:t,initialViewState:r});return a.current=l,l.setTiles(n),()=>{l.destroy(),a.current=null}},[e,t]),h.useEffect(()=>{const u=a.current;u&&u.setTiles(n)},[n]),h.useEffect(()=>{const u=a.current;!u||!r||u.setViewState(r)},[r]),We.jsx("canvas",{ref:s,className:i,style:c})}function Tt(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return null;const n=Pt(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=ut(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,d=a?new Uint32Array(r):null;let f=0;for(let b=0;b<r;b+=1){const w=i[b*2],x=i[b*2+1];Zt(w,x,n)&&(c[f*2]=w,c[f*2+1]=x,u[f]=o[b],l&&(l[f]=s[b]),d&&(d[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)),d&&(y.ids=d.subarray(0,f)),y}function Hr(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return new Uint32Array(0);const n=Pt(t??[]);if(n.length===0)return new Uint32Array(0);const r=ut(e);if(r===0)return new Uint32Array(0);const i=e.positions,o=new Uint32Array(r);let s=0;for(let a=0;a<r;a+=1){const c=i[a*2],u=i[a*2+1];Zt(c,u,n)&&(o[s]=a,s+=1)}return o.subarray(0,s)}let Wt=null;const cs=`
|
|
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 as(){if(typeof navigator>"u")return!1;const e=navigator;return typeof e.gpu=="object"&&e.gpu!==null}function Hr(){if(!as())return null;const t=navigator.gpu;if(!t||typeof t!="object")return null;const n=t;return typeof n.requestAdapter!="function"?null:n}const Wt=globalThis.GPUShaderStage?.COMPUTE??4,ln=globalThis.GPUBufferUsage?.STORAGE??128,Yt=globalThis.GPUBufferUsage?.COPY_DST??8,cs=globalThis.GPUBufferUsage?.COPY_SRC??4,us=globalThis.GPUBufferUsage?.UNIFORM??64,ls=globalThis.GPUBufferUsage?.MAP_READ??1,fs=globalThis.GPUMapMode?.READ??1;async function ds(){const e=Hr();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 hs(){return Ot||(Ot=(async()=>{const e=Hr();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:Wt,buffer:{type:"read-only-storage"}},{binding:1,visibility:Wt,buffer:{type:"read-only-storage"}},{binding:2,visibility:Wt,buffer:{type:"storage"}},{binding:3,visibility:Wt,buffer:{type:"uniform"}}]}),i=n.createComputePipeline({layout:n.createPipelineLayout({bindGroupLayouts:[r]}),compute:{module:n.createShaderModule({code:ss}),entryPoint:"main"}});return{device:n,pipeline:i,bindGroupLayout:r}})(),Ot)}function Xt(e,t){return Math.ceil(e/t)*t}async function $r(e,t,n){const r=await hs();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:Xt(a,4),usage:ln|Yt}),f=r.device.createBuffer({size:Xt(c,4),usage:ln|Yt}),b=r.device.createBuffer({size:Xt(u,4),usage:ln|cs}),g=r.device.createBuffer({size:16,usage:us|Yt}),y=r.device.createBuffer({size:Xt(u,4),usage:Yt|ls});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(g,0,new Uint32Array([s,o,0,0]));const x=r.device.createBindGroup({layout:r.bindGroupLayout,entries:[{binding:0,resource:{buffer:h}},{binding:1,resource:{buffer:f}},{binding:2,resource:{buffer:b}},{binding:3,resource:{buffer:g}}]}),R=r.device.createCommandEncoder(),v=R.beginComputePass();v.setPipeline(r.pipeline),v.setBindGroup(0,x),v.dispatchWorkgroups(Math.ceil(s/256)),v.end(),R.copyBufferToBuffer(b,0,y,0,u),r.device.queue.submit([R.finish()]),await y.mapAsync(fs);const O=y.getMappedRange(),P=new Uint32Array(O.slice(0));return y.unmap(),h.destroy(),f.destroy(),b.destroy(),g.destroy(),y.destroy(),P}async function Zr(e,t,n={}){const r=le(),i=n.bridgeToDraw===!0;if(!e||!e.count||!e.positions||!e.paletteIndices)return{data:null,meta:{mode:"hybrid-webgpu",durationMs:le()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}};const o=It(t??[]);if(o.length===0){const P={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return e.fillModes instanceof Uint8Array&&(P.fillModes=new Uint8Array(0)),e.ids instanceof Uint32Array&&(P.ids=new Uint32Array(0)),{data:P,meta:{mode:"hybrid-webgpu",durationMs:le()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const s=ut(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 P={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(P.fillModes=new Uint8Array(0)),c&&(P.ids=new Uint32Array(0)),{data:P,meta:{mode:"hybrid-webgpu",durationMs:le()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const u=new Float32Array(o.length*4);for(let P=0;P<o.length;P+=1){const U=P*4,H=o[P];u[U]=H.minX,u[U+1]=H.minY,u[U+2]=H.maxX,u[U+3]=H.maxY}let l=null,h=!1;try{l=await $r(e.positions,s,u),h=!!l}catch{l=null,h=!1}if(!l)return{data:Ct(e,t),meta:{mode:"hybrid-webgpu",durationMs:le()-r,usedWebGpu:!1,candidateCount:s,bridgedToDraw:!1}};let f=0;for(let P=0;P<s;P+=1)l[P]===1&&(f+=1);const b=new Uint32Array(f);if(f>0){let P=0;for(let U=0;U<s;U+=1)l[U]===1&&(b[P]=U,P+=1)}if(f===0){if(i){const U={count:s,positions:e.positions.subarray(0,s*2),paletteIndices:e.paletteIndices.subarray(0,s),drawIndices:new Uint32Array(0)};return a&&(U.fillModes=a.subarray(0,s)),c&&(U.ids=c.subarray(0,s)),{data:U,meta:{mode:"hybrid-webgpu",durationMs:le()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!0}}}const P={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(P.fillModes=new Uint8Array(0)),c&&(P.ids=new Uint32Array(0)),{data:P,meta:{mode:"hybrid-webgpu",durationMs:le()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const P=new Uint32Array(f);let U=0;for(let $=0;$<f;$+=1){const te=b[$]??0,ie=e.positions[te*2],ce=e.positions[te*2+1];$t(ie,ce,o)&&(P[U]=te,U+=1)}const H={count:s,positions:e.positions.subarray(0,s*2),paletteIndices:e.paletteIndices.subarray(0,s),drawIndices:P.subarray(0,U)};return a&&(H.fillModes=a.subarray(0,s)),c&&(H.ids=c.subarray(0,s)),{data:H,meta:{mode:"hybrid-webgpu",durationMs:le()-r,usedWebGpu:!0,candidateCount:f,bridgedToDraw:!0}}}const g=new Float32Array(f*2),y=new Uint16Array(f),x=a?new Uint8Array(f):null,R=c?new Uint32Array(f):null;let v=0;for(let P=0;P<f;P+=1){const U=b[P]??0,H=e.positions[U*2],$=e.positions[U*2+1];$t(H,$,o)&&(g[v*2]=H,g[v*2+1]=$,y[v]=e.paletteIndices[U],x&&(x[v]=a[U]),R&&(R[v]=c[U]),v+=1)}const O={count:v,positions:g.subarray(0,v*2),paletteIndices:y.subarray(0,v)};return x&&(O.fillModes=x.subarray(0,v)),R&&(O.ids=R.subarray(0,v)),{data:O,meta:{mode:"hybrid-webgpu",durationMs:le()-r,usedWebGpu:!0,candidateCount:f,bridgedToDraw:!1}}}class Kr{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 Kr(()=>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:bt&&bt.tagName.toUpperCase()==="SCRIPT"&&bt.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:le()-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:le()-t.startMs}})},rejectPending:(e,t)=>{e.reject(t)}});function ms(){Pt.terminate("worker terminated")}async function jr(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return{data:null,meta:{mode:"worker",durationMs:0}};const n=ut(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=le(),l=Pt.beginRequest({kind:"data",resolve:a,reject:c,startMs:u});if(!l){a({data:Ct(e,t),meta:{mode:"sync",durationMs:le()-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(b){const g=Pt.cancelRequest(l.id);g?g.reject(b):c(b)}})}async function gs(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return{indices:new Uint32Array(0),meta:{mode:"worker",durationMs:0}};const n=ut(e),r=e.positions.slice(0,n*2);return new Promise((i,o)=>{const s=le(),a=Pt.beginRequest({kind:"index",resolve:i,reject:o,startMs:s});if(!a){i({indices:qr(e,t),meta:{mode:"sync",durationMs:le()-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 ps=24,bs=1024,ws=4,Ht=-1;function Mt(e,t,n){return(e*73856093^t*19349663)>>>0&n}function ys(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))*ws;return Math.max(ps,Math.min(bs,o))}function Ss(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 xs(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=Ss(e.drawIndices??null,r),o=i?i.length:r;if(o===0)return null;const s=ys(e.sourceWidth,e.sourceHeight,o),a=1/s,c=new Int32Array(o),u=new Int32Array(o);let l=0;if(i)for(let A=0;A<o;A+=1){const B=i[A],Y=e.positions[B*2],W=e.positions[B*2+1];!Number.isFinite(Y)||!Number.isFinite(W)||(c[l]=Math.floor(Y*a),u[l]=Math.floor(W*a),l+=1)}else for(let A=0;A<r;A+=1){const B=e.positions[A*2],Y=e.positions[A*2+1];!Number.isFinite(B)||!Number.isFinite(Y)||(c[l]=Math.floor(B*a),u[l]=Math.floor(Y*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 b=f-1,g=new Int32Array(f*2),y=new Int32Array(f);g.fill(2147483647);let x=0;const R=new Int32Array(l);for(let A=0;A<l;A+=1){const B=c[A],Y=u[A];let W=Mt(B,Y,b);for(;;){const q=g[W*2];if(q===2147483647){if(g[W*2]=B,g[W*2+1]=Y,y[W]=1,R[A]=W,x+=1,x*4>f*3){const Le=f;f<<=1,b=f-1;const Ae=new Int32Array(f*2),Ge=new Int32Array(f);Ae.fill(2147483647);for(let fe=0;fe<Le;fe+=1){if(g[fe*2]===2147483647)continue;const ne=g[fe*2],I=g[fe*2+1];let E=Mt(ne,I,b);for(;Ae[E*2]!==2147483647;)E=E+1&b;Ae[E*2]=ne,Ae[E*2+1]=I,Ge[E]=y[fe]}for(g=Ae,y=Ge,W=Mt(B,Y,b);g[W*2]!==B||g[W*2+1]!==Y;)W=W+1&b;R[A]=W}break}if(q===B&&g[W*2+1]===Y){y[W]+=1,R[A]=W;break}W=W+1&b}}const v=new Int32Array(x*2),O=new Uint32Array(x),P=new Uint32Array(x),U=new Int32Array(f);U.fill(Ht);let H=0,$=0;for(let A=0;A<f;A+=1)g[A*2]!==2147483647&&(v[H*2]=g[A*2],v[H*2+1]=g[A*2+1],O[H]=$,P[H]=y[A],U[A]=H,$+=y[A],H+=1);const te=new Uint32Array(l),ie=new Uint32Array(x);if(ie.set(O),i)for(let A=0;A<l;A+=1){const B=U[R[A]];te[ie[B]]=i[A],ie[B]+=1}else{let A=0;for(let B=0;B<r;B+=1){const Y=e.positions[B*2],W=e.positions[B*2+1];if(!Number.isFinite(Y)||!Number.isFinite(W))continue;const q=U[R[A]];te[ie[q]]=B,ie[q]+=1,A+=1}}let ce=1;for(;ce<x*2;)ce<<=1;const be=ce-1,ge=new Int32Array(ce);ge.fill(Ht);for(let A=0;A<x;A+=1){const B=v[A*2],Y=v[A*2+1];let W=Mt(B,Y,be);for(;ge[W]!==Ht;)W=W+1&be;ge[W]=A}return{cellSize:s,safeCount:r,cellCount:x,hashCapacity:ce,hashTable:ge,cellKeys:v,cellOffsets:O,cellLengths:P,pointIndices:te}}function Jr(e,t,n){const{hashTable:r,cellKeys:i,hashMask:o}=e;let s=Mt(t,n,o);for(;;){const a=r[s];if(a===Ht)return-1;if(i[a*2]===t&&i[a*2+1]===n)return a;s=s+1&o}}function Ms(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 Kr(()=>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:bt&&bt.tagName.toUpperCase()==="SCRIPT"&&bt.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(Ms(e,t.pointData))},rejectPending:(e,t)=>{e.reject(t)}});function Ts(){wn.terminate("worker terminated")}function Rs(e,t){const n=ut(e);if(n<=0)return null;const r=e.positions.subarray(0,n*2),i=xs({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 Qr(e,t){if(!e||!e.positions||!e.paletteIndices)return null;const n=ut(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(Rs(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 As(e){const t=[];for(let n=0;n<e.length;n+=1){const r=e[n],i=It([Et(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 Cs(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 ei(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 b=f.length;for(let g=0;g<f.length;g+=1)f[g]<r||(b-=1);if(b===f.length)i=f;else if(b>0){const g=new Uint32Array(b);let y=0;for(let x=0;x<f.length;x+=1){const R=f[x];R>=r||(g[y]=R,y+=1)}i=g}else i=new Uint32Array(0)}const o=i?i.length:r,s=As(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 b=i?i[f]:f,g=e.positions[b*2],y=e.positions[b*2+1];let x=null;for(const O of s){let P=!1;for(const U of O.polygons)if(_r(g,y,U)){P=!0;break}P&&(!x||O.area<x.area)&&(x=O)}if(!x)continue;u+=1;const R=e.paletteIndices[b]??0,v=a.get(x.regionIndex)??new Map;v.set(R,(v.get(R)??0)+1),a.set(x.regionIndex,v),c.set(x.regionIndex,(c.get(x.regionIndex)??0)+1)}const l=n.includeEmptyRegions??!1,h=[];for(const f of s){const b=c.get(f.regionIndex)??0;if(!l&&b<=0)continue;const g=a.get(f.regionIndex)??new Map,y=Array.from(g.entries()).map(([x,R])=>({termId:Cs(x,n.paletteIndexToTermId),paletteIndex:x,count:R})).sort((x,R)=>R.count-x.count||x.paletteIndex-R.paletteIndex);h.push({regionId:f.regionId,regionIndex:f.regionIndex,totalCount:b,termCounts:y})}return{groups:h,inputPointCount:o,pointsInsideAnyRegion:u,unmatchedPointCount:Math.max(0,o-u)}}function Ps(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 ti{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:le()};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-le());this.timerId=window.setTimeout(()=>{this.timerId=null,this.pump()},n)}takeNextReadyQueueItem(){if(this.queue.length===0)return null;const t=le(),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=Ps(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:le()+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 Es(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 Is(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 vs(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 yn=.35,Sn=.5,_s=256,xn=[{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}],Fs=.1,Bs=5,Us=-100,Ls=100,Ds=2e3;function ni(e){return e*Math.PI/180}function Vt(e,t){return!e||!t?e===t:e.buffer===t.buffer&&e.byteOffset===t.byteOffset&&e.byteLength===t.byteLength}function Mn(e){return e.map(t=>({zoom:t.zoom,size:t.size}))}function yr(e){if(!e)return Mn(xn);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?Mn(xn):Array.from(t.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function ks(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 Ns(e,t){if(!Number.isFinite(e))return t[0]?.size??Sn;if(t.length===0)return Sn;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=N((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 Sr(e){return typeof e!="number"||!Number.isFinite(e)?1:N(e,Fs,Bs)}function fn(e){return typeof e!="number"||!Number.isFinite(e)?0:N(e,Us,Ls)}function xr(e){const t=fn(e?.brightness),n=fn(e?.contrast),r=fn(e?.saturation);return{brightness:t/200,contrast:n/100,saturation:r/100}}function ri(e){return e}function dn(e){return typeof e!="number"||!Number.isFinite(e)?0:N(e,0,Ds)}function Gt(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:Math.max(1e-6,e)}function hn(e){return typeof e=="function"?e:ri}function ii(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 oi(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 zs(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"?ii(n,t.clientX,t.clientY):null,n.classList.add("dragging"),n.setPointerCapture(t.pointerId))}function Os(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=ii(n,t.clientX,t.clientY),f=r.rotateLastAngleRad;if(r.rotateLastAngleRad=h,f!==null){const b=h-f,g=Math.atan2(Math.sin(b),Math.cos(b)),y=i.rotationDragSensitivityDegPerPixel/yn,x=o.getViewState();o.setViewState({rotationDeg:x.rotationDeg-g*180/Math.PI*y})}}else{const h=o.getViewState(),f=Math.max(1e-6,h.zoom),b=ni(h.rotationDeg),g=Math.cos(b),y=Math.sin(b),x=(u*g-l*y)/f,R=(u*y+l*g)/f;o.setViewState({offsetX:h.offsetX-x,offsetY:h.offsetY-R})}s(),a(),c()}function Ws(e,t,n){e.pointerId===n.pointerId&&oi(t,n)}function Ys(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 Xs(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 Vs(e,t){(t||e.ctrlKey||e.metaKey)&&e.preventDefault()}function _n(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=_n(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,b=l-s,g=t.height-l+s,y=h<=f?N(a,h,f):t.width*.5,x=b<=g?N(c,b,g):t.height*.5;e.setCenter(y,x)}function Gs(e,t){const n=Math.max(1e-6,e.getViewState().zoom),r=t.maxTierZoom+Math.log2(n);return N(Math.floor(r),0,t.maxTierZoom)}function qs(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function si(e,t,n){const r=_n(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],b=N(Math.floor(u/i/t.tileSize),0,a-1),g=N(Math.floor((h-1)/i/t.tileSize),0,a-1),y=N(Math.floor(l/i/t.tileSize),0,c-1),x=N(Math.floor((f-1)/i/t.tileSize),0,c-1);if(b>g||y>x)return[];const R=(u+h)*.5/i/t.tileSize,v=(l+f)*.5/i/t.tileSize,O=[];for(let P=y;P<=x;P+=1)for(let U=b;U<=g;U+=1){const H=U*t.tileSize*i,$=P*t.tileSize*i,te=Math.min((U+1)*t.tileSize,o)*i,ie=Math.min((P+1)*t.tileSize,s)*i,ce=U-R,be=P-v;O.push({key:`${n}/${U}/${P}`,tier:n,x:U,y:P,bounds:[H,$,te,ie],distance2:ce*ce+be*be,url:vn(t,n,U,P)})}return O.sort((P,U)=>P.distance2-U.distance2),O}function Hs(e,t){const n=Gs(e,t);return{tier:n,visible:si(e,t,n)}}function $s(e){e.interactionLocked||zs({event:e.event,canvas:e.canvas,state:e.state,config:{ctrlDragRotate:e.ctrlDragRotate,rotationDragSensitivityDegPerPixel:e.rotationDragSensitivityDegPerPixel},cancelViewAnimation:e.cancelViewAnimation})}function Zs(e){e.interactionLocked||Os({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 Ks(e){e.interactionLocked||Ws(e.event,e.canvas,e.state)}function js(e){if(e.interactionLocked){e.event.preventDefault();return}Ys({event:e.event,canvas:e.canvas,onZoomBy:e.onZoomBy})}function Js(e){e.interactionLocked||Xs({event:e.event,canvas:e.canvas,onZoomBy:e.onZoomBy})}function Qs(e){Vs(e.event,e.state.dragging)}function ea(e,t){oi(e,t)}function ta(e){return{pointerDown:t=>$s({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state,ctrlDragRotate:e.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:e.getRotationDragSensitivityDegPerPixel(),cancelViewAnimation:e.cancelViewAnimation}),pointerMove:t=>Zs({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=>Ks({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state}),wheel:t=>js({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,onZoomBy:e.zoomBy}),doubleClick:t=>Js({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,onZoomBy:e.zoomBy}),contextMenu:t=>Qs({event:t,canvas:e.canvas,state:e.state})}}function na(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 ra(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 ia(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=ra(t,i);i.close(),l&&(n.set(r.key,{key:r.key,texture:l,bounds:r.bounds,tier:r.tier,lastUsed:o}),na({gl:t,cache:n,maxCacheTiles:s}),u())}function oa(e,t){for(const[,n]of t)e.deleteTexture(n.texture)}function sa(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 aa(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()&&(oa(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 ca(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 ua(e,t){return t<=0?new Uint8Array(0):e.length<t?new Uint8Array(t):e.subarray(0,t)}function la(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 fa(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?ca(i.drawIndices,a):null,b=e.lastPointData,g=b?.fillModes instanceof Uint8Array,y=e.pointBuffersDirty||!b||b.count!==a||!Vt(b.positions,c)||!Vt(b.paletteIndices,u)||g!==s||s&&(!b?.fillModes||!Vt(b.fillModes,l)),x=e.pointBuffersDirty||h&&(!b?.drawIndices||!Vt(b.drawIndices,f))||!h&&!!b?.drawIndices,R={...e,lastPointData:{count:a,positions:c,paletteIndices:u,fillModes:l,drawIndices:h?f??void 0:void 0}};if(r||t.isContextLost())return R;const v=R.lastPointData;if(!v)return R;if(y){t.bindBuffer(t.ARRAY_BUFFER,n.posBuffer),t.bufferData(t.ARRAY_BUFFER,v.positions,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,n.termBuffer),t.bufferData(t.ARRAY_BUFFER,v.paletteIndices,t.STATIC_DRAW);const O=ua(R.zeroFillModes,a);t.bindBuffer(t.ARRAY_BUFFER,n.fillModeBuffer),t.bufferData(t.ARRAY_BUFFER,v.fillModes??O,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,null),R.zeroFillModes=O}return h&&x&&(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)),R.usePointIndices=h,R.pointCount=h?f?.length??0:v.count,(y||x)&&(R.pointBuffersDirty=!1),R}function da(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,pointSizePx:b,tileScheduler:g,getVisibleTiles:y,getVisibleTilesForTier:x,getViewBounds:R,intersectsBounds:v}=e;t.clearColor(.03,.06,.1,1),t.clear(t.COLOR_BUFFER_BIT);const{tier:O,visible:P}=y(),U=R(),H=new Set(P.map(B=>B.key));t.useProgram(s.program),t.bindVertexArray(s.vao),t.uniformMatrix3fv(s.uCamera,!1,n.getMatrix()),t.uniform1i(s.uTexture,0),t.uniform1f(s.uBrightness,c.brightness),t.uniform1f(s.uContrast,c.contrast),t.uniform1f(s.uSaturation,c.saturation);const $=[];for(const[,B]of i)H.has(B.key)||v(B.bounds,U)&&$.push(B);$.sort((B,Y)=>B.tier-Y.tier);for(const B of $)B.lastUsed=o,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,B.texture),t.uniform4f(s.uBounds,B.bounds[0],B.bounds[1],B.bounds[2],B.bounds[3]),t.drawArrays(t.TRIANGLE_STRIP,0,4);let te=0;const ie=[];for(const B of P){const Y=i.get(B.key);if(!Y){ie.push(B);continue}Y.lastUsed=o,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,Y.texture),t.uniform4f(s.uBounds,Y.bounds[0],Y.bounds[1],Y.bounds[2],Y.bounds[3]),t.drawArrays(t.TRIANGLE_STRIP,0,4),te+=1}const ce=ie.slice(),be=1e6,ge=[];O>0&&ge.push(O-1),O<r.maxTierZoom&&ge.push(O+1);for(const B of ge){const Y=x(B);for(const W of Y)i.has(W.key)||(W.distance2+=be,ce.push(W))}g.schedule(ce),t.bindTexture(t.TEXTURE_2D,null),t.bindVertexArray(null);let A=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.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),A=u),{tier:O,visible:P.length,rendered:te,points:A,fallback:$.length,cacheHits:te,cacheMisses:ie.length,drawCalls:$.length+te+(A>0?1:0)}}function Mr(e){const r=An(e,`#version 300 es
|
|
63
|
+
`;function us(){if(typeof navigator>"u")return!1;const e=navigator;return typeof e.gpu=="object"&&e.gpu!==null}function $r(){if(!us())return null;const t=navigator.gpu;if(!t||typeof t!="object")return null;const n=t;return typeof n.requestAdapter!="function"?null:n}const Yt=globalThis.GPUShaderStage?.COMPUTE??4,ln=globalThis.GPUBufferUsage?.STORAGE??128,Xt=globalThis.GPUBufferUsage?.COPY_DST??8,ls=globalThis.GPUBufferUsage?.COPY_SRC??4,fs=globalThis.GPUBufferUsage?.UNIFORM??64,ds=globalThis.GPUBufferUsage?.MAP_READ??1,hs=globalThis.GPUMapMode?.READ??1;async function ms(){const e=$r();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 gs(){return Wt||(Wt=(async()=>{const e=$r();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:Yt,buffer:{type:"read-only-storage"}},{binding:1,visibility:Yt,buffer:{type:"read-only-storage"}},{binding:2,visibility:Yt,buffer:{type:"storage"}},{binding:3,visibility:Yt,buffer:{type:"uniform"}}]}),i=n.createComputePipeline({layout:n.createPipelineLayout({bindGroupLayouts:[r]}),compute:{module:n.createShaderModule({code:cs}),entryPoint:"main"}});return{device:n,pipeline:i,bindGroupLayout:r}})(),Wt)}function Vt(e,t){return Math.ceil(e/t)*t}async function Zr(e,t,n){const r=await gs();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 d=r.device.createBuffer({size:Vt(a,4),usage:ln|Xt}),f=r.device.createBuffer({size:Vt(c,4),usage:ln|Xt}),y=r.device.createBuffer({size:Vt(u,4),usage:ln|ls}),b=r.device.createBuffer({size:16,usage:fs|Xt}),w=r.device.createBuffer({size:Vt(u,4),usage:Xt|ds});r.device.queue.writeBuffer(d,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 x=r.device.createBindGroup({layout:r.bindGroupLayout,entries:[{binding:0,resource:{buffer:d}},{binding:1,resource:{buffer:f}},{binding:2,resource:{buffer:y}},{binding:3,resource:{buffer:b}}]}),R=r.device.createCommandEncoder(),E=R.beginComputePass();E.setPipeline(r.pipeline),E.setBindGroup(0,x),E.dispatchWorkgroups(Math.ceil(s/256)),E.end(),R.copyBufferToBuffer(y,0,w,0,u),r.device.queue.submit([R.finish()]),await w.mapAsync(hs);const X=w.getMappedRange(),A=new Uint32Array(X.slice(0));return w.unmap(),d.destroy(),f.destroy(),y.destroy(),b.destroy(),w.destroy(),A}async function Kr(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=Pt(t??[]);if(o.length===0){const A={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return e.fillModes instanceof Uint8Array&&(A.fillModes=new Uint8Array(0)),e.ids instanceof Uint32Array&&(A.ids=new Uint32Array(0)),{data:A,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const s=ut(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 A={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(A.fillModes=new Uint8Array(0)),c&&(A.ids=new Uint32Array(0)),{data:A,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const u=new Float32Array(o.length*4);for(let A=0;A<o.length;A+=1){const F=A*4,K=o[A];u[F]=K.minX,u[F+1]=K.minY,u[F+2]=K.maxX,u[F+3]=K.maxY}let l=null,d=!1;try{l=await Zr(e.positions,s,u),d=!!l}catch{l=null,d=!1}if(!l)return{data:Tt(e,t),meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!1,candidateCount:s,bridgedToDraw:!1}};let f=0;for(let A=0;A<s;A+=1)l[A]===1&&(f+=1);const y=new Uint32Array(f);if(f>0){let A=0;for(let F=0;F<s;F+=1)l[F]===1&&(y[A]=F,A+=1)}if(f===0){if(i){const F={count:s,positions:e.positions.subarray(0,s*2),paletteIndices:e.paletteIndices.subarray(0,s),drawIndices:new Uint32Array(0)};return a&&(F.fillModes=a.subarray(0,s)),c&&(F.ids=c.subarray(0,s)),{data:F,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!0}}}const A={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(A.fillModes=new Uint8Array(0)),c&&(A.ids=new Uint32Array(0)),{data:A,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const A=new Uint32Array(f);let F=0;for(let oe=0;oe<f;oe+=1){const Q=y[oe]??0,ee=e.positions[Q*2],se=e.positions[Q*2+1];Zt(ee,se,o)&&(A[F]=Q,F+=1)}const K={count:s,positions:e.positions.subarray(0,s*2),paletteIndices:e.paletteIndices.subarray(0,s),drawIndices:A.subarray(0,F)};return a&&(K.fillModes=a.subarray(0,s)),c&&(K.ids=c.subarray(0,s)),{data:K,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!0,candidateCount:f,bridgedToDraw:!0}}}const b=new Float32Array(f*2),w=new Uint16Array(f),x=a?new Uint8Array(f):null,R=c?new Uint32Array(f):null;let E=0;for(let A=0;A<f;A+=1){const F=y[A]??0,K=e.positions[F*2],oe=e.positions[F*2+1];Zt(K,oe,o)&&(b[E*2]=K,b[E*2+1]=oe,w[E]=e.paletteIndices[F],x&&(x[E]=a[F]),R&&(R[E]=c[F]),E+=1)}const X={count:E,positions:b.subarray(0,E*2),paletteIndices:w.subarray(0,E)};return x&&(X.fillModes=x.subarray(0,E)),R&&(X.ids=R.subarray(0,E)),{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 Rt=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 ps(){Rt.terminate("worker terminated")}async function Jr(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return{data:null,meta:{mode:"worker",durationMs:0}};const n=ut(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=Rt.beginRequest({kind:"data",resolve:a,reject:c,startMs:u});if(!l){a({data:Tt(e,t),meta:{mode:"sync",durationMs:fe()-u}});return}const d={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(d,f)}catch(y){const b=Rt.cancelRequest(l.id);b?b.reject(y):c(y)}})}async function bs(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return{indices:new Uint32Array(0),meta:{mode:"worker",durationMs:0}};const n=ut(e),r=e.positions.slice(0,n*2);return new Promise((i,o)=>{const s=fe(),a=Rt.beginRequest({kind:"index",resolve:i,reject:o,startMs:s});if(!a){i({indices:Hr(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=Rt.cancelRequest(a.id);l?l.reject(u):o(u)}})}const ys=24,ws=1024,Ss=4,$t=-1;function St(e,t,n){return(e*73856093^t*19349663)>>>0&n}function xs(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))*Ss;return Math.max(ys,Math.min(ws,o))}function Ms(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 As(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=Ms(e.drawIndices??null,r),o=i?i.length:r;if(o===0)return null;const s=xs(e.sourceWidth,e.sourceHeight,o),a=1/s,c=new Int32Array(o),u=new Int32Array(o);let l=0;if(i)for(let _=0;_<o;_+=1){const L=i[_],O=e.positions[L*2],D=e.positions[L*2+1];!Number.isFinite(O)||!Number.isFinite(D)||(c[l]=Math.floor(O*a),u[l]=Math.floor(D*a),l+=1)}else for(let _=0;_<r;_+=1){const L=e.positions[_*2],O=e.positions[_*2+1];!Number.isFinite(L)||!Number.isFinite(O)||(c[l]=Math.floor(L*a),u[l]=Math.floor(O*a),l+=1)}if(l===0)return null;let d=Math.min(l,Math.max(64,l>>>3));(!Number.isFinite(d)||d<=0)&&(d=l);let f=1;for(;f<d*2;)f<<=1;let y=f-1,b=new Int32Array(f*2),w=new Int32Array(f);b.fill(2147483647);let x=0;const R=new Int32Array(l);for(let _=0;_<l;_+=1){const L=c[_],O=u[_];let D=St(L,O,y);for(;;){const V=b[D*2];if(V===2147483647){if(b[D*2]=L,b[D*2+1]=O,w[D]=1,R[_]=D,x+=1,x*4>f*3){const Le=f;f<<=1,y=f-1;const Re=new Int32Array(f*2),Ve=new Int32Array(f);Re.fill(2147483647);for(let de=0;de<Le;de+=1){if(b[de*2]===2147483647)continue;const ae=b[de*2],v=b[de*2+1];let P=St(ae,v,y);for(;Re[P*2]!==2147483647;)P=P+1&y;Re[P*2]=ae,Re[P*2+1]=v,Ve[P]=w[de]}for(b=Re,w=Ve,D=St(L,O,y);b[D*2]!==L||b[D*2+1]!==O;)D=D+1&y;R[_]=D}break}if(V===L&&b[D*2+1]===O){w[D]+=1,R[_]=D;break}D=D+1&y}}const E=new Int32Array(x*2),X=new Uint32Array(x),A=new Uint32Array(x),F=new Int32Array(f);F.fill($t);let K=0,oe=0;for(let _=0;_<f;_+=1)b[_*2]!==2147483647&&(E[K*2]=b[_*2],E[K*2+1]=b[_*2+1],X[K]=oe,A[K]=w[_],F[_]=K,oe+=w[_],K+=1);const Q=new Uint32Array(l),ee=new Uint32Array(x);if(ee.set(X),i)for(let _=0;_<l;_+=1){const L=F[R[_]];Q[ee[L]]=i[_],ee[L]+=1}else{let _=0;for(let L=0;L<r;L+=1){const O=e.positions[L*2],D=e.positions[L*2+1];if(!Number.isFinite(O)||!Number.isFinite(D))continue;const V=F[R[_]];Q[ee[V]]=L,ee[V]+=1,_+=1}}let se=1;for(;se<x*2;)se<<=1;const ge=se-1,Te=new Int32Array(se);Te.fill($t);for(let _=0;_<x;_+=1){const L=E[_*2],O=E[_*2+1];let D=St(L,O,ge);for(;Te[D]!==$t;)D=D+1≥Te[D]=_}return{cellSize:s,safeCount:r,cellCount:x,hashCapacity:se,hashTable:Te,cellKeys:E,cellOffsets:X,cellLengths:A,pointIndices:Q}}function Qr(e,t,n){const{hashTable:r,cellKeys:i,hashMask:o}=e;let s=St(t,n,o);for(;;){const a=r[s];if(a===$t)return-1;if(i[a*2]===t&&i[a*2+1]===n)return a;s=s+1&o}}function Ts(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 yn=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(Ts(e,t.pointData))},rejectPending:(e,t)=>{e.reject(t)}});function Rs(){yn.terminate("worker terminated")}function Cs(e,t){const n=ut(e);if(n<=0)return null;const r=e.positions.subarray(0,n*2),i=As({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 ei(e,t){if(!e||!e.positions||!e.paletteIndices)return null;const n=ut(e);return n<=0?null:new Promise((r,i)=>{const o={resolve:r,reject:i,pointData:e},s=yn.beginRequest(o);if(!s||!s.worker){r(Cs(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(d){const f=yn.cancelRequest(s.id);f?f.reject(d):i(d)}})}function Ps(e){const t=[];for(let n=0;n<e.length;n+=1){const r=e[n],i=Pt([Ct(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 Is(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 ti(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 w=0;for(let x=0;x<f.length;x+=1){const R=f[x];R>=r||(b[w]=R,w+=1)}i=b}else i=new Uint32Array(0)}const o=i?i.length:r,s=Ps(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],w=e.positions[y*2+1];let x=null;for(const X of s){let A=!1;for(const F of X.polygons)if(Fr(b,w,F)){A=!0;break}A&&(!x||X.area<x.area)&&(x=X)}if(!x)continue;u+=1;const R=e.paletteIndices[y]??0,E=a.get(x.regionIndex)??new Map;E.set(R,(E.get(R)??0)+1),a.set(x.regionIndex,E),c.set(x.regionIndex,(c.get(x.regionIndex)??0)+1)}const l=n.includeEmptyRegions??!1,d=[];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,w=Array.from(b.entries()).map(([x,R])=>({termId:Is(x,n.paletteIndexToTermId),paletteIndex:x,count:R})).sort((x,R)=>R.count-x.count||x.paletteIndex-R.paletteIndex);d.push({regionId:f.regionId,regionIndex:f.regionIndex,totalCount:y,termCounts:w})}return{groups:d,inputPointCount:o,pointsInsideAnyRegion:u,unmatchedPointCount:Math.max(0,o-u)}}function Es(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 ni{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=Es(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 vs(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 _s(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 Fs(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 wn=.35,Sn=.5,Bs=256,xn=[{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,Us=5,Ds=0,ks=1,Ns=-100,zs=100,Os=2e3;function ri(e){return e*Math.PI/180}function Gt(e,t){return!e||!t?e===t:e.buffer===t.buffer&&e.byteOffset===t.byteOffset&&e.byteLength===t.byteLength}function Mn(e){return e.map(t=>({zoom:t.zoom,size:t.size}))}function wr(e){if(!e)return Mn(xn);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?Mn(xn):Array.from(t.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function Ws(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 Ys(e,t){if(!Number.isFinite(e))return t[0]?.size??Sn;if(t.length===0)return Sn;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 Sr(e){return typeof e!="number"||!Number.isFinite(e)?1:k(e,Ls,Us)}function xr(e){return typeof e!="number"||!Number.isFinite(e)?0:k(e,Ds,ks)}function fn(e){return typeof e!="number"||!Number.isFinite(e)?0:k(e,Ns,zs)}function Mr(e){const t=fn(e?.brightness),n=fn(e?.contrast),r=fn(e?.saturation);return{brightness:t/200,contrast:n/100,saturation:r/100}}function ii(e){return e}function dn(e){return typeof e!="number"||!Number.isFinite(e)?0:k(e,0,Os)}function qt(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:Math.max(1e-6,e)}function hn(e){return typeof e=="function"?e:ii}function oi(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 si(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 Xs(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"?oi(n,t.clientX,t.clientY):null,n.classList.add("dragging"),n.setPointerCapture(t.pointerId))}function Vs(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 d=oi(n,t.clientX,t.clientY),f=r.rotateLastAngleRad;if(r.rotateLastAngleRad=d,f!==null){const y=d-f,b=Math.atan2(Math.sin(y),Math.cos(y)),w=i.rotationDragSensitivityDegPerPixel/wn,x=o.getViewState();o.setViewState({rotationDeg:x.rotationDeg-b*180/Math.PI*w})}}else{const d=o.getViewState(),f=Math.max(1e-6,d.zoom),y=ri(d.rotationDeg),b=Math.cos(y),w=Math.sin(y),x=(u*b-l*w)/f,R=(u*w+l*b)/f;o.setViewState({offsetX:d.offsetX-x,offsetY:d.offsetY-R})}s(),a(),c()}function Gs(e,t,n){e.pointerId===n.pointerId&&si(t,n)}function qs(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 Hs(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 $s(e,t){(t||e.ctrlKey||e.metaKey)&&e.preventDefault()}function _n(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 An(e,t){const n=_n(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,d=u-o,f=t.width-u+o,y=l-s,b=t.height-l+s,w=d<=f?k(a,d,f):t.width*.5,x=y<=b?k(c,y,b):t.height*.5;e.setCenter(w,x)}function Zs(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 Ks(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function ai(e,t,n){const r=_n(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],d=r[2],f=r[3],y=k(Math.floor(u/i/t.tileSize),0,a-1),b=k(Math.floor((d-1)/i/t.tileSize),0,a-1),w=k(Math.floor(l/i/t.tileSize),0,c-1),x=k(Math.floor((f-1)/i/t.tileSize),0,c-1);if(y>b||w>x)return[];const R=(u+d)*.5/i/t.tileSize,E=(l+f)*.5/i/t.tileSize,X=[];for(let A=w;A<=x;A+=1)for(let F=y;F<=b;F+=1){const K=F*t.tileSize*i,oe=A*t.tileSize*i,Q=Math.min((F+1)*t.tileSize,o)*i,ee=Math.min((A+1)*t.tileSize,s)*i,se=F-R,ge=A-E;X.push({key:`${n}/${F}/${A}`,tier:n,x:F,y:A,bounds:[K,oe,Q,ee],distance2:se*se+ge*ge,url:vn(t,n,F,A)})}return X.sort((A,F)=>A.distance2-F.distance2),X}function js(e,t){const n=Zs(e,t);return{tier:n,visible:ai(e,t,n)}}function Js(e){e.interactionLocked||Xs({event:e.event,canvas:e.canvas,state:e.state,config:{ctrlDragRotate:e.ctrlDragRotate,rotationDragSensitivityDegPerPixel:e.rotationDragSensitivityDegPerPixel},cancelViewAnimation:e.cancelViewAnimation})}function Qs(e){e.interactionLocked||Vs({event:e.event,canvas:e.canvas,state:e.state,config:{ctrlDragRotate:e.ctrlDragRotate,rotationDragSensitivityDegPerPixel:e.rotationDragSensitivityDegPerPixel},camera:e.camera,clampViewState:()=>An(e.camera,e.source),emitViewState:e.emitViewState,requestRender:e.requestRender})}function ea(e){e.interactionLocked||Gs(e.event,e.canvas,e.state)}function ta(e){if(e.interactionLocked){e.event.preventDefault();return}qs({event:e.event,canvas:e.canvas,onZoomBy:e.onZoomBy})}function na(e){e.interactionLocked||Hs({event:e.event,canvas:e.canvas,onZoomBy:e.onZoomBy})}function ra(e){$s(e.event,e.state.dragging)}function ia(e,t){si(e,t)}function oa(e){return{pointerDown:t=>Js({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state,ctrlDragRotate:e.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:e.getRotationDragSensitivityDegPerPixel(),cancelViewAnimation:e.cancelViewAnimation}),pointerMove:t=>Qs({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=>ea({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state}),wheel:t=>ta({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,onZoomBy:e.zoomBy}),doubleClick:t=>na({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,onZoomBy:e.zoomBy}),contextMenu:t=>ra({event:t,canvas:e.canvas,state:e.state})}}function sa(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 aa(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 ca(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=aa(t,i);i.close(),l&&(n.set(r.key,{key:r.key,texture:l,bounds:r.bounds,tier:r.tier,lastUsed:o}),sa({gl:t,cache:n,maxCacheTiles:s}),u())}function ua(e,t){for(const[,n]of t)e.deleteTexture(n.texture)}function la(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 fa(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()&&(ua(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 da(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 ha(e,t){return t<=0?new Uint8Array(0):e.length<t?new Uint8Array(t):e.subarray(0,t)}function ma(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 ga(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,d=i.drawIndices instanceof Uint32Array,f=d?da(i.drawIndices,a):null,y=e.lastPointData,b=y?.fillModes instanceof Uint8Array,w=e.pointBuffersDirty||!y||y.count!==a||!Gt(y.positions,c)||!Gt(y.paletteIndices,u)||b!==s||s&&(!y?.fillModes||!Gt(y.fillModes,l)),x=e.pointBuffersDirty||d&&(!y?.drawIndices||!Gt(y.drawIndices,f))||!d&&!!y?.drawIndices,R={...e,lastPointData:{count:a,positions:c,paletteIndices:u,fillModes:l,drawIndices:d?f??void 0:void 0}};if(r||t.isContextLost())return R;const E=R.lastPointData;if(!E)return R;if(w){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=ha(R.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),R.zeroFillModes=X}return d&&x&&(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)),R.usePointIndices=d,R.pointCount=d?f?.length??0:E.count,(w||x)&&(R.pointBuffersDirty=!1),R}function pa(e){const{gl:t,camera:n,source:r,cache:i,frameSerial:o,tileProgram:s,pointProgram:a,imageColorSettings:c,pointCount:u,usePointIndices:l,pointPaletteSize:d,pointStrokeScale:f,pointInnerFillOpacity:y,pointSizePx:b,tileScheduler:w,getVisibleTiles:x,getVisibleTilesForTier:R,getViewBounds:E,intersectsBounds:X}=e;t.clearColor(.03,.06,.1,1),t.clear(t.COLOR_BUFFER_BIT);const{tier:A,visible:F}=x(),K=E(),oe=new Set(F.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 Q=[];for(const[,O]of i)oe.has(O.key)||X(O.bounds,K)&&Q.push(O);Q.sort((O,D)=>O.tier-D.tier);for(const O of Q)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 ee=0;const se=[];for(const O of F){const D=i.get(O.key);if(!D){se.push(O);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),ee+=1}const ge=se.slice(),Te=1e6,_=[];A>0&&_.push(A-1),A<r.maxTierZoom&&_.push(A+1);for(const O of _){const D=R(O);for(const V of D)i.has(V.key)||(V.distance2+=Te,ge.push(V))}w.schedule(ge),t.bindTexture(t.TEXTURE_2D,null),t.bindVertexArray(null);let L=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,d),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),L=u),{tier:A,visible:F.length,rendered:ee,points:L,fallback:Q.length,cacheHits:ee,cacheMisses:se.length,drawCalls:Q.length+ee+(L>0?1:0)}}function Ar(e){const r=Rn(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=Ee(e,r,"uCamera"),o=Ee(e,r,"uBounds"),s=Ee(e,r,"uTexture"),a=Ee(e,r,"uBrightness"),c=Ee(e,r,"uContrast"),u=Ee(e,r,"uSaturation"),l=e.createVertexArray(),d=e.createBuffer();if(!l||!d)throw new Error("buffer allocation failed");e.bindVertexArray(l),e.bindBuffer(e.ARRAY_BUFFER,d),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:d,uCamera:i,uBounds:o,uTexture:s,uBrightness:a,uContrast:c,uSaturation:u}}function Tr(e){const r=Rn(e,`#version 300 es
|
|
109
109
|
precision highp float;
|
|
110
110
|
in vec2 aPosition;
|
|
111
111
|
in uint aTerm;
|
|
@@ -128,6 +128,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
128
128
|
uniform float uPaletteSize;
|
|
129
129
|
uniform float uPointSize;
|
|
130
130
|
uniform float uPointStrokeScale;
|
|
131
|
+
uniform float uPointInnerFillAlpha;
|
|
131
132
|
out vec4 outColor;
|
|
132
133
|
void main() {
|
|
133
134
|
vec2 pc = gl_PointCoord * 2.0 - 1.0;
|
|
@@ -141,19 +142,22 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
141
142
|
|
|
142
143
|
float aa = 1.5 / max(1.0, uPointSize);
|
|
143
144
|
float outerMask = 1.0 - smoothstep(1.0 - aa, 1.0 + aa, r);
|
|
144
|
-
float alpha = 0.0;
|
|
145
145
|
if (vFillMode != 0u) {
|
|
146
|
-
alpha = outerMask * color.a;
|
|
146
|
+
float alpha = outerMask * color.a;
|
|
147
|
+
if (alpha <= 0.001) discard;
|
|
148
|
+
outColor = vec4(color.rgb * alpha, alpha);
|
|
147
149
|
} else {
|
|
148
150
|
float s = uPointStrokeScale;
|
|
149
151
|
float ringWidth = clamp(3.0 * s / max(1.0, uPointSize), 0.12 * s, 0.62 * s);
|
|
150
152
|
float innerRadius = 1.0 - ringWidth;
|
|
151
153
|
float innerMask = smoothstep(innerRadius - aa, innerRadius + aa, r);
|
|
152
|
-
|
|
154
|
+
float ringAlpha = outerMask * innerMask * color.a;
|
|
155
|
+
float fillAlpha = outerMask * (1.0 - innerMask) * clamp(uPointInnerFillAlpha, 0.0, 1.0);
|
|
156
|
+
float alpha = ringAlpha + fillAlpha;
|
|
157
|
+
if (alpha <= 0.001) discard;
|
|
158
|
+
// Premultiplied alpha output: inner fill is black, so it only contributes alpha.
|
|
159
|
+
outColor = vec4(color.rgb * ringAlpha, alpha);
|
|
153
160
|
}
|
|
154
|
-
if (alpha <= 0.001) discard;
|
|
155
|
-
|
|
156
|
-
outColor = vec4(color.rgb * alpha, alpha);
|
|
157
|
-
}`),i=Be(e,r,"uCamera"),o=Be(e,r,"uPointSize"),s=Be(e,r,"uPointStrokeScale"),a=Be(e,r,"uPalette"),c=Be(e,r,"uPaletteSize"),u=e.createVertexArray(),l=e.createBuffer(),h=e.createBuffer(),f=e.createBuffer(),b=e.createBuffer(),g=e.createTexture();if(!u||!l||!h||!f||!b||!g)throw new Error("point buffer allocation failed");e.bindVertexArray(u),e.bindBuffer(e.ARRAY_BUFFER,l),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const y=e.getAttribLocation(r,"aPosition");if(y<0)throw new Error("point position attribute not found");e.enableVertexAttribArray(y),e.vertexAttribPointer(y,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,h),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const x=e.getAttribLocation(r,"aTerm");if(x<0)throw new Error("point term attribute not found");e.enableVertexAttribArray(x),e.vertexAttribIPointer(x,1,e.UNSIGNED_SHORT,0,0),e.bindBuffer(e.ARRAY_BUFFER,f),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const R=e.getAttribLocation(r,"aFillMode");if(R<0)throw new Error("point fill mode attribute not found");return e.enableVertexAttribArray(R),e.vertexAttribIPointer(R,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,g),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:u,posBuffer:l,termBuffer:h,fillModeBuffer:f,indexBuffer:b,paletteTexture:g,uCamera:i,uPointSize:o,uPointStrokeScale:s,uPalette:a,uPaletteSize:c}}function ai(e){e.animation=null,e.frame!==null&&(cancelAnimationFrame(e.frame),e.frame=null)}function ha(e){const{state:t,camera:n,target:r,durationMs:i,easing:o,onUpdate:s}=e,a=n.getViewState();ai(t),t.animation={startMs:le(),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,le()-u.startMs),h=u.durationMs<=0?1:N(l/u.durationMs,0,1);let f=h;try{f=u.easing(h)}catch{f=h}if(Number.isFinite(f)||(f=h),f=N(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 ma(e){const t=Math.max(e*.5,1e-6),n=Math.max(1,e*8);return{minZoom:t,maxZoom:Math.max(t,n)}}function ga(e,t,n){const r=ma(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 pa(e,t,n,r,i){const o=e.getViewState(),s={zoom:typeof r.zoom=="number"&&Number.isFinite(r.zoom)?N(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 ba(e,t,n,r,i){const o=Math.min(t/e.width,n/e.height),s=Number.isFinite(o)&&o>0?o:1,a=N(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 wa(e,t,n,r,i,o){const s=e.getViewState(),a=N(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,b=ni(s.rotationDeg),g=Math.cos(b),y=Math.sin(b),x=h/a*g-f/a*y,R=h/a*y+f/a*g,v=c-x,O=u-R;return{zoom:a,offsetX:v-l.width/(2*a),offsetY:O-l.height/(2*a)}}class ci{constructor(t,n,r={}){S(this,"canvas");S(this,"source");S(this,"gl");S(this,"camera",new Cr);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",yn);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",ri);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",Mn(xn));S(this,"pointStrokeScale",1);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):yn,this.pointSizeStops=yr(r.pointSizeByZoom),this.pointStrokeScale=Sr(r.pointStrokeScale),this.imageColorSettings=xr(r.imageColorSettings),this.minZoomOverride=Gt(r.minZoom),this.maxZoomOverride=Gt(r.maxZoom),this.viewTransitionDurationMs=dn(r.viewTransition?.duration),this.viewTransitionEasing=hn(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=Mr(this.gl),this.pointProgram=Tr(this.gl),this.tileScheduler=new ti({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)=>ia({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=ta({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),Es(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=ga(this.fitZoom,this.minZoomOverride,this.maxZoomOverride);this.minZoom=t.minZoom,this.maxZoom=t.maxZoom}resolveTargetViewState(t){return pa(this.camera,this.minZoom,this.maxZoom,t,()=>Tn(this.camera,this.source))}cancelViewAnimation(){ai(this.viewAnimationState)}startViewAnimation(t,n,r){ha({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=Gt(t),i=Gt(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();gn(s,o)||this.applyViewStateAndRender(o)}setViewTransition(t){this.viewTransitionDurationMs=dn(t?.duration),this.viewTransitionEasing=hn(t?.easing)}setViewState(t,n){const r=this.resolveTargetViewState(t),i=this.camera.getViewState();if(gn(i,r))return;const o=dn(n?.duration??this.viewTransitionDurationMs),s=hn(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=la(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,t);this.applyPointBufferRuntime(n),!(!t||t.length===0)&&this.requestRender()}setPointData(t){const n=fa(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=yr(t);ks(this.pointSizeStops,n)||(this.pointSizeStops=n,this.requestRender())}setPointStrokeScale(t){const n=Sr(t);this.pointStrokeScale!==n&&(this.pointStrokeScale=n,this.requestRender())}setImageColorSettings(t){const n=xr(t),r=this.imageColorSettings;r.brightness===n.brightness&&r.contrast===n.contrast&&r.saturation===n.saturation||(this.imageColorSettings=n,this.requestRender())}cancelDrag(){ea(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=Ns(n,this.pointSizeStops);return N(r,Sn,_s)}fitToImage(t){const n=this.canvas.getBoundingClientRect(),r=Math.max(1,n.width||1),i=Math.max(1,n.height||1),o=ba(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=wa(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?le():0;this.frameSerial+=1;const n=da({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,pointSizePx:this.getPointSizeByZoom(),tileScheduler:this.tileScheduler,getVisibleTiles:()=>Hs(this.camera,this.source),getVisibleTilesForTier:r=>si(this.camera,this.source,r),getViewBounds:()=>_n(this.camera),intersectsBounds:qs});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:le()-t})}}requestRender(){this.frame!==null||this.destroyed||this.contextLost||this.gl.isContextLost()||(this.frame=requestAnimationFrame(()=>{this.frame=null,this.render()}))}resize(){vs(this.canvas,this.gl,this.camera),this.requestRender()}onWebGlContextLost(t){const n=sa({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=Mr(this.gl),this.pointProgram=Tr(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=aa({destroyed:this.destroyed,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),resizeObserver:this.resizeObserver,removeCanvasEventListeners:()=>Is(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 ya=6;function Rn(e,t){return e.id??t}function Sa(e,t,n,r,i,o){const s=i-n,a=o-r,c=s*s+a*a;if(c<=1e-12){const g=e-n,y=t-r;return g*g+y*y}const u=N(((e-n)*s+(t-r)*a)/c,0,1),l=n+s*u,h=r+a*u,f=e-l,b=t-h;return f*f+b*b}function Rr(e,t,n,r){for(let i=1;i<n.length;i+=1){const o=n[i-1],s=n[i];if(Sa(e,t,o[0],o[1],s[0],s[1])<=r)return!0}return!1}function xa(e,t,n,r){if(e<n.minX-r||e>n.maxX+r||t<n.minY-r||t>n.maxY+r)return!1;const i=r*r;if(Rr(e,t,n.outer,i))return!0;for(const o of n.holes)if(Rr(e,t,o,i))return!0;return!1}function Ma(e,t,n,r,i,o){if(!e.label||!e.labelAnchor)return!1;const s=Kt(n.worldToScreen(e.labelAnchor[0],e.labelAnchor[1]));if(!s)return!1;const c=En(e.label,r)+r.paddingX*2,u=r.fontSize+r.paddingY*2,l=N(s[0],c*.5+1,i-c*.5-1),h=N(s[1]-r.offsetY,u*.5+1,o-u*.5-1),f=l-c*.5,b=l+c*.5,g=h-u*.5,y=h+u*.5;return t[0]>=f&&t[0]<=b&&t[1]>=g&&t[1]<=y}function Ta(e){const t=[];for(let n=0;n<e.length;n+=1){const r=e[n],i=It([Et(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?Or(i):null})}return t}function Ra(e,t,n,r,i,o,s,a,c){const u=e[0],l=e[1],h=Math.max(1e-6,r.getViewState().zoom),f=Math.max(0,s),b=ya/h;for(let g=n.length-1;g>=0;g-=1){const y=n[g];for(const R of y.polygons)if(xa(u,l,R,b))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId};let x=Wr(i,o?.({region:y.region,regionId:y.regionId,regionIndex:y.regionIndex,zoom:h}));if(f>0&&(x={...x,offsetY:x.offsetY+f}),!!Ma(y,t,r,x,a,c))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId}}return null}const mn=[],Aa=[],Ca={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)},Pa=.65,Ea=4,Ia=180,Ar=20;function va(e){const t=N(e,0,1);return t*t*(3-2*t)}function _a({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:b=!0,pointData:g=null,pointPalette:y=null,pointSizeByZoom:x,pointStrokeScale:R,minZoom:v,maxZoom:O,viewTransition:P,roiRegions:U,roiPolygons:H,clipPointsToRois:$=!1,clipMode:te="worker",onClipStats:ie,onRoiPointGroups:ce,roiPaletteIndexToTermId:be,interactionLock:ge=!1,drawTool:A="cursor",stampOptions:B,brushOptions:Y,drawFillColor:W,regionStrokeStyle:q,regionStrokeHoverStyle:Le,regionStrokeActiveStyle:Ae,patchStrokeStyle:Ge,resolveRegionStrokeStyle:fe,resolveRegionLabelStyle:ne,overlayShapes:I,customLayers:E,patchRegions:z,regionLabelStyle:re,drawAreaTooltip:X,autoLiftRegionLabelAtMaxZoom:de=!1,onPointerWorldMove:ye,onPointHover:ee,onPointClick:Z,onRegionHover:oe,onRegionClick:he,activeRegionId:se,onActiveRegionChange:J,getCellByCoordinatesRef:pe,onDrawComplete:me,onPatchComplete:j,overviewMapConfig:Se,className:Ee,style:Ye}){const ke=Se?.show??!1,Ie=Se?.options,xe=m.useRef(null),_=m.useRef(null),Te=m.useRef(null),Ce=m.useRef(null),ve=m.useRef(r),we=m.useRef(i),Re=m.useRef(c),[et,tt]=m.useState(null),[Jt,wt]=m.useState(()=>se??null),nt=se!==void 0,d=nt?se??null:Jt,[w,T]=m.useState(null),[M,D]=m.useState(null),[ue,G]=m.useState(0),V=m.useRef(null),Q=m.useRef(null),ae=m.useRef(null),Me=m.useRef(0),Pe=m.useRef({rafId:null,startMs:0,from:0,to:0}),Ne=m.useRef(0),He=U??mn,lt=z??mn,rt=H??Aa,ft=(E?.length??0)>0,yt=m.useMemo(()=>({position:"relative",width:"100%",height:"100%",...Ye}),[Ye]),ui=m.useMemo(()=>({position:"absolute",top:8,left:8,zIndex:7,margin:0,padding:"8px 10px",maxWidth:"min(420px, 80%)",pointerEvents:"none",whiteSpace:"pre-wrap",lineHeight:1.35,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:11,color:"#cde6ff",background:"rgba(6, 12, 20, 0.82)",border:"1px solid rgba(173, 216, 255, 0.28)",borderRadius:8,boxShadow:"0 8px 22px rgba(0,0,0,0.35)",...u}),[u]),Xe=m.useMemo(()=>He.length>0?He:rt.length===0?mn:rt.map((p,C)=>({id:C,coordinates:p})),[He,rt]),$e=m.useMemo(()=>Ta(Xe),[Xe]),Fn=m.useMemo(()=>In(re),[re]),dt=m.useCallback(p=>{const C=N(p,0,Ar);Math.abs(Me.current-C)<1e-4||(Me.current=C,G(C))},[]),it=m.useCallback(()=>{const p=Pe.current;p.rafId!==null&&(cancelAnimationFrame(p.rafId),p.rafId=null)},[]),Qt=m.useCallback(p=>{const C=N(p,0,Ar),F=Pe.current,L=Me.current;if(Math.abs(L-C)<1e-4){it(),F.to=C,dt(C);return}it(),F.startMs=performance.now(),F.from=L,F.to=C;const k=K=>{const _e=Pe.current,ze=Math.max(0,K-_e.startMs),gt=N(ze/Ia,0,1),en=va(gt),tn=_e.from+(_e.to-_e.from)*en;if(dt(tn),Te.current?.(),gt>=1){_e.rafId=null,dt(_e.to);return}_e.rafId=requestAnimationFrame(k)};F.rafId=requestAnimationFrame(k)},[dt,it]),Ze=m.useCallback(p=>{const C=_.current;if(!C||typeof p!="number"||!Number.isFinite(p)){Qt(0);return}const F=Yr(de,p,C.getZoomRange());Qt(F)},[de,Qt]),ot=m.useMemo(()=>Xe.map(p=>Et(p.coordinates)).filter(p=>p!=null),[Xe]),[st,vt]=m.useState(g);m.useEffect(()=>{const p=++Ne.current;let C=!1;if(!$)return vt(g),()=>{C=!0};if(!g||!g.count||!g.positions||!g.paletteIndices)return vt(null),()=>{C=!0};if(ot.length===0)return vt(Ca),ie?.({mode:te,durationMs:0,inputCount:g.count,outputCount:0,polygonCount:0}),()=>{C=!0};const F=(k,K)=>{if(C||p!==Ne.current)return;const _e=g.count,ze=k?.drawIndices?k.drawIndices.length:k?.count??0;vt(k),ie?.({mode:K.mode,durationMs:K.durationMs,inputCount:_e,outputCount:ze,polygonCount:ot.length,usedWebGpu:K.usedWebGpu,candidateCount:K.candidateCount,bridgedToDraw:K.bridgedToDraw})};return(async()=>{if(te==="sync"){const k=performance.now(),K=Ct(g,ot);F(K,{mode:"sync",durationMs:performance.now()-k});return}if(te==="hybrid-webgpu"){const k=await Zr(g,ot,{bridgeToDraw:!0});F(k.data,{mode:k.meta.mode,durationMs:k.meta.durationMs,usedWebGpu:k.meta.usedWebGpu,candidateCount:k.meta.candidateCount,bridgedToDraw:k.meta.bridgedToDraw});return}try{const k=await jr(g,ot);F(k.data,{mode:k.meta.mode,durationMs:k.meta.durationMs})}catch{const k=performance.now(),K=Ct(g,ot);F(K,{mode:"sync",durationMs:performance.now()-k})}})(),()=>{C=!0}},[$,te,g,ot,ie]);const Bn=!!(ee||Z||pe),[qe,Un]=m.useState(null);m.useEffect(()=>{if(!Bn||!st){Un(null);return}let p=!1;return Qr(st,e).then(C=>{p||Un(C)}),()=>{p=!0}},[Bn,st,e]);const at=m.useCallback(p=>{const C=_.current;if(!C||!qe)return null;const F=Number(p[0]),L=Number(p[1]);if(!Number.isFinite(F)||!Number.isFinite(L))return null;const k=Math.max(1e-6,C.getViewState().zoom),K=C.getPointSizeByZoom(),ze=Math.max(Ea,K*Pa)/k;if(!Number.isFinite(ze)||ze<=0)return null;const{cellSize:gt,cellOffsets:en,cellLengths:tn,pointIndices:pi,positions:Wn,safeCount:bi}=qe,Yn=Math.floor(F/gt),Xn=Math.floor(L/gt),Bt=Math.max(1,Math.ceil(ze/gt)),wi=ze*ze;let Ut=-1,Vn=wi,Gn=0,qn=0;for(let nn=Yn-Bt;nn<=Yn+Bt;nn+=1)for(let rn=Xn-Bt;rn<=Xn+Bt;rn+=1){const on=Jr(qe,nn,rn);if(on<0)continue;const Hn=en[on],Si=Hn+tn[on];for(let sn=Hn;sn<Si;sn+=1){const Lt=pi[sn];if(Lt>=bi)continue;const $n=Wn[Lt*2],Zn=Wn[Lt*2+1],Kn=$n-F,jn=Zn-L,Jn=Kn*Kn+jn*jn;Jn>Vn||(Vn=Jn,Ut=Lt,Gn=$n,qn=Zn)}}if(Ut<0)return null;const yi=qe.ids?Number(qe.ids[Ut]):null;return{index:Ut,id:yi,coordinate:[F,L],pointCoordinate:[Gn,qn]}},[qe]),ht=m.useCallback((p,C)=>{if(!ee)return;const F=p?.index??null,L=p?.id??null;Q.current===F&&ae.current===L||(Q.current=F,ae.current=L,ee({index:F,id:L,coordinate:C,pointCoordinate:p?.pointCoordinate??null}))},[ee]),_t=m.useCallback((p,C)=>{if(!Z)return;const F=at(p);F&&Z({...F,button:C})},[Z,at]);m.useEffect(()=>{if(pe)return pe.current=at,()=>{pe.current===at&&(pe.current=null)}},[pe,at]),m.useEffect(()=>{nt&&wt(se??null)},[nt,se]);const Ke=m.useCallback(p=>{String(d)!==String(p)&&(nt||wt(p),J?.(p))},[d,nt,J]);m.useEffect(()=>{ve.current=r},[r]),m.useEffect(()=>{we.current=i},[i]),m.useEffect(()=>{Re.current=c,c||D(null)},[c]),m.useEffect(()=>()=>{it()},[it]);const Ln=m.useCallback(p=>{we.current?.(p),Re.current&&D(p)},[]),li=m.useMemo(()=>M?[`tier ${M.tier} | frame ${M.frameMs?.toFixed(2)??"-"} ms | drawCalls ${M.drawCalls??"-"}`,`tiles visible ${M.visible} | rendered ${M.rendered} | fallback ${M.fallback}`,`cache size ${M.cache} | hit ${M.cacheHits??"-"} | miss ${M.cacheMisses??"-"}`,`queue inflight ${M.inflight} | queued ${M.queued??"-"} | retries ${M.retries??"-"} | failed ${M.failed??"-"} | aborted ${M.aborted??"-"}`,`points ${M.points}`].join(`
|
|
158
|
-
`):"stats: waiting for first frame...",[M]);m.useEffect(()=>{!(d===null?!0:Xe.some((L,k)=>String(Rn(L,k))===String(d)))&&d!==null&&Ke(null);const C=V.current;!(C===null?!0:Xe.some((L,k)=>String(Rn(L,k))===String(C)))&&C!==null&&(V.current=null,tt(null),oe?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[Xe,d,oe,Ke]),m.useEffect(()=>{const p=Q.current;p!==null&&(qe&&p<qe.safeCount||(Q.current=null,ae.current=null,ee?.({index:null,id:null,coordinate:null,pointCoordinate:null})))},[qe,ee]);const Dn=m.useCallback(p=>{Ze(p.zoom),ft&&T(p);const C=ve.current;C&&C(p),Te.current?.(),Ce.current?.()},[ft,Ze]);m.useEffect(()=>{const p=_.current;p&&Ze(p.getViewState().zoom)},[Ze,v,O]),m.useEffect(()=>{A!=="cursor"&&V.current!==null&&(V.current=null,tt(null),oe?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[A,oe]),m.useEffect(()=>{A!=="cursor"&&Q.current!==null&&(Q.current=null,ae.current=null,ee?.({index:null,id:null,coordinate:null,pointCoordinate:null}))},[A,ee]);const je=m.useCallback((p,C)=>{const F=_.current;if(!F)return null;const L=F.screenToWorld(p,C);if(!Array.isArray(L)||L.length<2)return null;const k=Number(L[0]),K=Number(L[1]);return!Number.isFinite(k)||!Number.isFinite(K)?null:[k,K]},[]),kn=m.useCallback((p,C)=>{const F=_.current;if(!F)return null;const L=F.worldToScreen(p,C);return Kt(L)},[]),Ft=m.useCallback((p,C)=>{const F=xe.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 k=p-L.left,K=C-L.top;return!Number.isFinite(k)||!Number.isFinite(K)?null:{screenCoord:[k,K],canvasWidth:Math.max(1,L.width),canvasHeight:Math.max(1,L.height)}},[]),mt=m.useCallback((p,C,F,L)=>{const k=_.current;return k?Ra(p,C,$e,k,Fn,ne,ue,F,L):null},[$e,Fn,ne,ue]),Nn=m.useCallback(()=>{_.current?.requestRender(),Te.current?.(),Ce.current?.()},[]),zn=m.useMemo(()=>w??_.current?.getViewState()??null,[w]),On=m.useMemo(()=>{if(!e)return null;const p=zn;return p?{source:e,viewState:p,drawTool:A,interactionLock:ge,worldToScreen:kn,screenToWorld:je,requestRedraw:Nn}:null},[e,zn,A,ge,kn,je,Nn]),fi=m.useCallback(p=>{const C=p.target===xe.current,F=je(p.clientX,p.clientY);if(ye){const ze=!!F&&F[0]>=0&&F[1]>=0&&!!e&&F[0]<=e.width&&F[1]<=e.height;ye({coordinate:F,clientX:p.clientX,clientY:p.clientY,insideImage:ze})}if(A!=="cursor")return;if(!C){ht(null,null),V.current!==null&&(V.current=null,tt(null),oe?.({region:null,regionId:null,regionIndex:-1,coordinate:null}));return}if(!F){ht(null,null);return}if(ee&&ht(at(F),F),!$e.length)return;const L=Ft(p.clientX,p.clientY);if(!L)return;const k=mt(F,L.screenCoord,L.canvasWidth,L.canvasHeight),K=k?.regionId??null,_e=V.current;String(_e)!==String(K)&&(V.current=K,tt(K),oe?.({region:k?.region??null,regionId:K,regionIndex:k?.regionIndex??-1,coordinate:F}))},[A,$e,je,oe,ye,e,ht,at,ee,Ft,mt]),di=m.useCallback(()=>{ye?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1}),ht(null,null),V.current!==null&&(V.current=null,tt(null),oe?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[oe,ye,ht]),hi=m.useCallback(p=>{if(A!=="cursor"||p.target!==xe.current)return;const C=je(p.clientX,p.clientY);if(!C)return;if(_t(C,p.button),!$e.length){Ke(null);return}const F=Ft(p.clientX,p.clientY);if(!F)return;const L=mt(C,F.screenCoord,F.canvasWidth,F.canvasHeight);if(!L){Ke(null);return}const k=d!==null&&String(d)===String(L.regionId)?null:L.regionId;Ke(k),he?.({region:L.region,regionId:L.regionId,regionIndex:L.regionIndex,coordinate:C})},[A,$e,je,he,d,Ke,_t,Ft,mt]),mi=m.useCallback(p=>{if(A!=="brush"||Y?.clickSelectRoi!==!0||!$e.length)return!1;const C=_.current,F=xe.current;if(!C||!F)return!1;const L=F.getBoundingClientRect();if(L.width<=0||L.height<=0)return!1;const k=Kt(C.worldToScreen(p[0],p[1]));if(!k)return!1;const K=mt(p,k,L.width,L.height);if(!K)return!1;const _e=d!==null&&String(d)===String(K.regionId)?null:K.regionId;return Ke(_e),he?.({region:K.region,regionId:K.regionId,regionIndex:K.regionIndex,coordinate:p}),!0},[A,Y?.clickSelectRoi,$e,d,Ke,he,mt]),gi=m.useCallback(p=>{if(!Z||A!=="cursor"||p.target!==xe.current)return;p.preventDefault();const C=je(p.clientX,p.clientY);C&&_t(C,p.button)},[A,je,_t,Z]);return m.useEffect(()=>{const p=xe.current;if(!p||!e)return;const C=new ci(p,e,{onViewStateChange:Dn,onStats:Ln,onTileError:o,onContextLost:s,onContextRestored:a,authToken:f,imageColorSettings:n,ctrlDragRotate:b,pointSizeByZoom:x,pointStrokeScale:R,minZoom:v,maxZoom:O,viewTransition:P});return _.current=C,t&&C.setViewState(t),Ze(C.getViewState().zoom),C.setInteractionLock(ge),ft&&T(C.getViewState()),()=>{it(),dt(0),C.destroy(),_.current=null}},[e,Ln,o,s,a,f,b,x,R,Dn,ft,Ze,it,dt]),m.useEffect(()=>{const p=_.current;!p||!t||p.setViewState(t)},[t]),m.useEffect(()=>{const p=_.current;p&&p.fitToImage()},[l]),m.useEffect(()=>{const p=_.current;p&&p.resetRotation()},[h]),m.useEffect(()=>{const p=_.current;!p||!y||p.setPointPalette(y)},[y]),m.useEffect(()=>{const p=_.current;p&&p.setPointSizeByZoom(x)},[x]),m.useEffect(()=>{const p=_.current;p&&p.setPointStrokeScale(R)},[R]),m.useEffect(()=>{const p=_.current;p&&(p.setZoomRange(v,O),Ze(p.getViewState().zoom))},[v,O,Ze]),m.useEffect(()=>{const p=_.current;p&&p.setViewTransition(P)},[P]),m.useEffect(()=>{const p=_.current;p&&p.setImageColorSettings(n)},[n]),m.useEffect(()=>{const p=_.current;p&&p.setPointData(st)},[st]),m.useEffect(()=>{if(!ce)return;const C=ei($?st:g,Xe,{paletteIndexToTermId:be,includeEmptyRegions:!0});ce(C)},[ce,$,g,st,Xe,be]),m.useEffect(()=>{const p=_.current;p&&p.setInteractionLock(ge)},[ge]),We.jsxs("div",{className:Ee,style:yt,onPointerMove:fi,onPointerLeave:di,onClick:hi,onContextMenu:gi,children:[We.jsx("canvas",{ref:xe,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none",cursor:A==="cursor"&&et!==null?"pointer":ge?"crosshair":"grab"}}),e&&On&&Array.isArray(E)&&E.length>0?E.map((p,C)=>We.jsx("div",{className:p.className,style:{position:"absolute",inset:0,zIndex:p.zIndex??3,pointerEvents:p.pointerEvents??"none",...p.style},children:p.render(On)},p.id??C)):null,e?We.jsx(Xr,{tool:A,enabled:A!=="cursor",imageWidth:e.width,imageHeight:e.height,imageMpp:e.mpp,imageZoom:e.maxTierZoom,stampOptions:B,brushOptions:Y,drawFillColor:W,projectorRef:_,onBrushTap:mi,viewStateSignal:t,persistedRegions:Xe,patchRegions:lt,regionStrokeStyle:q,regionStrokeHoverStyle:Le,regionStrokeActiveStyle:Ae,patchStrokeStyle:Ge,resolveRegionStrokeStyle:fe,resolveRegionLabelStyle:ne,overlayShapes:I,hoveredRegionId:et,activeRegionId:d,regionLabelStyle:re,drawAreaTooltip:X,autoLiftRegionLabelAtMaxZoom:de,regionLabelAutoLiftOffsetPx:ue,invalidateRef:Te,onDrawComplete:me,onPatchComplete:j}):null,c?We.jsx("pre",{"data-open-plant-debug-overlay":!0,style:ui,children:li}):null,e&&ke&&We.jsx(Gr,{source:e,projectorRef:_,authToken:f,options:Ie,invalidateRef:Ce,className:Se?.className,style:Se?.style})]})}exports.DEFAULT_POINT_COLOR=Cn;exports.DrawLayer=Xr;exports.M1TileRenderer=Pr;exports.OverviewMap=Gr;exports.TileScheduler=ti;exports.TileViewerCanvas=os;exports.WsiTileRenderer=ci;exports.WsiViewerCanvas=_a;exports.buildPointSpatialIndexAsync=Qr;exports.buildTermPalette=vi;exports.calcScaleLength=Ei;exports.calcScaleResolution=Pn;exports.clamp=N;exports.closeRing=Ue;exports.computeRoiPointGroups=ei;exports.createCircle=bn;exports.createRectangle=jt;exports.filterPointDataByPolygons=Ct;exports.filterPointDataByPolygonsHybrid=Zr;exports.filterPointDataByPolygonsInWorker=jr;exports.filterPointIndicesByPolygons=qr;exports.filterPointIndicesByPolygonsInWorker=gs;exports.getWebGpuCapabilities=ds;exports.hexToRgba=Fr;exports.isSameViewState=gn;exports.lookupCellIndex=Jr;exports.normalizeImageInfo=rs;exports.prefilterPointsByBoundsWebGpu=$r;exports.terminatePointHitIndexWorker=Ts;exports.terminateRoiClipWorker=ms;exports.toBearerToken=Ii;exports.toRoiGeometry=Et;exports.toTileUrl=vn;
|
|
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(),d=e.createBuffer(),f=e.createBuffer(),y=e.createBuffer(),b=e.createBuffer(),w=e.createTexture();if(!l||!d||!f||!y||!b||!w)throw new Error("point buffer allocation failed");e.bindVertexArray(l),e.bindBuffer(e.ARRAY_BUFFER,d),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const x=e.getAttribLocation(r,"aPosition");if(x<0)throw new Error("point position attribute not found");e.enableVertexAttribArray(x),e.vertexAttribPointer(x,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,f),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const R=e.getAttribLocation(r,"aTerm");if(R<0)throw new Error("point term attribute not found");e.enableVertexAttribArray(R),e.vertexAttribIPointer(R,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,w),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:d,termBuffer:f,fillModeBuffer:y,indexBuffer:b,paletteTexture:w,uCamera:i,uPointSize:o,uPointStrokeScale:s,uPointInnerFillAlpha:a,uPalette:c,uPaletteSize:u}}function ci(e){e.animation=null,e.frame!==null&&(cancelAnimationFrame(e.frame),e.frame=null)}function ba(e){const{state:t,camera:n,target:r,durationMs:i,easing:o,onUpdate:s}=e,a=n.getViewState();ci(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),d=u.durationMs<=0?1:k(l/u.durationMs,0,1);let f=d;try{f=u.easing(d)}catch{f=d}if(Number.isFinite(f)||(f=d),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(),d>=1){t.animation=null,t.frame=null;return}t.frame=requestAnimationFrame(c)};t.frame=requestAnimationFrame(c)}function ya(e){const t=Math.max(e*.5,1e-6),n=Math.max(1,e*8);return{minZoom:t,maxZoom:Math.max(t,n)}}function wa(e,t,n){const r=ya(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 Sa(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 xa(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 Ma(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(),d=i-l.width*.5,f=o-l.height*.5,y=ri(s.rotationDeg),b=Math.cos(y),w=Math.sin(y),x=d/a*b-f/a*w,R=d/a*w+f/a*b,E=c-x,X=u-R;return{zoom:a,offsetX:E-l.width/(2*a),offsetY:X-l.height/(2*a)}}class ui{constructor(t,n,r={}){S(this,"canvas");S(this,"source");S(this,"gl");S(this,"camera",new Pr);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",wn);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",ii);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",Mn(xn));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):wn,this.pointSizeStops=wr(r.pointSizeByZoom),this.pointStrokeScale=Sr(r.pointStrokeScale),this.pointInnerFillOpacity=xr(r.pointInnerFillOpacity),this.imageColorSettings=Mr(r.imageColorSettings),this.minZoomOverride=qt(r.minZoom),this.maxZoomOverride=qt(r.maxZoom),this.viewTransitionDurationMs=dn(r.viewTransition?.duration),this.viewTransitionEasing=hn(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=Ar(this.gl),this.pointProgram=Tr(this.gl),this.tileScheduler=new ni({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)=>ca({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=oa({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),vs(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=wa(this.fitZoom,this.minZoomOverride,this.maxZoomOverride);this.minZoom=t.minZoom,this.maxZoom=t.maxZoom}resolveTargetViewState(t){return Sa(this.camera,this.minZoom,this.maxZoom,t,()=>An(this.camera,this.source))}cancelViewAnimation(){ci(this.viewAnimationState)}startViewAnimation(t,n,r){ba({state:this.viewAnimationState,camera:this.camera,target:t,durationMs:n,easing:r,onUpdate:()=>{An(this.camera,this.source),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}})}getPointBufferRuntime(){return{pointCount:this.pointCount,usePointIndices:this.usePointIndices,pointBuffersDirty:this.pointBuffersDirty,lastPointData:this.lastPointData,zeroFillModes:this.zeroFillModes,lastPointPalette:this.lastPointPalette,pointPaletteSize:this.pointPaletteSize}}applyPointBufferRuntime(t){this.pointCount=t.pointCount,this.usePointIndices=t.usePointIndices,this.pointBuffersDirty=t.pointBuffersDirty,this.lastPointData=t.lastPointData,this.zeroFillModes=t.zeroFillModes,this.lastPointPalette=t.lastPointPalette,this.pointPaletteSize=t.pointPaletteSize}applyViewStateAndRender(t,n=!0){n&&this.cancelViewAnimation(),this.camera.setViewState(t),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}setAuthToken(t){this.authToken=String(t??""),this.tileScheduler.setAuthToken(this.authToken)}setZoomRange(t,n){const r=qt(t),i=qt(n);if(this.minZoomOverride===r&&this.maxZoomOverride===i)return;this.minZoomOverride=r,this.maxZoomOverride=i,this.applyZoomBounds();const o=this.resolveTargetViewState({}),s=this.camera.getViewState();gn(s,o)||this.applyViewStateAndRender(o)}setViewTransition(t){this.viewTransitionDurationMs=dn(t?.duration),this.viewTransitionEasing=hn(t?.easing)}setViewState(t,n){const r=this.resolveTargetViewState(t),i=this.camera.getViewState();if(gn(i,r))return;const o=dn(n?.duration??this.viewTransitionDurationMs),s=hn(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=ma(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,t);this.applyPointBufferRuntime(n),!(!t||t.length===0)&&this.requestRender()}setPointData(t){const n=ga(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=wr(t);Ws(this.pointSizeStops,n)||(this.pointSizeStops=n,this.requestRender())}setPointStrokeScale(t){const n=Sr(t);this.pointStrokeScale!==n&&(this.pointStrokeScale=n,this.requestRender())}setPointInnerFillOpacity(t){const n=xr(t);this.pointInnerFillOpacity!==n&&(this.pointInnerFillOpacity=n,this.requestRender())}setImageColorSettings(t){const n=Mr(t),r=this.imageColorSettings;r.brightness===n.brightness&&r.contrast===n.contrast&&r.saturation===n.saturation||(this.imageColorSettings=n,this.requestRender())}cancelDrag(){ia(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=Ys(n,this.pointSizeStops);return k(r,Sn,Bs)}fitToImage(t){const n=this.canvas.getBoundingClientRect(),r=Math.max(1,n.width||1),i=Math.max(1,n.height||1),o=xa(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=Ma(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=pa({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=>ai(this.camera,this.source,r),getViewBounds:()=>_n(this.camera),intersectsBounds:Ks});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(){Fs(this.canvas,this.gl,this.camera),this.requestRender()}onWebGlContextLost(t){const n=la({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=Ar(this.gl),this.pointProgram=Tr(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=fa({destroyed:this.destroyed,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),resizeObserver:this.resizeObserver,removeCanvasEventListeners:()=>_s(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 Aa=6;function Tn(e,t){return e.id??t}function Ta(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,w=t-r;return b*b+w*w}const u=k(((e-n)*s+(t-r)*a)/c,0,1),l=n+s*u,d=r+a*u,f=e-l,y=t-d;return f*f+y*y}function Rr(e,t,n,r){for(let i=1;i<n.length;i+=1){const o=n[i-1],s=n[i];if(Ta(e,t,o[0],o[1],s[0],s[1])<=r)return!0}return!1}function Ra(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(Rr(e,t,n.outer,i))return!0;for(const o of n.holes)if(Rr(e,t,o,i))return!0;return!1}function Ca(e,t,n,r,i,o){if(!e.label||!e.labelAnchor)return!1;const s=jt(n.worldToScreen(e.labelAnchor[0],e.labelAnchor[1]));if(!s)return!1;const c=In(e.label,r)+r.paddingX*2,u=r.fontSize+r.paddingY*2,l=k(s[0],c*.5+1,i-c*.5-1),d=k(s[1]-r.offsetY,u*.5+1,o-u*.5-1),f=l-c*.5,y=l+c*.5,b=d-u*.5,w=d+u*.5;return t[0]>=f&&t[0]<=y&&t[1]>=b&&t[1]<=w}function Pa(e){const t=[];for(let n=0;n<e.length;n+=1){const r=e[n],i=Pt([Ct(r?.coordinates)]);if(i.length===0)continue;const o=typeof r?.label=="string"?r.label.trim():"";t.push({region:r,regionIndex:n,regionId:Tn(r,n),polygons:i,label:o,labelAnchor:o?Wr(i):null})}return t}function Ia(e,t,n,r,i,o,s,a,c){const u=e[0],l=e[1],d=Math.max(1e-6,r.getViewState().zoom),f=Math.max(0,s),y=Aa/d;for(let b=n.length-1;b>=0;b-=1){const w=n[b];for(const R of w.polygons)if(Ra(u,l,R,y))return{region:w.region,regionIndex:w.regionIndex,regionId:w.regionId};let x=Yr(i,o?.({region:w.region,regionId:w.regionId,regionIndex:w.regionIndex,zoom:d}));if(f>0&&(x={...x,offsetY:x.offsetY+f}),!!Ca(w,t,r,x,a,c))return{region:w.region,regionIndex:w.regionIndex,regionId:w.regionId}}return null}const mn=[],Ea=[],va={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)},_a=.65,Fa=4,Ba=180,Cr=20;function La(e){const t=k(e,0,1);return t*t*(3-2*t)}function Ua({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:d=0,authToken:f="",ctrlDragRotate:y=!0,pointData:b=null,pointPalette:w=null,pointSizeByZoom:x,pointStrokeScale:R,pointInnerFillOpacity:E,minZoom:X,maxZoom:A,viewTransition:F,roiRegions:K,roiPolygons:oe,clipPointsToRois:Q=!1,clipMode:ee="worker",onClipStats:se,onRoiPointGroups:ge,roiPaletteIndexToTermId:Te,interactionLock:_=!1,drawTool:L="cursor",stampOptions:O,brushOptions:D,drawFillColor:V,regionStrokeStyle:Le,regionStrokeHoverStyle:Re,regionStrokeActiveStyle:Ve,patchStrokeStyle:de,resolveRegionStrokeStyle:ae,resolveRegionLabelStyle:v,overlayShapes:P,customLayers:N,patchRegions:ce,regionLabelStyle:G,drawAreaTooltip:pe,autoLiftRegionLabelAtMaxZoom:Se=!1,onPointerWorldMove:le,onPointHover:q,onPointClick:he,onRegionHover:te,onRegionClick:ue,activeRegionId:Z,onActiveRegionChange:xe,getCellByCoordinatesRef:ne,onDrawComplete:J,onPatchComplete:Ce,overviewMapConfig:we,className:Ge,style:Ue}){const ve=we?.show??!1,De=we?.options,W=h.useRef(null),Y=h.useRef(null),Me=h.useRef(null),Pe=h.useRef(null),be=h.useRef(r),Ae=h.useRef(i),tt=h.useRef(c),[It,nt]=h.useState(null),[Et,vt]=h.useState(()=>Z??null),m=Z!==void 0,g=m?Z??null:Et,[M,C]=h.useState(null),[I,me]=h.useState(null),[H,ie]=h.useState(0),$=h.useRef(null),re=h.useRef(null),ye=h.useRef(null),Ie=h.useRef(0),ke=h.useRef({rafId:null,startMs:0,from:0,to:0}),rt=h.useRef(0),He=K??mn,pt=ce??mn,bt=oe??Ea,$e=(N?.length??0)>0,li=h.useMemo(()=>({position:"relative",width:"100%",height:"100%",...Ue}),[Ue]),fi=h.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=h.useMemo(()=>He.length>0?He:bt.length===0?mn:bt.map((p,T)=>({id:T,coordinates:p})),[He,bt]),Ze=h.useMemo(()=>Pa(Ye),[Ye]),Fn=h.useMemo(()=>En(G),[G]),lt=h.useCallback(p=>{const T=k(p,0,Cr);Math.abs(Ie.current-T)<1e-4||(Ie.current=T,ie(T))},[]),it=h.useCallback(()=>{const p=ke.current;p.rafId!==null&&(cancelAnimationFrame(p.rafId),p.rafId=null)},[]),Qt=h.useCallback(p=>{const T=k(p,0,Cr),B=ke.current,U=Ie.current;if(Math.abs(U-T)<1e-4){it(),B.to=T,lt(T);return}it(),B.startMs=performance.now(),B.from=U,B.to=T;const z=j=>{const _e=ke.current,ze=Math.max(0,j-_e.startMs),ht=k(ze/Ba,0,1),en=La(ht),tn=_e.from+(_e.to-_e.from)*en;if(lt(tn),Me.current?.(),ht>=1){_e.rafId=null,lt(_e.to);return}_e.rafId=requestAnimationFrame(z)};B.rafId=requestAnimationFrame(z)},[lt,it]),Ke=h.useCallback(p=>{const T=Y.current;if(!T||typeof p!="number"||!Number.isFinite(p)){Qt(0);return}const B=Xr(Se,p,T.getZoomRange());Qt(B)},[Se,Qt]),ot=h.useMemo(()=>Ye.map(p=>Ct(p.coordinates)).filter(p=>p!=null),[Ye]),[st,_t]=h.useState(b);h.useEffect(()=>{const p=++rt.current;let T=!1;if(!Q)return _t(b),()=>{T=!0};if(!b||!b.count||!b.positions||!b.paletteIndices)return _t(null),()=>{T=!0};if(ot.length===0)return _t(va),se?.({mode:ee,durationMs:0,inputCount:b.count,outputCount:0,polygonCount:0}),()=>{T=!0};const B=(z,j)=>{if(T||p!==rt.current)return;const _e=b.count,ze=z?.drawIndices?z.drawIndices.length:z?.count??0;_t(z),se?.({mode:j.mode,durationMs:j.durationMs,inputCount:_e,outputCount:ze,polygonCount:ot.length,usedWebGpu:j.usedWebGpu,candidateCount:j.candidateCount,bridgedToDraw:j.bridgedToDraw})};return(async()=>{if(ee==="sync"){const z=performance.now(),j=Tt(b,ot);B(j,{mode:"sync",durationMs:performance.now()-z});return}if(ee==="hybrid-webgpu"){const z=await Kr(b,ot,{bridgeToDraw:!0});B(z.data,{mode:z.meta.mode,durationMs:z.meta.durationMs,usedWebGpu:z.meta.usedWebGpu,candidateCount:z.meta.candidateCount,bridgedToDraw:z.meta.bridgedToDraw});return}try{const z=await Jr(b,ot);B(z.data,{mode:z.meta.mode,durationMs:z.meta.durationMs})}catch{const z=performance.now(),j=Tt(b,ot);B(j,{mode:"sync",durationMs:performance.now()-z})}})(),()=>{T=!0}},[Q,ee,b,ot,se]);const Bn=!!(q||he||ne),[qe,Ln]=h.useState(null);h.useEffect(()=>{if(!Bn||!st){Ln(null);return}let p=!1;return ei(st,e).then(T=>{p||Ln(T)}),()=>{p=!0}},[Bn,st,e]);const at=h.useCallback(p=>{const T=Y.current;if(!T||!qe)return null;const B=Number(p[0]),U=Number(p[1]);if(!Number.isFinite(B)||!Number.isFinite(U))return null;const z=Math.max(1e-6,T.getViewState().zoom),j=T.getPointSizeByZoom(),ze=Math.max(Fa,j*_a)/z;if(!Number.isFinite(ze)||ze<=0)return null;const{cellSize:ht,cellOffsets:en,cellLengths:tn,pointIndices:yi,positions:Wn,safeCount:wi}=qe,Yn=Math.floor(B/ht),Xn=Math.floor(U/ht),Lt=Math.max(1,Math.ceil(ze/ht)),Si=ze*ze;let Ut=-1,Vn=Si,Gn=0,qn=0;for(let nn=Yn-Lt;nn<=Yn+Lt;nn+=1)for(let rn=Xn-Lt;rn<=Xn+Lt;rn+=1){const on=Qr(qe,nn,rn);if(on<0)continue;const Hn=en[on],Mi=Hn+tn[on];for(let sn=Hn;sn<Mi;sn+=1){const Dt=yi[sn];if(Dt>=wi)continue;const $n=Wn[Dt*2],Zn=Wn[Dt*2+1],Kn=$n-B,jn=Zn-U,Jn=Kn*Kn+jn*jn;Jn>Vn||(Vn=Jn,Ut=Dt,Gn=$n,qn=Zn)}}if(Ut<0)return null;const xi=qe.ids?Number(qe.ids[Ut]):null;return{index:Ut,id:xi,coordinate:[B,U],pointCoordinate:[Gn,qn]}},[qe]),ft=h.useCallback((p,T)=>{if(!q)return;const B=p?.index??null,U=p?.id??null;re.current===B&&ye.current===U||(re.current=B,ye.current=U,q({index:B,id:U,coordinate:T,pointCoordinate:p?.pointCoordinate??null}))},[q]),Ft=h.useCallback((p,T)=>{if(!he)return;const B=at(p);B&&he({...B,button:T})},[he,at]);h.useEffect(()=>{if(ne)return ne.current=at,()=>{ne.current===at&&(ne.current=null)}},[ne,at]),h.useEffect(()=>{m&&vt(Z??null)},[m,Z]);const je=h.useCallback(p=>{String(g)!==String(p)&&(m||vt(p),xe?.(p))},[g,m,xe]);h.useEffect(()=>{be.current=r},[r]),h.useEffect(()=>{Ae.current=i},[i]),h.useEffect(()=>{tt.current=c,c||me(null)},[c]),h.useEffect(()=>()=>{it()},[it]);const Un=h.useCallback(p=>{Ae.current?.(p),tt.current&&me(p)},[]),di=h.useMemo(()=>I?[`tier ${I.tier} | frame ${I.frameMs?.toFixed(2)??"-"} ms | drawCalls ${I.drawCalls??"-"}`,`tiles visible ${I.visible} | rendered ${I.rendered} | fallback ${I.fallback}`,`cache size ${I.cache} | hit ${I.cacheHits??"-"} | miss ${I.cacheMisses??"-"}`,`queue inflight ${I.inflight} | queued ${I.queued??"-"} | retries ${I.retries??"-"} | failed ${I.failed??"-"} | aborted ${I.aborted??"-"}`,`points ${I.points}`].join(`
|
|
162
|
+
`):"stats: waiting for first frame...",[I]);h.useEffect(()=>{!(g===null?!0:Ye.some((U,z)=>String(Tn(U,z))===String(g)))&&g!==null&&je(null);const T=$.current;!(T===null?!0:Ye.some((U,z)=>String(Tn(U,z))===String(T)))&&T!==null&&($.current=null,nt(null),te?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[Ye,g,te,je]),h.useEffect(()=>{const p=re.current;p!==null&&(qe&&p<qe.safeCount||(re.current=null,ye.current=null,q?.({index:null,id:null,coordinate:null,pointCoordinate:null})))},[qe,q]);const Dn=h.useCallback(p=>{Ke(p.zoom),$e&&C(p);const T=be.current;T&&T(p),Me.current?.(),Pe.current?.()},[$e,Ke]);h.useEffect(()=>{const p=Y.current;p&&Ke(p.getViewState().zoom)},[Ke,X,A]),h.useEffect(()=>{L!=="cursor"&&$.current!==null&&($.current=null,nt(null),te?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[L,te]),h.useEffect(()=>{L!=="cursor"&&re.current!==null&&(re.current=null,ye.current=null,q?.({index:null,id:null,coordinate:null,pointCoordinate:null}))},[L,q]);const Je=h.useCallback((p,T)=>{const B=Y.current;if(!B)return null;const U=B.screenToWorld(p,T);if(!Array.isArray(U)||U.length<2)return null;const z=Number(U[0]),j=Number(U[1]);return!Number.isFinite(z)||!Number.isFinite(j)?null:[z,j]},[]),kn=h.useCallback((p,T)=>{const B=Y.current;if(!B)return null;const U=B.worldToScreen(p,T);return jt(U)},[]),Bt=h.useCallback((p,T)=>{const B=W.current;if(!B)return null;const U=B.getBoundingClientRect();if(!Number.isFinite(U.width)||!Number.isFinite(U.height)||U.width<=0||U.height<=0)return null;const z=p-U.left,j=T-U.top;return!Number.isFinite(z)||!Number.isFinite(j)?null:{screenCoord:[z,j],canvasWidth:Math.max(1,U.width),canvasHeight:Math.max(1,U.height)}},[]),dt=h.useCallback((p,T,B,U)=>{const z=Y.current;return z?Ia(p,T,Ze,z,Fn,v,H,B,U):null},[Ze,Fn,v,H]),Nn=h.useCallback(()=>{Y.current?.requestRender(),Me.current?.(),Pe.current?.()},[]),zn=h.useMemo(()=>M??Y.current?.getViewState()??null,[M]),On=h.useMemo(()=>{if(!e)return null;const p=zn;return p?{source:e,viewState:p,drawTool:L,interactionLock:_,worldToScreen:kn,screenToWorld:Je,requestRedraw:Nn}:null},[e,zn,L,_,kn,Je,Nn]),hi=h.useCallback(p=>{const T=p.target===W.current,B=Je(p.clientX,p.clientY);if(le){const ze=!!B&&B[0]>=0&&B[1]>=0&&!!e&&B[0]<=e.width&&B[1]<=e.height;le({coordinate:B,clientX:p.clientX,clientY:p.clientY,insideImage:ze})}if(L!=="cursor")return;if(!T){ft(null,null),$.current!==null&&($.current=null,nt(null),te?.({region:null,regionId:null,regionIndex:-1,coordinate:null}));return}if(!B){ft(null,null);return}if(q&&ft(at(B),B),!Ze.length)return;const U=Bt(p.clientX,p.clientY);if(!U)return;const z=dt(B,U.screenCoord,U.canvasWidth,U.canvasHeight),j=z?.regionId??null,_e=$.current;String(_e)!==String(j)&&($.current=j,nt(j),te?.({region:z?.region??null,regionId:j,regionIndex:z?.regionIndex??-1,coordinate:B}))},[L,Ze,Je,te,le,e,ft,at,q,Bt,dt]),mi=h.useCallback(()=>{le?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1}),ft(null,null),$.current!==null&&($.current=null,nt(null),te?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[te,le,ft]),gi=h.useCallback(p=>{if(L!=="cursor"||p.target!==W.current)return;const T=Je(p.clientX,p.clientY);if(!T)return;if(Ft(T,p.button),!Ze.length){je(null);return}const B=Bt(p.clientX,p.clientY);if(!B)return;const U=dt(T,B.screenCoord,B.canvasWidth,B.canvasHeight);if(!U){je(null);return}const z=g!==null&&String(g)===String(U.regionId)?null:U.regionId;je(z),ue?.({region:U.region,regionId:U.regionId,regionIndex:U.regionIndex,coordinate:T})},[L,Ze,Je,ue,g,je,Ft,Bt,dt]),pi=h.useCallback(p=>{if(L!=="brush"||D?.clickSelectRoi!==!0||!Ze.length)return!1;const T=Y.current,B=W.current;if(!T||!B)return!1;const U=B.getBoundingClientRect();if(U.width<=0||U.height<=0)return!1;const z=jt(T.worldToScreen(p[0],p[1]));if(!z)return!1;const j=dt(p,z,U.width,U.height);if(!j)return!1;const _e=g!==null&&String(g)===String(j.regionId)?null:j.regionId;return je(_e),ue?.({region:j.region,regionId:j.regionId,regionIndex:j.regionIndex,coordinate:p}),!0},[L,D?.clickSelectRoi,Ze,g,je,ue,dt]),bi=h.useCallback(p=>{if(!he||L!=="cursor"||p.target!==W.current)return;p.preventDefault();const T=Je(p.clientX,p.clientY);T&&Ft(T,p.button)},[L,Je,Ft,he]);return h.useEffect(()=>{const p=W.current;if(!p||!e)return;const T=new ui(p,e,{onViewStateChange:Dn,onStats:Un,onTileError:o,onContextLost:s,onContextRestored:a,authToken:f,imageColorSettings:n,ctrlDragRotate:y,pointSizeByZoom:x,pointStrokeScale:R,pointInnerFillOpacity:E,minZoom:X,maxZoom:A,viewTransition:F});return Y.current=T,t&&T.setViewState(t),Ke(T.getViewState().zoom),T.setInteractionLock(_),$e&&C(T.getViewState()),()=>{it(),lt(0),T.destroy(),Y.current=null}},[e,Un,o,s,a,f,y,Dn,$e,Ke,it,lt]),h.useEffect(()=>{const p=Y.current;!p||!t||p.setViewState(t)},[t]),h.useEffect(()=>{const p=Y.current;p&&p.fitToImage()},[l]),h.useEffect(()=>{const p=Y.current;p&&p.resetRotation()},[d]),h.useEffect(()=>{const p=Y.current;!p||!w||p.setPointPalette(w)},[w]),h.useEffect(()=>{const p=Y.current;p&&p.setPointSizeByZoom(x)},[x]),h.useEffect(()=>{const p=Y.current;p&&p.setPointStrokeScale(R)},[R]),h.useEffect(()=>{const p=Y.current;p&&p.setPointInnerFillOpacity(E)},[E]),h.useEffect(()=>{const p=Y.current;p&&(p.setZoomRange(X,A),Ke(p.getViewState().zoom))},[X,A,Ke]),h.useEffect(()=>{const p=Y.current;p&&p.setViewTransition(F)},[F]),h.useEffect(()=>{const p=Y.current;p&&p.setImageColorSettings(n)},[n]),h.useEffect(()=>{const p=Y.current;p&&p.setPointData(st)},[st]),h.useEffect(()=>{if(!ge)return;const T=ti(Q?st:b,Ye,{paletteIndexToTermId:Te,includeEmptyRegions:!0});ge(T)},[ge,Q,b,st,Ye,Te]),h.useEffect(()=>{const p=Y.current;p&&p.setInteractionLock(_)},[_]),We.jsxs("div",{className:Ge,style:li,onPointerMove:hi,onPointerLeave:mi,onClick:gi,onContextMenu:bi,children:[We.jsx("canvas",{ref:W,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none",cursor:L==="cursor"&&It!==null?"pointer":_?"crosshair":"grab"}}),e&&On&&Array.isArray(N)&&N.length>0?N.map((p,T)=>We.jsx("div",{className:p.className,style:{position:"absolute",inset:0,zIndex:p.zIndex??3,pointerEvents:p.pointerEvents??"none",...p.style},children:p.render(On)},p.id??T)):null,e?We.jsx(Vr,{tool:L,enabled:L!=="cursor",imageWidth:e.width,imageHeight:e.height,imageMpp:e.mpp,imageZoom:e.maxTierZoom,stampOptions:O,brushOptions:D,drawFillColor:V,projectorRef:Y,onBrushTap:pi,viewStateSignal:t,persistedRegions:Ye,patchRegions:pt,regionStrokeStyle:Le,regionStrokeHoverStyle:Re,regionStrokeActiveStyle:Ve,patchStrokeStyle:de,resolveRegionStrokeStyle:ae,resolveRegionLabelStyle:v,overlayShapes:P,hoveredRegionId:It,activeRegionId:g,regionLabelStyle:G,drawAreaTooltip:pe,autoLiftRegionLabelAtMaxZoom:Se,regionLabelAutoLiftOffsetPx:H,invalidateRef:Me,onDrawComplete:J,onPatchComplete:Ce}):null,c?We.jsx("pre",{"data-open-plant-debug-overlay":!0,style:fi,children:di}):null,e&&ve&&We.jsx(qr,{source:e,projectorRef:Y,authToken:f,options:De,invalidateRef:Pe,className:we?.className,style:we?.style})]})}exports.DEFAULT_POINT_COLOR=Cn;exports.DrawLayer=Vr;exports.M1TileRenderer=Ir;exports.OverviewMap=qr;exports.TileScheduler=ni;exports.TileViewerCanvas=as;exports.WsiTileRenderer=ui;exports.WsiViewerCanvas=Ua;exports.buildPointSpatialIndexAsync=ei;exports.buildTermPalette=Fi;exports.calcScaleLength=vi;exports.calcScaleResolution=Pn;exports.clamp=k;exports.closeRing=Be;exports.computeRoiPointGroups=ti;exports.createCircle=bn;exports.createRectangle=Jt;exports.filterPointDataByPolygons=Tt;exports.filterPointDataByPolygonsHybrid=Kr;exports.filterPointDataByPolygonsInWorker=Jr;exports.filterPointIndicesByPolygons=Hr;exports.filterPointIndicesByPolygonsInWorker=bs;exports.getWebGpuCapabilities=ms;exports.hexToRgba=Br;exports.isSameViewState=gn;exports.lookupCellIndex=Qr;exports.normalizeImageInfo=os;exports.prefilterPointsByBoundsWebGpu=Zr;exports.terminatePointHitIndexWorker=Rs;exports.terminateRoiClipWorker=ps;exports.toBearerToken=_i;exports.toRoiGeometry=Ct;exports.toTileUrl=vn;
|
|
159
163
|
//# sourceMappingURL=index.cjs.map
|