open-plant 1.3.6 → 1.3.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +8 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +3445 -2309
- package/dist/index.js.map +1 -1
- package/dist/types/react/draw-layer.d.ts +1 -1
- package/dist/types/react/draw-layer.d.ts.map +1 -1
- package/dist/types/wsi/brush-stroke.d.ts.map +1 -1
- package/package.json +4 -1
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var So=Object.defineProperty;var Eo=(t,e,n)=>e in t?So(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var E=(t,e,n)=>Eo(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Xt=require("react/jsx-runtime"),g=require("react");var Ce=typeof document<"u"?document.currentScript:null;function Tr(t,e,n){const r=t.createShader(e);if(!r)throw new Error("Failed to create shader.");if(t.shaderSource(r,n),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const o=t.getShaderInfoLog(r)??"unknown shader error";throw t.deleteShader(r),new Error(o)}return r}function er(t,e,n){const r=Tr(t,t.VERTEX_SHADER,e),i=Tr(t,t.FRAGMENT_SHADER,n),o=t.createProgram();if(!o)throw t.deleteShader(r),t.deleteShader(i),new Error("Failed to create program.");if(t.attachShader(o,r),t.attachShader(o,i),t.linkProgram(o),t.deleteShader(r),t.deleteShader(i),!t.getProgramParameter(o,t.LINK_STATUS)){const a=t.getProgramInfoLog(o)??"unknown link error";throw t.deleteProgram(o),new Error(a)}return o}function Tt(t,e,n){const r=t.getUniformLocation(e,n);if(!r)throw new Error(`Failed to get uniform location: ${n}`);return r}function Mo(t){const e=t.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,stencil:!1,preserveDrawingBuffer:!1,powerPreference:"high-performance"});if(!e)throw new Error("WebGL2 is not available.");return e}function Tn(t){return t*Math.PI/180}class Ei{constructor(){E(this,"viewportWidth",1);E(this,"viewportHeight",1);E(this,"viewState",{offsetX:0,offsetY:0,zoom:1,rotationDeg:0})}setViewport(e,n){this.viewportWidth=Math.max(1,e),this.viewportHeight=Math.max(1,n)}getViewportSize(){return{width:this.viewportWidth,height:this.viewportHeight}}setViewState(e){e.offsetX!==void 0&&(this.viewState.offsetX=e.offsetX),e.offsetY!==void 0&&(this.viewState.offsetY=e.offsetY),e.zoom!==void 0&&(this.viewState.zoom=Math.max(1e-4,e.zoom)),typeof e.rotationDeg=="number"&&Number.isFinite(e.rotationDeg)&&(this.viewState.rotationDeg=e.rotationDeg)}getViewState(){return{...this.viewState}}getCenter(){const e=Math.max(1e-6,this.viewState.zoom);return[this.viewState.offsetX+this.viewportWidth/(2*e),this.viewState.offsetY+this.viewportHeight/(2*e)]}setCenter(e,n){const r=Math.max(1e-6,this.viewState.zoom);this.viewState.offsetX=e-this.viewportWidth/(2*r),this.viewState.offsetY=n-this.viewportHeight/(2*r)}screenToWorld(e,n){const r=Math.max(1e-6,this.viewState.zoom),[i,o]=this.getCenter(),s=this.viewState.rotationDeg??0,a=(e-this.viewportWidth*.5)/r,u=(n-this.viewportHeight*.5)/r,c=Tn(s),f=Math.cos(c),l=Math.sin(c);return[i+a*f-u*l,o+a*l+u*f]}worldToScreen(e,n){const r=Math.max(1e-6,this.viewState.zoom),[i,o]=this.getCenter(),s=this.viewState.rotationDeg??0,a=e-i,u=n-o,c=Tn(s),f=Math.cos(c),l=Math.sin(c),h=a*f+u*l,d=-a*l+u*f;return[this.viewportWidth*.5+h*r,this.viewportHeight*.5+d*r]}getViewCorners(){const e=this.viewportWidth,n=this.viewportHeight;return[this.screenToWorld(0,0),this.screenToWorld(e,0),this.screenToWorld(e,n),this.screenToWorld(0,n)]}getMatrix(){const e=Math.max(1e-6,this.viewState.zoom),n=this.viewState.rotationDeg??0;if(n===0){const m=this.viewportWidth/e,p=this.viewportHeight/e,x=2/m,w=-2/p,M=-1-this.viewState.offsetX*x,N=1-this.viewState.offsetY*w;return new Float32Array([x,0,0,0,w,0,M,N,1])}const[r,i]=this.getCenter(),o=Tn(n),s=Math.cos(o),a=Math.sin(o),u=2*e*s/this.viewportWidth,c=2*e*a/this.viewportWidth,f=2*e*a/this.viewportHeight,l=-2*e*s/this.viewportHeight,h=-(u*r+c*i),d=-(f*r+l*i);return new Float32Array([u,f,0,c,l,0,h,d,1])}}const Ao=`#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
|
+
`,Ro=`#version 300 es
|
|
22
22
|
precision highp float;
|
|
23
23
|
|
|
24
24
|
in vec2 vUv;
|
|
@@ -29,7 +29,8 @@ out vec4 outColor;
|
|
|
29
29
|
void main() {
|
|
30
30
|
outColor = texture(uTexture, vUv);
|
|
31
31
|
}
|
|
32
|
-
`;class Dr{constructor(t){w(this,"canvas");w(this,"gl");w(this,"camera",new zr);w(this,"imageWidth");w(this,"imageHeight");w(this,"clearColor");w(this,"program");w(this,"vao");w(this,"quadBuffer");w(this,"uCameraLocation");w(this,"uBoundsLocation");w(this,"uTextureLocation");w(this,"resizeObserver");w(this,"tiles",[]);w(this,"frameId",null);w(this,"loadVersion",0);w(this,"destroyed",!1);w(this,"fitted",!1);w(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=zi(this.canvas),this.program=Bn(this.gl,Di,Oi);const n=this.gl.createVertexArray(),r=this.gl.createBuffer();if(!n||!r)throw new Error("Failed to create WebGL buffers.");this.vao=n,this.quadBuffer=r,this.gl.bindVertexArray(this.vao),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.quadBuffer);const i=new Float32Array([0,0,0,0,1,0,1,0,0,1,0,1,1,1,1,1]);this.gl.bufferData(this.gl.ARRAY_BUFFER,i,this.gl.STATIC_DRAW);const o=this.gl.getAttribLocation(this.program,"aUnit"),s=this.gl.getAttribLocation(this.program,"aUv");if(o<0||s<0)throw new Error("Failed to get attribute locations.");const a=4*Float32Array.BYTES_PER_ELEMENT;this.gl.enableVertexAttribArray(o),this.gl.vertexAttribPointer(o,2,this.gl.FLOAT,!1,a,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,a,2*Float32Array.BYTES_PER_ELEMENT),this.gl.bindVertexArray(null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.uCameraLocation=Pe(this.gl,this.program,"uCamera"),this.uBoundsLocation=Pe(this.gl,this.program,"uBounds"),this.uTextureLocation=Pe(this.gl,this.program,"uTexture"),t.initialViewState&&(this.controlledViewState=!0,this.camera.setViewState(t.initialViewState)),this.resizeObserver=new ResizeObserver(()=>{this.resize()}),this.resizeObserver.observe(this.canvas),this.resize()}async setTiles(t){if(this.destroyed)return;const n=++this.loadVersion,r=await Promise.all(t.map(async i=>await this.loadTile(i,n)));if(this.destroyed||n!==this.loadVersion){for(const i of r)i&&this.gl.deleteTexture(i.texture);return}this.disposeTiles(this.tiles),this.tiles=r.filter(i=>i!==null),this.requestRender()}setViewState(t){this.controlledViewState=!0,this.camera.setViewState(t),this.requestRender()}getViewState(){return this.camera.getViewState()}destroy(){this.destroyed||(this.destroyed=!0,this.loadVersion+=1,this.frameId!==null&&(cancelAnimationFrame(this.frameId),this.frameId=null),this.resizeObserver.disconnect(),this.disposeTiles(this.tiles),this.tiles=[],this.gl.deleteBuffer(this.quadBuffer),this.gl.deleteVertexArray(this.vao),this.gl.deleteProgram(this.program))}async loadTile(t,n){try{const r=await fetch(t.url);if(!r.ok)throw new Error(`Tile fetch failed: ${r.status} ${r.statusText}`);const i=await r.blob(),o=await createImageBitmap(i);if(this.destroyed||n!==this.loadVersion)return o.close(),null;const s=this.gl.createTexture();if(!s)throw o.close(),new Error("Failed to create tile texture.");return this.gl.bindTexture(this.gl.TEXTURE_2D,s),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,1),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),this.gl.bindTexture(this.gl.TEXTURE_2D,null),o.close(),{id:t.id,bounds:t.bounds,texture:s}}catch(r){return console.error(`[M1TileRenderer] tile load failed: ${t.id}`,r),null}}resize(){if(this.destroyed)return;const t=this.canvas.getBoundingClientRect(),n=Math.max(1,t.width||this.canvas.clientWidth||1),r=Math.max(1,t.height||this.canvas.clientHeight||1),i=Math.max(1,window.devicePixelRatio||1),o=Math.max(1,Math.round(n*i)),s=Math.max(1,Math.round(r*i));(this.canvas.width!==o||this.canvas.height!==s)&&(this.canvas.width=o,this.canvas.height=s),this.camera.setViewport(n,r),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),!this.fitted&&!this.controlledViewState&&(this.fitToImage(),this.fitted=!0),this.requestRender()}fitToImage(){const t=this.camera.getViewportSize(),n=Math.min(t.width/this.imageWidth,t.height/this.imageHeight),r=Number.isFinite(n)&&n>0?n:1,i=t.width/r,o=t.height/r,s=(this.imageWidth-i)*.5,a=(this.imageHeight-o)*.5;this.camera.setViewState({zoom:r,offsetX:s,offsetY:a})}requestRender(){this.frameId!==null||this.destroyed||(this.frameId=requestAnimationFrame(()=>{this.frameId=null,this.render()}))}render(){if(!this.destroyed){this.gl.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.useProgram(this.program),this.gl.bindVertexArray(this.vao),this.gl.uniformMatrix3fv(this.uCameraLocation,!1,this.camera.getMatrix()),this.gl.uniform1i(this.uTextureLocation,0);for(const t of this.tiles)this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,t.texture),this.gl.uniform4f(this.uBoundsLocation,t.bounds[0],t.bounds[1],t.bounds[2],t.bounds[3]),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindVertexArray(null)}}disposeTiles(t){for(const n of t)this.gl.deleteTexture(n.texture)}}function Et(e){return e==null?null:Or(e)||Yr(e)||Yi(e)?e:null}function cr(e){return typeof e=="number"&&Number.isFinite(e)}function Jt(e){return Array.isArray(e)&&e.length>=2&&cr(e[0])&&cr(e[1])}function Or(e){return Array.isArray(e)&&e.length>0&&e.every(t=>Jt(t))}function Yr(e){return Array.isArray(e)&&e.length>0&&e.every(t=>Or(t))}function Yi(e){return Array.isArray(e)&&e.length>0&&e.every(t=>Yr(t))}function Ue(e){if(!Array.isArray(e)||e.length<3)return[];const t=[];for(const i of e){if(!Array.isArray(i)||i.length<2)continue;const o=Number(i[0]),s=Number(i[1]);if(!Number.isFinite(o)||!Number.isFinite(s))continue;const a=t[t.length-1];a&&a[0]===o&&a[1]===s||t.push([o,s])}if(t.length<3)return[];const n=t[0],r=t[t.length-1];return(n[0]!==r[0]||n[1]!==r[1])&&t.push([n[0],n[1]]),t.length>=4?t:[]}function 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 gn(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const o of e){const s=Ue(o);s.length>=4&&t.push(s)}if(t.length===0)return[];if(t.length===1)return[t[0]];let n=0,r=0;for(let o=0;o<t.length;o+=1){const s=Math.abs(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 Xr(e){if(!Array.isArray(e)||e.length===0)return[];const t=e[0];if(Jt(t)){const i=gn([e]);return i.length>0?[i]:[]}if(!Array.isArray(t)||t.length===0)return[];const n=t[0];if(Jt(n)){const i=gn(e);return i.length>0?[i]:[]}if(!Array.isArray(n)||n.length===0||!Jt(n[0]))return[];const r=[];for(const i of e){const o=gn(i);o.length>0&&r.push(o)}return r}function ur(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],l=n[o][1];if(a===l||a>t==l>t)continue;e<(c-s)*(t-a)/(l-a)+s&&(r=!r)}return r}function vt(e){const t=[];for(const n of e??[]){const r=Xr(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,l=-1/0;for(const[f,d]of o)f<s&&(s=f),f>c&&(c=f),d<a&&(a=d),d>l&&(l=d);if(!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(c)||!Number.isFinite(l))continue;let u=Math.abs(Rt(o));for(let f=1;f<i.length;f+=1)u-=Math.abs(Rt(i[f]));t.push({outer:o,holes:i.slice(1),minX:s,minY:a,maxX:c,maxY:l,area:Math.max(1e-6,u)})}}return t}function Wr(e,t,n){if(e<n.minX||e>n.maxX||t<n.minY||t>n.maxY||!ur(e,t,n.outer))return!1;for(const r of n.holes)if(ur(e,t,r))return!1;return!0}function tn(e,t,n){for(const r of n)if(Wr(e,t,r))return!0;return!1}const Un=[160,160,160,255];function L(e,t,n){return Math.max(t,Math.min(n,e))}function Nn(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 Xi(e,t,n){let i=100*Nn(e,t,n);if(Number(e)){let o="μm";return i>1e3&&(i/=1e3,o="mm"),`${i.toPrecision(3)} ${o}`}return`${Math.round(i*1e3)/1e3} pixels`}function fe(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function at(e){const t=e.fillModes instanceof Uint8Array?e.fillModes.length:Number.MAX_SAFE_INTEGER;return Math.max(0,Math.min(Math.floor(e.count??0),Math.floor((e.positions?.length??0)/2),e.paletteIndices?.length??0,t))}function Cn(e,t){return!e&&!t?!0:!e||!t?!1:Math.abs((e.zoom??0)-(t.zoom??0))<1e-6&&Math.abs((e.offsetX??0)-(t.offsetX??0))<1e-6&&Math.abs((e.offsetY??0)-(t.offsetY??0))<1e-6&&Math.abs((e.rotationDeg??0)-(t.rotationDeg??0))<1e-6}function Wi(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 Vr(e){const n=String(e??"").trim().match(/^#?([0-9a-fA-F]{6})$/);if(!n)return[...Un];const r=Number.parseInt(n[1],16);return[r>>16&255,r>>8&255,r&255,255]}function Vi(e){const t=[[...Un]],n=new Map;for(const i of e??[]){const o=String(i?.termId??"");!o||n.has(o)||(n.set(o,t.length),t.push(Vr(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 Gi=.1,qi=4e6,Hi=4096,Zi=64,$i=1,Ki=4,Gr=1e-6,ji=24;function Ji(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 Qi(e,t,n){if(t<=Gr||n<8)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([e[0]+Math.cos(o)*t,e[1]+Math.sin(o)*t])}return Ue(r)}function pn(e,t){if(!e.length)return[];let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,c]of e)a<n&&(n=a),a>i&&(i=a),c<r&&(r=c),c>o&&(o=c);if(!Number.isFinite(n)||!Number.isFinite(r))return[];const s=Math.max(t,1);return Ue([[n-s,r-s],[i+s,r-s],[i+s,o+s],[n-s,o+s]])}function eo(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 to(e,t,n){const r=Math.max(Gi,Number(n.minRasterStep)||0),i=Math.max(32768,Math.floor(n.maxRasterPixels||qi)),o=Math.max(256,Math.floor(n.maxRasterSize||Hi)),s=Math.max(.001,e[2]-e[0]),a=Math.max(.001,e[3]-e[1]);let c=Math.max(r,Number.EPSILON),l=3,u=Math.ceil(s/c)+l*2+1,f=Math.ceil(a/c)+l*2+1;for(;(u>o||f>o||u*f>i)&&(c*=1.15,u=Math.ceil(s/c)+l*2+1,f=Math.ceil(a/c)+l*2+1,!(c>Math.max(s,a))););return u=Math.max(8,u),f=Math.max(8,f),{minX:e[0],minY:e[1],step:c,padding:l,width:u,height:f}}let xt=null;function no(e,t,n){e.width!==t&&(e.width=t),e.height!==n&&(e.height=n)}function ro(e,t){if(xt)return no(xt.canvas,e,t),xt.context;if(typeof OffscreenCanvas<"u"){const n=new OffscreenCanvas(e,t),r=n.getContext("2d",{willReadFrequently:!0});if(r)return xt={canvas:n,context:r},r}if(typeof document<"u"){const n=document.createElement("canvas");n.width=e,n.height=t;const r=n.getContext("2d",{willReadFrequently:!0});if(r)return xt={canvas:n,context:r},r}return null}function io(e,t){return[(e[0]-t.minX)/t.step+t.padding,(e[1]-t.minY)/t.step+t.padding]}function oo(e,t,n){const r=ro(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=>io(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]>=ji?1:0;return s}function so(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 ao(e,t){const n=(t-e+4)%4;return n===1?0:n===0?1:n===3?2:3}function co(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 l=[o.start,o.end];n[i]=1;let u=0;const f=e.length*3;for(;a!==s&&u<f;){const d=t.get(a);if(!d||d.length===0)break;let g=-1,p=1/0;for(const x of d){if(n[x])continue;const M=e[x],R=ao(c,M.dir);R<p&&(p=R,g=x)}if(g<0)break;n[g]=1;const S=e[g];a=S.end,c=S.dir,l.push(a),u+=1}l.length>=4&&l[0]===l[l.length-1]&&r.push(l)}return r}function uo(e,t,n){const r=t+1,i=[];for(const o of e){const s=o%r,a=Math.floor(o/r);i.push([n.minX+(s-n.padding)*n.step,n.minY+(a-n.padding)*n.step])}return Ue(i)}function lo(e,t=1e-9){const n=Ue(e);if(n.length<5)return n;const r=[n[0]];for(let i=1;i<n.length-1;i+=1){const o=r[r.length-1],s=n[i],a=n[i+1],c=(s[0]-o[0])*(a[1]-s[1])-(s[1]-o[1])*(a[0]-s[0]);Math.abs(c)<=t||r.push(s)}return r.push(r[0]),Ue(r)}function fo(e,t,n){const r=n[0]-t[0],i=n[1]-t[1],o=r*r+i*i;if(o<=1e-12){const f=e[0]-t[0],d=e[1]-t[1];return f*f+d*d}const s=L(((e[0]-t[0])*r+(e[1]-t[1])*i)/o,0,1),a=t[0]+r*s,c=t[1]+i*s,l=e[0]-a,u=e[1]-c;return l*l+u*u}function ho(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 l=0,u=-1;for(let f=a+1;f<c;f+=1){const d=fo(e[f],e[a],e[c]);d>l&&(l=d,u=f)}u>=0&&l>r&&(n[u]=1,i.push([a,u],[u,c]))}const o=[];for(let s=0;s<e.length;s+=1)n[s]&&o.push(e[s]);return o}function mo(e,t){const n=Ue(e);if(n.length<5||t<=0)return n;const r=n.slice(0,-1),i=ho(r,t);return i.length<3?n:Ue(i)}function go(e,t){let n=Ue(e);if(t<=0||n.length<5)return n;for(let r=0;r<t;r+=1){const i=n.slice(0,-1);if(i.length<3)break;const o=[];for(let s=0;s<i.length;s+=1){const a=i[s],c=i[(s+1)%i.length];o.push([a[0]*.75+c[0]*.25,a[1]*.75+c[1]*.25],[a[0]*.25+c[0]*.75,a[1]*.25+c[1]*.75])}n=Ue(o)}return n}function St(e,t){return t?Ue(e.map(([n,r])=>[L(n,t[0],t[2]),L(r,t[1],t[3])])):e}function po(e,t){const n=Ji(e),r=Math.max(Gr,Number(t.radius)||0);if(n.length===0||!Number.isFinite(r))return[];const i=Math.max(12,Math.floor(t.circleSides||Zi));if(n.length===1)return St(Qi(n[0],r,i),t.clipBounds);const o=eo(n,r),s=to(o,r,t),a=oo(n,r,s);if(!a.length)return St(pn(n,r),t.clipBounds);const c=so(a,s.width,s.height),l=co(c);if(!l.length)return St(pn(n,r),t.clipBounds);let u=[],f=0;for(const S of l){const x=uo(S,s.width,s),M=Math.abs(Rt(x));M<=f||(f=M,u=x)}if(!u.length)return St(pn(n,r),t.clipBounds);const d=typeof t.simplifyTolerance=="number"&&Number.isFinite(t.simplifyTolerance)?Math.max(0,t.simplifyTolerance):s.step*.2,g=typeof t.smoothingPasses=="number"&&Number.isFinite(t.smoothingPasses)?Math.round(L(t.smoothingPasses,0,Ki)):$i,p=mo(go(lo(u,s.step*.001),g),d);return St(p,t.clipBounds)}const Tt=[],lr=[],je={color:"#ff4d4f",width:2,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},bo={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},yo="rgba(23, 23, 25, 0.1)",wo=6,ze={fontFamily:"Pretendard, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:11,fontWeight:600,textColor:"#171719",backgroundColor:"#FFCC00",borderColor:"rgba(0, 0, 0, 0)",borderWidth:0,paddingX:8,paddingY:4,offsetY:10,borderRadius:4},Je={fontFamily:"Pretendard, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:13,fontWeight:500,textColor:"#FFFFFF",backgroundColor:"rgba(23, 23, 25, 0.5)",borderRadius:4,paddingX:6,paddingY:3},fr={x:16,y:-24},xo=20,dr=1e-6,hr="transparent",So=3,Mo=2,qr=96,Co=1,mr=1e3,Hr=2,Zr=2,Ao=4096,Ro=.2,To=1.12,Io=.89,Po=32,Eo="#000000",vo=.1,_o="#FFCF00",Fo="#FF0000",Bo=1.5,gr=[2,2],Uo=1,No=.25,ko=4,Lo=1,zo=0,Do=4,Oo=.05,Yo=256,pr=1.5;function nn(e,t,n){return[L(e[0],0,t),L(e[1],0,n)]}function rn(e){if(!Array.isArray(e)||e.length<2)return null;const t=Number(e[0]),n=Number(e[1]);return!Number.isFinite(t)||!Number.isFinite(n)?null:[t,n]}const st=rn;function Fe(e){return Ue(e)}function Qt(e){return Math.abs(Rt(Fe(e)))}function br(e){if(!Array.isArray(e)||e.length===0)return[0,0,0,0];let t=1/0,n=1/0,r=-1/0,i=-1/0;for(const[o,s]of e)o<t&&(t=o),o>r&&(r=o),s<n&&(n=s),s>i&&(i=s);return[t,n,r,i]}function An(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 We(e,t,n,r=!1,i=!1,o="rgba(255, 77, 79, 0.16)"){t.length!==0&&(e.beginPath(),An(e,t,r),i&&r&&(e.fillStyle=o,e.fill()),e.strokeStyle=n.color,e.lineWidth=n.width,e.lineJoin=n.lineJoin,e.lineCap=n.lineCap,e.shadowColor=n.shadowColor,e.shadowBlur=n.shadowBlur,e.shadowOffsetX=n.shadowOffsetX,e.shadowOffsetY=n.shadowOffsetY,e.setLineDash(n.lineDash),e.stroke(),e.setLineDash(Tt),e.shadowColor="rgba(0, 0, 0, 0)",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0)}function $r(e){const t=Array.isArray(e?.lineDash)?e.lineDash.filter(s=>Number.isFinite(s)&&s>=0):Tt,n=typeof e?.width=="number"&&Number.isFinite(e.width)?Math.max(0,e.width):je.width,r=typeof e?.shadowBlur=="number"&&Number.isFinite(e.shadowBlur)?Math.max(0,e.shadowBlur):je.shadowBlur,i=typeof e?.shadowOffsetX=="number"&&Number.isFinite(e.shadowOffsetX)?e.shadowOffsetX:je.shadowOffsetX,o=typeof e?.shadowOffsetY=="number"&&Number.isFinite(e.shadowOffsetY)?e.shadowOffsetY:je.shadowOffsetY;return{color:e?.color||je.color,width:n,lineDash:t.length?t:Tt,lineJoin:e?.lineJoin||je.lineJoin,lineCap:e?.lineCap||je.lineCap,shadowColor:e?.shadowColor||je.shadowColor,shadowBlur:r,shadowOffsetX:i,shadowOffsetY:o}}function Mt(e,t){return t?$r({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 yr(e,t){return e==null||t===null||t===void 0?!1:String(e)===String(t)}function wr(e){return typeof e=="number"&&Number.isFinite(e)}function Xo(e){return Array.isArray(e)&&e.length>=2&&wr(e[0])&&wr(e[1])}function Wo(e){return Array.isArray(e)&&e.length>=2&&e.every(t=>Xo(t))}function Kr(e,t){if(!(!Array.isArray(e)||e.length===0)){if(Wo(e)){t.push(e.map(([n,r])=>[n,r]));return}for(const n of e)Kr(n,t)}}function xr(e,t){const n=[];Kr(e,n);const r=[];for(const i of n){if(i.length<2)continue;const o=t?Fe(i):i;o.length>=(t?4:2)&&r.push(o)}return r}function At(e,t){return typeof e!="number"||!Number.isFinite(e)||e<=0?t:e}function Vo(e,t){return typeof e!="number"||!Number.isFinite(e)?t:L(e,0,1)}function jr(e,t,n,r,i,o){const s=Math.max(0,Math.min(o,r*.5,i*.5));e.beginPath(),e.moveTo(t+s,n),e.lineTo(t+r-s,n),e.quadraticCurveTo(t+r,n,t+r,n+s),e.lineTo(t+r,n+i-s),e.quadraticCurveTo(t+r,n+i,t+r-s,n+i),e.lineTo(t+s,n+i),e.quadraticCurveTo(t,n+i,t,n+i-s),e.lineTo(t,n+s),e.quadraticCurveTo(t,n,t+s,n),e.closePath()}function Go(e){const t=e[0];return Array.isArray(t)&&Array.isArray(t[0])}function on(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 on(e,t);s.push(c)}return Fe(s)}}return Fe([[e[0],e[1]],[t[0],e[1]],[t[0],t[1]],[e[0],t[1]]])}function Rn(e,t,n=qr){if(!e||!t)return[];const r=(e[0]+t[0])*.5,i=(e[1]+t[1])*.5,o=Math.hypot(t[0]-e[0],t[1]-e[1])*.5;if(o<1)return[];const s=[];for(let a=0;a<=n;a+=1){const c=a/n*Math.PI*2;s.push([r+Math.cos(c)*o,i+Math.sin(c)*o])}return Fe(s)}function Sr(e){const t=Xr(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(([l,u])=>[l,u]))}n.push({outer:o,holes:s})}return n}function qo(e){if(!Array.isArray(e))return gr;const t=e.filter(n=>Number.isFinite(n)&&n>=0);return t.length>0?t:gr}function Ho(e){return typeof e!="number"||!Number.isFinite(e)?Uo:L(e,No,ko)}function Zo(e){return typeof e!="number"||!Number.isFinite(e)?Lo:Math.round(L(e,zo,Do))}function $o(e){const t=At(e?.radius,Po),n=At(e?.cursorLineWidth,Bo),r=Ho(e?.edgeDetail),i=Zo(e?.edgeSmoothing);return{radius:t,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:e?.clickSelectRoi===!0,fillColor:e?.fillColor||Eo,fillOpacity:Vo(e?.fillOpacity,vo),cursorColor:e?.cursorColor||_o,cursorActiveColor:e?.cursorActiveColor||Fo,cursorLineWidth:n,cursorLineDash:qo(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 jo(e,t,n,r){const i=t.cursor;if(!i)return;const o=t.cursorScreen??st(n?.worldToScreen(i[0],i[1])??[]);if(!o)return;const s=r.radius;!Number.isFinite(s)||s<=0||(e.save(),e.beginPath(),e.arc(o[0],o[1],s,0,Math.PI*2),e.strokeStyle=t.isDrawing?r.cursorActiveColor:r.cursorColor,e.lineWidth=r.cursorLineWidth,e.setLineDash(r.cursorLineDash),e.stroke(),e.setLineDash(Tt),e.restore())}const Jo=.58,Qo=4096,es=.5;let Xt=null;const Wt=new Map;function ts(){if(Xt)return Xt;if(typeof document>"u")return null;const t=document.createElement("canvas").getContext("2d");return t?(Xt=t,Xt):null}function kn(e,t){const n=`${t.fontWeight}|${t.fontSize}|${t.fontFamily}|${e}`,r=Wt.get(n);if(r!==void 0)return r;const i=e.length*t.fontSize*Jo,o=ts();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 Wt.size>Qo&&Wt.clear(),Wt.set(n,s),s}function ns(e,t="top-center"){if(!e.length)return null;let n=1/0;for(const o of e)o[1]<n&&(n=o[1]);if(!Number.isFinite(n))return null;let r=1/0,i=-1/0;for(const o of e)Math.abs(o[1]-n)>es||(o[0]<r&&(r=o[0]),o[0]>i&&(i=o[0]));return!Number.isFinite(r)||!Number.isFinite(i)?null:t==="top-center"?[(r+i)*.5,n]:[r,n]}function Jr(e,t="top-center"){let n=null;for(const r of e){const i=ns(r.outer,t);i&&(!n||i[1]<n[1]||i[1]===n[1]&&i[0]<n[0])&&(n=i)}return n}function Ln(e){const t=typeof e?.paddingX=="number"&&Number.isFinite(e.paddingX)?Math.max(0,e.paddingX):ze.paddingX,n=typeof e?.paddingY=="number"&&Number.isFinite(e.paddingY)?Math.max(0,e.paddingY):ze.paddingY,r=typeof e?.fontSize=="number"&&Number.isFinite(e.fontSize)?Math.max(8,e.fontSize):ze.fontSize,i=typeof e?.borderWidth=="number"&&Number.isFinite(e.borderWidth)?Math.max(0,e.borderWidth):ze.borderWidth,o=typeof e?.offsetY=="number"&&Number.isFinite(e.offsetY)?e.offsetY:ze.offsetY,s=typeof e?.borderRadius=="number"&&Number.isFinite(e.borderRadius)?Math.max(0,e.borderRadius):ze.borderRadius;return{fontFamily:e?.fontFamily||ze.fontFamily,fontSize:r,fontWeight:e?.fontWeight||ze.fontWeight,textColor:e?.textColor||ze.textColor,backgroundColor:e?.backgroundColor||ze.backgroundColor,borderColor:e?.borderColor||ze.borderColor,borderWidth:i,paddingX:t,paddingY:n,offsetY:o,borderRadius:s}}function Qr(e,t){return t?Ln({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 ei(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<=dr||!Number.isFinite(t)?0:t>=i-dr?xo:0}function rs(e){const t=typeof e?.fontSize=="number"&&Number.isFinite(e.fontSize)?Math.max(8,e.fontSize):Je.fontSize,n=typeof e?.borderRadius=="number"&&Number.isFinite(e.borderRadius)?Math.max(0,e.borderRadius):Je.borderRadius,r=typeof e?.paddingX=="number"&&Number.isFinite(e.paddingX)?Math.max(0,e.paddingX):Je.paddingX,i=typeof e?.paddingY=="number"&&Number.isFinite(e.paddingY)?Math.max(0,e.paddingY):Je.paddingY;return{fontFamily:e?.fontFamily||Je.fontFamily,fontSize:t,fontWeight:e?.fontWeight||Je.fontWeight,textColor:e?.textColor||Je.textColor,backgroundColor:e?.backgroundColor||Je.backgroundColor,borderRadius:n,paddingX:r,paddingY:i}}function is(e){const t=typeof e?.x=="number"&&Number.isFinite(e.x)?e.x:fr.x,n=typeof e?.y=="number"&&Number.isFinite(e.y)?e.y:fr.y;return{x:t,y:n}}function os(e){return Number.isFinite(e)?`${Math.max(0,e).toFixed(3)} mm²`:"0.000 mm²"}function ss(e){const t=typeof e?.format=="function"?e.format:os,n=is(e?.cursorOffset);return{enabled:e?.enabled===!0,format:t,style:rs(e?.style),cursorOffsetX:n.x,cursorOffsetY:n.y}}function as(e,t,n,r,i,o,s=!0){const a=t.trim();if(!a)return;e.save(),e.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,e.textAlign="center",e.textBaseline="middle";const l=kn(a,o)+o.paddingX*2,u=o.fontSize+o.paddingY*2,f=n[0],d=n[1]-o.offsetY,g=s?L(f,l*.5+1,r-l*.5-1):f,p=s?L(d,u*.5+1,i-u*.5-1):d,S=g-l*.5,x=p-u*.5;e.fillStyle=o.backgroundColor,e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,jr(e,S,x,l,u,o.borderRadius),e.fill(),o.borderWidth>0&&e.stroke(),e.fillStyle=o.textColor,e.fillText(a,g,p+.5),e.restore()}function cs(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 u=kn(c,o)+o.paddingX*2,f=o.fontSize+o.paddingY*2,d=L(n[0]+s,u*.5+1,r-u*.5-1),g=L(n[1]+a,f*.5+1,i-f*.5-1),p=d-u*.5,S=g-f*.5;e.fillStyle=o.backgroundColor,jr(e,p,S,u,f,o.borderRadius),e.fill(),e.fillStyle=o.textColor,e.fillText(c,d,g+.5),e.restore()}function us(e,t,n,r){if(!(t.length<4||n.length===0)){e.save(),e.beginPath(),An(e,t,!0);for(const i of n)i.length<4||An(e,i,!0);e.fillStyle=r,e.fill("evenodd"),e.restore()}}function ls(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 l=n[c];if(!l?.coordinates?.length||l.visible===!1)continue;const u=l.closed??Go(l.coordinates),f=xr(l.coordinates,u);if(l.invertedFill?.fillColor){const g=[],p=xr(l.coordinates,!0);for(const S of p){const x=i(S);x.length>=4&&g.push(x)}a&&s&&s({id:l.id??c,outerRingPoints:r.length,sourceRingCount:p.length,holeRingCount:g.length,fillColor:l.invertedFill.fillColor}),us(t,r,g,l.invertedFill.fillColor)}if(f.length===0)continue;const d=Mt(o,l.stroke??l.strokeStyle);for(const g of f){const p=i(g);p.length<2||We(t,p,d,u,l.fill??!1)}}}function Vt(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 fs(e){return{rectangleAreaMm2:At(e?.rectangleAreaMm2,Hr),circleAreaMm2:At(e?.circleAreaMm2,Zr),rectanglePixelSize:At(e?.rectanglePixelSize,Ao)}}const Mr=1e3;function ds(e){return e*Mr*Mr}function Cr(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 l=n.screenToWorld(c);if(!l)throw new Error("Failed to create rectangle");a.push(l)}return Fe(a)}}return Fe([[e[0]-t,e[1]-t],[e[0]+t,e[1]-t],[e[0]+t,e[1]+t],[e[0]-t,e[1]+t]])}function hs(e,t,n=qr){if(!e||!Number.isFinite(t)||t<=0)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([e[0]+Math.cos(o)*t,e[1]+Math.sin(o)*t])}return Fe(r)}function ms(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 f=r.rectanglePixelSize*.5;return Cr(n,f,a()).map(d=>nn(d,i,o))}let c=0;if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"?c=t==="stamp-rectangle-2mm2"?Hr:r.rectangleAreaMm2:(t==="stamp-circle"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2")&&(c=t==="stamp-circle-hpf-0.2mm2"?Ro:t==="stamp-circle-2mm2"?Zr:r.circleAreaMm2),!Number.isFinite(c)||c<=0)return[];const l=ds(c);let u=[];if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"){const f=s(Math.sqrt(l)*.5);u=Cr(n,f,a())}else if(t==="stamp-circle"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2"){const f=s(Math.sqrt(l/Math.PI));u=hs(n,f)}return u.length?u.map(f=>nn(f,i,o)):[]}function gs(e){return{color:yo,width:wo,lineDash:Tt,lineJoin:e.lineJoin,lineCap:e.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function ps(e){if(typeof e!="string")return hr;const t=e.trim();return t.length>0?t:hr}function Ar(e){return Array.isArray(e)&&e.length>=4&&Qt(e)>Co}function ti({tool:e,imageWidth:t,imageHeight:n,imageMpp:r,imageZoom:i,stampOptions:o,brushOptions:s,projectorRef:a,onBrushTap:c,onDrawComplete:l,onPatchComplete:u,enabled:f,viewStateSignal:d,persistedRegions:g,patchRegions:p,persistedPolygons:S,drawFillColor:x,regionStrokeStyle:M,regionStrokeHoverStyle:R,regionStrokeActiveStyle:V,patchStrokeStyle:T,resolveRegionStrokeStyle:F,resolveRegionLabelStyle:G,overlayShapes:J,hoveredRegionId:j=null,activeRegionId:Q=null,regionLabelStyle:se,drawAreaTooltip:pe,autoLiftRegionLabelAtMaxZoom:Re=!1,regionLabelAnchor:B="top-center",clampRegionLabelToViewport:k=!0,regionLabelAutoLiftOffsetPx:O,invalidateRef:U,className:ee,style:Ne}){const ue=h.useRef(null),Oe=h.useRef(!1),Be=h.useRef(new Map),Ye=h.useRef(e),P=h.useRef({isDrawing:!1,pointerId:null,start:null,current:null,cursor:null,cursorScreen:null,points:[],screenPoints:[],stampCenter:null}),C=f??e!=="cursor",D=h.useMemo(()=>g&&g.length>0?g:!S||S.length===0?lr:S.map((m,y)=>({id:y,coordinates:m})),[g,S]),ae=h.useMemo(()=>p??lr,[p]),Z=h.useMemo(()=>{const m=[];for(let y=0;y<D.length;y+=1){const A=D[y],I=Sr(A.coordinates);I.length!==0&&m.push({region:A,regionIndex:y,regionKey:A.id??y,polygons:I})}return m},[D]),le=h.useMemo(()=>{const m=[];for(let y=0;y<ae.length;y+=1){const A=ae[y],I=Sr(A.coordinates);I.length!==0&&m.push({region:A,regionIndex:y,regionKey:A.id??y,polygons:I})}return m},[ae]),de=h.useMemo(()=>$r(M),[M]),we=h.useMemo(()=>Mt(de,R),[de,R]),te=h.useMemo(()=>Mt(de,V),[de,V]),he=h.useMemo(()=>Mt(bo,T),[T]),re=h.useMemo(()=>ps(x),[x]),ne=h.useMemo(()=>Ln(se),[se]),K=h.useMemo(()=>ss(pe),[pe]),Me=h.useMemo(()=>fs(o),[o]),H=h.useMemo(()=>$o(s),[s]),xe=h.useMemo(()=>({position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",touchAction:"none",pointerEvents:C?"auto":"none",cursor:C?e==="brush"?"none":"crosshair":"default",...Ne}),[C,e,Ne]),be=h.useCallback(()=>{const m=ue.current;if(!m)return;const y=m.getBoundingClientRect(),A=Math.max(1,window.devicePixelRatio||1),I=Math.max(1,Math.round(y.width*A)),v=Math.max(1,Math.round(y.height*A));(m.width!==I||m.height!==v)&&(m.width=I,m.height=v)},[]),Se=h.useCallback(m=>{const y=a.current;if(!y||m.length===0)return[];const A=new Array(m.length);for(let I=0;I<m.length;I+=1){const v=st(y.worldToScreen(m[I][0],m[I][1]));if(!v)return[];A[I]=v}return A},[a]),ke=h.useCallback(m=>{const y=a.current,A=ue.current;if(!y||!A)return null;const I=A.getBoundingClientRect(),v=st(y.screenToWorld(I.left+m[0],I.top+m[1]));return v?nn(v,t,n):null},[a,t,n]),Ce=h.useCallback(()=>{const m=a.current,y=m?.getViewState?.().rotationDeg??0;if(!(Math.abs(y%360)<.01||!m))return{worldToScreen:(A,I)=>st(m.worldToScreen(A,I)),screenToWorld:ke}},[a,ke]),Ee=h.useCallback(m=>{if(!Number.isFinite(m)||m<=0)return 0;const y=typeof r=="number"&&Number.isFinite(r)&&r>0?r:1,A=typeof i=="number"&&Number.isFinite(i)?i:0,I=a.current?.getViewState?.().zoom,v=typeof I=="number"&&Number.isFinite(I)&&I>0?I:1,me=A+Math.log2(v),q=Math.max(1e-9,Nn(y,A,me));return m/q/v},[r,i,a]),Te=h.useCallback((m,y)=>ms({stampTool:m,center:y,resolvedStampOptions:Me,imageWidth:t,imageHeight:n,micronsToWorldPixels:Ee,getRectangleProjection:Ce}),[Ee,t,n,Me,Ce]),ct=h.useCallback(()=>{const m=P.current;return Vt(e)?Te(e,m.stampCenter):e==="brush"?[]:m.isDrawing?e==="freehand"?m.points:e==="rectangle"?on(m.start,m.current,Ce()):e==="circular"?Rn(m.start,m.current):[]:[]},[e,Te,Ce]),ut=h.useCallback(()=>{be();const m=ue.current;if(!m)return;const y=m.getContext("2d");if(!y)return;const A=Math.max(1,window.devicePixelRatio||1),I=m.width/A,v=m.height/A;if(y.setTransform(1,0,0,1,0,0),y.clearRect(0,0,m.width,m.height),y.setTransform(A,0,0,A,0,0),Z.length>0)for(const q of Z){const{region:W,polygons:oe,regionIndex:ce,regionKey:Ae}=q,ge=yr(Q,Ae)?"active":yr(j,Ae)?"hover":"default";let Ie=ge==="active"?te:ge==="hover"?we:de;if(F){const qe=F({region:W,regionId:Ae,regionIndex:ce,state:ge});Ie=Mt(Ie,qe||void 0)}const Ve=ge==="default"?null:gs(Ie);for(const qe of oe){const et=Se(qe.outer);et.length>=4&&(Ve&&We(y,et,Ve,!0,!1),We(y,et,Ie,!0,!1));for(const Ut of qe.holes){const tt=Se(Ut);tt.length>=4&&(Ve&&We(y,tt,Ve,!0,!1),We(y,tt,Ie,!0,!1))}}}if(le.length>0)for(const q of le)for(const W of q.polygons){const oe=Se(W.outer);oe.length>=4&&We(y,oe,he,!0,!1);for(const ce of W.holes){const Ae=Se(ce);Ae.length>=4&&We(y,Ae,he,!0,!1)}}if(Array.isArray(J)&&J.length>0){const q=Se(Fe([[0,0],[t,0],[t,n],[0,n]]));ls({ctx:y,overlayShapes:J,imageOuterRing:q,worldToScreenPoints:Se,baseStrokeStyle:de,onInvertedFillDebug:globalThis.__OPEN_PLANT_DEBUG_OVERLAY__?W=>{const oe=String(W.id),ce=`${W.outerRingPoints}|${W.sourceRingCount}|${W.holeRingCount}|${W.fillColor}`;Be.current.get(oe)!==ce&&(Be.current.set(oe,ce),console.debug("[open-plant] invertedFill",W))}:void 0})}const me=ct();if(C){if(e==="brush")Ko(y,P.current,H),jo(y,P.current,a.current,H);else if(me.length>0)if(e==="freehand"){const q=Se(me);q.length>=2&&We(y,q,de,!1,!1),q.length>=3&&We(y,Se(Fe(me)),de,!0,!0,re)}else{const q=Se(me);q.length>=4&&We(y,q,de,!0,!0,re)}}if(Z.length>0){const q=Math.max(1e-6,a.current?.getViewState?.().zoom??1),W=typeof O=="number"&&Number.isFinite(O)?Math.max(0,O):ei(Re,q,a.current?.getZoomRange?.());for(const oe of Z){if(!oe.region.label)continue;const ce=Jr(oe.polygons,B);if(!ce)continue;const Ae=st(a.current?.worldToScreen(ce[0],ce[1])??[]);if(!Ae)continue;let ge=Qr(ne,G?.({region:oe.region,regionId:oe.regionKey,regionIndex:oe.regionIndex,zoom:q}));W>0&&(ge={...ge,offsetY:ge.offsetY+W}),as(y,oe.region.label,Ae,I,v,ge,k)}}if(K.enabled&&C&&(e==="freehand"||e==="rectangle"||e==="circular")){const q=P.current;if(q.isDrawing){const W=e==="freehand"?Fe(me):me;if(W.length>=4){const oe=Qt(W),ce=typeof r=="number"&&Number.isFinite(r)&&r>0?r:0,Ae=ce>0?oe*ce*ce/(mr*mr):0,ge=K.format(Ae),Ie=q.cursorScreen??(q.current?st(a.current?.worldToScreen(q.current[0],q.current[1])??[]):null);Ie&&cs(y,ge,Ie,I,v,K.style,K.cursorOffsetX,K.cursorOffsetY)}}}},[C,e,ct,be,Se,t,n,a,Z,J,j,Q,de,we,te,re,le,he,F,G,ne,K,Re,B,k,O,r,H]),Y=h.useCallback(()=>{Oe.current||(Oe.current=!0,requestAnimationFrame(()=>{Oe.current=!1,ut()}))},[ut]),X=h.useCallback((m=!1)=>{const y=P.current,A=ue.current;A&&y.pointerId!==null&&A.hasPointerCapture(y.pointerId)&&A.releasePointerCapture(y.pointerId),y.isDrawing=!1,y.pointerId=null,y.start=null,y.current=null,y.points=[],y.screenPoints=[],y.stampCenter=null,m||(y.cursor=null,y.cursorScreen=null)},[]),ie=h.useCallback(m=>{const y=a.current;if(!y||t<=0||n<=0)return null;const A=st(y.screenToWorld(m.clientX,m.clientY));return A?nn(A,t,n):null},[a,t,n]),ye=h.useCallback(m=>{const y=ue.current;if(!y)return null;const A=y.getBoundingClientRect(),I=L(m.clientX-A.left,0,A.width),v=L(m.clientY-A.top,0,A.height);return!Number.isFinite(I)||!Number.isFinite(v)?null:[I,v]},[]),bt=h.useCallback(()=>{const m=P.current;if(!m.isDrawing){X(!0),Y();return}let y=[];if(e==="freehand")m.points.length>=So&&(y=Fe(m.points));else if(e==="rectangle")y=on(m.start,m.current,Ce());else if(e==="circular")y=Rn(m.start,m.current);else if(e==="brush"){const A=m.points[m.points.length-1]??m.current??m.start;if(H.clickSelectRoi&&A&&m.points.length<=1&&c?.(A)){X(!0),Y();return}const I=H.edgeDetail,v=Math.max(Oo,H.radius*2/(Yo*I)),me=m.screenPoints.length>0?m.screenPoints:Se(m.points),q=po(me,{radius:H.radius,minRasterStep:v,circleSides:Math.max(24,Math.round(64*I)),simplifyTolerance:v*.25,smoothingPasses:H.edgeSmoothing}),W=[];for(const oe of q){const ce=ke(oe);ce&&W.push(ce)}y=Fe(W)}(e==="freehand"||e==="rectangle"||e==="circular"||e==="brush")&&Ar(y)&&l&&l({tool:e,intent:e==="brush"?"brush":"roi",coordinates:y,bbox:br(y),areaPx:Qt(y)}),X(!0),Y()},[e,l,X,Y,Se,ke,Ce,H.radius,H.edgeDetail,H.edgeSmoothing,H.clickSelectRoi,c]),yt=h.useCallback((m,y)=>{const A=Te(m,y);if(!Ar(A))return;const I=m==="stamp-rectangle-4096px"?"patch":"roi",v={tool:m,intent:I,coordinates:A,bbox:br(A),areaPx:Qt(A)};l?.(v),I==="patch"&&u&&u(v)},[Te,l,u]),Qe=h.useCallback((m,y,A)=>{const I=pr*pr,v=m.screenPoints[m.screenPoints.length-1];if(!v){m.points.push(y),m.screenPoints.push(A),m.current=y;return}const me=A[0]-v[0],q=A[1]-v[1];me*me+q*q>=I?(m.points.push(y),m.screenPoints.push(A)):(m.points[m.points.length-1]=y,m.screenPoints[m.screenPoints.length-1]=A),m.current=y},[]),_t=h.useCallback(m=>{if(!C||e==="cursor"||m.button!==0)return;const y=ie(m);if(!y)return;const A=ye(m);if(!A)return;if(m.preventDefault(),m.stopPropagation(),Vt(e)){const me=P.current;me.stampCenter=y,yt(e,y),Y();return}const I=ue.current;I&&I.setPointerCapture(m.pointerId);const v=P.current;v.isDrawing=!0,v.pointerId=m.pointerId,v.start=y,v.current=y,v.cursor=y,v.cursorScreen=A,v.points=e==="freehand"||e==="brush"?[y]:[],v.screenPoints=e==="brush"?[A]:[],Y()},[C,e,ie,ye,yt,Y]),Ft=h.useCallback(m=>{if(!C||e==="cursor")return;const y=ie(m);if(!y)return;const A=ye(m);if(!A)return;const I=P.current;if(I.cursor=y,I.cursorScreen=A,Vt(e)){I.stampCenter=y,m.preventDefault(),m.stopPropagation(),Y();return}if(e==="brush"){if(!I.isDrawing||I.pointerId!==m.pointerId){Y();return}m.preventDefault(),m.stopPropagation(),Qe(I,y,A),Y();return}if(!(!I.isDrawing||I.pointerId!==m.pointerId)){if(m.preventDefault(),m.stopPropagation(),e==="freehand"){const v=a.current,me=Math.max(1e-6,v?.getViewState?.().zoom??1),q=Mo/me,W=q*q,oe=I.points[I.points.length-1];if(!oe)I.points.push(y);else{const ce=y[0]-oe[0],Ae=y[1]-oe[1];ce*ce+Ae*Ae>=W&&I.points.push(y)}}else I.current=y;Y()}},[C,e,ie,ye,Y,a,Qe]),wt=h.useCallback(m=>{const y=P.current;if(!y.isDrawing||y.pointerId!==m.pointerId)return;m.preventDefault(),m.stopPropagation();const A=ie(m),I=ye(m);A&&(y.cursor=A,I&&(y.cursorScreen=I),e==="brush"?I&&Qe(y,A,I):y.current=A);const v=ue.current;v&&v.hasPointerCapture(m.pointerId)&&v.releasePointerCapture(m.pointerId),bt()},[bt,ie,ye,e,Qe]),Bt=h.useCallback(()=>{const m=P.current;let y=!1;e==="brush"&&!m.isDrawing&&m.cursor&&(m.cursor=null,m.cursorScreen=null,y=!0),Vt(e)&&m.stampCenter&&(m.stampCenter=null,y=!0),y&&Y()},[e,Y]);return h.useEffect(()=>{be(),Y();const m=ue.current;if(!m)return;const y=new ResizeObserver(()=>{be(),Y()});return y.observe(m),()=>{y.disconnect()}},[be,Y]),h.useEffect(()=>{C||X(),Y()},[C,Y,X]),h.useEffect(()=>{Ye.current!==e&&(Ye.current=e,X(),Y())},[e,X,Y]),h.useEffect(()=>{Y()},[d,D,J,Y]),h.useEffect(()=>{if(U)return U.current=Y,()=>{U.current===Y&&(U.current=null)}},[U,Y]),h.useEffect(()=>{if(!C)return;const m=y=>{y.key==="Escape"&&(X(),Y())};return window.addEventListener("keydown",m),()=>{window.removeEventListener("keydown",m)}},[C,X,Y]),De.jsx("canvas",{ref:ue,className:ee,style:xe,onPointerDown:_t,onPointerMove:Ft,onPointerUp:wt,onPointerCancel:wt,onPointerLeave:Bt,onContextMenu:m=>{C&&m.preventDefault()},onWheel:m=>{if(!C)return;const y=ue.current,A=a.current;if(!y||typeof A?.zoomBy!="function")return;m.preventDefault(),m.stopPropagation();const I=y.getBoundingClientRect(),v=m.clientX-I.left,me=m.clientY-I.top;A.zoomBy(m.deltaY<0?To:Io,v,me),Y()}})}function Rr(e){return String(e??"").replace(/\/+$/,"")}function ni(e){const t=String(e??"");return t.startsWith("/")?t:`/${t}`}function bs(e){const t=Rr(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=Rr(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 ys(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??""),l=Number(n.mpp??e?.mpp??0);if(!i||!o||!s||!c)throw new Error("Incomplete image metadata: width/height/tileSize/path required");const u=Array.isArray(e?.terms)?e.terms.map(p=>({termId:String(p?.termId??""),termName:String(p?.termName??""),termColor:String(p?.termColor??"")})):[],f=ni(c),d=bs(t),g=r?(p,S,x)=>`${d}${f}/${p}/${x}_${S}.webp`:void 0;return{id:e?._id||"unknown",name:e?.name||"unknown",width:i,height:o,mpp:Number.isFinite(l)&&l>0?l:void 0,tileSize:s,maxTierZoom:Number.isFinite(a)?Math.max(0,Math.floor(a)):0,tilePath:c,tileBaseUrl:t,terms:u,tileUrlBuilder:g}}function zn(e,t,n,r){if(e.tileUrlBuilder)return e.tileUrlBuilder(t,n,r);const i=ni(e.tilePath);return`${e.tileBaseUrl}${i}/${t}/${r}_${n}.webp`}const _e={width:200,height:125,margin:16,position:"bottom-right",borderRadius:6,borderWidth:0,backgroundColor:"rgba(4, 10, 18, 0.88)",borderColor:"rgba(230, 244, 255, 0.35)",viewportBorderColor:"#171719",viewportBorderStyle:"dash",viewportFillColor:"transparent",interactive:!0,showThumbnail:!0,maxThumbnailTiles:16};function Tr(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 l=Math.max(1,Math.round((c+r)/(n+r))),u=l*n+(l-1)*r,f=c/Math.max(1e-6,u),d=n*f,g=r*f;e.beginPath(),e.moveTo(s[0],s[1]),e.lineTo(a[0],a[1]),e.setLineDash([d,g]),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 Gt(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 ws={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 ri({source:e,projectorRef:t,authToken:n="",options:r,invalidateRef:i,className:o,style:s}){const a=h.useRef(null),c=h.useRef(null),l=h.useRef(null),u=h.useRef({active:!1,pointerId:null}),f=h.useRef(null),d=h.useRef(!1),g=mt(r?.width,_e.width,64),p=mt(r?.height,_e.height,48),S=h.useMemo(()=>{const P=Math.max(1,e.width),C=Math.max(1,e.height),D=P/C,ae=g/p;let Z,le;return D>ae?(Z=g,le=g/D):(le=p,Z=p*D),{x:(g-Z)/2,y:(p-le)/2,w:Z,h:le}},[e.width,e.height,g,p]),x=mt(r?.margin,_e.margin,0),M=mt(r?.borderRadius,_e.borderRadius,0),R=mt(r?.borderWidth,_e.borderWidth,0),V=Math.max(1,Math.round(mt(r?.maxThumbnailTiles,_e.maxThumbnailTiles,1))),T=r?.backgroundColor||_e.backgroundColor,F=r?.borderColor||_e.borderColor,G=r?.viewportBorderColor||_e.viewportBorderColor,J=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:_e.viewportBorderStyle,j=r?.viewportFillColor??_e.viewportFillColor,Q=r?.interactive??_e.interactive,se=r?.showThumbnail??_e.showThumbnail,pe=r?.position||_e.position,Re=r?.onClose,B=r?.closeIcon,k=r?.closeButtonStyle,O=h.useMemo(()=>{const P={};return pe==="top-left"||pe==="bottom-left"?P.left=x:P.right=x,pe==="top-left"||pe==="top-right"?P.top=x:P.bottom=x,{position:"absolute",...P,width:g,height:p,borderRadius:M,overflow:"hidden",zIndex:4,pointerEvents:Q?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[x,pe,g,p,M,Q,s]),U=h.useCallback(()=>{const P=a.current;if(!P)return;const C=P.getContext("2d");if(!C)return;const D=g,ae=p,Z=Math.max(1,window.devicePixelRatio||1),le=Math.max(1,Math.round(D*Z)),de=Math.max(1,Math.round(ae*Z));(P.width!==le||P.height!==de)&&(P.width=le,P.height=de),C.setTransform(1,0,0,1,0,0),C.clearRect(0,0,P.width,P.height),C.setTransform(Z,0,0,Z,0,0),C.fillStyle=T,C.fillRect(0,0,D,ae);const{x:we,y:te,w:he,h:re}=S,ne=c.current;ne&&C.drawImage(ne,we,te,he,re),C.strokeStyle=F,C.lineWidth=R,C.strokeRect(R*.5,R*.5,D-R,ae-R);const K=t.current,Me=K?.getViewBounds?.(),H=K?.getViewCorners?.(),xe=Gt(Me)?Me:Gt(l.current)?l.current:null;if(!xe)return;l.current=xe;const be=he/Math.max(1,e.width),Se=re/Math.max(1,e.height),ke=Array.isArray(H)&&H.length>=4&&H.every(ie=>Array.isArray(ie)&&ie.length>=2&&Number.isFinite(ie[0])&&Number.isFinite(ie[1]))?H:null,Ce=J==="dash";if(ke){const ie=ke.map(ye=>[we+ye[0]*be,te+ye[1]*Se]);C.save(),C.beginPath(),C.rect(we,te,he,re),C.clip(),C.beginPath();for(let ye=0;ye<ie.length;ye+=1)ye===0?C.moveTo(ie[ye][0],ie[ye][1]):C.lineTo(ie[ye][0],ie[ye][1]);C.closePath(),C.fillStyle=j,C.fill(),C.strokeStyle=G,C.lineWidth=2.25,Ce?Tr(C,ie,4,3):C.stroke(),C.restore();return}const Ee=L(we+xe[0]*be,we,we+he),Te=L(te+xe[1]*Se,te,te+re),ct=L(we+xe[2]*be,we,we+he),ut=L(te+xe[3]*Se,te,te+re),Y=Math.max(1,ct-Ee),X=Math.max(1,ut-Te);if(C.fillStyle=j,C.fillRect(Ee,Te,Y,X),C.strokeStyle=G,C.lineWidth=2.25,Ce){const ie=[[Ee+.5,Te+.5],[Ee+.5+Math.max(1,Y-1),Te+.5],[Ee+.5+Math.max(1,Y-1),Te+.5+Math.max(1,X-1)],[Ee+.5,Te+.5+Math.max(1,X-1)]];Tr(C,ie,4,3)}else C.strokeRect(Ee+.5,Te+.5,Math.max(1,Y-1),Math.max(1,X-1))},[g,p,S,T,F,R,t,e.width,e.height,j,G,J]),ee=h.useCallback(()=>{d.current||(d.current=!0,f.current=requestAnimationFrame(()=>{d.current=!1,f.current=null,U()}))},[U]),Ne=h.useCallback((P,C)=>{const D=a.current;if(!D)return null;const ae=D.getBoundingClientRect();if(!ae.width||!ae.height)return null;const Z=ae.width/g,le=ae.height/p,de=S.x*Z,we=S.y*le,te=S.w*Z,he=S.h*le,re=L((P-ae.left-de)/te,0,1),ne=L((C-ae.top-we)/he,0,1);return[re*e.width,ne*e.height]},[e.width,e.height,g,p,S]),ue=h.useCallback((P,C)=>{const D=t.current;if(!D)return;if(D.setViewCenter){D.setViewCenter(P,C),ee();return}const ae=D.getViewBounds?.(),Z=Gt(ae)?ae:Gt(l.current)?l.current:null;if(!Z)return;const le=Math.max(1e-6,Z[2]-Z[0]),de=Math.max(1e-6,Z[3]-Z[1]);D.setViewState({offsetX:P-le*.5,offsetY:C-de*.5}),ee()},[t,ee]),Oe=h.useCallback(P=>{if(!Q||P.button!==0)return;const C=a.current;if(!C)return;const D=Ne(P.clientX,P.clientY);D&&(P.preventDefault(),P.stopPropagation(),C.setPointerCapture(P.pointerId),u.current={active:!0,pointerId:P.pointerId},ue(D[0],D[1]))},[Q,Ne,ue]),Be=h.useCallback(P=>{const C=u.current;if(!C.active||C.pointerId!==P.pointerId)return;const D=Ne(P.clientX,P.clientY);D&&(P.preventDefault(),P.stopPropagation(),ue(D[0],D[1]))},[Ne,ue]),Ye=h.useCallback(P=>{const C=u.current;if(!C.active||C.pointerId!==P.pointerId)return;const D=a.current;if(D&&D.hasPointerCapture(P.pointerId))try{D.releasePointerCapture(P.pointerId)}catch{}u.current={active:!1,pointerId:null},ee()},[ee]);return h.useEffect(()=>{let P=!1;c.current=null,ee();const C=0,D=2**(e.maxTierZoom-C),ae=Math.ceil(e.width/D),Z=Math.ceil(e.height/D),le=Math.max(1,Math.ceil(ae/e.tileSize)),de=Math.max(1,Math.ceil(Z/e.tileSize)),we=le*de;if(!se||we>V)return;const te=document.createElement("canvas");te.width=Math.max(1,Math.round(S.w)),te.height=Math.max(1,Math.round(S.h));const he=te.getContext("2d");if(!he)return;he.fillStyle=T,he.fillRect(0,0,te.width,te.height);const re=[];for(let ne=0;ne<de;ne+=1)for(let K=0;K<le;K+=1){const Me=K*e.tileSize*D,H=ne*e.tileSize*D,xe=Math.min((K+1)*e.tileSize,ae)*D,be=Math.min((ne+1)*e.tileSize,Z)*D;re.push({url:zn(e,C,K,ne),bounds:[Me,H,xe,be]})}return Promise.allSettled(re.map(async ne=>{const K=!!n,Me=await fetch(ne.url,{headers:K?{Authorization:n}:void 0});if(!Me.ok)throw new Error(`HTTP ${Me.status}`);const H=await createImageBitmap(await Me.blob());return{tile:ne,bitmap:H}})).then(ne=>{if(P){for(const H of ne)H.status==="fulfilled"&&H.value.bitmap.close();return}const K=te.width/Math.max(1,e.width),Me=te.height/Math.max(1,e.height);for(const H of ne){if(H.status!=="fulfilled")continue;const{tile:{bounds:xe},bitmap:be}=H.value,Se=xe[0]*K,ke=xe[1]*Me,Ce=Math.max(1,(xe[2]-xe[0])*K),Ee=Math.max(1,(xe[3]-xe[1])*Me);he.drawImage(be,Se,ke,Ce,Ee),be.close()}c.current=te,ee()}),()=>{P=!0}},[e,n,S,T,se,V,ee]),h.useEffect(()=>{ee()},[ee]),h.useEffect(()=>{if(i)return i.current=ee,()=>{i.current===ee&&(i.current=null)}},[i,ee]),h.useEffect(()=>()=>{u.current={active:!1,pointerId:null},f.current!==null&&(cancelAnimationFrame(f.current),f.current=null),d.current=!1},[]),De.jsxs("div",{className:o,style:O,children:[De.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:Oe,onPointerMove:Be,onPointerUp:Ye,onPointerCancel:Ye,onContextMenu:P=>{P.preventDefault()},onWheel:P=>{P.preventDefault(),P.stopPropagation()}}),Re&&De.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:P=>{P.stopPropagation(),Re()},style:k?{...k}:{...ws},children:B??"×"})]})}function xs({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 l=s.current;if(!l)return;const u=new Dr({canvas:l,imageWidth:e,imageHeight:t,initialViewState:r});return a.current=u,u.setTiles(n),()=>{u.destroy(),a.current=null}},[e,t]),h.useEffect(()=>{const l=a.current;l&&l.setTiles(n)},[n]),h.useEffect(()=>{const l=a.current;!l||!r||l.setViewState(r)},[r]),De.jsx("canvas",{ref:s,className:i,style:c})}function It(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return null;const n=vt(t??[]);if(n.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)),p}const r=at(e),i=e.positions,o=e.paletteIndices,s=e.fillModes instanceof Uint8Array&&e.fillModes.length>=r?e.fillModes:null,a=e.ids instanceof Uint32Array&&e.ids.length>=r?e.ids:null,c=new Float32Array(r*2),l=new Uint16Array(r),u=s?new Uint8Array(r):null,f=a?new Uint32Array(r):null;let d=0;for(let p=0;p<r;p+=1){const S=i[p*2],x=i[p*2+1];tn(S,x,n)&&(c[d*2]=S,c[d*2+1]=x,l[d]=o[p],u&&(u[d]=s[p]),f&&(f[d]=a[p]),d+=1)}const g={count:d,positions:c.subarray(0,d*2),paletteIndices:l.subarray(0,d)};return u&&(g.fillModes=u.subarray(0,d)),f&&(g.ids=f.subarray(0,d)),g}function ii(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return new Uint32Array(0);const n=vt(t??[]);if(n.length===0)return new Uint32Array(0);const r=at(e);if(r===0)return new Uint32Array(0);const i=e.positions,o=new Uint32Array(r);let s=0;for(let a=0;a<r;a+=1){const c=i[a*2],l=i[a*2+1];tn(c,l,n)&&(o[s]=a,s+=1)}return o.subarray(0,s)}let qt=null;const Ss=`
|
|
32
|
+
`;class Mi{constructor(e){E(this,"canvas");E(this,"gl");E(this,"camera",new Ei);E(this,"imageWidth");E(this,"imageHeight");E(this,"clearColor");E(this,"program");E(this,"vao");E(this,"quadBuffer");E(this,"uCameraLocation");E(this,"uBoundsLocation");E(this,"uTextureLocation");E(this,"resizeObserver");E(this,"tiles",[]);E(this,"frameId",null);E(this,"loadVersion",0);E(this,"destroyed",!1);E(this,"fitted",!1);E(this,"controlledViewState",!1);this.canvas=e.canvas,this.imageWidth=Math.max(1,e.imageWidth),this.imageHeight=Math.max(1,e.imageHeight),this.clearColor=e.clearColor??[.03,.05,.08,1],this.gl=Mo(this.canvas),this.program=er(this.gl,Ao,Ro);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=Tt(this.gl,this.program,"uCamera"),this.uBoundsLocation=Tt(this.gl,this.program,"uBounds"),this.uTextureLocation=Tt(this.gl,this.program,"uTexture"),e.initialViewState&&(this.controlledViewState=!0,this.camera.setViewState(e.initialViewState)),this.resizeObserver=new ResizeObserver(()=>{this.resize()}),this.resizeObserver.observe(this.canvas),this.resize()}async setTiles(e){if(this.destroyed)return;const n=++this.loadVersion,r=await Promise.all(e.map(async i=>await this.loadTile(i,n)));if(this.destroyed||n!==this.loadVersion){for(const i of r)i&&this.gl.deleteTexture(i.texture);return}this.disposeTiles(this.tiles),this.tiles=r.filter(i=>i!==null),this.requestRender()}setViewState(e){this.controlledViewState=!0,this.camera.setViewState(e),this.requestRender()}getViewState(){return this.camera.getViewState()}destroy(){this.destroyed||(this.destroyed=!0,this.loadVersion+=1,this.frameId!==null&&(cancelAnimationFrame(this.frameId),this.frameId=null),this.resizeObserver.disconnect(),this.disposeTiles(this.tiles),this.tiles=[],this.gl.deleteBuffer(this.quadBuffer),this.gl.deleteVertexArray(this.vao),this.gl.deleteProgram(this.program))}async loadTile(e,n){try{const r=await fetch(e.url);if(!r.ok)throw new Error(`Tile fetch failed: ${r.status} ${r.statusText}`);const i=await r.blob(),o=await createImageBitmap(i);if(this.destroyed||n!==this.loadVersion)return o.close(),null;const s=this.gl.createTexture();if(!s)throw o.close(),new Error("Failed to create tile texture.");return this.gl.bindTexture(this.gl.TEXTURE_2D,s),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,1),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),this.gl.bindTexture(this.gl.TEXTURE_2D,null),o.close(),{id:e.id,bounds:e.bounds,texture:s}}catch(r){return console.error(`[M1TileRenderer] tile load failed: ${e.id}`,r),null}}resize(){if(this.destroyed)return;const e=this.canvas.getBoundingClientRect(),n=Math.max(1,e.width||this.canvas.clientWidth||1),r=Math.max(1,e.height||this.canvas.clientHeight||1),i=Math.max(1,window.devicePixelRatio||1),o=Math.max(1,Math.round(n*i)),s=Math.max(1,Math.round(r*i));(this.canvas.width!==o||this.canvas.height!==s)&&(this.canvas.width=o,this.canvas.height=s),this.camera.setViewport(n,r),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),!this.fitted&&!this.controlledViewState&&(this.fitToImage(),this.fitted=!0),this.requestRender()}fitToImage(){const e=this.camera.getViewportSize(),n=Math.min(e.width/this.imageWidth,e.height/this.imageHeight),r=Number.isFinite(n)&&n>0?n:1,i=e.width/r,o=e.height/r,s=(this.imageWidth-i)*.5,a=(this.imageHeight-o)*.5;this.camera.setViewState({zoom:r,offsetX:s,offsetY:a})}requestRender(){this.frameId!==null||this.destroyed||(this.frameId=requestAnimationFrame(()=>{this.frameId=null,this.render()}))}render(){if(!this.destroyed){this.gl.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.useProgram(this.program),this.gl.bindVertexArray(this.vao),this.gl.uniformMatrix3fv(this.uCameraLocation,!1,this.camera.getMatrix()),this.gl.uniform1i(this.uTextureLocation,0);for(const e of this.tiles)this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,e.texture),this.gl.uniform4f(this.uBoundsLocation,e.bounds[0],e.bounds[1],e.bounds[2],e.bounds[3]),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindVertexArray(null)}}disposeTiles(e){for(const n of e)this.gl.deleteTexture(n.texture)}}class ae{constructor(e,n){this.next=null,this.key=e,this.data=n,this.left=null,this.right=null}}function Co(t,e){return t>e?1:t<e?-1:0}function ie(t,e,n){const r=new ae(null,null);let i=r,o=r;for(;;){const s=n(t,e.key);if(s<0){if(e.left===null)break;if(n(t,e.left.key)<0){const a=e.left;if(e.left=a.right,a.right=e,e=a,e.left===null)break}o.left=e,o=e,e=e.left}else if(s>0){if(e.right===null)break;if(n(t,e.right.key)>0){const a=e.right;if(e.right=a.left,a.left=e,e=a,e.right===null)break}i.right=e,i=e,e=e.right}else break}return i.right=e.left,o.left=e.right,e.left=r.right,e.right=r.left,e}function _n(t,e,n,r){const i=new ae(t,e);if(n===null)return i.left=i.right=null,i;n=ie(t,n,r);const o=r(t,n.key);return o<0?(i.left=n.left,i.right=n,n.left=null):o>=0&&(i.right=n.right,i.left=n,n.right=null),i}function _r(t,e,n){let r=null,i=null;if(e){e=ie(t,e,n);const o=n(e.key,t);o===0?(r=e.left,i=e.right):o<0?(i=e.right,e.right=null,r=e):(r=e.left,e.left=null,i=e)}return{left:r,right:i}}function Io(t,e,n){return e===null?t:(t===null||(e=ie(t.key,e,n),e.left=t),e)}function On(t,e,n,r,i){if(t){r(`${e}${n?"└── ":"├── "}${i(t)}
|
|
33
|
+
`);const o=e+(n?" ":"│ ");t.left&&On(t.left,o,!1,r,i),t.right&&On(t.right,o,!0,r,i)}}class nr{constructor(e=Co){this._root=null,this._size=0,this._comparator=e}insert(e,n){return this._size++,this._root=_n(e,n,this._root,this._comparator)}add(e,n){const r=new ae(e,n);this._root===null&&(r.left=r.right=null,this._size++,this._root=r);const i=this._comparator,o=ie(e,this._root,i),s=i(e,o.key);return s===0?this._root=o:(s<0?(r.left=o.left,r.right=o,o.left=null):s>0&&(r.right=o.right,r.left=o,o.right=null),this._size++,this._root=r),this._root}remove(e){this._root=this._remove(e,this._root,this._comparator)}_remove(e,n,r){let i;return n===null?null:(n=ie(e,n,r),r(e,n.key)===0?(n.left===null?i=n.right:(i=ie(e,n.left,r),i.right=n.right),this._size--,i):n)}pop(){let e=this._root;if(e){for(;e.left;)e=e.left;return this._root=ie(e.key,this._root,this._comparator),this._root=this._remove(e.key,this._root,this._comparator),{key:e.key,data:e.data}}return null}findStatic(e){let n=this._root;const r=this._comparator;for(;n;){const i=r(e,n.key);if(i===0)return n;i<0?n=n.left:n=n.right}return null}find(e){return this._root&&(this._root=ie(e,this._root,this._comparator),this._comparator(e,this._root.key)!==0)?null:this._root}contains(e){let n=this._root;const r=this._comparator;for(;n;){const i=r(e,n.key);if(i===0)return!0;i<0?n=n.left:n=n.right}return!1}forEach(e,n){let r=this._root;const i=[];let o=!1;for(;!o;)r!==null?(i.push(r),r=r.left):i.length!==0?(r=i.pop(),e.call(n,r),r=r.right):o=!0;return this}range(e,n,r,i){const o=[],s=this._comparator;let a=this._root,u;for(;o.length!==0||a;)if(a)o.push(a),a=a.left;else{if(a=o.pop(),u=s(a.key,n),u>0)break;if(s(a.key,e)>=0&&r.call(i,a))return this;a=a.right}return this}keys(){const e=[];return this.forEach(({key:n})=>{e.push(n)}),e}values(){const e=[];return this.forEach(({data:n})=>{e.push(n)}),e}min(){return this._root?this.minNode(this._root).key:null}max(){return this._root?this.maxNode(this._root).key:null}minNode(e=this._root){if(e)for(;e.left;)e=e.left;return e}maxNode(e=this._root){if(e)for(;e.right;)e=e.right;return e}at(e){let n=this._root,r=!1,i=0;const o=[];for(;!r;)if(n)o.push(n),n=n.left;else if(o.length>0){if(n=o.pop(),i===e)return n;i++,n=n.right}else r=!0;return null}next(e){let n=this._root,r=null;if(e.right){for(r=e.right;r.left;)r=r.left;return r}const i=this._comparator;for(;n;){const o=i(e.key,n.key);if(o===0)break;o<0?(r=n,n=n.left):n=n.right}return r}prev(e){let n=this._root,r=null;if(e.left!==null){for(r=e.left;r.right;)r=r.right;return r}const i=this._comparator;for(;n;){const o=i(e.key,n.key);if(o===0)break;o<0?n=n.left:(r=n,n=n.right)}return r}clear(){return this._root=null,this._size=0,this}toList(){return vo(this._root)}load(e,n=[],r=!1){let i=e.length;const o=this._comparator;if(r&&Wn(e,n,0,i-1,o),this._root===null)this._root=Yn(e,n,0,i),this._size=i;else{const s=To(this.toList(),Po(e,n),o);i=this._size+i,this._root=Xn({head:s},0,i)}return this}isEmpty(){return this._root===null}get size(){return this._size}get root(){return this._root}toString(e=n=>String(n.key)){const n=[];return On(this._root,"",!0,r=>n.push(r),e),n.join("")}update(e,n,r){const i=this._comparator;let{left:o,right:s}=_r(e,this._root,i);i(e,n)<0?s=_n(n,r,s,i):o=_n(n,r,o,i),this._root=Io(o,s,i)}split(e){return _r(e,this._root,this._comparator)}*[Symbol.iterator](){let e=this._root;const n=[];let r=!1;for(;!r;)e!==null?(n.push(e),e=e.left):n.length!==0?(e=n.pop(),yield e,e=e.right):r=!0}}function Yn(t,e,n,r){const i=r-n;if(i>0){const o=n+Math.floor(i/2),s=t[o],a=e[o],u=new ae(s,a);return u.left=Yn(t,e,n,o),u.right=Yn(t,e,o+1,r),u}return null}function Po(t,e){const n=new ae(null,null);let r=n;for(let i=0;i<t.length;i++)r=r.next=new ae(t[i],e[i]);return r.next=null,n.next}function vo(t){let e=t;const n=[];let r=!1;const i=new ae(null,null);let o=i;for(;!r;)e?(n.push(e),e=e.left):n.length>0?(e=o=o.next=n.pop(),e=e.right):r=!0;return o.next=null,i.next}function Xn(t,e,n){const r=n-e;if(r>0){const i=e+Math.floor(r/2),o=Xn(t,e,i),s=t.head;return s.left=o,t.head=t.head.next,s.right=Xn(t,i+1,n),s}return null}function To(t,e,n){const r=new ae(null,null);let i=r,o=t,s=e;for(;o!==null&&s!==null;)n(o.key,s.key)<0?(i.next=o,o=o.next):(i.next=s,s=s.next),i=i.next;return o!==null?i.next=o:s!==null&&(i.next=s),r.next}function Wn(t,e,n,r,i){if(n>=r)return;const o=t[n+r>>1];let s=n-1,a=r+1;for(;;){do s++;while(i(t[s],o)<0);do a--;while(i(t[a],o)>0);if(s>=a)break;let u=t[s];t[s]=t[a],t[a]=u,u=e[s],e[s]=e[a],e[a]=u}Wn(t,e,n,a,i),Wn(t,e,a+1,r,i)}const Kt=11102230246251565e-32,Ct=134217729,_o=(3+8*Kt)*Kt;function Fn(t,e,n,r,i){let o,s,a,u,c=e[0],f=r[0],l=0,h=0;f>c==f>-c?(o=c,c=e[++l]):(o=f,f=r[++h]);let d=0;if(l<t&&h<n)for(f>c==f>-c?(s=c+o,a=o-(s-c),c=e[++l]):(s=f+o,a=o-(s-f),f=r[++h]),o=s,a!==0&&(i[d++]=a);l<t&&h<n;)f>c==f>-c?(s=o+c,u=s-o,a=o-(s-u)+(c-u),c=e[++l]):(s=o+f,u=s-o,a=o-(s-u)+(f-u),f=r[++h]),o=s,a!==0&&(i[d++]=a);for(;l<t;)s=o+c,u=s-o,a=o-(s-u)+(c-u),c=e[++l],o=s,a!==0&&(i[d++]=a);for(;h<n;)s=o+f,u=s-o,a=o-(s-u)+(f-u),f=r[++h],o=s,a!==0&&(i[d++]=a);return(o!==0||d===0)&&(i[d++]=o),d}function Fo(t,e){let n=e[0];for(let r=1;r<t;r++)n+=e[r];return n}function De(t){return new Float64Array(t)}const No=(3+16*Kt)*Kt,ko=(2+12*Kt)*Kt,Lo=(9+64*Kt)*Kt*Kt,Me=De(4),Fr=De(8),Nr=De(12),kr=De(16),vt=De(4);function Bo(t,e,n,r,i,o,s){let a,u,c,f,l,h,d,m,p,x,w,M,N,A,C,U,H,O;const $=t-i,Z=n-i,Q=e-o,rt=r-o;A=$*rt,h=Ct*$,d=h-(h-$),m=$-d,h=Ct*rt,p=h-(h-rt),x=rt-p,C=m*x-(A-d*p-m*p-d*x),U=Q*Z,h=Ct*Q,d=h-(h-Q),m=Q-d,h=Ct*Z,p=h-(h-Z),x=Z-p,H=m*x-(U-d*p-m*p-d*x),w=C-H,l=C-w,Me[0]=C-(w+l)+(l-H),M=A+w,l=M-A,N=A-(M-l)+(w-l),w=N-U,l=N-w,Me[1]=N-(w+l)+(l-U),O=M+w,l=O-M,Me[2]=M-(O-l)+(w-l),Me[3]=O;let _=Fo(4,Me),k=ko*s;if(_>=k||-_>=k||(l=t-$,a=t-($+l)+(l-i),l=n-Z,c=n-(Z+l)+(l-i),l=e-Q,u=e-(Q+l)+(l-o),l=r-rt,f=r-(rt+l)+(l-o),a===0&&u===0&&c===0&&f===0)||(k=Lo*s+_o*Math.abs(_),_+=$*f+rt*a-(Q*c+Z*u),_>=k||-_>=k))return _;A=a*rt,h=Ct*a,d=h-(h-a),m=a-d,h=Ct*rt,p=h-(h-rt),x=rt-p,C=m*x-(A-d*p-m*p-d*x),U=u*Z,h=Ct*u,d=h-(h-u),m=u-d,h=Ct*Z,p=h-(h-Z),x=Z-p,H=m*x-(U-d*p-m*p-d*x),w=C-H,l=C-w,vt[0]=C-(w+l)+(l-H),M=A+w,l=M-A,N=A-(M-l)+(w-l),w=N-U,l=N-w,vt[1]=N-(w+l)+(l-U),O=M+w,l=O-M,vt[2]=M-(O-l)+(w-l),vt[3]=O;const Y=Fn(4,Me,4,vt,Fr);A=$*f,h=Ct*$,d=h-(h-$),m=$-d,h=Ct*f,p=h-(h-f),x=f-p,C=m*x-(A-d*p-m*p-d*x),U=Q*c,h=Ct*Q,d=h-(h-Q),m=Q-d,h=Ct*c,p=h-(h-c),x=c-p,H=m*x-(U-d*p-m*p-d*x),w=C-H,l=C-w,vt[0]=C-(w+l)+(l-H),M=A+w,l=M-A,N=A-(M-l)+(w-l),w=N-U,l=N-w,vt[1]=N-(w+l)+(l-U),O=M+w,l=O-M,vt[2]=M-(O-l)+(w-l),vt[3]=O;const B=Fn(Y,Fr,4,vt,Nr);A=a*f,h=Ct*a,d=h-(h-a),m=a-d,h=Ct*f,p=h-(h-f),x=f-p,C=m*x-(A-d*p-m*p-d*x),U=u*c,h=Ct*u,d=h-(h-u),m=u-d,h=Ct*c,p=h-(h-c),x=c-p,H=m*x-(U-d*p-m*p-d*x),w=C-H,l=C-w,vt[0]=C-(w+l)+(l-H),M=A+w,l=M-A,N=A-(M-l)+(w-l),w=N-U,l=N-w,vt[1]=N-(w+l)+(l-U),O=M+w,l=O-M,vt[2]=M-(O-l)+(w-l),vt[3]=O;const nt=Fn(B,Nr,4,vt,kr);return kr[nt-1]}function Uo(t,e,n,r,i,o){const s=(e-o)*(n-i),a=(t-i)*(r-o),u=s-a,c=Math.abs(s+a);return Math.abs(u)>=No*c?u:-Bo(t,e,n,r,i,o,c)}const Te=(t,e)=>t.ll.x<=e.x&&e.x<=t.ur.x&&t.ll.y<=e.y&&e.y<=t.ur.y,Vn=(t,e)=>{if(e.ur.x<t.ll.x||t.ur.x<e.ll.x||e.ur.y<t.ll.y||t.ur.y<e.ll.y)return null;const n=t.ll.x<e.ll.x?e.ll.x:t.ll.x,r=t.ur.x<e.ur.x?t.ur.x:e.ur.x,i=t.ll.y<e.ll.y?e.ll.y:t.ll.y,o=t.ur.y<e.ur.y?t.ur.y:e.ur.y;return{ll:{x:n,y:i},ur:{x:r,y:o}}};let oe=Number.EPSILON;oe===void 0&&(oe=Math.pow(2,-52));const zo=oe*oe,Lr=(t,e)=>{if(-oe<t&&t<oe&&-oe<e&&e<oe)return 0;const n=t-e;return n*n<zo*t*e?0:t<e?-1:1};class Do{constructor(){this.reset()}reset(){this.xRounder=new Br,this.yRounder=new Br}round(e,n){return{x:this.xRounder.round(e),y:this.yRounder.round(n)}}}class Br{constructor(){this.tree=new nr,this.round(0)}round(e){const n=this.tree.add(e),r=this.tree.prev(n);if(r!==null&&Lr(n.key,r.key)===0)return this.tree.remove(e),r.key;const i=this.tree.next(n);return i!==null&&Lr(n.key,i.key)===0?(this.tree.remove(e),i.key):e}}const ke=new Do,fn=(t,e)=>t.x*e.y-t.y*e.x,Ai=(t,e)=>t.x*e.x+t.y*e.y,Ur=(t,e,n)=>{const r=Uo(t.x,t.y,e.x,e.y,n.x,n.y);return r>0?-1:r<0?1:0},gn=t=>Math.sqrt(Ai(t,t)),Oo=(t,e,n)=>{const r={x:e.x-t.x,y:e.y-t.y},i={x:n.x-t.x,y:n.y-t.y};return fn(i,r)/gn(i)/gn(r)},Yo=(t,e,n)=>{const r={x:e.x-t.x,y:e.y-t.y},i={x:n.x-t.x,y:n.y-t.y};return Ai(i,r)/gn(i)/gn(r)},zr=(t,e,n)=>e.y===0?null:{x:t.x+e.x/e.y*(n-t.y),y:n},Dr=(t,e,n)=>e.x===0?null:{x:n,y:t.y+e.y/e.x*(n-t.x)},Xo=(t,e,n,r)=>{if(e.x===0)return Dr(n,r,t.x);if(r.x===0)return Dr(t,e,n.x);if(e.y===0)return zr(n,r,t.y);if(r.y===0)return zr(t,e,n.y);const i=fn(e,r);if(i==0)return null;const o={x:n.x-t.x,y:n.y-t.y},s=fn(o,e)/i,a=fn(o,r)/i,u=t.x+a*e.x,c=n.x+s*r.x,f=t.y+a*e.y,l=n.y+s*r.y,h=(u+c)/2,d=(f+l)/2;return{x:h,y:d}};class Ut{static compare(e,n){const r=Ut.comparePoints(e.point,n.point);return r!==0?r:(e.point!==n.point&&e.link(n),e.isLeft!==n.isLeft?e.isLeft?1:-1:se.compare(e.segment,n.segment))}static comparePoints(e,n){return e.x<n.x?-1:e.x>n.x?1:e.y<n.y?-1:e.y>n.y?1:0}constructor(e,n){e.events===void 0?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=n}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const n=e.point.events;for(let r=0,i=n.length;r<i;r++){const o=n[r];this.point.events.push(o),o.point=this.point}this.checkForConsuming()}checkForConsuming(){const e=this.point.events.length;for(let n=0;n<e;n++){const r=this.point.events[n];if(r.segment.consumedBy===void 0)for(let i=n+1;i<e;i++){const o=this.point.events[i];o.consumedBy===void 0&&r.otherSE.point.events===o.otherSE.point.events&&r.segment.consume(o.segment)}}}getAvailableLinkedEvents(){const e=[];for(let n=0,r=this.point.events.length;n<r;n++){const i=this.point.events[n];i!==this&&!i.segment.ringOut&&i.segment.isInResult()&&e.push(i)}return e}getLeftmostComparator(e){const n=new Map,r=i=>{const o=i.otherSE;n.set(i,{sine:Oo(this.point,e.point,o.point),cosine:Yo(this.point,e.point,o.point)})};return(i,o)=>{n.has(i)||r(i),n.has(o)||r(o);const{sine:s,cosine:a}=n.get(i),{sine:u,cosine:c}=n.get(o);return s>=0&&u>=0?a<c?1:a>c?-1:0:s<0&&u<0?a<c?-1:a>c?1:0:u<s?-1:u>s?1:0}}}let Wo=0;class se{static compare(e,n){const r=e.leftSE.point.x,i=n.leftSE.point.x,o=e.rightSE.point.x,s=n.rightSE.point.x;if(s<r)return 1;if(o<i)return-1;const a=e.leftSE.point.y,u=n.leftSE.point.y,c=e.rightSE.point.y,f=n.rightSE.point.y;if(r<i){if(u<a&&u<c)return 1;if(u>a&&u>c)return-1;const l=e.comparePoint(n.leftSE.point);if(l<0)return 1;if(l>0)return-1;const h=n.comparePoint(e.rightSE.point);return h!==0?h:-1}if(r>i){if(a<u&&a<f)return-1;if(a>u&&a>f)return 1;const l=n.comparePoint(e.leftSE.point);if(l!==0)return l;const h=e.comparePoint(n.rightSE.point);return h<0?1:h>0?-1:1}if(a<u)return-1;if(a>u)return 1;if(o<s){const l=n.comparePoint(e.rightSE.point);if(l!==0)return l}if(o>s){const l=e.comparePoint(n.rightSE.point);if(l<0)return 1;if(l>0)return-1}if(o!==s){const l=c-a,h=o-r,d=f-u,m=s-i;if(l>h&&d<m)return 1;if(l<h&&d>m)return-1}return o>s?1:o<s||c<f?-1:c>f?1:e.id<n.id?-1:e.id>n.id?1:0}constructor(e,n,r,i){this.id=++Wo,this.leftSE=e,e.segment=this,e.otherSE=n,this.rightSE=n,n.segment=this,n.otherSE=e,this.rings=r,this.windings=i}static fromRing(e,n,r){let i,o,s;const a=Ut.comparePoints(e,n);if(a<0)i=e,o=n,s=1;else if(a>0)i=n,o=e,s=-1;else throw new Error(`Tried to create degenerate segment at [${e.x}, ${e.y}]`);const u=new Ut(i,!0),c=new Ut(o,!1);return new se(u,c,[r],[s])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,n=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e<n?e:n},ur:{x:this.rightSE.point.x,y:e>n?e:n}}}vector(){return{x:this.rightSE.point.x-this.leftSE.point.x,y:this.rightSE.point.y-this.leftSE.point.y}}isAnEndpoint(e){return e.x===this.leftSE.point.x&&e.y===this.leftSE.point.y||e.x===this.rightSE.point.x&&e.y===this.rightSE.point.y}comparePoint(e){if(this.isAnEndpoint(e))return 0;const n=this.leftSE.point,r=this.rightSE.point,i=this.vector();if(n.x===r.x)return e.x===n.x?0:e.x<n.x?1:-1;const o=(e.y-n.y)/i.y,s=n.x+o*i.x;if(e.x===s)return 0;const a=(e.x-n.x)/i.x,u=n.y+a*i.y;return e.y===u?0:e.y<u?-1:1}getIntersection(e){const n=this.bbox(),r=e.bbox(),i=Vn(n,r);if(i===null)return null;const o=this.leftSE.point,s=this.rightSE.point,a=e.leftSE.point,u=e.rightSE.point,c=Te(n,a)&&this.comparePoint(a)===0,f=Te(r,o)&&e.comparePoint(o)===0,l=Te(n,u)&&this.comparePoint(u)===0,h=Te(r,s)&&e.comparePoint(s)===0;if(f&&c)return h&&!l?s:!h&&l?u:null;if(f)return l&&o.x===u.x&&o.y===u.y?null:o;if(c)return h&&s.x===a.x&&s.y===a.y?null:a;if(h&&l)return null;if(h)return s;if(l)return u;const d=Xo(o,this.vector(),a,e.vector());return d===null||!Te(i,d)?null:ke.round(d.x,d.y)}split(e){const n=[],r=e.events!==void 0,i=new Ut(e,!0),o=new Ut(e,!1),s=this.rightSE;this.replaceRightSE(o),n.push(o),n.push(i);const a=new se(i,s,this.rings.slice(),this.windings.slice());return Ut.comparePoints(a.leftSE.point,a.rightSE.point)>0&&a.swapEvents(),Ut.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),r&&(i.checkForConsuming(),o.checkForConsuming()),n}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let n=0,r=this.windings.length;n<r;n++)this.windings[n]*=-1}consume(e){let n=this,r=e;for(;n.consumedBy;)n=n.consumedBy;for(;r.consumedBy;)r=r.consumedBy;const i=se.compare(n,r);if(i!==0){if(i>0){const o=n;n=r,r=o}if(n.prev===r){const o=n;n=r,r=o}for(let o=0,s=r.rings.length;o<s;o++){const a=r.rings[o],u=r.windings[o],c=n.rings.indexOf(a);c===-1?(n.rings.push(a),n.windings.push(u)):n.windings[c]+=u}r.rings=null,r.windings=null,r.consumedBy=n,r.leftSE.consumedBy=n.leftSE,r.rightSE.consumedBy=n.rightSE}}prevInResult(){return this._prevInResult!==void 0?this._prevInResult:(this.prev?this.prev.isInResult()?this._prevInResult=this.prev:this._prevInResult=this.prev.prevInResult():this._prevInResult=null,this._prevInResult)}beforeState(){if(this._beforeState!==void 0)return this._beforeState;if(!this.prev)this._beforeState={rings:[],windings:[],multiPolys:[]};else{const e=this.prev.consumedBy||this.prev;this._beforeState=e.afterState()}return this._beforeState}afterState(){if(this._afterState!==void 0)return this._afterState;const e=this.beforeState();this._afterState={rings:e.rings.slice(0),windings:e.windings.slice(0),multiPolys:[]};const n=this._afterState.rings,r=this._afterState.windings,i=this._afterState.multiPolys;for(let a=0,u=this.rings.length;a<u;a++){const c=this.rings[a],f=this.windings[a],l=n.indexOf(c);l===-1?(n.push(c),r.push(f)):r[l]+=f}const o=[],s=[];for(let a=0,u=n.length;a<u;a++){if(r[a]===0)continue;const c=n[a],f=c.poly;if(s.indexOf(f)===-1)if(c.isExterior)o.push(f);else{s.indexOf(f)===-1&&s.push(f);const l=o.indexOf(c.poly);l!==-1&&o.splice(l,1)}}for(let a=0,u=o.length;a<u;a++){const c=o[a].multiPoly;i.indexOf(c)===-1&&i.push(c)}return this._afterState}isInResult(){if(this.consumedBy)return!1;if(this._isInResult!==void 0)return this._isInResult;const e=this.beforeState().multiPolys,n=this.afterState().multiPolys;switch(Wt.type){case"union":{const r=e.length===0,i=n.length===0;this._isInResult=r!==i;break}case"intersection":{let r,i;e.length<n.length?(r=e.length,i=n.length):(r=n.length,i=e.length),this._isInResult=i===Wt.numMultiPolys&&r<i;break}case"xor":{const r=Math.abs(e.length-n.length);this._isInResult=r%2===1;break}case"difference":{const r=i=>i.length===1&&i[0].isSubject;this._isInResult=r(e)!==r(n);break}default:throw new Error(`Unrecognized operation type found ${Wt.type}`)}return this._isInResult}}class Or{constructor(e,n,r){if(!Array.isArray(e)||e.length===0)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=n,this.isExterior=r,this.segments=[],typeof e[0][0]!="number"||typeof e[0][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const i=ke.round(e[0][0],e[0][1]);this.bbox={ll:{x:i.x,y:i.y},ur:{x:i.x,y:i.y}};let o=i;for(let s=1,a=e.length;s<a;s++){if(typeof e[s][0]!="number"||typeof e[s][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");let u=ke.round(e[s][0],e[s][1]);u.x===o.x&&u.y===o.y||(this.segments.push(se.fromRing(o,u,this)),u.x<this.bbox.ll.x&&(this.bbox.ll.x=u.x),u.y<this.bbox.ll.y&&(this.bbox.ll.y=u.y),u.x>this.bbox.ur.x&&(this.bbox.ur.x=u.x),u.y>this.bbox.ur.y&&(this.bbox.ur.y=u.y),o=u)}(i.x!==o.x||i.y!==o.y)&&this.segments.push(se.fromRing(o,i,this))}getSweepEvents(){const e=[];for(let n=0,r=this.segments.length;n<r;n++){const i=this.segments[n];e.push(i.leftSE),e.push(i.rightSE)}return e}}class Vo{constructor(e,n){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");this.exteriorRing=new Or(e[0],this,!0),this.bbox={ll:{x:this.exteriorRing.bbox.ll.x,y:this.exteriorRing.bbox.ll.y},ur:{x:this.exteriorRing.bbox.ur.x,y:this.exteriorRing.bbox.ur.y}},this.interiorRings=[];for(let r=1,i=e.length;r<i;r++){const o=new Or(e[r],this,!1);o.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=o.bbox.ll.x),o.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=o.bbox.ll.y),o.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=o.bbox.ur.x),o.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=o.bbox.ur.y),this.interiorRings.push(o)}this.multiPoly=n}getSweepEvents(){const e=this.exteriorRing.getSweepEvents();for(let n=0,r=this.interiorRings.length;n<r;n++){const i=this.interiorRings[n].getSweepEvents();for(let o=0,s=i.length;o<s;o++)e.push(i[o])}return e}}class Yr{constructor(e,n){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");try{typeof e[0][0][0]=="number"&&(e=[e])}catch{}this.polys=[],this.bbox={ll:{x:Number.POSITIVE_INFINITY,y:Number.POSITIVE_INFINITY},ur:{x:Number.NEGATIVE_INFINITY,y:Number.NEGATIVE_INFINITY}};for(let r=0,i=e.length;r<i;r++){const o=new Vo(e[r],this);o.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=o.bbox.ll.x),o.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=o.bbox.ll.y),o.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=o.bbox.ur.x),o.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=o.bbox.ur.y),this.polys.push(o)}this.isSubject=n}getSweepEvents(){const e=[];for(let n=0,r=this.polys.length;n<r;n++){const i=this.polys[n].getSweepEvents();for(let o=0,s=i.length;o<s;o++)e.push(i[o])}return e}}class pn{static factory(e){const n=[];for(let r=0,i=e.length;r<i;r++){const o=e[r];if(!o.isInResult()||o.ringOut)continue;let s=null,a=o.leftSE,u=o.rightSE;const c=[a],f=a.point,l=[];for(;s=a,a=u,c.push(a),a.point!==f;)for(;;){const h=a.getAvailableLinkedEvents();if(h.length===0){const p=c[0].point,x=c[c.length-1].point;throw new Error(`Unable to complete output ring starting at [${p.x}, ${p.y}]. Last matching segment found ends at [${x.x}, ${x.y}].`)}if(h.length===1){u=h[0].otherSE;break}let d=null;for(let p=0,x=l.length;p<x;p++)if(l[p].point===a.point){d=p;break}if(d!==null){const p=l.splice(d)[0],x=c.splice(p.index);x.unshift(x[0].otherSE),n.push(new pn(x.reverse()));continue}l.push({index:c.length,point:a.point});const m=a.getLeftmostComparator(s);u=h.sort(m)[0].otherSE;break}n.push(new pn(c))}return n}constructor(e){this.events=e;for(let n=0,r=e.length;n<r;n++)e[n].segment.ringOut=this;this.poly=null}getGeom(){let e=this.events[0].point;const n=[e];for(let c=1,f=this.events.length-1;c<f;c++){const l=this.events[c].point,h=this.events[c+1].point;Ur(l,e,h)!==0&&(n.push(l),e=l)}if(n.length===1)return null;const r=n[0],i=n[1];Ur(r,e,i)===0&&n.shift(),n.push(n[0]);const o=this.isExteriorRing()?1:-1,s=this.isExteriorRing()?0:n.length-1,a=this.isExteriorRing()?n.length:-1,u=[];for(let c=s;c!=a;c+=o)u.push([n[c].x,n[c].y]);return u}isExteriorRing(){if(this._isExteriorRing===void 0){const e=this.enclosingRing();this._isExteriorRing=e?!e.isExteriorRing():!0}return this._isExteriorRing}enclosingRing(){return this._enclosingRing===void 0&&(this._enclosingRing=this._calcEnclosingRing()),this._enclosingRing}_calcEnclosingRing(){let e=this.events[0];for(let i=1,o=this.events.length;i<o;i++){const s=this.events[i];Ut.compare(e,s)>0&&(e=s)}let n=e.segment.prevInResult(),r=n?n.prevInResult():null;for(;;){if(!n)return null;if(!r)return n.ringOut;if(r.ringOut!==n.ringOut)return r.ringOut.enclosingRing()!==n.ringOut?n.ringOut:n.ringOut.enclosingRing();n=r.prevInResult(),r=n?n.prevInResult():null}}}class Xr{constructor(e){this.exteriorRing=e,e.poly=this,this.interiorRings=[]}addInterior(e){this.interiorRings.push(e),e.poly=this}getGeom(){const e=[this.exteriorRing.getGeom()];if(e[0]===null)return null;for(let n=0,r=this.interiorRings.length;n<r;n++){const i=this.interiorRings[n].getGeom();i!==null&&e.push(i)}return e}}class Go{constructor(e){this.rings=e,this.polys=this._composePolys(e)}getGeom(){const e=[];for(let n=0,r=this.polys.length;n<r;n++){const i=this.polys[n].getGeom();i!==null&&e.push(i)}return e}_composePolys(e){const n=[];for(let r=0,i=e.length;r<i;r++){const o=e[r];if(!o.poly)if(o.isExteriorRing())n.push(new Xr(o));else{const s=o.enclosingRing();s.poly||n.push(new Xr(s)),s.poly.addInterior(o)}}return n}}class qo{constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:se.compare;this.queue=e,this.tree=new nr(n),this.segments=[]}process(e){const n=e.segment,r=[];if(e.consumedBy)return e.isLeft?this.queue.remove(e.otherSE):this.tree.remove(n),r;const i=e.isLeft?this.tree.add(n):this.tree.find(n);if(!i)throw new Error(`Unable to find segment #${n.id} [${n.leftSE.point.x}, ${n.leftSE.point.y}] -> [${n.rightSE.point.x}, ${n.rightSE.point.y}] in SweepLine tree.`);let o=i,s=i,a,u;for(;a===void 0;)o=this.tree.prev(o),o===null?a=null:o.key.consumedBy===void 0&&(a=o.key);for(;u===void 0;)s=this.tree.next(s),s===null?u=null:s.key.consumedBy===void 0&&(u=s.key);if(e.isLeft){let c=null;if(a){const l=a.getIntersection(n);if(l!==null&&(n.isAnEndpoint(l)||(c=l),!a.isAnEndpoint(l))){const h=this._splitSafely(a,l);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}}let f=null;if(u){const l=u.getIntersection(n);if(l!==null&&(n.isAnEndpoint(l)||(f=l),!u.isAnEndpoint(l))){const h=this._splitSafely(u,l);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}}if(c!==null||f!==null){let l=null;c===null?l=f:f===null?l=c:l=Ut.comparePoints(c,f)<=0?c:f,this.queue.remove(n.rightSE),r.push(n.rightSE);const h=n.split(l);for(let d=0,m=h.length;d<m;d++)r.push(h[d])}r.length>0?(this.tree.remove(n),r.push(e)):(this.segments.push(n),n.prev=a)}else{if(a&&u){const c=a.getIntersection(u);if(c!==null){if(!a.isAnEndpoint(c)){const f=this._splitSafely(a,c);for(let l=0,h=f.length;l<h;l++)r.push(f[l])}if(!u.isAnEndpoint(c)){const f=this._splitSafely(u,c);for(let l=0,h=f.length;l<h;l++)r.push(f[l])}}}this.tree.remove(n)}return r}_splitSafely(e,n){this.tree.remove(e);const r=e.rightSE;this.queue.remove(r);const i=e.split(n);return i.push(r),e.consumedBy===void 0&&this.tree.add(e),i}}const Wr=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_QUEUE_SIZE||1e6,Ho=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS||1e6;class $o{run(e,n,r){Wt.type=e,ke.reset();const i=[new Yr(n,!0)];for(let l=0,h=r.length;l<h;l++)i.push(new Yr(r[l],!1));if(Wt.numMultiPolys=i.length,Wt.type==="difference"){const l=i[0];let h=1;for(;h<i.length;)Vn(i[h].bbox,l.bbox)!==null?h++:i.splice(h,1)}if(Wt.type==="intersection")for(let l=0,h=i.length;l<h;l++){const d=i[l];for(let m=l+1,p=i.length;m<p;m++)if(Vn(d.bbox,i[m].bbox)===null)return[]}const o=new nr(Ut.compare);for(let l=0,h=i.length;l<h;l++){const d=i[l].getSweepEvents();for(let m=0,p=d.length;m<p;m++)if(o.insert(d[m]),o.size>Wr)throw new Error("Infinite loop when putting segment endpoints in a priority queue (queue size too big).")}const s=new qo(o);let a=o.size,u=o.pop();for(;u;){const l=u.key;if(o.size===a){const d=l.segment;throw new Error(`Unable to pop() ${l.isLeft?"left":"right"} SweepEvent [${l.point.x}, ${l.point.y}] from segment #${d.id} [${d.leftSE.point.x}, ${d.leftSE.point.y}] -> [${d.rightSE.point.x}, ${d.rightSE.point.y}] from queue.`)}if(o.size>Wr)throw new Error("Infinite loop when passing sweep line over endpoints (queue size too big).");if(s.segments.length>Ho)throw new Error("Infinite loop when passing sweep line over endpoints (too many sweep line segments).");const h=s.process(l);for(let d=0,m=h.length;d<m;d++){const p=h[d];p.consumedBy===void 0&&o.insert(p)}a=o.size,u=o.pop()}ke.reset();const c=pn.factory(s.segments);return new Go(c).getGeom()}}const Wt=new $o,Zo=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Wt.run("union",t,n)},Ko=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Wt.run("intersection",t,n)},jo=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Wt.run("xor",t,n)},Qo=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Wt.run("difference",t,n)};var Jo={union:Zo,intersection:Ko,xor:jo,difference:Qo};function Oe(t){return t==null?null:Ri(t)||Ci(t)||ts(t)?t:null}function Vr(t){return typeof t=="number"&&Number.isFinite(t)}function hn(t){return Array.isArray(t)&&t.length>=2&&Vr(t[0])&&Vr(t[1])}function Ri(t){return Array.isArray(t)&&t.length>0&&t.every(e=>hn(e))}function Ci(t){return Array.isArray(t)&&t.length>0&&t.every(e=>Ri(e))}function ts(t){return Array.isArray(t)&&t.length>0&&t.every(e=>Ci(e))}function Lt(t){if(!Array.isArray(t)||t.length<3)return[];const e=[];for(const i of t){if(!Array.isArray(i)||i.length<2)continue;const o=Number(i[0]),s=Number(i[1]);if(!Number.isFinite(o)||!Number.isFinite(s))continue;const a=e[e.length-1];a&&a[0]===o&&a[1]===s||e.push([o,s])}if(e.length<3)return[];const n=e[0],r=e[e.length-1];return(n[0]!==r[0]||n[1]!==r[1])&&e.push([n[0],n[1]]),e.length>=4?e:[]}function Le(t){if(!Array.isArray(t)||t.length<4)return 0;let e=0;for(let n=0;n<t.length-1;n+=1){const r=t[n],i=t[n+1];e+=r[0]*i[1]-i[0]*r[1]}return e*.5}function Nn(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const o of t){const s=Lt(o);s.length>=4&&e.push(s)}if(e.length===0)return[];if(e.length===1)return[e[0]];let n=0,r=0;for(let o=0;o<e.length;o+=1){const s=Math.abs(Le(e[o]));s<=r||(r=s,n=o)}const i=[e[n]];for(let o=0;o<e.length;o+=1)o!==n&&i.push(e[o]);return i}function Ii(t){if(!Array.isArray(t)||t.length===0)return[];const e=t[0];if(hn(e)){const i=Nn([t]);return i.length>0?[i]:[]}if(!Array.isArray(e)||e.length===0)return[];const n=e[0];if(hn(n)){const i=Nn(t);return i.length>0?[i]:[]}if(!Array.isArray(n)||n.length===0||!hn(n[0]))return[];const r=[];for(const i of t){const o=Nn(i);o.length>0&&r.push(o)}return r}function Gr(t,e,n){let r=!1;for(let i=0,o=n.length-1;i<n.length;o=i,i+=1){const s=n[i][0],a=n[i][1],u=n[o][0],c=n[o][1];if(a===c||a>e==c>e)continue;t<(u-s)*(e-a)/(c-a)+s&&(r=!r)}return r}function Ye(t){const e=[];for(const n of t??[]){const r=Ii(n);for(const i of r){const o=i[0];if(!o||o.length<4)continue;let s=1/0,a=1/0,u=-1/0,c=-1/0;for(const[l,h]of o)l<s&&(s=l),l>u&&(u=l),h<a&&(a=h),h>c&&(c=h);if(!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(u)||!Number.isFinite(c))continue;let f=Math.abs(Le(o));for(let l=1;l<i.length;l+=1)f-=Math.abs(Le(i[l]));e.push({outer:o,holes:i.slice(1),minX:s,minY:a,maxX:u,maxY:c,area:Math.max(1e-6,f)})}}return e}function Pi(t,e,n){if(t<n.minX||t>n.maxX||e<n.minY||e>n.maxY||!Gr(t,e,n.outer))return!1;for(const r of n.holes)if(Gr(t,e,r))return!1;return!0}function yn(t,e,n){for(const r of n)if(Pi(t,e,r))return!0;return!1}const rr=[160,160,160,255];function D(t,e,n){return Math.max(e,Math.min(n,t))}function ir(t,e,n){const r=Number(t),i=Number(e),o=Number(n);return!Number.isFinite(r)||r<=0?1:!Number.isFinite(i)||!Number.isFinite(o)?r:Math.pow(2,i-o)*r}function es(t,e,n){let i=100*ir(t,e,n);if(Number(t)){let o="μm";return i>1e3&&(i/=1e3,o="mm"),`${i.toPrecision(3)} ${o}`}return`${Math.round(i*1e3)/1e3} pixels`}function mt(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function pe(t){const e=t.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER;return Math.max(0,Math.min(Math.floor(t.count??0),Math.floor((t.positions?.length??0)/2),t.paletteIndices?.length??0,e))}function Gn(t,e){return!t&&!e?!0:!t||!e?!1:Math.abs((t.zoom??0)-(e.zoom??0))<1e-6&&Math.abs((t.offsetX??0)-(e.offsetX??0))<1e-6&&Math.abs((t.offsetY??0)-(e.offsetY??0))<1e-6&&Math.abs((t.rotationDeg??0)-(e.rotationDeg??0))<1e-6}function ns(t){const e=String(t??"").trim();if(!e)return"";if(/^bearer\s+/i.test(e)){const n=e.replace(/^bearer\s+/i,"").trim();return n?`Bearer ${n}`:""}return`Bearer ${e}`}function vi(t){const n=String(t??"").trim().match(/^#?([0-9a-fA-F]{6})$/);if(!n)return[...rr];const r=Number.parseInt(n[1],16);return[r>>16&255,r>>8&255,r&255,255]}function rs(t){const e=[[...rr]],n=new Map;for(const i of t??[]){const o=String(i?.termId??"");!o||n.has(o)||(n.set(o,e.length),e.push(vi(i?.termColor)))}const r=new Uint8Array(e.length*4);for(let i=0;i<e.length;i+=1)r[i*4]=e[i][0],r[i*4+1]=e[i][1],r[i*4+2]=e[i][2],r[i*4+3]=e[i][3];return{colors:r,termToPaletteIndex:n}}const is=[6,4,2],os=64,ss=.04,as=1,ls=4,bn=1e-6,us=.1;function cs(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const n of t){if(!Array.isArray(n)||n.length<2)continue;const r=Number(n[0]),i=Number(n[1]);if(!Number.isFinite(r)||!Number.isFinite(i))continue;const o=e[e.length-1];o&&Math.abs(o[0]-r)<1e-9&&Math.abs(o[1]-i)<1e-9||e.push([r,i])}return e}function qr(t,e,n){if(e<=bn||n<8)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([t[0]+Math.cos(o)*e,t[1]+Math.sin(o)*e])}return Lt(r)}function fs(t,e,n,r){const i=e[0]-t[0],o=e[1]-t[1],s=Math.sqrt(i*i+o*o);if(!Number.isFinite(s)||s<=r)return[];const a=i/s,c=-(o/s),f=a,l=Math.max(bn,n);return Lt([[t[0]+c*l,t[1]+f*l],[e[0]+c*l,e[1]+f*l],[e[0]-c*l,e[1]-f*l],[t[0]-c*l,t[1]-f*l]])}function Hr(t,e){if(!t.length)return[];let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,u]of t)a<n&&(n=a),a>i&&(i=a),u<r&&(r=u),u>o&&(o=u);if(!Number.isFinite(n)||!Number.isFinite(r))return[];const s=Math.max(e,1);return Lt([[n-s,r-s],[i+s,r-s],[i+s,o+s],[n-s,o+s]])}function Je(t,e){return Lt(e?t.map(([n,r])=>[D(n,e[0],e[2]),D(r,e[1],e[3])]):t)}function $r(t,e){return Number.isFinite(t)?Number(t.toFixed(e)):t}function hs(t,e){if(!Array.isArray(t)||t.length===0)return[];const n=[];for(const r of t){if(!Array.isArray(r)||r.length<2)continue;const i=$r(Number(r[0]),e),o=$r(Number(r[1]),e);if(!Number.isFinite(i)||!Number.isFinite(o))continue;const s=n[n.length-1];(!s||s[0]!==i||s[1]!==o)&&n.push([i,o])}if(n.length>=2){const r=n[0],i=n[n.length-1];if(!r||!i)return[];(r[0]!==i[0]||r[1]!==i[1])&&n.push([r[0],r[1]])}return n.length>=4?n:[]}function ds(t,e){if(!Array.isArray(t)||t.length===0)return[];const n=t.map(r=>hs(r,e)).filter(r=>r.length>=4);return n.length>0?n:[]}function ms(t,e){const n=t.map(i=>ds(i,e)).filter(i=>i.length>0);if(n.length===0)return null;let r=[n[0]];try{for(let i=1;i<n.length;i+=1)if(r=Jo.union(r,[n[i]]),!Array.isArray(r)||r.length===0)return null}catch(i){return console.error("buildBrushStrokePolygon union failed",e,i),null}return r.length>0?r:null}function gs(t){if(t.length===0)return null;for(const e of is){const n=ms(t,e);if(n)return n}return null}function ps(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const n of t){if(!Array.isArray(n)||n.length<2)continue;const r=Number(n[0]),i=Number(n[1]);!Number.isFinite(r)||!Number.isFinite(i)||e.push([r,i])}return Lt(e)}function ys(t){let e=[],n=0;for(const r of t){if(!Array.isArray(r)||r.length===0)continue;const i=ps(r[0]??[]);if(i.length<4)continue;const o=Math.abs(Le(i));o<=n||(n=o,e=i)}return e}function bs(t,e=1e-9){const n=Lt(t);if(n.length<5)return n;const r=[n[0]];for(let i=1;i<n.length-1;i+=1){const o=r[r.length-1],s=n[i],a=n[i+1],u=(s[0]-o[0])*(a[1]-s[1])-(s[1]-o[1])*(a[0]-s[0]);Math.abs(u)<=e||r.push(s)}return r.push(r[0]),Lt(r)}function xs(t,e,n){const r=n[0]-e[0],i=n[1]-e[1],o=r*r+i*i;if(o<=1e-12){const l=t[0]-e[0],h=t[1]-e[1];return l*l+h*h}const s=D(((t[0]-e[0])*r+(t[1]-e[1])*i)/o,0,1),a=e[0]+r*s,u=e[1]+i*s,c=t[0]-a,f=t[1]-u;return c*c+f*f}function ws(t,e){if(t.length<=2||e<=0)return t.slice();const n=new Uint8Array(t.length);n[0]=1,n[t.length-1]=1;const r=e*e,i=[[0,t.length-1]];for(;i.length>0;){const s=i.pop();if(!s)break;const[a,u]=s;if(u-a<=1)continue;let c=0,f=-1;for(let l=a+1;l<u;l+=1){const h=xs(t[l],t[a],t[u]);h>c&&(c=h,f=l)}f>=0&&c>r&&(n[f]=1,i.push([a,f],[f,u]))}const o=[];for(let s=0;s<t.length;s+=1)n[s]&&o.push(t[s]);return o}function Ss(t,e){const n=Lt(t);if(n.length<5||e<=0)return n;const r=n.slice(0,-1),i=ws(r,e);return i.length<3?n:Lt(i)}function Es(t,e){let n=Lt(t);if(e<=0||n.length<5)return n;for(let r=0;r<e;r+=1){const i=n.slice(0,-1);if(i.length<3)break;const o=[];for(let s=0;s<i.length;s+=1){const a=i[s],u=i[(s+1)%i.length];o.push([a[0]*.75+u[0]*.25,a[1]*.75+u[1]*.25],[a[0]*.25+u[0]*.75,a[1]*.25+u[1]*.75])}n=Lt(o)}return n}function Ms(t,e){const n=cs(t),r=Math.max(bn,Number(e.radius)||0);if(n.length===0||!Number.isFinite(r))return[];const i=Math.max(12,Math.floor(e.circleSides||os));if(n.length===1)return Je(qr(n[0],r,i),e.clipBounds);const o=[],s=Math.max(bn,r*us);for(let h=0;h<n.length;h+=1){const d=n[h],m=qr(d,r,i);if(m.length>=4&&o.push([m]),h===0)continue;const p=fs(n[h-1],d,r,s);p.length>=4&&o.push([p])}const a=gs(o),u=a?ys(a):[];if(!u.length)return Je(Hr(n,r),e.clipBounds);const c=typeof e.simplifyTolerance=="number"&&Number.isFinite(e.simplifyTolerance)?Math.max(0,e.simplifyTolerance):Math.max(.25,r*ss),f=typeof e.smoothingPasses=="number"&&Number.isFinite(e.smoothingPasses)?Math.round(D(e.smoothingPasses,0,ls)):as,l=Ss(Es(bs(u,1e-9),f),c);return l.length<4?Je(Hr(n,r),e.clipBounds):Je(l,e.clipBounds)}const Be=[],Zr=[],ne={color:"#ff4d4f",width:2,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},As={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},Rs="rgba(23, 23, 25, 0.1)",Cs=6,Yt={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},re={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},Kr={x:16,y:-24},Is=20,jr=1e-6,Qr="transparent",Ps=3,vs=2,Ti=96,Ts=1,Jr=1e3,_i=2,Fi=2,_s=4096,Fs=.2,Ns=1.12,ks=.89,Ls=32,Bs="#000000",Us=.1,zs="#FFCF00",Ds="#FF0000",Os=1.5,ti=[2,2],Ys=1,Xs=.25,Ws=4,Vs=1,Gs=0,qs=4,Hs=1.5;function xn(t,e,n){return[D(t[0],0,e),D(t[1],0,n)]}function wn(t){if(!Array.isArray(t)||t.length<2)return null;const e=Number(t[0]),n=Number(t[1]);return!Number.isFinite(e)||!Number.isFinite(n)?null:[e,n]}const ge=wn;function kt(t){return Lt(t)}function dn(t){return Math.abs(Le(kt(t)))}function ei(t){if(!Array.isArray(t)||t.length===0)return[0,0,0,0];let e=1/0,n=1/0,r=-1/0,i=-1/0;for(const[o,s]of t)o<e&&(e=o),o>r&&(r=o),s<n&&(n=s),s>i&&(i=s);return[e,n,r,i]}function qn(t,e,n=!1){if(e.length!==0){t.moveTo(e[0][0],e[0][1]);for(let r=1;r<e.length;r+=1)t.lineTo(e[r][0],e[r][1]);n&&t.closePath()}}function Ht(t,e,n,r=!1,i=!1,o="rgba(255, 77, 79, 0.16)"){e.length!==0&&(t.beginPath(),qn(t,e,r),i&&r&&(t.fillStyle=o,t.fill()),t.strokeStyle=n.color,t.lineWidth=n.width,t.lineJoin=n.lineJoin,t.lineCap=n.lineCap,t.shadowColor=n.shadowColor,t.shadowBlur=n.shadowBlur,t.shadowOffsetX=n.shadowOffsetX,t.shadowOffsetY=n.shadowOffsetY,t.setLineDash(n.lineDash),t.stroke(),t.setLineDash(Be),t.shadowColor="rgba(0, 0, 0, 0)",t.shadowBlur=0,t.shadowOffsetX=0,t.shadowOffsetY=0)}function Ni(t){const e=Array.isArray(t?.lineDash)?t.lineDash.filter(s=>Number.isFinite(s)&&s>=0):Be,n=typeof t?.width=="number"&&Number.isFinite(t.width)?Math.max(0,t.width):ne.width,r=typeof t?.shadowBlur=="number"&&Number.isFinite(t.shadowBlur)?Math.max(0,t.shadowBlur):ne.shadowBlur,i=typeof t?.shadowOffsetX=="number"&&Number.isFinite(t.shadowOffsetX)?t.shadowOffsetX:ne.shadowOffsetX,o=typeof t?.shadowOffsetY=="number"&&Number.isFinite(t.shadowOffsetY)?t.shadowOffsetY:ne.shadowOffsetY;return{color:t?.color||ne.color,width:n,lineDash:e.length?e:Be,lineJoin:t?.lineJoin||ne.lineJoin,lineCap:t?.lineCap||ne.lineCap,shadowColor:t?.shadowColor||ne.shadowColor,shadowBlur:r,shadowOffsetX:i,shadowOffsetY:o}}function _e(t,e){return e?Ni({color:e.color??t.color,width:e.width??t.width,lineDash:e.lineDash??t.lineDash,lineJoin:e.lineJoin??t.lineJoin,lineCap:e.lineCap??t.lineCap,shadowColor:e.shadowColor??t.shadowColor,shadowBlur:e.shadowBlur??t.shadowBlur,shadowOffsetX:e.shadowOffsetX??t.shadowOffsetX,shadowOffsetY:e.shadowOffsetY??t.shadowOffsetY}):t}function ni(t,e){return t==null||e===null||e===void 0?!1:String(t)===String(e)}function ri(t){return typeof t=="number"&&Number.isFinite(t)}function $s(t){return Array.isArray(t)&&t.length>=2&&ri(t[0])&&ri(t[1])}function Zs(t){return Array.isArray(t)&&t.length>=2&&t.every(e=>$s(e))}function ki(t,e){if(!(!Array.isArray(t)||t.length===0)){if(Zs(t)){e.push(t.map(([n,r])=>[n,r]));return}for(const n of t)ki(n,e)}}function ii(t,e){const n=[];ki(t,n);const r=[];for(const i of n){if(i.length<2)continue;const o=e?kt(i):i;o.length>=(e?4:2)&&r.push(o)}return r}function Ne(t,e){return typeof t!="number"||!Number.isFinite(t)||t<=0?e:t}function Ks(t,e){return typeof t!="number"||!Number.isFinite(t)?e:D(t,0,1)}function Li(t,e,n,r,i,o){const s=Math.max(0,Math.min(o,r*.5,i*.5));t.beginPath(),t.moveTo(e+s,n),t.lineTo(e+r-s,n),t.quadraticCurveTo(e+r,n,e+r,n+s),t.lineTo(e+r,n+i-s),t.quadraticCurveTo(e+r,n+i,e+r-s,n+i),t.lineTo(e+s,n+i),t.quadraticCurveTo(e,n+i,e,n+i-s),t.lineTo(e,n+s),t.quadraticCurveTo(e,n,e+s,n),t.closePath()}function js(t){const e=t[0];return Array.isArray(e)&&Array.isArray(e[0])}function Sn(t,e,n){if(!t||!e)return[];if(n){const r=n.worldToScreen(t[0],t[1]),i=n.worldToScreen(e[0],e[1]);if(r&&i){const o=[[r[0],r[1]],[i[0],r[1]],[i[0],i[1]],[r[0],i[1]]],s=[];for(const a of o){const u=n.screenToWorld(a);if(!u)return Sn(t,e);s.push(u)}return kt(s)}}return kt([[t[0],t[1]],[e[0],t[1]],[e[0],e[1]],[t[0],e[1]]])}function Hn(t,e,n=Ti){if(!t||!e)return[];const r=(t[0]+e[0])*.5,i=(t[1]+e[1])*.5,o=Math.hypot(e[0]-t[0],e[1]-t[1])*.5;if(o<1)return[];const s=[];for(let a=0;a<=n;a+=1){const u=a/n*Math.PI*2;s.push([r+Math.cos(u)*o,i+Math.sin(u)*o])}return kt(s)}function oi(t){const e=Ii(Oe(t));if(e.length===0)return[];const n=[];for(const r of e){const i=r[0];if(!i||i.length<4)continue;const o=i.map(([a,u])=>[a,u]),s=[];for(let a=1;a<r.length;a+=1){const u=r[a];!u||u.length<4||s.push(u.map(([c,f])=>[c,f]))}n.push({outer:o,holes:s})}return n}function Qs(t){if(!Array.isArray(t))return ti;const e=t.filter(n=>Number.isFinite(n)&&n>=0);return e.length>0?e:ti}function Js(t){return typeof t!="number"||!Number.isFinite(t)?Ys:D(t,Xs,Ws)}function ta(t){return typeof t!="number"||!Number.isFinite(t)?Vs:Math.round(D(t,Gs,qs))}function ea(t){const e=Ne(t?.radius,Ls),n=Ne(t?.cursorLineWidth,Os),r=Js(t?.edgeDetail),i=ta(t?.edgeSmoothing);return{radius:e,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:t?.clickSelectRoi===!0,fillColor:t?.fillColor||Bs,fillOpacity:Ks(t?.fillOpacity,Us),cursorColor:t?.cursorColor||zs,cursorActiveColor:t?.cursorActiveColor||Ds,cursorLineWidth:n,cursorLineDash:Qs(t?.cursorLineDash)}}function na(t,e,n){if(!e.isDrawing||e.screenPoints.length===0)return;const r=e.screenPoints;if(r.length===0)return;const i=n.radius;if(!(!Number.isFinite(i)||i<=0)){if(t.save(),t.globalAlpha=n.fillOpacity,t.fillStyle=n.fillColor,t.strokeStyle=n.fillColor,t.lineCap="round",t.lineJoin="round",t.lineWidth=i*2,r.length===1)t.beginPath(),t.arc(r[0][0],r[0][1],i,0,Math.PI*2),t.fill();else{t.beginPath(),t.moveTo(r[0][0],r[0][1]);for(let o=1;o<r.length;o+=1)t.lineTo(r[o][0],r[o][1]);t.stroke()}t.restore()}}function ra(t,e,n,r){const i=e.cursor;if(!i)return;const o=e.cursorScreen??ge(n?.worldToScreen(i[0],i[1])??[]);if(!o)return;const s=r.radius;!Number.isFinite(s)||s<=0||(t.save(),t.beginPath(),t.arc(o[0],o[1],s,0,Math.PI*2),t.strokeStyle=e.isDrawing?r.cursorActiveColor:r.cursorColor,t.lineWidth=r.cursorLineWidth,t.setLineDash(r.cursorLineDash),t.stroke(),t.setLineDash(Be),t.restore())}const ia=.58,oa=4096,sa=.5;let tn=null;const en=new Map;function aa(){if(tn)return tn;if(typeof document>"u")return null;const e=document.createElement("canvas").getContext("2d");return e?(tn=e,tn):null}function or(t,e){const n=`${e.fontWeight}|${e.fontSize}|${e.fontFamily}|${t}`,r=en.get(n);if(r!==void 0)return r;const i=t.length*e.fontSize*ia,o=aa();let s=i;if(o){o.font=`${e.fontWeight} ${e.fontSize}px ${e.fontFamily}`;const a=o.measureText(t).width;Number.isFinite(a)&&a>=0&&(s=a)}return en.size>oa&&en.clear(),en.set(n,s),s}function la(t,e="top-center"){if(!t.length)return null;let n=1/0;for(const o of t)o[1]<n&&(n=o[1]);if(!Number.isFinite(n))return null;let r=1/0,i=-1/0;for(const o of t)Math.abs(o[1]-n)>sa||(o[0]<r&&(r=o[0]),o[0]>i&&(i=o[0]));return!Number.isFinite(r)||!Number.isFinite(i)?null:e==="top-center"?[(r+i)*.5,n]:[r,n]}function Bi(t,e="top-center"){let n=null;for(const r of t){const i=la(r.outer,e);i&&(!n||i[1]<n[1]||i[1]===n[1]&&i[0]<n[0])&&(n=i)}return n}function sr(t){const e=typeof t?.paddingX=="number"&&Number.isFinite(t.paddingX)?Math.max(0,t.paddingX):Yt.paddingX,n=typeof t?.paddingY=="number"&&Number.isFinite(t.paddingY)?Math.max(0,t.paddingY):Yt.paddingY,r=typeof t?.fontSize=="number"&&Number.isFinite(t.fontSize)?Math.max(8,t.fontSize):Yt.fontSize,i=typeof t?.borderWidth=="number"&&Number.isFinite(t.borderWidth)?Math.max(0,t.borderWidth):Yt.borderWidth,o=typeof t?.offsetY=="number"&&Number.isFinite(t.offsetY)?t.offsetY:Yt.offsetY,s=typeof t?.borderRadius=="number"&&Number.isFinite(t.borderRadius)?Math.max(0,t.borderRadius):Yt.borderRadius;return{fontFamily:t?.fontFamily||Yt.fontFamily,fontSize:r,fontWeight:t?.fontWeight||Yt.fontWeight,textColor:t?.textColor||Yt.textColor,backgroundColor:t?.backgroundColor||Yt.backgroundColor,borderColor:t?.borderColor||Yt.borderColor,borderWidth:i,paddingX:e,paddingY:n,offsetY:o,borderRadius:s}}function Ui(t,e){return e?sr({fontFamily:e.fontFamily??t.fontFamily,fontSize:e.fontSize??t.fontSize,fontWeight:e.fontWeight??t.fontWeight,textColor:e.textColor??t.textColor,backgroundColor:e.backgroundColor??t.backgroundColor,borderColor:e.borderColor??t.borderColor,borderWidth:e.borderWidth??t.borderWidth,paddingX:e.paddingX??t.paddingX,paddingY:e.paddingY??t.paddingY,offsetY:e.offsetY??t.offsetY,borderRadius:e.borderRadius??t.borderRadius}):t}function zi(t,e,n){if(!t||!n)return 0;const r=Number(n.minZoom),i=Number(n.maxZoom);return!Number.isFinite(r)||!Number.isFinite(i)||i-r<=jr||!Number.isFinite(e)?0:e>=i-jr?Is:0}function ua(t){const e=typeof t?.fontSize=="number"&&Number.isFinite(t.fontSize)?Math.max(8,t.fontSize):re.fontSize,n=typeof t?.borderRadius=="number"&&Number.isFinite(t.borderRadius)?Math.max(0,t.borderRadius):re.borderRadius,r=typeof t?.paddingX=="number"&&Number.isFinite(t.paddingX)?Math.max(0,t.paddingX):re.paddingX,i=typeof t?.paddingY=="number"&&Number.isFinite(t.paddingY)?Math.max(0,t.paddingY):re.paddingY;return{fontFamily:t?.fontFamily||re.fontFamily,fontSize:e,fontWeight:t?.fontWeight||re.fontWeight,textColor:t?.textColor||re.textColor,backgroundColor:t?.backgroundColor||re.backgroundColor,borderRadius:n,paddingX:r,paddingY:i}}function ca(t){const e=typeof t?.x=="number"&&Number.isFinite(t.x)?t.x:Kr.x,n=typeof t?.y=="number"&&Number.isFinite(t.y)?t.y:Kr.y;return{x:e,y:n}}function fa(t){return Number.isFinite(t)?`${Math.max(0,t).toFixed(3)} mm²`:"0.000 mm²"}function ha(t){const e=typeof t?.format=="function"?t.format:fa,n=ca(t?.cursorOffset);return{enabled:t?.enabled===!0,format:e,style:ua(t?.style),cursorOffsetX:n.x,cursorOffsetY:n.y}}function da(t,e,n,r,i,o,s=!0){const a=e.trim();if(!a)return;t.save(),t.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,t.textAlign="center",t.textBaseline="middle";const c=or(a,o)+o.paddingX*2,f=o.fontSize+o.paddingY*2,l=n[0],h=n[1]-o.offsetY,d=s?D(l,c*.5+1,r-c*.5-1):l,m=s?D(h,f*.5+1,i-f*.5-1):h,p=d-c*.5,x=m-f*.5;t.fillStyle=o.backgroundColor,t.strokeStyle=o.borderColor,t.lineWidth=o.borderWidth,Li(t,p,x,c,f,o.borderRadius),t.fill(),o.borderWidth>0&&t.stroke(),t.fillStyle=o.textColor,t.fillText(a,d,m+.5),t.restore()}function ma(t,e,n,r,i,o,s,a){const u=e.trim();if(!u)return;t.save(),t.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,t.textAlign="center",t.textBaseline="middle";const f=or(u,o)+o.paddingX*2,l=o.fontSize+o.paddingY*2,h=D(n[0]+s,f*.5+1,r-f*.5-1),d=D(n[1]+a,l*.5+1,i-l*.5-1),m=h-f*.5,p=d-l*.5;t.fillStyle=o.backgroundColor,Li(t,m,p,f,l,o.borderRadius),t.fill(),t.fillStyle=o.textColor,t.fillText(u,h,d+.5),t.restore()}function ga(t,e,n,r){if(!(e.length<4||n.length===0)){t.save(),t.beginPath(),qn(t,e,!0);for(const i of n)i.length<4||qn(t,i,!0);t.fillStyle=r,t.fill("evenodd"),t.restore()}}function pa(t){const{ctx:e,overlayShapes:n,imageOuterRing:r,worldToScreenPoints:i,baseStrokeStyle:o,onInvertedFillDebug:s}=t,a=!!globalThis.__OPEN_PLANT_DEBUG_OVERLAY__;for(let u=0;u<n.length;u+=1){const c=n[u];if(!c?.coordinates?.length||c.visible===!1)continue;const f=c.closed??js(c.coordinates),l=ii(c.coordinates,f);if(c.invertedFill?.fillColor){const d=[],m=ii(c.coordinates,!0);for(const p of m){const x=i(p);x.length>=4&&d.push(x)}a&&s&&s({id:c.id??u,outerRingPoints:r.length,sourceRingCount:m.length,holeRingCount:d.length,fillColor:c.invertedFill.fillColor}),ga(e,r,d,c.invertedFill.fillColor)}if(l.length===0)continue;const h=_e(o,c.stroke??c.strokeStyle);for(const d of l){const m=i(d);m.length<2||Ht(e,m,h,f,c.fill??!1)}}}function nn(t){return t==="stamp-rectangle"||t==="stamp-circle"||t==="stamp-rectangle-4096px"||t==="stamp-rectangle-2mm2"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2"}function ya(t){return{rectangleAreaMm2:Ne(t?.rectangleAreaMm2,_i),circleAreaMm2:Ne(t?.circleAreaMm2,Fi),rectanglePixelSize:Ne(t?.rectanglePixelSize,_s)}}const si=1e3;function ba(t){return t*si*si}function ai(t,e,n){if(!t||!Number.isFinite(e)||e<=0)return[];if(n){const r=n.worldToScreen(t[0],t[1]),i=n.worldToScreen(t[0]+e,t[1]);if(r&&i){const o=Math.hypot(i[0]-r[0],i[1]-r[1]),s=[[r[0]-o,r[1]-o],[r[0]+o,r[1]-o],[r[0]+o,r[1]+o],[r[0]-o,r[1]+o]],a=[];for(const u of s){const c=n.screenToWorld(u);if(!c)throw new Error("Failed to create rectangle");a.push(c)}return kt(a)}}return kt([[t[0]-e,t[1]-e],[t[0]+e,t[1]-e],[t[0]+e,t[1]+e],[t[0]-e,t[1]+e]])}function xa(t,e,n=Ti){if(!t||!Number.isFinite(e)||e<=0)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([t[0]+Math.cos(o)*e,t[1]+Math.sin(o)*e])}return kt(r)}function wa(t){const{stampTool:e,center:n,resolvedStampOptions:r,imageWidth:i,imageHeight:o,micronsToWorldPixels:s,getRectangleProjection:a}=t;if(!n)return[];if(e==="stamp-rectangle-4096px"){const l=r.rectanglePixelSize*.5;return ai(n,l,a()).map(h=>xn(h,i,o))}let u=0;if(e==="stamp-rectangle"||e==="stamp-rectangle-2mm2"?u=e==="stamp-rectangle-2mm2"?_i:r.rectangleAreaMm2:(e==="stamp-circle"||e==="stamp-circle-2mm2"||e==="stamp-circle-hpf-0.2mm2")&&(u=e==="stamp-circle-hpf-0.2mm2"?Fs:e==="stamp-circle-2mm2"?Fi:r.circleAreaMm2),!Number.isFinite(u)||u<=0)return[];const c=ba(u);let f=[];if(e==="stamp-rectangle"||e==="stamp-rectangle-2mm2"){const l=s(Math.sqrt(c)*.5);f=ai(n,l,a())}else if(e==="stamp-circle"||e==="stamp-circle-2mm2"||e==="stamp-circle-hpf-0.2mm2"){const l=s(Math.sqrt(c/Math.PI));f=xa(n,l)}return f.length?f.map(l=>xn(l,i,o)):[]}function Sa(t){return{color:Rs,width:Cs,lineDash:Be,lineJoin:t.lineJoin,lineCap:t.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function Ea(t){if(typeof t!="string")return Qr;const e=t.trim();return e.length>0?e:Qr}function li(t){return Array.isArray(t)&&t.length>=4&&dn(t)>Ts}function Di({tool:t,imageWidth:e,imageHeight:n,imageMpp:r,imageZoom:i,stampOptions:o,brushOptions:s,projectorRef:a,onBrushTap:u,onDrawComplete:c,onPatchComplete:f,enabled:l,viewStateSignal:h,persistedRegions:d,patchRegions:m,persistedPolygons:p,drawFillColor:x,regionStrokeStyle:w,regionStrokeHoverStyle:M,regionStrokeActiveStyle:N,patchStrokeStyle:A,resolveRegionStrokeStyle:C,resolveRegionLabelStyle:U,overlayShapes:H,hoveredRegionId:O=null,activeRegionId:$=null,regionLabelStyle:Z,drawAreaTooltip:Q,autoLiftRegionLabelAtMaxZoom:rt=!1,regionLabelAnchor:_="top-center",clampRegionLabelToViewport:k=!0,regionLabelAutoLiftOffsetPx:Y,invalidateRef:B,className:nt,style:zt}){const ft=g.useRef(null),Vt=g.useRef(!1),Bt=g.useRef(new Map),Gt=g.useRef(t),v=g.useRef({isDrawing:!1,pointerId:null,start:null,current:null,cursor:null,cursorScreen:null,points:[],screenPoints:[],stampCenter:null}),R=l??t!=="cursor",W=g.useMemo(()=>d&&d.length>0?d:!p||p.length===0?Zr:p.map((y,S)=>({id:S,coordinates:y})),[d,p]),ut=g.useMemo(()=>m??Zr,[m]),J=g.useMemo(()=>{const y=[];for(let S=0;S<W.length;S+=1){const I=W[S],P=oi(I.coordinates);P.length!==0&&y.push({region:I,regionIndex:S,regionKey:I.id??S,polygons:P})}return y},[W]),ht=g.useMemo(()=>{const y=[];for(let S=0;S<ut.length;S+=1){const I=ut[S],P=oi(I.coordinates);P.length!==0&&y.push({region:I,regionIndex:S,regionKey:I.id??S,polygons:P})}return y},[ut]),gt=g.useMemo(()=>Ni(w),[w]),wt=g.useMemo(()=>_e(gt,M),[gt,M]),it=g.useMemo(()=>_e(gt,N),[gt,N]),pt=g.useMemo(()=>_e(As,A),[A]),st=g.useMemo(()=>Ea(x),[x]),ot=g.useMemo(()=>sr(Z),[Z]),et=g.useMemo(()=>ha(Q),[Q]),Mt=g.useMemo(()=>ya(o),[o]),K=g.useMemo(()=>ea(s),[s]),St=g.useMemo(()=>({position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",touchAction:"none",pointerEvents:R?"auto":"none",cursor:R?t==="brush"?"none":"crosshair":"default",...zt}),[R,t,zt]),bt=g.useCallback(()=>{const y=ft.current;if(!y)return;const S=y.getBoundingClientRect(),I=Math.max(1,window.devicePixelRatio||1),P=Math.max(1,Math.round(S.width*I)),L=Math.max(1,Math.round(S.height*I));(y.width!==P||y.height!==L)&&(y.width=P,y.height=L)},[]),Et=g.useCallback(y=>{const S=a.current;if(!S||y.length===0)return[];const I=new Array(y.length);for(let P=0;P<y.length;P+=1){const L=ge(S.worldToScreen(y[P][0],y[P][1]));if(!L)return[];I[P]=L}return I},[a]),Dt=g.useCallback(y=>{const S=a.current,I=ft.current;if(!S||!I)return null;const P=I.getBoundingClientRect(),L=ge(S.screenToWorld(P.left+y[0],P.top+y[1]));return L?xn(L,e,n):null},[a,e,n]),At=g.useCallback(()=>{const y=a.current,S=y?.getViewState?.().rotationDeg??0;if(!(Math.abs(S%360)<.01||!y))return{worldToScreen:(I,P)=>ge(y.worldToScreen(I,P)),screenToWorld:Dt}},[a,Dt]),_t=g.useCallback(y=>{if(!Number.isFinite(y)||y<=0)return 0;const S=typeof r=="number"&&Number.isFinite(r)&&r>0?r:1,I=typeof i=="number"&&Number.isFinite(i)?i:0,P=a.current?.getViewState?.().zoom,L=typeof P=="number"&&Number.isFinite(P)&&P>0?P:1,dt=I+Math.log2(L),j=Math.max(1e-9,ir(S,I,dt));return y/j/L},[r,i,a]),It=g.useCallback((y,S)=>wa({stampTool:y,center:S,resolvedStampOptions:Mt,imageWidth:e,imageHeight:n,micronsToWorldPixels:_t,getRectangleProjection:At}),[_t,e,n,Mt,At]),ye=g.useCallback(()=>{const y=v.current;return nn(t)?It(t,y.stampCenter):t==="brush"?[]:y.isDrawing?t==="freehand"?y.points:t==="rectangle"?Sn(y.start,y.current,At()):t==="circular"?Hn(y.start,y.current):[]:[]},[t,It,At]),be=g.useCallback(()=>{bt();const y=ft.current;if(!y)return;const S=y.getContext("2d");if(!S)return;const I=Math.max(1,window.devicePixelRatio||1),P=y.width/I,L=y.height/I;if(S.setTransform(1,0,0,1,0,0),S.clearRect(0,0,y.width,y.height),S.setTransform(I,0,0,I,0,0),J.length>0)for(const j of J){const{region:V,polygons:lt,regionIndex:ct,regionKey:Rt}=j,yt=ni($,Rt)?"active":ni(O,Rt)?"hover":"default";let Pt=yt==="active"?it:yt==="hover"?wt:gt;if(C){const jt=C({region:V,regionId:Rt,regionIndex:ct,state:yt});Pt=_e(Pt,jt||void 0)}const $t=yt==="default"?null:Sa(Pt);for(const jt of lt){const ue=Et(jt.outer);ue.length>=4&&($t&&Ht(S,ue,$t,!0,!1),Ht(S,ue,Pt,!0,!1));for(const Ge of jt.holes){const ce=Et(Ge);ce.length>=4&&($t&&Ht(S,ce,$t,!0,!1),Ht(S,ce,Pt,!0,!1))}}}if(ht.length>0)for(const j of ht)for(const V of j.polygons){const lt=Et(V.outer);lt.length>=4&&Ht(S,lt,pt,!0,!1);for(const ct of V.holes){const Rt=Et(ct);Rt.length>=4&&Ht(S,Rt,pt,!0,!1)}}if(Array.isArray(H)&&H.length>0){const j=Et(kt([[0,0],[e,0],[e,n],[0,n]]));pa({ctx:S,overlayShapes:H,imageOuterRing:j,worldToScreenPoints:Et,baseStrokeStyle:gt,onInvertedFillDebug:globalThis.__OPEN_PLANT_DEBUG_OVERLAY__?V=>{const lt=String(V.id),ct=`${V.outerRingPoints}|${V.sourceRingCount}|${V.holeRingCount}|${V.fillColor}`;Bt.current.get(lt)!==ct&&(Bt.current.set(lt,ct),console.debug("[open-plant] invertedFill",V))}:void 0})}const dt=ye();if(R){if(t==="brush")na(S,v.current,K),ra(S,v.current,a.current,K);else if(dt.length>0)if(t==="freehand"){const j=Et(dt);j.length>=2&&Ht(S,j,gt,!1,!1),j.length>=3&&Ht(S,Et(kt(dt)),gt,!0,!0,st)}else{const j=Et(dt);j.length>=4&&Ht(S,j,gt,!0,!0,st)}}if(J.length>0){const j=Math.max(1e-6,a.current?.getViewState?.().zoom??1),V=typeof Y=="number"&&Number.isFinite(Y)?Math.max(0,Y):zi(rt,j,a.current?.getZoomRange?.());for(const lt of J){if(!lt.region.label)continue;const ct=Bi(lt.polygons,_);if(!ct)continue;const Rt=ge(a.current?.worldToScreen(ct[0],ct[1])??[]);if(!Rt)continue;let yt=Ui(ot,U?.({region:lt.region,regionId:lt.regionKey,regionIndex:lt.regionIndex,zoom:j}));V>0&&(yt={...yt,offsetY:yt.offsetY+V}),da(S,lt.region.label,Rt,P,L,yt,k)}}if(et.enabled&&R&&(t==="freehand"||t==="rectangle"||t==="circular")){const j=v.current;if(j.isDrawing){const V=t==="freehand"?kt(dt):dt;if(V.length>=4){const lt=dn(V),ct=typeof r=="number"&&Number.isFinite(r)&&r>0?r:0,Rt=ct>0?lt*ct*ct/(Jr*Jr):0,yt=et.format(Rt),Pt=j.cursorScreen??(j.current?ge(a.current?.worldToScreen(j.current[0],j.current[1])??[]):null);Pt&&ma(S,yt,Pt,P,L,et.style,et.cursorOffsetX,et.cursorOffsetY)}}}},[R,t,ye,bt,Et,e,n,a,J,H,O,$,gt,wt,it,st,ht,pt,C,U,ot,et,rt,_,k,Y,r,K]),G=g.useCallback(()=>{Vt.current||(Vt.current=!0,requestAnimationFrame(()=>{Vt.current=!1,be()}))},[be]),q=g.useCallback((y=!1)=>{const S=v.current,I=ft.current;I&&S.pointerId!==null&&I.hasPointerCapture(S.pointerId)&&I.releasePointerCapture(S.pointerId),S.isDrawing=!1,S.pointerId=null,S.start=null,S.current=null,S.points=[],S.screenPoints=[],S.stampCenter=null,y||(S.cursor=null,S.cursorScreen=null)},[]),at=g.useCallback(y=>{const S=a.current;if(!S||e<=0||n<=0)return null;const I=ge(S.screenToWorld(y.clientX,y.clientY));return I?xn(I,e,n):null},[a,e,n]),xt=g.useCallback(y=>{const S=ft.current;if(!S)return null;const I=S.getBoundingClientRect(),P=D(y.clientX-I.left,0,I.width),L=D(y.clientY-I.top,0,I.height);return!Number.isFinite(P)||!Number.isFinite(L)?null:[P,L]},[]),Ie=g.useCallback(()=>{const y=v.current;if(!y.isDrawing){q(!0),G();return}let S=[];if(t==="freehand")y.points.length>=Ps&&(S=kt(y.points));else if(t==="rectangle")S=Sn(y.start,y.current,At());else if(t==="circular")S=Hn(y.start,y.current);else if(t==="brush"){const I=y.points[y.points.length-1]??y.current??y.start;if(K.clickSelectRoi&&I&&y.points.length<=1&&u?.(I)){q(!0),G();return}const P=Math.max(.25,K.edgeDetail),L=y.screenPoints.length>0?y.screenPoints:Et(y.points),dt=Math.max(.5,K.radius*.04/P),j=Ms(L,{radius:K.radius,circleSides:Math.max(16,Math.round(32*P)),simplifyTolerance:dt,smoothingPasses:K.edgeSmoothing}),V=[];for(const lt of j){const ct=Dt(lt);ct&&V.push(ct)}S=kt(V)}(t==="freehand"||t==="rectangle"||t==="circular"||t==="brush")&&li(S)&&c&&c({tool:t,intent:t==="brush"?"brush":"roi",coordinates:S,bbox:ei(S),areaPx:dn(S)}),q(!0),G()},[t,c,q,G,Et,Dt,At,K.radius,K.edgeDetail,K.edgeSmoothing,K.clickSelectRoi,u]),Pe=g.useCallback((y,S)=>{const I=It(y,S);if(!li(I))return;const P=y==="stamp-rectangle-4096px"?"patch":"roi",L={tool:y,intent:P,coordinates:I,bbox:ei(I),areaPx:dn(I)};c?.(L),P==="patch"&&f&&f(L)},[It,c,f]),le=g.useCallback((y,S,I)=>{const P=Math.max(Hs,K.radius*.1),L=P*P,dt=y.screenPoints[y.screenPoints.length-1];if(!dt){y.points.push(S),y.screenPoints.push(I),y.current=S;return}const j=I[0]-dt[0],V=I[1]-dt[1];j*j+V*V>=L?(y.points.push(S),y.screenPoints.push(I)):(y.points[y.points.length-1]=S,y.screenPoints[y.screenPoints.length-1]=I),y.current=S},[K.radius]),Xe=g.useCallback(y=>{if(!R||t==="cursor"||y.button!==0)return;const S=at(y);if(!S)return;const I=xt(y);if(!I)return;if(y.preventDefault(),y.stopPropagation(),nn(t)){const dt=v.current;dt.stampCenter=S,Pe(t,S),G();return}const P=ft.current;P&&P.setPointerCapture(y.pointerId);const L=v.current;L.isDrawing=!0,L.pointerId=y.pointerId,L.start=S,L.current=S,L.cursor=S,L.cursorScreen=I,L.points=t==="freehand"||t==="brush"?[S]:[],L.screenPoints=t==="brush"?[I]:[],G()},[R,t,at,xt,Pe,G]),We=g.useCallback(y=>{if(!R||t==="cursor")return;const S=at(y);if(!S)return;const I=xt(y);if(!I)return;const P=v.current;if(P.cursor=S,P.cursorScreen=I,nn(t)){P.stampCenter=S,y.preventDefault(),y.stopPropagation(),G();return}if(t==="brush"){if(!P.isDrawing||P.pointerId!==y.pointerId){G();return}y.preventDefault(),y.stopPropagation(),le(P,S,I),G();return}if(!(!P.isDrawing||P.pointerId!==y.pointerId)){if(y.preventDefault(),y.stopPropagation(),t==="freehand"){const L=a.current,dt=Math.max(1e-6,L?.getViewState?.().zoom??1),j=vs/dt,V=j*j,lt=P.points[P.points.length-1];if(!lt)P.points.push(S);else{const ct=S[0]-lt[0],Rt=S[1]-lt[1];ct*ct+Rt*Rt>=V&&P.points.push(S)}}else P.current=S;G()}},[R,t,at,xt,G,a,le]),ve=g.useCallback(y=>{const S=v.current;if(!S.isDrawing||S.pointerId!==y.pointerId)return;y.preventDefault(),y.stopPropagation();const I=at(y),P=xt(y);I&&(S.cursor=I,P&&(S.cursorScreen=P),t==="brush"?P&&le(S,I,P):S.current=I);const L=ft.current;L&&L.hasPointerCapture(y.pointerId)&&L.releasePointerCapture(y.pointerId),Ie()},[Ie,at,xt,t,le]),Ve=g.useCallback(()=>{const y=v.current;let S=!1;t==="brush"&&!y.isDrawing&&y.cursor&&(y.cursor=null,y.cursorScreen=null,S=!0),nn(t)&&y.stampCenter&&(y.stampCenter=null,S=!0),S&&G()},[t,G]);return g.useEffect(()=>{bt(),G();const y=ft.current;if(!y)return;const S=new ResizeObserver(()=>{bt(),G()});return S.observe(y),()=>{S.disconnect()}},[bt,G]),g.useEffect(()=>{R||q(),G()},[R,G,q]),g.useEffect(()=>{Gt.current!==t&&(Gt.current=t,q(),G())},[t,q,G]),g.useEffect(()=>{G()},[h,W,H,G]),g.useEffect(()=>{if(B)return B.current=G,()=>{B.current===G&&(B.current=null)}},[B,G]),g.useEffect(()=>{if(!R)return;const y=S=>{S.key==="Escape"&&(q(),G())};return window.addEventListener("keydown",y),()=>{window.removeEventListener("keydown",y)}},[R,q,G]),Xt.jsx("canvas",{ref:ft,className:nt,style:St,onPointerDown:Xe,onPointerMove:We,onPointerUp:ve,onPointerCancel:ve,onPointerLeave:Ve,onContextMenu:y=>{R&&y.preventDefault()},onWheel:y=>{if(!R)return;const S=ft.current,I=a.current;if(!S||typeof I?.zoomBy!="function")return;y.preventDefault(),y.stopPropagation();const P=S.getBoundingClientRect(),L=y.clientX-P.left,dt=y.clientY-P.top;I.zoomBy(y.deltaY<0?Ns:ks,L,dt),G()}})}function ui(t){return String(t??"").replace(/\/+$/,"")}function Oi(t){const e=String(t??"");return e.startsWith("/")?e:`/${e}`}function Ma(t){const e=ui(t);if(!e)return"";if(/\/TileGroup\d+$/i.test(e))return e;let n=null;try{n=new URL(e)}catch{n=null}if(n){const r=`${n.protocol}//${n.host}`,i=ui(n.pathname||"");return/\/ims$/i.test(i)?`${r}${i}`:/\/tiles$/i.test(i)?`${r}${i}`:`${r}${i}/tiles`}return/\/ims$/i.test(e)?"/ims":/\/tiles$/i.test(e)?`${e}`:`${e}/tiles`}function Aa(t,e){const n=t?.imsInfo??{},r=!!t?.imsInfo,i=Number(n.width??t?.width??0),o=Number(n.height??t?.height??0),s=Number(n.tileSize??t?.tileSize??0),a=Number(n.zoom??t?.zoom??0),u=String(n.path??t?.path??""),c=Number(n.mpp??t?.mpp??0);if(!i||!o||!s||!u)throw new Error("Incomplete image metadata: width/height/tileSize/path required");const f=Array.isArray(t?.terms)?t.terms.map(m=>({termId:String(m?.termId??""),termName:String(m?.termName??""),termColor:String(m?.termColor??"")})):[],l=Oi(u),h=Ma(e),d=r?(m,p,x)=>`${h}${l}/${m}/${x}_${p}.webp`:void 0;return{id:t?._id||"unknown",name:t?.name||"unknown",width:i,height:o,mpp:Number.isFinite(c)&&c>0?c:void 0,tileSize:s,maxTierZoom:Number.isFinite(a)?Math.max(0,Math.floor(a)):0,tilePath:u,tileBaseUrl:e,terms:f,tileUrlBuilder:d}}function ar(t,e,n,r){if(t.tileUrlBuilder)return t.tileUrlBuilder(e,n,r);const i=Oi(t.tilePath);return`${t.tileBaseUrl}${i}/${e}/${r}_${n}.webp`}const Nt={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 ci(t,e,n,r){const i=e.length;if(i===4){for(let o=0;o<i;o+=1){const s=e[o],a=e[(o+1)%i],u=Math.hypot(a[0]-s[0],a[1]-s[1]);if(u<1e-6)continue;const c=Math.max(1,Math.round((u+r)/(n+r))),f=c*n+(c-1)*r,l=u/Math.max(1e-6,f),h=n*l,d=r*l;t.beginPath(),t.moveTo(s[0],s[1]),t.lineTo(a[0],a[1]),t.setLineDash([h,d]),t.lineDashOffset=0,t.stroke()}t.setLineDash([]),t.lineDashOffset=0}}function Ae(t,e,n=1){return typeof t!="number"||!Number.isFinite(t)?e:Math.max(n,t)}function rn(t){return Array.isArray(t)&&t.length===4&&Number.isFinite(t[0])&&Number.isFinite(t[1])&&Number.isFinite(t[2])&&Number.isFinite(t[3])}const Ra={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 Yi({source:t,projectorRef:e,authToken:n="",options:r,invalidateRef:i,className:o,style:s}){const a=g.useRef(null),u=g.useRef(null),c=g.useRef(null),f=g.useRef({active:!1,pointerId:null}),l=g.useRef(null),h=g.useRef(!1),d=Ae(r?.width,Nt.width,64),m=Ae(r?.height,Nt.height,48),p=g.useMemo(()=>{const v=Math.max(1,t.width),R=Math.max(1,t.height),W=v/R,ut=d/m;let J,ht;return W>ut?(J=d,ht=d/W):(ht=m,J=m*W),{x:(d-J)/2,y:(m-ht)/2,w:J,h:ht}},[t.width,t.height,d,m]),x=Ae(r?.margin,Nt.margin,0),w=Ae(r?.borderRadius,Nt.borderRadius,0),M=Ae(r?.borderWidth,Nt.borderWidth,0),N=Math.max(1,Math.round(Ae(r?.maxThumbnailTiles,Nt.maxThumbnailTiles,1))),A=r?.backgroundColor||Nt.backgroundColor,C=r?.borderColor||Nt.borderColor,U=r?.viewportBorderColor||Nt.viewportBorderColor,H=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:Nt.viewportBorderStyle,O=r?.viewportFillColor??Nt.viewportFillColor,$=r?.interactive??Nt.interactive,Z=r?.showThumbnail??Nt.showThumbnail,Q=r?.position||Nt.position,rt=r?.onClose,_=r?.closeIcon,k=r?.closeButtonStyle,Y=g.useMemo(()=>{const v={};return Q==="top-left"||Q==="bottom-left"?v.left=x:v.right=x,Q==="top-left"||Q==="top-right"?v.top=x:v.bottom=x,{position:"absolute",...v,width:d,height:m,borderRadius:w,overflow:"hidden",zIndex:4,pointerEvents:$?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[x,Q,d,m,w,$,s]),B=g.useCallback(()=>{const v=a.current;if(!v)return;const R=v.getContext("2d");if(!R)return;const W=d,ut=m,J=Math.max(1,window.devicePixelRatio||1),ht=Math.max(1,Math.round(W*J)),gt=Math.max(1,Math.round(ut*J));(v.width!==ht||v.height!==gt)&&(v.width=ht,v.height=gt),R.setTransform(1,0,0,1,0,0),R.clearRect(0,0,v.width,v.height),R.setTransform(J,0,0,J,0,0),R.fillStyle=A,R.fillRect(0,0,W,ut);const{x:wt,y:it,w:pt,h:st}=p,ot=u.current;ot&&R.drawImage(ot,wt,it,pt,st),R.strokeStyle=C,R.lineWidth=M,R.strokeRect(M*.5,M*.5,W-M,ut-M);const et=e.current,Mt=et?.getViewBounds?.(),K=et?.getViewCorners?.(),St=rn(Mt)?Mt:rn(c.current)?c.current:null;if(!St)return;c.current=St;const bt=pt/Math.max(1,t.width),Et=st/Math.max(1,t.height),Dt=Array.isArray(K)&&K.length>=4&&K.every(at=>Array.isArray(at)&&at.length>=2&&Number.isFinite(at[0])&&Number.isFinite(at[1]))?K:null,At=H==="dash";if(Dt){const at=Dt.map(xt=>[wt+xt[0]*bt,it+xt[1]*Et]);R.save(),R.beginPath(),R.rect(wt,it,pt,st),R.clip(),R.beginPath();for(let xt=0;xt<at.length;xt+=1)xt===0?R.moveTo(at[xt][0],at[xt][1]):R.lineTo(at[xt][0],at[xt][1]);R.closePath(),R.fillStyle=O,R.fill(),R.strokeStyle=U,R.lineWidth=2.25,At?ci(R,at,4,3):R.stroke(),R.restore();return}const _t=D(wt+St[0]*bt,wt,wt+pt),It=D(it+St[1]*Et,it,it+st),ye=D(wt+St[2]*bt,wt,wt+pt),be=D(it+St[3]*Et,it,it+st),G=Math.max(1,ye-_t),q=Math.max(1,be-It);if(R.fillStyle=O,R.fillRect(_t,It,G,q),R.strokeStyle=U,R.lineWidth=2.25,At){const at=[[_t+.5,It+.5],[_t+.5+Math.max(1,G-1),It+.5],[_t+.5+Math.max(1,G-1),It+.5+Math.max(1,q-1)],[_t+.5,It+.5+Math.max(1,q-1)]];ci(R,at,4,3)}else R.strokeRect(_t+.5,It+.5,Math.max(1,G-1),Math.max(1,q-1))},[d,m,p,A,C,M,e,t.width,t.height,O,U,H]),nt=g.useCallback(()=>{h.current||(h.current=!0,l.current=requestAnimationFrame(()=>{h.current=!1,l.current=null,B()}))},[B]),zt=g.useCallback((v,R)=>{const W=a.current;if(!W)return null;const ut=W.getBoundingClientRect();if(!ut.width||!ut.height)return null;const J=ut.width/d,ht=ut.height/m,gt=p.x*J,wt=p.y*ht,it=p.w*J,pt=p.h*ht,st=D((v-ut.left-gt)/it,0,1),ot=D((R-ut.top-wt)/pt,0,1);return[st*t.width,ot*t.height]},[t.width,t.height,d,m,p]),ft=g.useCallback((v,R)=>{const W=e.current;if(!W)return;if(W.setViewCenter){W.setViewCenter(v,R),nt();return}const ut=W.getViewBounds?.(),J=rn(ut)?ut:rn(c.current)?c.current:null;if(!J)return;const ht=Math.max(1e-6,J[2]-J[0]),gt=Math.max(1e-6,J[3]-J[1]);W.setViewState({offsetX:v-ht*.5,offsetY:R-gt*.5}),nt()},[e,nt]),Vt=g.useCallback(v=>{if(!$||v.button!==0)return;const R=a.current;if(!R)return;const W=zt(v.clientX,v.clientY);W&&(v.preventDefault(),v.stopPropagation(),R.setPointerCapture(v.pointerId),f.current={active:!0,pointerId:v.pointerId},ft(W[0],W[1]))},[$,zt,ft]),Bt=g.useCallback(v=>{const R=f.current;if(!R.active||R.pointerId!==v.pointerId)return;const W=zt(v.clientX,v.clientY);W&&(v.preventDefault(),v.stopPropagation(),ft(W[0],W[1]))},[zt,ft]),Gt=g.useCallback(v=>{const R=f.current;if(!R.active||R.pointerId!==v.pointerId)return;const W=a.current;if(W&&W.hasPointerCapture(v.pointerId))try{W.releasePointerCapture(v.pointerId)}catch{}f.current={active:!1,pointerId:null},nt()},[nt]);return g.useEffect(()=>{let v=!1;u.current=null,nt();const R=0,W=2**(t.maxTierZoom-R),ut=Math.ceil(t.width/W),J=Math.ceil(t.height/W),ht=Math.max(1,Math.ceil(ut/t.tileSize)),gt=Math.max(1,Math.ceil(J/t.tileSize)),wt=ht*gt;if(!Z||wt>N)return;const it=document.createElement("canvas");it.width=Math.max(1,Math.round(p.w)),it.height=Math.max(1,Math.round(p.h));const pt=it.getContext("2d");if(!pt)return;pt.fillStyle=A,pt.fillRect(0,0,it.width,it.height);const st=[];for(let ot=0;ot<gt;ot+=1)for(let et=0;et<ht;et+=1){const Mt=et*t.tileSize*W,K=ot*t.tileSize*W,St=Math.min((et+1)*t.tileSize,ut)*W,bt=Math.min((ot+1)*t.tileSize,J)*W;st.push({url:ar(t,R,et,ot),bounds:[Mt,K,St,bt]})}return Promise.allSettled(st.map(async ot=>{const et=!!n,Mt=await fetch(ot.url,{headers:et?{Authorization:n}:void 0});if(!Mt.ok)throw new Error(`HTTP ${Mt.status}`);const K=await createImageBitmap(await Mt.blob());return{tile:ot,bitmap:K}})).then(ot=>{if(v){for(const K of ot)K.status==="fulfilled"&&K.value.bitmap.close();return}const et=it.width/Math.max(1,t.width),Mt=it.height/Math.max(1,t.height);for(const K of ot){if(K.status!=="fulfilled")continue;const{tile:{bounds:St},bitmap:bt}=K.value,Et=St[0]*et,Dt=St[1]*Mt,At=Math.max(1,(St[2]-St[0])*et),_t=Math.max(1,(St[3]-St[1])*Mt);pt.drawImage(bt,Et,Dt,At,_t),bt.close()}u.current=it,nt()}),()=>{v=!0}},[t,n,p,A,Z,N,nt]),g.useEffect(()=>{nt()},[nt]),g.useEffect(()=>{if(i)return i.current=nt,()=>{i.current===nt&&(i.current=null)}},[i,nt]),g.useEffect(()=>()=>{f.current={active:!1,pointerId:null},l.current!==null&&(cancelAnimationFrame(l.current),l.current=null),h.current=!1},[]),Xt.jsxs("div",{className:o,style:Y,children:[Xt.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:Vt,onPointerMove:Bt,onPointerUp:Gt,onPointerCancel:Gt,onContextMenu:v=>{v.preventDefault()},onWheel:v=>{v.preventDefault(),v.stopPropagation()}}),rt&&Xt.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:v=>{v.stopPropagation(),rt()},style:k?{...k}:{...Ra},children:_??"×"})]})}function Ca({imageWidth:t,imageHeight:e,tiles:n,viewState:r,className:i,style:o}){const s=g.useRef(null),a=g.useRef(null),u=g.useMemo(()=>({width:"100%",height:"100%",display:"block",...o}),[o]);return g.useEffect(()=>{const c=s.current;if(!c)return;const f=new Mi({canvas:c,imageWidth:t,imageHeight:e,initialViewState:r});return a.current=f,f.setTiles(n),()=>{f.destroy(),a.current=null}},[t,e]),g.useEffect(()=>{const c=a.current;c&&c.setTiles(n)},[n]),g.useEffect(()=>{const c=a.current;!c||!r||c.setViewState(r)},[r]),Xt.jsx("canvas",{ref:s,className:i,style:u})}function Ue(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return null;const n=Ye(e??[]);if(n.length===0){const m={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return t.fillModes instanceof Uint8Array&&(m.fillModes=new Uint8Array(0)),t.ids instanceof Uint32Array&&(m.ids=new Uint32Array(0)),m}const r=pe(t),i=t.positions,o=t.paletteIndices,s=t.fillModes instanceof Uint8Array&&t.fillModes.length>=r?t.fillModes:null,a=t.ids instanceof Uint32Array&&t.ids.length>=r?t.ids:null,u=new Float32Array(r*2),c=new Uint16Array(r),f=s?new Uint8Array(r):null,l=a?new Uint32Array(r):null;let h=0;for(let m=0;m<r;m+=1){const p=i[m*2],x=i[m*2+1];yn(p,x,n)&&(u[h*2]=p,u[h*2+1]=x,c[h]=o[m],f&&(f[h]=s[m]),l&&(l[h]=a[m]),h+=1)}const d={count:h,positions:u.subarray(0,h*2),paletteIndices:c.subarray(0,h)};return f&&(d.fillModes=f.subarray(0,h)),l&&(d.ids=l.subarray(0,h)),d}function Xi(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return new Uint32Array(0);const n=Ye(e??[]);if(n.length===0)return new Uint32Array(0);const r=pe(t);if(r===0)return new Uint32Array(0);const i=t.positions,o=new Uint32Array(r);let s=0;for(let a=0;a<r;a+=1){const u=i[a*2],c=i[a*2+1];yn(u,c,n)&&(o[s]=a,s+=1)}return o.subarray(0,s)}let on=null;const Ia=`
|
|
33
34
|
struct Params {
|
|
34
35
|
pointCount: u32,
|
|
35
36
|
boundsCount: u32,
|
|
@@ -60,7 +61,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
60
61
|
}
|
|
61
62
|
outputMask[i] = inside;
|
|
62
63
|
}
|
|
63
|
-
`;function Ms(){if(typeof navigator>"u")return!1;const e=navigator;return typeof e.gpu=="object"&&e.gpu!==null}function oi(){if(!Ms())return null;const t=navigator.gpu;if(!t||typeof t!="object")return null;const n=t;return typeof n.requestAdapter!="function"?null:n}const Ht=globalThis.GPUShaderStage?.COMPUTE??4,bn=globalThis.GPUBufferUsage?.STORAGE??128,Zt=globalThis.GPUBufferUsage?.COPY_DST??8,Cs=globalThis.GPUBufferUsage?.COPY_SRC??4,As=globalThis.GPUBufferUsage?.UNIFORM??64,Rs=globalThis.GPUBufferUsage?.MAP_READ??1,Ts=globalThis.GPUMapMode?.READ??1;async function Is(){const e=oi();if(!e)return{supported:!1,features:[]};const t=await e.requestAdapter();return t?{supported:!0,adapterName:t.info?.description??t.info?.vendor??"unknown",features:Array.from(t.features),limits:{maxStorageBufferBindingSize:Number(t.limits.maxStorageBufferBindingSize),maxComputeInvocationsPerWorkgroup:Number(t.limits.maxComputeInvocationsPerWorkgroup),maxComputeWorkgroupSizeX:Number(t.limits.maxComputeWorkgroupSizeX)}}:{supported:!1,features:[]}}async function Ps(){return qt||(qt=(async()=>{const e=oi();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:Ht,buffer:{type:"read-only-storage"}},{binding:1,visibility:Ht,buffer:{type:"read-only-storage"}},{binding:2,visibility:Ht,buffer:{type:"storage"}},{binding:3,visibility:Ht,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}})(),qt)}function $t(e,t){return Math.ceil(e/t)*t}async function si(e,t,n){const r=await Ps();if(!r)return null;const i=Math.max(0,Math.floor(t)),o=Math.max(0,Math.floor(n.length/4));if(i===0||o===0)return new Uint32Array(0);const s=Math.min(i,Math.floor(e.length/2));if(s===0)return new Uint32Array(0);const a=s*2*Float32Array.BYTES_PER_ELEMENT,c=o*4*Float32Array.BYTES_PER_ELEMENT,l=s*Uint32Array.BYTES_PER_ELEMENT,u=Number(r.device.limits.maxStorageBufferBindingSize);if(a>u||c>u||l>u)return null;const f=r.device.createBuffer({size:$t(a,4),usage:bn|Zt}),d=r.device.createBuffer({size:$t(c,4),usage:bn|Zt}),g=r.device.createBuffer({size:$t(l,4),usage:bn|Cs}),p=r.device.createBuffer({size:16,usage:As|Zt}),S=r.device.createBuffer({size:$t(l,4),usage:Zt|Rs});let x=!1;try{r.device.queue.writeBuffer(f,0,e.buffer,e.byteOffset,a),r.device.queue.writeBuffer(d,0,n.buffer,n.byteOffset,c),r.device.queue.writeBuffer(p,0,new Uint32Array([s,o,0,0]));const M=r.device.createBindGroup({layout:r.bindGroupLayout,entries:[{binding:0,resource:{buffer:f}},{binding:1,resource:{buffer:d}},{binding:2,resource:{buffer:g}},{binding:3,resource:{buffer:p}}]}),R=r.device.createCommandEncoder(),V=R.beginComputePass();V.setPipeline(r.pipeline),V.setBindGroup(0,M),V.dispatchWorkgroups(Math.ceil(s/256)),V.end(),R.copyBufferToBuffer(g,0,S,0,l),r.device.queue.submit([R.finish()]),await S.mapAsync(Ts),x=!0;const T=S.getMappedRange();return new Uint32Array(T.slice(0))}finally{if(x)try{S.unmap()}catch{}f.destroy(),d.destroy(),g.destroy(),p.destroy(),S.destroy()}}async function ai(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=vt(t??[]);if(o.length===0){const T={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return e.fillModes instanceof Uint8Array&&(T.fillModes=new Uint8Array(0)),e.ids instanceof Uint32Array&&(T.ids=new Uint32Array(0)),{data:T,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const s=at(e),a=e.fillModes instanceof Uint8Array&&e.fillModes.length>=s?e.fillModes:null,c=e.ids instanceof Uint32Array&&e.ids.length>=s?e.ids:null;if(s===0){const T={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(T.fillModes=new Uint8Array(0)),c&&(T.ids=new Uint32Array(0)),{data:T,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const l=new Float32Array(o.length*4);for(let T=0;T<o.length;T+=1){const F=T*4,G=o[T];l[F]=G.minX,l[F+1]=G.minY,l[F+2]=G.maxX,l[F+3]=G.maxY}let u=null,f=!1;try{u=await si(e.positions,s,l),f=!!u}catch{u=null,f=!1}if(!u)return{data:It(e,t),meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!1,candidateCount:s,bridgedToDraw:!1}};let d=0;for(let T=0;T<s;T+=1)u[T]===1&&(d+=1);const g=new Uint32Array(d);if(d>0){let T=0;for(let F=0;F<s;F+=1)u[F]===1&&(g[T]=F,T+=1)}if(d===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 T={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(T.fillModes=new Uint8Array(0)),c&&(T.ids=new Uint32Array(0)),{data:T,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const T=new Uint32Array(d);let F=0;for(let J=0;J<d;J+=1){const j=g[J]??0,Q=e.positions[j*2],se=e.positions[j*2+1];tn(Q,se,o)&&(T[F]=j,F+=1)}const G={count:s,positions:e.positions.subarray(0,s*2),paletteIndices:e.paletteIndices.subarray(0,s),drawIndices:T.subarray(0,F)};return a&&(G.fillModes=a.subarray(0,s)),c&&(G.ids=c.subarray(0,s)),{data:G,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!0,candidateCount:d,bridgedToDraw:!0}}}const p=new Float32Array(d*2),S=new Uint16Array(d),x=a?new Uint8Array(d):null,M=c?new Uint32Array(d):null;let R=0;for(let T=0;T<d;T+=1){const F=g[T]??0,G=e.positions[F*2],J=e.positions[F*2+1];tn(G,J,o)&&(p[R*2]=G,p[R*2+1]=J,S[R]=e.paletteIndices[F],x&&(x[R]=a[F]),M&&(M[R]=c[F]),R+=1)}const V={count:R,positions:p.subarray(0,R*2),paletteIndices:S.subarray(0,R)};return x&&(V.fillModes=x.subarray(0,R)),M&&(V.ids=M.subarray(0,R)),{data:V,meta:{mode:"hybrid-webgpu",durationMs:fe()-r,usedWebGpu:!0,candidateCount:d,bridgedToDraw:!1}}}class ci{constructor(t,n){w(this,"worker",null);w(this,"supported",!0);w(this,"requestId",1);w(this,"pendingById",new Map);w(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))});w(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 ci(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/roi-clip-worker-BuNuUQQg.js").href:new URL("assets/roi-clip-worker-BuNuUQQg.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:pt&&pt.tagName.toUpperCase()==="SCRIPT"&&pt.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)),l=new Uint32Array(e.indices).subarray(0,c);t.resolve({indices:l,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 Es(){Pt.terminate("worker terminated")}async function ui(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return{data:null,meta:{mode:"worker",durationMs:0}};const n=at(e),r=e.positions.slice(0,n*2),i=e.paletteIndices.slice(0,n),o=e.fillModes instanceof Uint8Array&&e.fillModes.length>=n?e.fillModes.slice(0,n):null,s=e.ids instanceof Uint32Array&&e.ids.length>=n?e.ids.slice(0,n):null;return new Promise((a,c)=>{const l=fe(),u=Pt.beginRequest({kind:"data",resolve:a,reject:c,startMs:l});if(!u){a({data:It(e,t),meta:{mode:"sync",durationMs:fe()-l}});return}const f={type:"roi-clip-request",id:u.id,count:n,positions:r.buffer,paletteIndices:i.buffer,fillModes:o?.buffer,ids:s?.buffer,polygons:t??[]},d=[r.buffer,i.buffer];o&&d.push(o.buffer),s&&d.push(s.buffer);try{u.worker.postMessage(f,d)}catch(g){const p=Pt.cancelRequest(u.id);p?p.reject(g):c(g)}})}async function vs(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return{indices:new Uint32Array(0),meta:{mode:"worker",durationMs:0}};const n=at(e),r=e.positions.slice(0,n*2);return new Promise((i,o)=>{const s=fe(),a=Pt.beginRequest({kind:"index",resolve:i,reject:o,startMs:s});if(!a){i({indices:ii(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(l){const u=Pt.cancelRequest(a.id);u?u.reject(l):o(l)}})}const _s=24,Fs=1024,Bs=4,en=-1;function Ct(e,t,n){return(e*73856093^t*19349663)>>>0&n}function Us(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))*Bs;return Math.max(_s,Math.min(Fs,o))}function Ns(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 ks(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=Ns(e.drawIndices??null,r),o=i?i.length:r;if(o===0)return null;const s=Us(e.sourceWidth,e.sourceHeight,o),a=1/s,c=new Int32Array(o),l=new Int32Array(o);let u=0;if(i)for(let B=0;B<o;B+=1){const k=i[B],O=e.positions[k*2],U=e.positions[k*2+1];!Number.isFinite(O)||!Number.isFinite(U)||(c[u]=Math.floor(O*a),l[u]=Math.floor(U*a),u+=1)}else for(let B=0;B<r;B+=1){const k=e.positions[B*2],O=e.positions[B*2+1];!Number.isFinite(k)||!Number.isFinite(O)||(c[u]=Math.floor(k*a),l[u]=Math.floor(O*a),u+=1)}if(u===0)return null;let f=Math.min(u,Math.max(64,u>>>3));(!Number.isFinite(f)||f<=0)&&(f=u);let d=1;for(;d<f*2;)d<<=1;let g=d-1,p=new Int32Array(d*2),S=new Int32Array(d);p.fill(2147483647);let x=0;const M=new Int32Array(u);for(let B=0;B<u;B+=1){const k=c[B],O=l[B];let U=Ct(k,O,g);for(;;){const ee=p[U*2];if(ee===2147483647){if(p[U*2]=k,p[U*2+1]=O,S[U]=1,M[B]=U,x+=1,x*4>d*3){const Ne=d;d<<=1,g=d-1;const ue=new Int32Array(d*2),Oe=new Int32Array(d);ue.fill(2147483647);for(let Be=0;Be<Ne;Be+=1){if(p[Be*2]===2147483647)continue;const Ye=p[Be*2],P=p[Be*2+1];let C=Ct(Ye,P,g);for(;ue[C*2]!==2147483647;)C=C+1&g;ue[C*2]=Ye,ue[C*2+1]=P,Oe[C]=S[Be]}for(p=ue,S=Oe,U=Ct(k,O,g);p[U*2]!==k||p[U*2+1]!==O;)U=U+1&g;M[B]=U}break}if(ee===k&&p[U*2+1]===O){S[U]+=1,M[B]=U;break}U=U+1&g}}const R=new Int32Array(x*2),V=new Uint32Array(x),T=new Uint32Array(x),F=new Int32Array(d);F.fill(en);let G=0,J=0;for(let B=0;B<d;B+=1)p[B*2]!==2147483647&&(R[G*2]=p[B*2],R[G*2+1]=p[B*2+1],V[G]=J,T[G]=S[B],F[B]=G,J+=S[B],G+=1);const j=new Uint32Array(u),Q=new Uint32Array(x);if(Q.set(V),i)for(let B=0;B<u;B+=1){const k=F[M[B]];j[Q[k]]=i[B],Q[k]+=1}else{let B=0;for(let k=0;k<r;k+=1){const O=e.positions[k*2],U=e.positions[k*2+1];if(!Number.isFinite(O)||!Number.isFinite(U))continue;const ee=F[M[B]];j[Q[ee]]=k,Q[ee]+=1,B+=1}}let se=1;for(;se<x*2;)se<<=1;const pe=se-1,Re=new Int32Array(se);Re.fill(en);for(let B=0;B<x;B+=1){const k=R[B*2],O=R[B*2+1];let U=Ct(k,O,pe);for(;Re[U]!==en;)U=U+1&pe;Re[U]=B}return{cellSize:s,safeCount:r,cellCount:x,hashCapacity:se,hashTable:Re,cellKeys:R,cellOffsets:V,cellLengths:T,pointIndices:j}}function li(e,t,n){const{hashTable:r,cellKeys:i,hashMask:o}=e;let s=Ct(t,n,o);for(;;){const a=r[s];if(a===en)return-1;if(i[a*2]===t&&i[a*2+1]===n)return a;s=s+1&o}}function Ls(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 Tn=new ci(()=>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:pt&&pt.tagName.toUpperCase()==="SCRIPT"&&pt.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(Ls(e,t.pointData))},rejectPending:(e,t)=>{e.reject(t)}});function zs(){Tn.terminate("worker terminated")}function Ds(e,t){const n=at(e);if(n<=0)return null;const r=e.positions.subarray(0,n*2),i=ks({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 fi(e,t){if(!e||!e.positions||!e.paletteIndices)return null;const n=at(e);return n<=0?null:new Promise((r,i)=>{const o={resolve:r,reject:i,pointData:e},s=Tn.beginRequest(o);if(!s||!s.worker){r(Ds(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,l={type:"point-hit-index-request",id:s.id,count:n,positions:a.buffer,drawIndices:c?.buffer,sourceWidth:t?.width??0,sourceHeight:t?.height??0},u=[a.buffer];c&&u.push(c.buffer);try{s.worker.postMessage(l,u)}catch(f){const d=Tn.cancelRequest(s.id);d?d.reject(f):i(f)}})}function Os(e){const t=[];for(let n=0;n<e.length;n+=1){const r=e[n],i=vt([Et(r?.coordinates)]);if(i.length===0)continue;let o=0,s=1/0,a=1/0,c=-1/0,l=-1/0;for(const u of i)o+=u.area,u.minX<s&&(s=u.minX),u.minY<a&&(a=u.minY),u.maxX>c&&(c=u.maxX),u.maxY>l&&(l=u.maxY);!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(c)||!Number.isFinite(l)||t.push({regionId:r.id??n,regionIndex:n,polygons:i,area:Math.max(1e-6,o),minX:s,minY:a,maxX:c,maxY:l})}return t}const Ys=128,yn=[];function gt(e,t,n,r,i){if(i<=1||n<=t)return 0;const o=(e-t)/r;return!Number.isFinite(o)||o<=0?0:o>=i-1?i-1:Math.floor(o)}function Xs(e){if(e.length===0)return null;let t=1/0,n=1/0,r=-1/0,i=-1/0;for(const u of e)u.minX<t&&(t=u.minX),u.minY<n&&(n=u.minY),u.maxX>r&&(r=u.maxX),u.maxY>i&&(i=u.maxY);if(!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i))return null;const o=Math.ceil(Math.sqrt(e.length*2)),s=Math.max(1,Math.min(Ys,o)),a=r>t?(r-t)/s:1,c=i>n?(i-n)/s:1,l=Array.from({length:s*s},()=>[]);for(let u=0;u<e.length;u+=1){const f=e[u],d=gt(f.minX,t,r,a,s),g=gt(f.maxX,t,r,a,s),p=gt(f.minY,n,i,c,s),S=gt(f.maxY,n,i,c,s);for(let x=p;x<=S;x+=1)for(let M=d;M<=g;M+=1)l[x*s+M].push(u)}return{minX:t,minY:n,maxX:r,maxY:i,gridSize:s,cellWidth:a,cellHeight:c,buckets:l}}function Ws(e,t,n){if(!e||t<e.minX||t>e.maxX||n<e.minY||n>e.maxY)return yn;const r=gt(t,e.minX,e.maxX,e.cellWidth,e.gridSize),i=gt(n,e.minY,e.maxY,e.cellHeight,e.gridSize);return e.buckets[i*e.gridSize+r]??yn}function Vs(e,t){if(Array.isArray(t)){const n=t[e];if(typeof n=="string"&&n.length>0)return n}if(t instanceof Map){const n=t.get(e);if(typeof n=="string"&&n.length>0)return n}return String(e)}function di(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 g=e.drawIndices;let p=g.length;for(let S=0;S<g.length;S+=1)g[S]<r||(p-=1);if(p===g.length)i=g;else if(p>0){const S=new Uint32Array(p);let x=0;for(let M=0;M<g.length;M+=1){const R=g[M];R>=r||(S[x]=R,x+=1)}i=S}else i=new Uint32Array(0)}const o=i?i.length:r,s=Os(t??[]);if(!e||o===0||s.length===0)return{groups:[],inputPointCount:o,pointsInsideAnyRegion:0,unmatchedPointCount:o};const a=new Map,c=new Map,l=Xs(s);let u=0;for(let g=0;g<o;g+=1){const p=i?i[g]:g,S=e.positions[p*2],x=e.positions[p*2+1];if(!Number.isFinite(S)||!Number.isFinite(x))continue;let M=null;const R=Ws(l,S,x);if(R.length===0)continue;for(const F of R){const G=s[F];let J=!1;for(const j of G.polygons)if(Wr(S,x,j)){J=!0;break}J&&(!M||G.area<M.area)&&(M=G)}if(!M)continue;u+=1;const V=e.paletteIndices[p]??0,T=a.get(M.regionIndex)??new Map;T.set(V,(T.get(V)??0)+1),a.set(M.regionIndex,T),c.set(M.regionIndex,(c.get(M.regionIndex)??0)+1)}const f=n.includeEmptyRegions??!1,d=[];for(const g of s){const p=c.get(g.regionIndex)??0;if(!f&&p<=0)continue;const S=a.get(g.regionIndex)??new Map,x=Array.from(S.entries()).map(([M,R])=>({termId:Vs(M,n.paletteIndexToTermId),paletteIndex:M,count:R})).sort((M,R)=>R.count-M.count||M.paletteIndex-R.paletteIndex);d.push({regionId:g.regionId,regionIndex:g.regionIndex,totalCount:p,termCounts:x})}return{groups:d,inputPointCount:o,pointsInsideAnyRegion:u,unmatchedPointCount:Math.max(0,o-u)}}function Gs(e,t){if(!t)return!1;try{const r=new URL(e,typeof window<"u"?window.location.href:void 0).hostname.toLowerCase();if(r.includes("amazonaws.com")||r.startsWith("s3.")||r.includes(".s3."))return!1}catch{}return!0}class hi{constructor(t){w(this,"maxConcurrency");w(this,"maxRetries");w(this,"retryBaseDelayMs");w(this,"retryMaxDelayMs");w(this,"onTileLoad");w(this,"onTileError");w(this,"onStateChange");w(this,"authToken");w(this,"destroyed",!1);w(this,"queue",[]);w(this,"queuedByKey",new Map);w(this,"inflight",new Map);w(this,"visibleKeys",new Set);w(this,"timerId",null);w(this,"abortedCount",0);w(this,"retryCount",0);w(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=globalThis.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=Gs(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),l={tile:t.tile,attempt:a,readyAt:fe()+c},u=this.queuedByKey.get(t.tile.key);u?(u.tile=l.tile,u.readyAt=Math.min(u.readyAt,l.readyAt),u.attempt=Math.max(u.attempt,l.attempt)):(this.queue.push(l),this.queuedByKey.set(l.tile.key,l)),this.sortQueue();return}this.failedCount+=1,this.onTileError?.(t.tile,o,t.attempt+1)}).finally(()=>{this.inflight.delete(t.tile.key),this.pump(),this.emitStateChange()})}getRetryDelay(t){const n=Math.max(0,t-1),r=Math.min(this.retryMaxDelayMs,this.retryBaseDelayMs*2**n),i=.85+Math.random()*.3;return Math.round(r*i)}clearPumpTimer(){this.timerId!==null&&(globalThis.clearTimeout(this.timerId),this.timerId=null)}emitStateChange(){this.onStateChange?.(this.getSnapshot())}}function qs(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 Hs(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 Zs(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 In=.35,Pn=.5,$s=256,En=[{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}],Ks=.1,js=5,Js=0,Qs=1,ea=-100,ta=100,na=2e3;function mi(e){return e*Math.PI/180}function Kt(e,t){return!e||!t?e===t:e.buffer===t.buffer&&e.byteOffset===t.byteOffset&&e.byteLength===t.byteLength}function vn(e){return e.map(t=>({zoom:t.zoom,size:t.size}))}function Ir(e){if(!e)return vn(En);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?vn(En):Array.from(t.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function ra(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n].zoom!==t[n].zoom||e[n].size!==t[n].size)return!1;return!0}function ia(e,t){if(!Number.isFinite(e))return t[0]?.size??Pn;if(t.length===0)return Pn;if(t.length===1||e<=t[0].zoom)return t[0].size;for(let s=1;s<t.length;s+=1){const a=t[s-1],c=t[s];if(e>c.zoom)continue;const l=Math.max(1e-6,c.zoom-a.zoom),u=L((e-a.zoom)/l,0,1);return a.size+(c.size-a.size)*u}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 Pr(e){return typeof e!="number"||!Number.isFinite(e)?1:L(e,Ks,js)}function Er(e){return typeof e!="number"||!Number.isFinite(e)?0:L(e,Js,Qs)}function wn(e){return typeof e!="number"||!Number.isFinite(e)?0:L(e,ea,ta)}function vr(e){const t=wn(e?.brightness),n=wn(e?.contrast),r=wn(e?.saturation);return{brightness:t/200,contrast:n/100,saturation:r/100}}function gi(e){return e}function xn(e){return typeof e!="number"||!Number.isFinite(e)?0:L(e,0,na)}function jt(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:Math.max(1e-6,e)}function Sn(e){return typeof e=="function"?e:gi}function pi(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 bi(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 oa(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"?pi(n,t.clientX,t.clientY):null,n.classList.add("dragging"),n.setPointerCapture(t.pointerId))}function sa(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 l=t.clientX-r.lastPointerX,u=t.clientY-r.lastPointerY;if(r.lastPointerX=t.clientX,r.lastPointerY=t.clientY,r.mode==="rotate"){const f=pi(n,t.clientX,t.clientY),d=r.rotateLastAngleRad;if(r.rotateLastAngleRad=f,d!==null){const g=f-d,p=Math.atan2(Math.sin(g),Math.cos(g)),S=i.rotationDragSensitivityDegPerPixel/In,x=o.getViewState();o.setViewState({rotationDeg:x.rotationDeg-p*180/Math.PI*S})}}else{const f=o.getViewState(),d=Math.max(1e-6,f.zoom),g=mi(f.rotationDeg),p=Math.cos(g),S=Math.sin(g),x=(l*p-u*S)/d,M=(l*S+u*p)/d;o.setViewState({offsetX:f.offsetX-x,offsetY:f.offsetY-M})}s(),a(),c()}function aa(e,t,n){e.pointerId===n.pointerId&&bi(t,n)}function ca(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 ua(e){const{event:t,canvas:n,onZoomBy:r}=e,i=n.getBoundingClientRect(),o=t.clientX-i.left,s=t.clientY-i.top;r(t.shiftKey?.8:1.25,o,s)}function la(e,t){(t||e.ctrlKey||e.metaKey)&&e.preventDefault()}function Dn(e){const t=e.getViewCorners();let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[s,a]of t)s<n&&(n=s),s>i&&(i=s),a<r&&(r=a),a>o&&(o=a);return[n,r,i,o]}function _n(e,t){const n=Dn(e),r=Math.max(1e-6,n[2]-n[0]),i=Math.max(1e-6,n[3]-n[1]),o=r*.2,s=i*.2,[a,c]=e.getCenter(),l=r*.5,u=i*.5,f=l-o,d=t.width-l+o,g=u-s,p=t.height-u+s,S=f<=d?L(a,f,d):t.width*.5,x=g<=p?L(c,g,p):t.height*.5;e.setCenter(S,x)}function fa(e,t){const n=Math.max(1e-6,e.getViewState().zoom),r=t.maxTierZoom+Math.log2(n);return L(Math.floor(r),0,t.maxTierZoom)}function da(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function yi(e,t,n){const r=Dn(e),i=Math.pow(2,t.maxTierZoom-n),o=Math.ceil(t.width/i),s=Math.ceil(t.height/i),a=Math.max(1,Math.ceil(o/t.tileSize)),c=Math.max(1,Math.ceil(s/t.tileSize)),l=r[0],u=r[1],f=r[2],d=r[3],g=L(Math.floor(l/i/t.tileSize),0,a-1),p=L(Math.floor((f-1)/i/t.tileSize),0,a-1),S=L(Math.floor(u/i/t.tileSize),0,c-1),x=L(Math.floor((d-1)/i/t.tileSize),0,c-1);if(g>p||S>x)return[];const M=(l+f)*.5/i/t.tileSize,R=(u+d)*.5/i/t.tileSize,V=[];for(let T=S;T<=x;T+=1)for(let F=g;F<=p;F+=1){const G=F*t.tileSize*i,J=T*t.tileSize*i,j=Math.min((F+1)*t.tileSize,o)*i,Q=Math.min((T+1)*t.tileSize,s)*i,se=F-M,pe=T-R;V.push({key:`${n}/${F}/${T}`,tier:n,x:F,y:T,bounds:[G,J,j,Q],distance2:se*se+pe*pe,url:zn(t,n,F,T)})}return V.sort((T,F)=>T.distance2-F.distance2),V}function ha(e,t){const n=fa(e,t);return{tier:n,visible:yi(e,t,n)}}function ma(e){e.interactionLocked||oa({event:e.event,canvas:e.canvas,state:e.state,config:{ctrlDragRotate:e.ctrlDragRotate,rotationDragSensitivityDegPerPixel:e.rotationDragSensitivityDegPerPixel},cancelViewAnimation:e.cancelViewAnimation})}function ga(e){e.interactionLocked||sa({event:e.event,canvas:e.canvas,state:e.state,config:{ctrlDragRotate:e.ctrlDragRotate,rotationDragSensitivityDegPerPixel:e.rotationDragSensitivityDegPerPixel},camera:e.camera,clampViewState:()=>_n(e.camera,e.source),emitViewState:e.emitViewState,requestRender:e.requestRender})}function pa(e){e.interactionLocked||aa(e.event,e.canvas,e.state)}function ba(e){if(e.interactionLocked){e.event.preventDefault();return}ca({event:e.event,canvas:e.canvas,onZoomBy:e.onZoomBy})}function ya(e){e.interactionLocked||ua({event:e.event,canvas:e.canvas,onZoomBy:e.onZoomBy})}function wa(e){la(e.event,e.state.dragging)}function xa(e,t){bi(e,t)}function Sa(e){return{pointerDown:t=>ma({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state,ctrlDragRotate:e.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:e.getRotationDragSensitivityDegPerPixel(),cancelViewAnimation:e.cancelViewAnimation}),pointerMove:t=>ga({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=>pa({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state}),wheel:t=>ba({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,onZoomBy:e.zoomBy}),doubleClick:t=>ya({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,onZoomBy:e.zoomBy}),contextMenu:t=>wa({event:t,canvas:e.canvas,state:e.state})}}function Ma(e){const{gl:t,cache:n,maxCacheTiles:r}=e;if(n.size<=r)return;const i=Math.max(0,Math.floor(r));for(;n.size>i;){let o=null,s=null;for(const[a,c]of n)(!s||c.lastUsed<s.lastUsed)&&(o=a,s=c);if(!o||!s)break;t.deleteTexture(s.texture),n.delete(o)}}function Ca(e,t){if(e.isContextLost())return null;const n=e.createTexture();return n?(e.bindTexture(e.TEXTURE_2D,n),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,1),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.bindTexture(e.TEXTURE_2D,null),n):null}function Aa(e){const{gl:t,cache:n,tile:r,bitmap:i,frameSerial:o,maxCacheTiles:s,destroyed:a,contextLost:c,requestRender:l}=e;if(a||c||t.isContextLost()){i.close();return}if(n.has(r.key)){i.close();return}const u=Ca(t,i);i.close(),u&&(n.set(r.key,{key:r.key,texture:u,bounds:r.bounds,tier:r.tier,lastUsed:o}),Ma({gl:t,cache:n,maxCacheTiles:s}),l())}function Ra(e,t){for(const[,n]of t)e.deleteTexture(n.texture)}function Ta(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 l=e.frame;return l!==null&&(cancelAnimationFrame(l),l=null),i(),o(),s.clear(),a.clear(),c?.(),{handled:!0,frame:l}}function Ia(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()&&(Ra(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 Pa(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 Ea(e,t){return t<=0?new Uint8Array(0):e.length<t?new Uint8Array(t):e.subarray(0,t)}function va(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 _a(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),l=i.paletteIndices.subarray(0,a),u=s?o.subarray(0,a):void 0,f=i.drawIndices instanceof Uint32Array,d=f?Pa(i.drawIndices,a):null,g=e.lastPointData,p=g?.fillModes instanceof Uint8Array,S=e.pointBuffersDirty||!g||g.count!==a||!Kt(g.positions,c)||!Kt(g.paletteIndices,l)||p!==s||s&&(!g?.fillModes||!Kt(g.fillModes,u)),x=e.pointBuffersDirty||f&&(!g?.drawIndices||!Kt(g.drawIndices,d))||!f&&!!g?.drawIndices,M={...e,lastPointData:{count:a,positions:c,paletteIndices:l,fillModes:u,drawIndices:f?d??void 0:void 0}};if(r||t.isContextLost())return M;const R=M.lastPointData;if(!R)return M;if(S){t.bindBuffer(t.ARRAY_BUFFER,n.posBuffer),t.bufferData(t.ARRAY_BUFFER,R.positions,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,n.termBuffer),t.bufferData(t.ARRAY_BUFFER,R.paletteIndices,t.STATIC_DRAW);const V=Ea(M.zeroFillModes,a);t.bindBuffer(t.ARRAY_BUFFER,n.fillModeBuffer),t.bufferData(t.ARRAY_BUFFER,R.fillModes??V,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,null),M.zeroFillModes=V}return f&&x&&(t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,n.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,d??new Uint32Array(0),t.DYNAMIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null)),M.usePointIndices=f,M.pointCount=f?d?.length??0:R.count,(S||x)&&(M.pointBuffersDirty=!1),M}function Fa(e){const{gl:t,camera:n,source:r,cache:i,frameSerial:o,tileProgram:s,pointProgram:a,imageColorSettings:c,pointCount:l,usePointIndices:u,pointPaletteSize:f,pointStrokeScale:d,pointInnerFillOpacity:g,pointSizePx:p,tileScheduler:S,getVisibleTiles:x,getVisibleTilesForTier:M,getViewBounds:R,intersectsBounds:V}=e;t.clearColor(.03,.06,.1,1),t.clear(t.COLOR_BUFFER_BIT);const{tier:T,visible:F}=x(),G=R(),J=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 j=[];for(const[,O]of i)J.has(O.key)||V(O.bounds,G)&&j.push(O);j.sort((O,U)=>O.tier-U.tier);for(const O of j)O.lastUsed=o,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,O.texture),t.uniform4f(s.uBounds,O.bounds[0],O.bounds[1],O.bounds[2],O.bounds[3]),t.drawArrays(t.TRIANGLE_STRIP,0,4);let Q=0;const se=[];for(const O of F){const U=i.get(O.key);if(!U){se.push(O);continue}U.lastUsed=o,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,U.texture),t.uniform4f(s.uBounds,U.bounds[0],U.bounds[1],U.bounds[2],U.bounds[3]),t.drawArrays(t.TRIANGLE_STRIP,0,4),Q+=1}const pe=se.slice(),Re=1e6,B=[];T>0&&B.push(T-1),T<r.maxTierZoom&&B.push(T+1);for(const O of B){const U=M(O);for(const ee of U)i.has(ee.key)||(ee.distance2+=Re,pe.push(ee))}S.schedule(pe),t.bindTexture(t.TEXTURE_2D,null),t.bindVertexArray(null);let k=0;return l>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,p),t.uniform1f(a.uPointStrokeScale,d),t.uniform1f(a.uPointInnerFillAlpha,g),t.uniform1f(a.uPaletteSize,f),t.uniform1i(a.uPalette,1),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,a.paletteTexture),u?t.drawElements(t.POINTS,l,t.UNSIGNED_INT,0):t.drawArrays(t.POINTS,0,l),t.bindTexture(t.TEXTURE_2D,null),t.bindVertexArray(null),k=l),{tier:T,visible:F.length,rendered:Q,points:k,fallback:j.length,cacheHits:Q,cacheMisses:se.length,drawCalls:j.length+Q+(k>0?1:0)}}function _r(e){const r=Bn(e,`#version 300 es
|
|
64
|
+
`;function Pa(){if(typeof navigator>"u")return!1;const t=navigator;return typeof t.gpu=="object"&&t.gpu!==null}function Wi(){if(!Pa())return null;const e=navigator.gpu;if(!e||typeof e!="object")return null;const n=e;return typeof n.requestAdapter!="function"?null:n}const sn=globalThis.GPUShaderStage?.COMPUTE??4,kn=globalThis.GPUBufferUsage?.STORAGE??128,an=globalThis.GPUBufferUsage?.COPY_DST??8,va=globalThis.GPUBufferUsage?.COPY_SRC??4,Ta=globalThis.GPUBufferUsage?.UNIFORM??64,_a=globalThis.GPUBufferUsage?.MAP_READ??1,Fa=globalThis.GPUMapMode?.READ??1;async function Na(){const t=Wi();if(!t)return{supported:!1,features:[]};const e=await t.requestAdapter();return e?{supported:!0,adapterName:e.info?.description??e.info?.vendor??"unknown",features:Array.from(e.features),limits:{maxStorageBufferBindingSize:Number(e.limits.maxStorageBufferBindingSize),maxComputeInvocationsPerWorkgroup:Number(e.limits.maxComputeInvocationsPerWorkgroup),maxComputeWorkgroupSizeX:Number(e.limits.maxComputeWorkgroupSizeX)}}:{supported:!1,features:[]}}async function ka(){return on||(on=(async()=>{const t=Wi();if(!t)return null;const e=await t.requestAdapter();if(!e)return null;const n=await e.requestDevice(),r=n.createBindGroupLayout({entries:[{binding:0,visibility:sn,buffer:{type:"read-only-storage"}},{binding:1,visibility:sn,buffer:{type:"read-only-storage"}},{binding:2,visibility:sn,buffer:{type:"storage"}},{binding:3,visibility:sn,buffer:{type:"uniform"}}]}),i=n.createComputePipeline({layout:n.createPipelineLayout({bindGroupLayouts:[r]}),compute:{module:n.createShaderModule({code:Ia}),entryPoint:"main"}});return{device:n,pipeline:i,bindGroupLayout:r}})(),on)}function ln(t,e){return Math.ceil(t/e)*e}async function Vi(t,e,n){const r=await ka();if(!r)return null;const i=Math.max(0,Math.floor(e)),o=Math.max(0,Math.floor(n.length/4));if(i===0||o===0)return new Uint32Array(0);const s=Math.min(i,Math.floor(t.length/2));if(s===0)return new Uint32Array(0);const a=s*2*Float32Array.BYTES_PER_ELEMENT,u=o*4*Float32Array.BYTES_PER_ELEMENT,c=s*Uint32Array.BYTES_PER_ELEMENT,f=Number(r.device.limits.maxStorageBufferBindingSize);if(a>f||u>f||c>f)return null;const l=r.device.createBuffer({size:ln(a,4),usage:kn|an}),h=r.device.createBuffer({size:ln(u,4),usage:kn|an}),d=r.device.createBuffer({size:ln(c,4),usage:kn|va}),m=r.device.createBuffer({size:16,usage:Ta|an}),p=r.device.createBuffer({size:ln(c,4),usage:an|_a});let x=!1;try{r.device.queue.writeBuffer(l,0,t.buffer,t.byteOffset,a),r.device.queue.writeBuffer(h,0,n.buffer,n.byteOffset,u),r.device.queue.writeBuffer(m,0,new Uint32Array([s,o,0,0]));const w=r.device.createBindGroup({layout:r.bindGroupLayout,entries:[{binding:0,resource:{buffer:l}},{binding:1,resource:{buffer:h}},{binding:2,resource:{buffer:d}},{binding:3,resource:{buffer:m}}]}),M=r.device.createCommandEncoder(),N=M.beginComputePass();N.setPipeline(r.pipeline),N.setBindGroup(0,w),N.dispatchWorkgroups(Math.ceil(s/256)),N.end(),M.copyBufferToBuffer(d,0,p,0,c),r.device.queue.submit([M.finish()]),await p.mapAsync(Fa),x=!0;const A=p.getMappedRange();return new Uint32Array(A.slice(0))}finally{if(x)try{p.unmap()}catch{}l.destroy(),h.destroy(),d.destroy(),m.destroy(),p.destroy()}}async function Gi(t,e,n={}){const r=mt(),i=n.bridgeToDraw===!0;if(!t||!t.count||!t.positions||!t.paletteIndices)return{data:null,meta:{mode:"hybrid-webgpu",durationMs:mt()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}};const o=Ye(e??[]);if(o.length===0){const A={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return t.fillModes instanceof Uint8Array&&(A.fillModes=new Uint8Array(0)),t.ids instanceof Uint32Array&&(A.ids=new Uint32Array(0)),{data:A,meta:{mode:"hybrid-webgpu",durationMs:mt()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const s=pe(t),a=t.fillModes instanceof Uint8Array&&t.fillModes.length>=s?t.fillModes:null,u=t.ids instanceof Uint32Array&&t.ids.length>=s?t.ids:null;if(s===0){const A={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(A.fillModes=new Uint8Array(0)),u&&(A.ids=new Uint32Array(0)),{data:A,meta:{mode:"hybrid-webgpu",durationMs:mt()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const c=new Float32Array(o.length*4);for(let A=0;A<o.length;A+=1){const C=A*4,U=o[A];c[C]=U.minX,c[C+1]=U.minY,c[C+2]=U.maxX,c[C+3]=U.maxY}let f=null,l=!1;try{f=await Vi(t.positions,s,c),l=!!f}catch{f=null,l=!1}if(!f)return{data:Ue(t,e),meta:{mode:"hybrid-webgpu",durationMs:mt()-r,usedWebGpu:!1,candidateCount:s,bridgedToDraw:!1}};let h=0;for(let A=0;A<s;A+=1)f[A]===1&&(h+=1);const d=new Uint32Array(h);if(h>0){let A=0;for(let C=0;C<s;C+=1)f[C]===1&&(d[A]=C,A+=1)}if(h===0){if(i){const C={count:s,positions:t.positions.subarray(0,s*2),paletteIndices:t.paletteIndices.subarray(0,s),drawIndices:new Uint32Array(0)};return a&&(C.fillModes=a.subarray(0,s)),u&&(C.ids=u.subarray(0,s)),{data:C,meta:{mode:"hybrid-webgpu",durationMs:mt()-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)),u&&(A.ids=new Uint32Array(0)),{data:A,meta:{mode:"hybrid-webgpu",durationMs:mt()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const A=new Uint32Array(h);let C=0;for(let H=0;H<h;H+=1){const O=d[H]??0,$=t.positions[O*2],Z=t.positions[O*2+1];yn($,Z,o)&&(A[C]=O,C+=1)}const U={count:s,positions:t.positions.subarray(0,s*2),paletteIndices:t.paletteIndices.subarray(0,s),drawIndices:A.subarray(0,C)};return a&&(U.fillModes=a.subarray(0,s)),u&&(U.ids=u.subarray(0,s)),{data:U,meta:{mode:"hybrid-webgpu",durationMs:mt()-r,usedWebGpu:!0,candidateCount:h,bridgedToDraw:!0}}}const m=new Float32Array(h*2),p=new Uint16Array(h),x=a?new Uint8Array(h):null,w=u?new Uint32Array(h):null;let M=0;for(let A=0;A<h;A+=1){const C=d[A]??0,U=t.positions[C*2],H=t.positions[C*2+1];yn(U,H,o)&&(m[M*2]=U,m[M*2+1]=H,p[M]=t.paletteIndices[C],x&&(x[M]=a[C]),w&&(w[M]=u[C]),M+=1)}const N={count:M,positions:m.subarray(0,M*2),paletteIndices:p.subarray(0,M)};return x&&(N.fillModes=x.subarray(0,M)),w&&(N.ids=w.subarray(0,M)),{data:N,meta:{mode:"hybrid-webgpu",durationMs:mt()-r,usedWebGpu:!0,candidateCount:h,bridgedToDraw:!1}}}class qi{constructor(e,n){E(this,"worker",null);E(this,"supported",!0);E(this,"requestId",1);E(this,"pendingById",new Map);E(this,"handleMessage",e=>{const n=e.data;if(!n)return;const r=this.pendingById.get(n.id);r&&(this.pendingById.delete(n.id),this.handlers.onResponse(n,r))});E(this,"handleError",()=>{this.supported=!1,this.teardownWorker("worker crashed")});this.createWorker=e,this.handlers=n}beginRequest(e){const n=this.getOrCreateWorker();if(!n)return null;const r=this.requestId++;return this.pendingById.set(r,e),{id:r,worker:n}}cancelRequest(e){const n=this.pendingById.get(e);if(n)return this.pendingById.delete(e),n}terminate(e="worker terminated"){this.teardownWorker(e)}getOrCreateWorker(){if(!this.supported)return null;if(this.worker)return this.worker;try{const e=this.createWorker();return e.addEventListener("message",this.handleMessage),e.addEventListener("error",this.handleError),this.worker=e,e}catch{return this.supported=!1,null}}teardownWorker(e){this.worker&&(this.worker.removeEventListener("message",this.handleMessage),this.worker.removeEventListener("error",this.handleError),this.worker.terminate(),this.worker=null);const n=new Error(e);for(const[,r]of this.pendingById)this.handlers.rejectPending(r,n);this.pendingById.clear()}}const ze=new qi(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/roi-clip-worker-BuNuUQQg.js").href:new URL("assets/roi-clip-worker-BuNuUQQg.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:Ce&&Ce.tagName.toUpperCase()==="SCRIPT"&&Ce.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(t,e)=>{if(t.type==="roi-clip-failure"){e.reject(new Error(t.error||"worker clip failed"));return}if(t.type==="roi-clip-index-success"){if(e.kind!=="index"){e.reject(new Error("worker response mismatch: expected point data result"));return}const u=Math.max(0,Math.floor(t.count)),c=new Uint32Array(t.indices).subarray(0,u);e.resolve({indices:c,meta:{mode:"worker",durationMs:Number.isFinite(t.durationMs)?t.durationMs:mt()-e.startMs}});return}if(e.kind!=="data"){e.reject(new Error("worker response mismatch: expected index result"));return}const n=Math.max(0,Math.floor(t.count)),r=new Float32Array(t.positions),i=new Uint16Array(t.paletteIndices),o=t.fillModes?new Uint8Array(t.fillModes):null,s=t.ids?new Uint32Array(t.ids):null,a={count:n,positions:r.subarray(0,n*2),paletteIndices:i.subarray(0,n)};o&&(a.fillModes=o.subarray(0,n)),s&&(a.ids=s.subarray(0,n)),e.resolve({data:a,meta:{mode:"worker",durationMs:Number.isFinite(t.durationMs)?t.durationMs:mt()-e.startMs}})},rejectPending:(t,e)=>{t.reject(e)}});function La(){ze.terminate("worker terminated")}async function Hi(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return{data:null,meta:{mode:"worker",durationMs:0}};const n=pe(t),r=t.positions.slice(0,n*2),i=t.paletteIndices.slice(0,n),o=t.fillModes instanceof Uint8Array&&t.fillModes.length>=n?t.fillModes.slice(0,n):null,s=t.ids instanceof Uint32Array&&t.ids.length>=n?t.ids.slice(0,n):null;return new Promise((a,u)=>{const c=mt(),f=ze.beginRequest({kind:"data",resolve:a,reject:u,startMs:c});if(!f){a({data:Ue(t,e),meta:{mode:"sync",durationMs:mt()-c}});return}const l={type:"roi-clip-request",id:f.id,count:n,positions:r.buffer,paletteIndices:i.buffer,fillModes:o?.buffer,ids:s?.buffer,polygons:e??[]},h=[r.buffer,i.buffer];o&&h.push(o.buffer),s&&h.push(s.buffer);try{f.worker.postMessage(l,h)}catch(d){const m=ze.cancelRequest(f.id);m?m.reject(d):u(d)}})}async function Ba(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return{indices:new Uint32Array(0),meta:{mode:"worker",durationMs:0}};const n=pe(t),r=t.positions.slice(0,n*2);return new Promise((i,o)=>{const s=mt(),a=ze.beginRequest({kind:"index",resolve:i,reject:o,startMs:s});if(!a){i({indices:Xi(t,e),meta:{mode:"sync",durationMs:mt()-s}});return}const u={type:"roi-clip-index-request",id:a.id,count:n,positions:r.buffer,polygons:e??[]};try{a.worker.postMessage(u,[r.buffer])}catch(c){const f=ze.cancelRequest(a.id);f?f.reject(c):o(c)}})}const Ua=24,za=1024,Da=4,mn=-1;function Fe(t,e,n){return(t*73856093^e*19349663)>>>0&n}function Oa(t,e,n){if(t<=0||e<=0||n<=0)return 256;const r=Math.max(1,t*e),o=Math.sqrt(r/Math.max(1,n))*Da;return Math.max(Ua,Math.min(za,o))}function Ya(t,e){if(!(t instanceof Uint32Array)||t.length===0)return null;let n=!0;for(let o=0;o<t.length;o+=1)if(!(t[o]<e)){n=!1;break}if(n)return t;const r=new Uint32Array(t.length);let i=0;for(let o=0;o<t.length;o+=1)t[o]>=e||(r[i]=t[o],i+=1);return i>0?r.subarray(0,i):null}function Xa(t){const e=Math.max(0,Math.floor(t.count)),n=Math.floor(t.positions.length/2),r=Math.max(0,Math.min(e,n));if(r<=0)return null;const i=Ya(t.drawIndices??null,r),o=i?i.length:r;if(o===0)return null;const s=Oa(t.sourceWidth,t.sourceHeight,o),a=1/s,u=new Int32Array(o),c=new Int32Array(o);let f=0;if(i)for(let _=0;_<o;_+=1){const k=i[_],Y=t.positions[k*2],B=t.positions[k*2+1];!Number.isFinite(Y)||!Number.isFinite(B)||(u[f]=Math.floor(Y*a),c[f]=Math.floor(B*a),f+=1)}else for(let _=0;_<r;_+=1){const k=t.positions[_*2],Y=t.positions[_*2+1];!Number.isFinite(k)||!Number.isFinite(Y)||(u[f]=Math.floor(k*a),c[f]=Math.floor(Y*a),f+=1)}if(f===0)return null;let l=Math.min(f,Math.max(64,f>>>3));(!Number.isFinite(l)||l<=0)&&(l=f);let h=1;for(;h<l*2;)h<<=1;let d=h-1,m=new Int32Array(h*2),p=new Int32Array(h);m.fill(2147483647);let x=0;const w=new Int32Array(f);for(let _=0;_<f;_+=1){const k=u[_],Y=c[_];let B=Fe(k,Y,d);for(;;){const nt=m[B*2];if(nt===2147483647){if(m[B*2]=k,m[B*2+1]=Y,p[B]=1,w[_]=B,x+=1,x*4>h*3){const zt=h;h<<=1,d=h-1;const ft=new Int32Array(h*2),Vt=new Int32Array(h);ft.fill(2147483647);for(let Bt=0;Bt<zt;Bt+=1){if(m[Bt*2]===2147483647)continue;const Gt=m[Bt*2],v=m[Bt*2+1];let R=Fe(Gt,v,d);for(;ft[R*2]!==2147483647;)R=R+1&d;ft[R*2]=Gt,ft[R*2+1]=v,Vt[R]=p[Bt]}for(m=ft,p=Vt,B=Fe(k,Y,d);m[B*2]!==k||m[B*2+1]!==Y;)B=B+1&d;w[_]=B}break}if(nt===k&&m[B*2+1]===Y){p[B]+=1,w[_]=B;break}B=B+1&d}}const M=new Int32Array(x*2),N=new Uint32Array(x),A=new Uint32Array(x),C=new Int32Array(h);C.fill(mn);let U=0,H=0;for(let _=0;_<h;_+=1)m[_*2]!==2147483647&&(M[U*2]=m[_*2],M[U*2+1]=m[_*2+1],N[U]=H,A[U]=p[_],C[_]=U,H+=p[_],U+=1);const O=new Uint32Array(f),$=new Uint32Array(x);if($.set(N),i)for(let _=0;_<f;_+=1){const k=C[w[_]];O[$[k]]=i[_],$[k]+=1}else{let _=0;for(let k=0;k<r;k+=1){const Y=t.positions[k*2],B=t.positions[k*2+1];if(!Number.isFinite(Y)||!Number.isFinite(B))continue;const nt=C[w[_]];O[$[nt]]=k,$[nt]+=1,_+=1}}let Z=1;for(;Z<x*2;)Z<<=1;const Q=Z-1,rt=new Int32Array(Z);rt.fill(mn);for(let _=0;_<x;_+=1){const k=M[_*2],Y=M[_*2+1];let B=Fe(k,Y,Q);for(;rt[B]!==mn;)B=B+1&Q;rt[B]=_}return{cellSize:s,safeCount:r,cellCount:x,hashCapacity:Z,hashTable:rt,cellKeys:M,cellOffsets:N,cellLengths:A,pointIndices:O}}function $i(t,e,n){const{hashTable:r,cellKeys:i,hashMask:o}=t;let s=Fe(e,n,o);for(;;){const a=r[s];if(a===mn)return-1;if(i[a*2]===e&&i[a*2+1]===n)return a;s=s+1&o}}function Wa(t,e){if(t.safeCount<=0||t.cellCount<=0)return null;const n=t.safeCount;return{cellSize:t.cellSize,safeCount:n,positions:e.positions.subarray(0,n*2),ids:e.ids instanceof Uint32Array&&e.ids.length>=n?e.ids.subarray(0,n):null,hashCapacity:t.hashCapacity,hashMask:t.hashCapacity-1,hashTable:new Int32Array(t.hashTable),cellKeys:new Int32Array(t.cellKeys),cellOffsets:new Uint32Array(t.cellOffsets),cellLengths:new Uint32Array(t.cellLengths),pointIndices:new Uint32Array(t.pointIndices)}}const $n=new qi(()=>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:Ce&&Ce.tagName.toUpperCase()==="SCRIPT"&&Ce.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(t,e)=>{if(t.type==="point-hit-index-failure"){e.reject(new Error(t.error||"worker index build failed"));return}e.resolve(Wa(t,e.pointData))},rejectPending:(t,e)=>{t.reject(e)}});function Va(){$n.terminate("worker terminated")}function Ga(t,e){const n=pe(t);if(n<=0)return null;const r=t.positions.subarray(0,n*2),i=Xa({count:n,positions:r,drawIndices:t.drawIndices instanceof Uint32Array?t.drawIndices:null,sourceWidth:e?.width??0,sourceHeight:e?.height??0});return i?{cellSize:i.cellSize,safeCount:n,positions:r,ids:t.ids instanceof Uint32Array&&t.ids.length>=n?t.ids.subarray(0,n):null,hashCapacity:i.hashCapacity,hashMask:i.hashCapacity-1,hashTable:i.hashTable,cellKeys:i.cellKeys,cellOffsets:i.cellOffsets,cellLengths:i.cellLengths,pointIndices:i.pointIndices}:null}async function Zi(t,e){if(!t||!t.positions||!t.paletteIndices)return null;const n=pe(t);return n<=0?null:new Promise((r,i)=>{const o={resolve:r,reject:i,pointData:t},s=$n.beginRequest(o);if(!s||!s.worker){r(Ga(t,e));return}const a=t.positions.slice(0,n*2),u=t.drawIndices instanceof Uint32Array&&t.drawIndices.length>0?t.drawIndices.slice():void 0,c={type:"point-hit-index-request",id:s.id,count:n,positions:a.buffer,drawIndices:u?.buffer,sourceWidth:e?.width??0,sourceHeight:e?.height??0},f=[a.buffer];u&&f.push(u.buffer);try{s.worker.postMessage(c,f)}catch(l){const h=$n.cancelRequest(s.id);h?h.reject(l):i(l)}})}function qa(t){const e=[];for(let n=0;n<t.length;n+=1){const r=t[n],i=Ye([Oe(r?.coordinates)]);if(i.length===0)continue;let o=0,s=1/0,a=1/0,u=-1/0,c=-1/0;for(const f of i)o+=f.area,f.minX<s&&(s=f.minX),f.minY<a&&(a=f.minY),f.maxX>u&&(u=f.maxX),f.maxY>c&&(c=f.maxY);!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(u)||!Number.isFinite(c)||e.push({regionId:r.id??n,regionIndex:n,polygons:i,area:Math.max(1e-6,o),minX:s,minY:a,maxX:u,maxY:c})}return e}const Ha=128,Ln=[];function Re(t,e,n,r,i){if(i<=1||n<=e)return 0;const o=(t-e)/r;return!Number.isFinite(o)||o<=0?0:o>=i-1?i-1:Math.floor(o)}function $a(t){if(t.length===0)return null;let e=1/0,n=1/0,r=-1/0,i=-1/0;for(const f of t)f.minX<e&&(e=f.minX),f.minY<n&&(n=f.minY),f.maxX>r&&(r=f.maxX),f.maxY>i&&(i=f.maxY);if(!Number.isFinite(e)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i))return null;const o=Math.ceil(Math.sqrt(t.length*2)),s=Math.max(1,Math.min(Ha,o)),a=r>e?(r-e)/s:1,u=i>n?(i-n)/s:1,c=Array.from({length:s*s},()=>[]);for(let f=0;f<t.length;f+=1){const l=t[f],h=Re(l.minX,e,r,a,s),d=Re(l.maxX,e,r,a,s),m=Re(l.minY,n,i,u,s),p=Re(l.maxY,n,i,u,s);for(let x=m;x<=p;x+=1)for(let w=h;w<=d;w+=1)c[x*s+w].push(f)}return{minX:e,minY:n,maxX:r,maxY:i,gridSize:s,cellWidth:a,cellHeight:u,buckets:c}}function Za(t,e,n){if(!t||e<t.minX||e>t.maxX||n<t.minY||n>t.maxY)return Ln;const r=Re(e,t.minX,t.maxX,t.cellWidth,t.gridSize),i=Re(n,t.minY,t.maxY,t.cellHeight,t.gridSize);return t.buckets[i*t.gridSize+r]??Ln}function Ka(t,e){if(Array.isArray(e)){const n=e[t];if(typeof n=="string"&&n.length>0)return n}if(e instanceof Map){const n=e.get(t);if(typeof n=="string"&&n.length>0)return n}return String(t)}function Ki(t,e,n={}){const r=Math.max(0,Math.min(Math.floor(t?.count??0),Math.floor((t?.positions?.length??0)/2),t?.paletteIndices?.length??0,t?.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER));let i=null;if(t?.drawIndices instanceof Uint32Array){const d=t.drawIndices;let m=d.length;for(let p=0;p<d.length;p+=1)d[p]<r||(m-=1);if(m===d.length)i=d;else if(m>0){const p=new Uint32Array(m);let x=0;for(let w=0;w<d.length;w+=1){const M=d[w];M>=r||(p[x]=M,x+=1)}i=p}else i=new Uint32Array(0)}const o=i?i.length:r,s=qa(e??[]);if(!t||o===0||s.length===0)return{groups:[],inputPointCount:o,pointsInsideAnyRegion:0,unmatchedPointCount:o};const a=new Map,u=new Map,c=$a(s);let f=0;for(let d=0;d<o;d+=1){const m=i?i[d]:d,p=t.positions[m*2],x=t.positions[m*2+1];if(!Number.isFinite(p)||!Number.isFinite(x))continue;let w=null;const M=Za(c,p,x);if(M.length===0)continue;for(const C of M){const U=s[C];let H=!1;for(const O of U.polygons)if(Pi(p,x,O)){H=!0;break}H&&(!w||U.area<w.area)&&(w=U)}if(!w)continue;f+=1;const N=t.paletteIndices[m]??0,A=a.get(w.regionIndex)??new Map;A.set(N,(A.get(N)??0)+1),a.set(w.regionIndex,A),u.set(w.regionIndex,(u.get(w.regionIndex)??0)+1)}const l=n.includeEmptyRegions??!1,h=[];for(const d of s){const m=u.get(d.regionIndex)??0;if(!l&&m<=0)continue;const p=a.get(d.regionIndex)??new Map,x=Array.from(p.entries()).map(([w,M])=>({termId:Ka(w,n.paletteIndexToTermId),paletteIndex:w,count:M})).sort((w,M)=>M.count-w.count||w.paletteIndex-M.paletteIndex);h.push({regionId:d.regionId,regionIndex:d.regionIndex,totalCount:m,termCounts:x})}return{groups:h,inputPointCount:o,pointsInsideAnyRegion:f,unmatchedPointCount:Math.max(0,o-f)}}function ja(t,e){if(!e)return!1;try{const r=new URL(t,typeof window<"u"?window.location.href:void 0).hostname.toLowerCase();if(r.includes("amazonaws.com")||r.startsWith("s3.")||r.includes(".s3."))return!1}catch{}return!0}class ji{constructor(e){E(this,"maxConcurrency");E(this,"maxRetries");E(this,"retryBaseDelayMs");E(this,"retryMaxDelayMs");E(this,"onTileLoad");E(this,"onTileError");E(this,"onStateChange");E(this,"authToken");E(this,"destroyed",!1);E(this,"queue",[]);E(this,"queuedByKey",new Map);E(this,"inflight",new Map);E(this,"visibleKeys",new Set);E(this,"timerId",null);E(this,"abortedCount",0);E(this,"retryCount",0);E(this,"failedCount",0);this.maxConcurrency=Math.max(1,Math.floor(e.maxConcurrency??12)),this.maxRetries=Math.max(0,Math.floor(e.maxRetries??2)),this.retryBaseDelayMs=Math.max(10,Math.floor(e.retryBaseDelayMs??120)),this.retryMaxDelayMs=Math.max(this.retryBaseDelayMs,Math.floor(e.retryMaxDelayMs??1200)),this.authToken=e.authToken??"",this.onTileLoad=e.onTileLoad,this.onTileError=e.onTileError,this.onStateChange=e.onStateChange}setAuthToken(e){this.authToken=String(e??"")}schedule(e){if(this.destroyed)return;const n=new Set;for(const r of e)n.add(r.key);this.visibleKeys=n,this.dropInvisibleQueued(n),this.abortInvisibleInflight(n);for(const r of e){if(this.inflight.has(r.key)){const s=this.inflight.get(r.key);s&&(s.tile=r);continue}const i=this.queuedByKey.get(r.key);if(i){i.tile=r;continue}const o={tile:r,attempt:0,readyAt:mt()};this.queue.push(o),this.queuedByKey.set(r.key,o)}this.sortQueue(),this.pump(),this.emitStateChange()}clear(){this.clearPumpTimer(),this.visibleKeys.clear(),this.queue=[],this.queuedByKey.clear();for(const[,e]of this.inflight)e.controller.abort();this.inflight.clear(),this.emitStateChange()}destroy(){this.destroyed||(this.destroyed=!0,this.clear())}getInflightCount(){return this.inflight.size}getSnapshot(){return{inflight:this.inflight.size,queued:this.queue.length,aborted:this.abortedCount,retries:this.retryCount,failed:this.failedCount}}dropInvisibleQueued(e){if(this.queue.length===0)return;const n=[];for(const r of this.queue){if(!e.has(r.tile.key)){this.queuedByKey.delete(r.tile.key);continue}n.push(r)}this.queue=n}abortInvisibleInflight(e){for(const[n,r]of this.inflight)e.has(n)||(this.inflight.delete(n),this.abortedCount+=1,r.controller.abort())}sortQueue(){this.queue.sort((e,n)=>e.readyAt!==n.readyAt?e.readyAt-n.readyAt:e.tile.distance2!==n.tile.distance2?e.tile.distance2-n.tile.distance2:e.tile.tier!==n.tile.tier?n.tile.tier-e.tile.tier:e.tile.key.localeCompare(n.tile.key))}pump(){if(this.destroyed)return;for(this.clearPumpTimer();this.inflight.size<this.maxConcurrency;){const r=this.takeNextReadyQueueItem();if(!r)break;this.startFetch(r)}if(this.inflight.size>=this.maxConcurrency||this.queue.length===0)return;const e=this.queue[0]?.readyAt;if(typeof e!="number")return;const n=Math.max(0,e-mt());this.timerId=globalThis.setTimeout(()=>{this.timerId=null,this.pump()},n)}takeNextReadyQueueItem(){if(this.queue.length===0)return null;const e=mt(),n=this.queue[0];return!n||n.readyAt>e?null:(this.queue.shift(),this.queuedByKey.delete(n.tile.key),n)}startFetch(e){const n=new AbortController,r={tile:e.tile,attempt:e.attempt,controller:n};this.inflight.set(e.tile.key,r),this.emitStateChange();const i=ja(e.tile.url,this.authToken);fetch(e.tile.url,{signal:n.signal,headers:i?{Authorization:this.authToken}:void 0}).then(o=>{if(!o.ok)throw new Error(`HTTP ${o.status}`);return o.blob()}).then(o=>createImageBitmap(o)).then(o=>{if(this.destroyed||n.signal.aborted){o.close();return}if(!this.visibleKeys.has(e.tile.key)){o.close();return}this.onTileLoad(e.tile,o)}).catch(o=>{if(n.signal.aborted||this.destroyed)return;if(e.attempt<this.maxRetries&&this.visibleKeys.has(e.tile.key)){this.retryCount+=1;const a=e.attempt+1,u=this.getRetryDelay(a),c={tile:e.tile,attempt:a,readyAt:mt()+u},f=this.queuedByKey.get(e.tile.key);f?(f.tile=c.tile,f.readyAt=Math.min(f.readyAt,c.readyAt),f.attempt=Math.max(f.attempt,c.attempt)):(this.queue.push(c),this.queuedByKey.set(c.tile.key,c)),this.sortQueue();return}this.failedCount+=1,this.onTileError?.(e.tile,o,e.attempt+1)}).finally(()=>{this.inflight.delete(e.tile.key),this.pump(),this.emitStateChange()})}getRetryDelay(e){const n=Math.max(0,e-1),r=Math.min(this.retryMaxDelayMs,this.retryBaseDelayMs*2**n),i=.85+Math.random()*.3;return Math.round(r*i)}clearPumpTimer(){this.timerId!==null&&(globalThis.clearTimeout(this.timerId),this.timerId=null)}emitStateChange(){this.onStateChange?.(this.getSnapshot())}}function Qa(t,e){t.addEventListener("pointerdown",e.pointerDown),t.addEventListener("pointermove",e.pointerMove),t.addEventListener("pointerup",e.pointerUp),t.addEventListener("pointercancel",e.pointerUp),t.addEventListener("wheel",e.wheel,{passive:!1}),t.addEventListener("dblclick",e.doubleClick),t.addEventListener("contextmenu",e.contextMenu),t.addEventListener("webglcontextlost",e.contextLost),t.addEventListener("webglcontextrestored",e.contextRestored)}function Ja(t,e){t.removeEventListener("pointerdown",e.pointerDown),t.removeEventListener("pointermove",e.pointerMove),t.removeEventListener("pointerup",e.pointerUp),t.removeEventListener("pointercancel",e.pointerUp),t.removeEventListener("wheel",e.wheel),t.removeEventListener("dblclick",e.doubleClick),t.removeEventListener("contextmenu",e.contextMenu),t.removeEventListener("webglcontextlost",e.contextLost),t.removeEventListener("webglcontextrestored",e.contextRestored)}function tl(t,e,n){const r=t.getBoundingClientRect(),i=Math.max(1,r.width||t.clientWidth||1),o=Math.max(1,r.height||t.clientHeight||1),s=Math.max(1,window.devicePixelRatio||1),a=Math.max(1,Math.round(i*s)),u=Math.max(1,Math.round(o*s));(t.width!==a||t.height!==u)&&(t.width=a,t.height=u),n.setViewport(i,o),e.viewport(0,0,a,u)}const Zn=.35,Kn=.5,el=256,jn=[{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}],nl=.1,rl=5,il=0,ol=1,sl=-100,al=100,ll=2e3;function Qi(t){return t*Math.PI/180}function un(t,e){return!t||!e?t===e:t.buffer===e.buffer&&t.byteOffset===e.byteOffset&&t.byteLength===e.byteLength}function Qn(t){return t.map(e=>({zoom:e.zoom,size:e.size}))}function fi(t){if(!t)return Qn(jn);const e=new Map;for(const[n,r]of Object.entries(t)){const i=Number(n),o=Number(r);!Number.isFinite(i)||!Number.isFinite(o)||o<=0||e.set(i,o)}return e.size===0?Qn(jn):Array.from(e.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function ul(t,e){if(t===e)return!0;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n].zoom!==e[n].zoom||t[n].size!==e[n].size)return!1;return!0}function cl(t,e){if(!Number.isFinite(t))return e[0]?.size??Kn;if(e.length===0)return Kn;if(e.length===1||t<=e[0].zoom)return e[0].size;for(let s=1;s<e.length;s+=1){const a=e[s-1],u=e[s];if(t>u.zoom)continue;const c=Math.max(1e-6,u.zoom-a.zoom),f=D((t-a.zoom)/c,0,1);return a.size+(u.size-a.size)*f}const n=e[e.length-1],r=e[e.length-2],i=Math.max(1e-6,n.zoom-r.zoom),o=(n.size-r.size)/i;return n.size+(t-n.zoom)*o}function hi(t){return typeof t!="number"||!Number.isFinite(t)?1:D(t,nl,rl)}function di(t){return typeof t!="number"||!Number.isFinite(t)?0:D(t,il,ol)}function Bn(t){return typeof t!="number"||!Number.isFinite(t)?0:D(t,sl,al)}function mi(t){const e=Bn(t?.brightness),n=Bn(t?.contrast),r=Bn(t?.saturation);return{brightness:e/200,contrast:n/100,saturation:r/100}}function Ji(t){return t}function Un(t){return typeof t!="number"||!Number.isFinite(t)?0:D(t,0,ll)}function cn(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?null:Math.max(1e-6,t)}function zn(t){return typeof t=="function"?t:Ji}function to(t,e,n){const r=t.getBoundingClientRect(),i=e-r.left-r.width*.5,o=n-r.top-r.height*.5;return Math.atan2(o,i)}function eo(t,e){if(e.pointerId!==null&&t.hasPointerCapture(e.pointerId))try{t.releasePointerCapture(e.pointerId)}catch{}e.dragging=!1,e.mode="none",e.rotateLastAngleRad=null,e.pointerId=null,t.classList.remove("dragging")}function fl(t){const{event:e,canvas:n,state:r,config:i,cancelViewAnimation:o}=t,s=i.ctrlDragRotate&&(e.ctrlKey||e.metaKey);(e.button===0||s&&e.button===2)&&(o(),s&&e.preventDefault(),r.dragging=!0,r.mode=s?"rotate":"pan",r.pointerId=e.pointerId,r.lastPointerX=e.clientX,r.lastPointerY=e.clientY,r.rotateLastAngleRad=r.mode==="rotate"?to(n,e.clientX,e.clientY):null,n.classList.add("dragging"),n.setPointerCapture(e.pointerId))}function hl(t){const{event:e,canvas:n,state:r,config:i,camera:o,clampViewState:s,emitViewState:a,requestRender:u}=t;if(!r.dragging||e.pointerId!==r.pointerId)return;const c=e.clientX-r.lastPointerX,f=e.clientY-r.lastPointerY;if(r.lastPointerX=e.clientX,r.lastPointerY=e.clientY,r.mode==="rotate"){const l=to(n,e.clientX,e.clientY),h=r.rotateLastAngleRad;if(r.rotateLastAngleRad=l,h!==null){const d=l-h,m=Math.atan2(Math.sin(d),Math.cos(d)),p=i.rotationDragSensitivityDegPerPixel/Zn,x=o.getViewState();o.setViewState({rotationDeg:x.rotationDeg-m*180/Math.PI*p})}}else{const l=o.getViewState(),h=Math.max(1e-6,l.zoom),d=Qi(l.rotationDeg),m=Math.cos(d),p=Math.sin(d),x=(c*m-f*p)/h,w=(c*p+f*m)/h;o.setViewState({offsetX:l.offsetX-x,offsetY:l.offsetY-w})}s(),a(),u()}function dl(t,e,n){t.pointerId===n.pointerId&&eo(e,n)}function ml(t){const{event:e,canvas:n,onZoomBy:r}=t;e.preventDefault();const i=n.getBoundingClientRect(),o=e.clientX-i.left,s=e.clientY-i.top,a=e.deltaY<0?1.12:.89;r(a,o,s)}function gl(t){const{event:e,canvas:n,onZoomBy:r}=t,i=n.getBoundingClientRect(),o=e.clientX-i.left,s=e.clientY-i.top;r(e.shiftKey?.8:1.25,o,s)}function pl(t,e){(e||t.ctrlKey||t.metaKey)&&t.preventDefault()}function lr(t){const e=t.getViewCorners();let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[s,a]of e)s<n&&(n=s),s>i&&(i=s),a<r&&(r=a),a>o&&(o=a);return[n,r,i,o]}function Jn(t,e){const n=lr(t),r=Math.max(1e-6,n[2]-n[0]),i=Math.max(1e-6,n[3]-n[1]),o=r*.2,s=i*.2,[a,u]=t.getCenter(),c=r*.5,f=i*.5,l=c-o,h=e.width-c+o,d=f-s,m=e.height-f+s,p=l<=h?D(a,l,h):e.width*.5,x=d<=m?D(u,d,m):e.height*.5;t.setCenter(p,x)}function yl(t,e){const n=Math.max(1e-6,t.getViewState().zoom),r=e.maxTierZoom+Math.log2(n);return D(Math.floor(r),0,e.maxTierZoom)}function bl(t,e){return!(t[2]<=e[0]||t[0]>=e[2]||t[3]<=e[1]||t[1]>=e[3])}function no(t,e,n){const r=lr(t),i=Math.pow(2,e.maxTierZoom-n),o=Math.ceil(e.width/i),s=Math.ceil(e.height/i),a=Math.max(1,Math.ceil(o/e.tileSize)),u=Math.max(1,Math.ceil(s/e.tileSize)),c=r[0],f=r[1],l=r[2],h=r[3],d=D(Math.floor(c/i/e.tileSize),0,a-1),m=D(Math.floor((l-1)/i/e.tileSize),0,a-1),p=D(Math.floor(f/i/e.tileSize),0,u-1),x=D(Math.floor((h-1)/i/e.tileSize),0,u-1);if(d>m||p>x)return[];const w=(c+l)*.5/i/e.tileSize,M=(f+h)*.5/i/e.tileSize,N=[];for(let A=p;A<=x;A+=1)for(let C=d;C<=m;C+=1){const U=C*e.tileSize*i,H=A*e.tileSize*i,O=Math.min((C+1)*e.tileSize,o)*i,$=Math.min((A+1)*e.tileSize,s)*i,Z=C-w,Q=A-M;N.push({key:`${n}/${C}/${A}`,tier:n,x:C,y:A,bounds:[U,H,O,$],distance2:Z*Z+Q*Q,url:ar(e,n,C,A)})}return N.sort((A,C)=>A.distance2-C.distance2),N}function xl(t,e){const n=yl(t,e);return{tier:n,visible:no(t,e,n)}}function wl(t){t.interactionLocked||fl({event:t.event,canvas:t.canvas,state:t.state,config:{ctrlDragRotate:t.ctrlDragRotate,rotationDragSensitivityDegPerPixel:t.rotationDragSensitivityDegPerPixel},cancelViewAnimation:t.cancelViewAnimation})}function Sl(t){t.interactionLocked||hl({event:t.event,canvas:t.canvas,state:t.state,config:{ctrlDragRotate:t.ctrlDragRotate,rotationDragSensitivityDegPerPixel:t.rotationDragSensitivityDegPerPixel},camera:t.camera,clampViewState:()=>Jn(t.camera,t.source),emitViewState:t.emitViewState,requestRender:t.requestRender})}function El(t){t.interactionLocked||dl(t.event,t.canvas,t.state)}function Ml(t){if(t.interactionLocked){t.event.preventDefault();return}ml({event:t.event,canvas:t.canvas,onZoomBy:t.onZoomBy})}function Al(t){t.interactionLocked||gl({event:t.event,canvas:t.canvas,onZoomBy:t.onZoomBy})}function Rl(t){pl(t.event,t.state.dragging)}function Cl(t,e){eo(t,e)}function Il(t){return{pointerDown:e=>wl({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,state:t.state,ctrlDragRotate:t.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:t.getRotationDragSensitivityDegPerPixel(),cancelViewAnimation:t.cancelViewAnimation}),pointerMove:e=>Sl({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,state:t.state,ctrlDragRotate:t.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:t.getRotationDragSensitivityDegPerPixel(),camera:t.camera,source:t.source,emitViewState:t.emitViewState,requestRender:t.requestRender}),pointerUp:e=>El({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,state:t.state}),wheel:e=>Ml({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,onZoomBy:t.zoomBy}),doubleClick:e=>Al({event:e,interactionLocked:t.getInteractionLocked(),canvas:t.canvas,onZoomBy:t.zoomBy}),contextMenu:e=>Rl({event:e,canvas:t.canvas,state:t.state})}}function Pl(t){const{gl:e,cache:n,maxCacheTiles:r}=t;if(n.size<=r)return;const i=Math.max(0,Math.floor(r));for(;n.size>i;){let o=null,s=null;for(const[a,u]of n)(!s||u.lastUsed<s.lastUsed)&&(o=a,s=u);if(!o||!s)break;e.deleteTexture(s.texture),n.delete(o)}}function vl(t,e){if(t.isContextLost())return null;const n=t.createTexture();return n?(t.bindTexture(t.TEXTURE_2D,n),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,1),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),t.bindTexture(t.TEXTURE_2D,null),n):null}function Tl(t){const{gl:e,cache:n,tile:r,bitmap:i,frameSerial:o,maxCacheTiles:s,destroyed:a,contextLost:u,requestRender:c}=t;if(a||u||e.isContextLost()){i.close();return}if(n.has(r.key)){i.close();return}const f=vl(e,i);i.close(),f&&(n.set(r.key,{key:r.key,texture:f,bounds:r.bounds,tier:r.tier,lastUsed:o}),Pl({gl:e,cache:n,maxCacheTiles:s}),c())}function _l(t,e){for(const[,n]of e)t.deleteTexture(n.texture)}function Fl(t){const{event:e,destroyed:n,contextLost:r,cancelViewAnimation:i,cancelDrag:o,tileScheduler:s,cache:a,onContextLost:u}=t;if(e.preventDefault(),n||r)return{handled:!1,frame:t.frame};let c=t.frame;return c!==null&&(cancelAnimationFrame(c),c=null),i(),o(),s.clear(),a.clear(),u?.(),{handled:!0,frame:c}}function Nl(t){if(t.destroyed)return{didDestroy:!1,frame:t.frame};let e=t.frame;return e!==null&&(cancelAnimationFrame(e),e=null),t.cancelViewAnimation(),t.resizeObserver.disconnect(),t.removeCanvasEventListeners(),t.cancelDrag(),t.tileScheduler.destroy(),!t.contextLost&&!t.gl.isContextLost()&&(_l(t.gl,t.cache),t.gl.deleteBuffer(t.tileProgram.vbo),t.gl.deleteVertexArray(t.tileProgram.vao),t.gl.deleteProgram(t.tileProgram.program),t.gl.deleteBuffer(t.pointProgram.posBuffer),t.gl.deleteBuffer(t.pointProgram.termBuffer),t.gl.deleteBuffer(t.pointProgram.fillModeBuffer),t.gl.deleteBuffer(t.pointProgram.indexBuffer),t.gl.deleteTexture(t.pointProgram.paletteTexture),t.gl.deleteVertexArray(t.pointProgram.vao),t.gl.deleteProgram(t.pointProgram.program)),t.cache.clear(),{didDestroy:!0,frame:e}}function kl(t,e){if(e<=0||t.length===0)return new Uint32Array(0);let n=t.length;for(let o=0;o<t.length;o+=1)t[o]<e||(n-=1);if(n===t.length)return t;if(n<=0)return new Uint32Array(0);const r=new Uint32Array(n);let i=0;for(let o=0;o<t.length;o+=1){const s=t[o];s>=e||(r[i]=s,i+=1)}return r}function Ll(t,e){return e<=0?new Uint8Array(0):t.length<e?new Uint8Array(e):t.subarray(0,e)}function Bl(t,e,n,r,i){if(!i||i.length===0)return{...t,lastPointPalette:null};const o=new Uint8Array(i);if(r||e.isContextLost())return{...t,lastPointPalette:o};const s=Math.max(1,Math.floor(o.length/4));return e.bindTexture(e.TEXTURE_2D,n.paletteTexture),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,s,1,0,e.RGBA,e.UNSIGNED_BYTE,o),e.bindTexture(e.TEXTURE_2D,null),{...t,lastPointPalette:o,pointPaletteSize:s}}function Ul(t,e,n,r,i){if(!i||!i.count||!i.positions||!i.paletteIndices)return{...t,lastPointData:null,pointCount:0,usePointIndices:!1};const o=i.fillModes instanceof Uint8Array?i.fillModes:null,s=o!==null,a=Math.max(0,Math.min(i.count,Math.floor(i.positions.length/2),i.paletteIndices.length,s?o.length:Number.MAX_SAFE_INTEGER)),u=i.positions.subarray(0,a*2),c=i.paletteIndices.subarray(0,a),f=s?o.subarray(0,a):void 0,l=i.drawIndices instanceof Uint32Array,h=l?kl(i.drawIndices,a):null,d=t.lastPointData,m=d?.fillModes instanceof Uint8Array,p=t.pointBuffersDirty||!d||d.count!==a||!un(d.positions,u)||!un(d.paletteIndices,c)||m!==s||s&&(!d?.fillModes||!un(d.fillModes,f)),x=t.pointBuffersDirty||l&&(!d?.drawIndices||!un(d.drawIndices,h))||!l&&!!d?.drawIndices,w={...t,lastPointData:{count:a,positions:u,paletteIndices:c,fillModes:f,drawIndices:l?h??void 0:void 0}};if(r||e.isContextLost())return w;const M=w.lastPointData;if(!M)return w;if(p){e.bindBuffer(e.ARRAY_BUFFER,n.posBuffer),e.bufferData(e.ARRAY_BUFFER,M.positions,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,n.termBuffer),e.bufferData(e.ARRAY_BUFFER,M.paletteIndices,e.STATIC_DRAW);const N=Ll(w.zeroFillModes,a);e.bindBuffer(e.ARRAY_BUFFER,n.fillModeBuffer),e.bufferData(e.ARRAY_BUFFER,M.fillModes??N,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,null),w.zeroFillModes=N}return l&&x&&(e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n.indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,h??new Uint32Array(0),e.DYNAMIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),w.usePointIndices=l,w.pointCount=l?h?.length??0:M.count,(p||x)&&(w.pointBuffersDirty=!1),w}function zl(t){const{gl:e,camera:n,source:r,cache:i,frameSerial:o,tileProgram:s,pointProgram:a,imageColorSettings:u,pointCount:c,usePointIndices:f,pointPaletteSize:l,pointStrokeScale:h,pointInnerFillOpacity:d,pointSizePx:m,tileScheduler:p,getVisibleTiles:x,getVisibleTilesForTier:w,getViewBounds:M,intersectsBounds:N}=t;e.clearColor(.03,.06,.1,1),e.clear(e.COLOR_BUFFER_BIT);const{tier:A,visible:C}=x(),U=M(),H=new Set(C.map(Y=>Y.key));e.useProgram(s.program),e.bindVertexArray(s.vao),e.uniformMatrix3fv(s.uCamera,!1,n.getMatrix()),e.uniform1i(s.uTexture,0),e.uniform1f(s.uBrightness,u.brightness),e.uniform1f(s.uContrast,u.contrast),e.uniform1f(s.uSaturation,u.saturation);const O=[];for(const[,Y]of i)H.has(Y.key)||N(Y.bounds,U)&&O.push(Y);O.sort((Y,B)=>Y.tier-B.tier);for(const Y of O)Y.lastUsed=o,e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,Y.texture),e.uniform4f(s.uBounds,Y.bounds[0],Y.bounds[1],Y.bounds[2],Y.bounds[3]),e.drawArrays(e.TRIANGLE_STRIP,0,4);let $=0;const Z=[];for(const Y of C){const B=i.get(Y.key);if(!B){Z.push(Y);continue}B.lastUsed=o,e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,B.texture),e.uniform4f(s.uBounds,B.bounds[0],B.bounds[1],B.bounds[2],B.bounds[3]),e.drawArrays(e.TRIANGLE_STRIP,0,4),$+=1}const Q=Z.slice(),rt=1e6,_=[];A>0&&_.push(A-1),A<r.maxTierZoom&&_.push(A+1);for(const Y of _){const B=w(Y);for(const nt of B)i.has(nt.key)||(nt.distance2+=rt,Q.push(nt))}p.schedule(Q),e.bindTexture(e.TEXTURE_2D,null),e.bindVertexArray(null);let k=0;return c>0&&(e.enable(e.BLEND),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA),e.useProgram(a.program),e.bindVertexArray(a.vao),e.uniformMatrix3fv(a.uCamera,!1,n.getMatrix()),e.uniform1f(a.uPointSize,m),e.uniform1f(a.uPointStrokeScale,h),e.uniform1f(a.uPointInnerFillAlpha,d),e.uniform1f(a.uPaletteSize,l),e.uniform1i(a.uPalette,1),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,a.paletteTexture),f?e.drawElements(e.POINTS,c,e.UNSIGNED_INT,0):e.drawArrays(e.POINTS,0,c),e.bindTexture(e.TEXTURE_2D,null),e.bindVertexArray(null),k=c),{tier:A,visible:C.length,rendered:$,points:k,fallback:O.length,cacheHits:$,cacheMisses:Z.length,drawCalls:O.length+$+(k>0?1:0)}}function gi(t){const r=er(t,`#version 300 es
|
|
64
65
|
precision highp float;
|
|
65
66
|
in vec2 aUnit;
|
|
66
67
|
in vec2 aUv;
|
|
@@ -105,7 +106,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
105
106
|
|
|
106
107
|
color.rgb = clamp(color.rgb + uBrightness, vec3(0.0), vec3(1.0));
|
|
107
108
|
outColor = color;
|
|
108
|
-
}`),i=
|
|
109
|
+
}`),i=Tt(t,r,"uCamera"),o=Tt(t,r,"uBounds"),s=Tt(t,r,"uTexture"),a=Tt(t,r,"uBrightness"),u=Tt(t,r,"uContrast"),c=Tt(t,r,"uSaturation"),f=t.createVertexArray(),l=t.createBuffer();if(!f||!l)throw new Error("buffer allocation failed");t.bindVertexArray(f),t.bindBuffer(t.ARRAY_BUFFER,l),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,0,1,0,1,0,0,1,0,1,1,1,1,1]),t.STATIC_DRAW);const h=t.getAttribLocation(r,"aUnit"),d=t.getAttribLocation(r,"aUv");if(h<0||d<0)throw new Error("tile attribute lookup failed");return t.enableVertexAttribArray(h),t.enableVertexAttribArray(d),t.vertexAttribPointer(h,2,t.FLOAT,!1,16,0),t.vertexAttribPointer(d,2,t.FLOAT,!1,16,8),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null),{program:r,vao:f,vbo:l,uCamera:i,uBounds:o,uTexture:s,uBrightness:a,uContrast:u,uSaturation:c}}function pi(t){const r=er(t,`#version 300 es
|
|
109
110
|
precision highp float;
|
|
110
111
|
in vec2 aPosition;
|
|
111
112
|
in uint aTerm;
|
|
@@ -158,6 +159,6 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
158
159
|
// Premultiplied alpha output: inner fill is black, so it only contributes alpha.
|
|
159
160
|
outColor = vec4(color.rgb * ringAlpha, alpha);
|
|
160
161
|
}
|
|
161
|
-
}`),i=Pe(e,r,"uCamera"),o=Pe(e,r,"uPointSize"),s=Pe(e,r,"uPointStrokeScale"),a=Pe(e,r,"uPointInnerFillAlpha"),c=Pe(e,r,"uPalette"),l=Pe(e,r,"uPaletteSize"),u=e.createVertexArray(),f=e.createBuffer(),d=e.createBuffer(),g=e.createBuffer(),p=e.createBuffer(),S=e.createTexture();if(!u||!f||!d||!g||!p||!S)throw new Error("point buffer allocation failed");e.bindVertexArray(u),e.bindBuffer(e.ARRAY_BUFFER,f),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,d),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const M=e.getAttribLocation(r,"aTerm");if(M<0)throw new Error("point term attribute not found");e.enableVertexAttribArray(M),e.vertexAttribIPointer(M,1,e.UNSIGNED_SHORT,0,0),e.bindBuffer(e.ARRAY_BUFFER,g),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,p),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,S),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:f,termBuffer:d,fillModeBuffer:g,indexBuffer:p,paletteTexture:S,uCamera:i,uPointSize:o,uPointStrokeScale:s,uPointInnerFillAlpha:a,uPalette:c,uPaletteSize:l}}function wi(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();wi(t),t.animation={startMs:fe(),durationMs:Math.max(0,i),from:a,to:r,easing:o};const c=()=>{const l=t.animation;if(!l)return;const u=Math.max(0,fe()-l.startMs),f=l.durationMs<=0?1:L(u/l.durationMs,0,1);let d=f;try{d=l.easing(f)}catch{d=f}if(Number.isFinite(d)||(d=f),d=L(d,0,1),n.setViewState({zoom:l.from.zoom+(l.to.zoom-l.from.zoom)*d,offsetX:l.from.offsetX+(l.to.offsetX-l.from.offsetX)*d,offsetY:l.from.offsetY+(l.to.offsetY-l.from.offsetY)*d,rotationDeg:l.from.rotationDeg+(l.to.rotationDeg-l.from.rotationDeg)*d}),s(),f>=1){t.animation=null,t.frame=null;return}t.frame=requestAnimationFrame(c)};t.frame=requestAnimationFrame(c)}function Ua(e){const t=Math.max(e*.5,1e-6),n=Math.max(1,e*8);return{minZoom:t,maxZoom:Math.max(t,n)}}function Na(e,t,n){const r=Ua(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 ka(e,t,n,r,i){const o=e.getViewState(),s={zoom:typeof r.zoom=="number"&&Number.isFinite(r.zoom)?L(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 La(e,t,n,r,i){const o=Math.min(t/e.width,n/e.height),s=Number.isFinite(o)&&o>0?o:1,a=L(s,r,i),c=t/a,l=n/a;return{fitZoom:s,target:{zoom:a,offsetX:(e.width-c)*.5,offsetY:(e.height-l)*.5,rotationDeg:0}}}function za(e,t,n,r,i,o){const s=e.getViewState(),a=L(s.zoom*r,t,n);if(a===s.zoom)return null;const[c,l]=e.screenToWorld(i,o),u=e.getViewportSize(),f=i-u.width*.5,d=o-u.height*.5,g=mi(s.rotationDeg),p=Math.cos(g),S=Math.sin(g),x=f/a*p-d/a*S,M=f/a*S+d/a*p,R=c-x,V=l-M;return{zoom:a,offsetX:R-u.width/(2*a),offsetY:V-u.height/(2*a)}}class xi{constructor(t,n,r={}){w(this,"canvas");w(this,"source");w(this,"gl");w(this,"camera",new zr);w(this,"onViewStateChange");w(this,"onStats");w(this,"onTileError");w(this,"onContextLost");w(this,"onContextRestored");w(this,"resizeObserver");w(this,"tileProgram");w(this,"pointProgram");w(this,"tileScheduler");w(this,"authToken");w(this,"destroyed",!1);w(this,"contextLost",!1);w(this,"frame",null);w(this,"frameSerial",0);w(this,"interactionState",{dragging:!1,mode:"none",rotateLastAngleRad:null,pointerId:null,lastPointerX:0,lastPointerY:0});w(this,"interactionLocked",!1);w(this,"ctrlDragRotate",!0);w(this,"rotationDragSensitivityDegPerPixel",In);w(this,"maxCacheTiles");w(this,"fitZoom",1);w(this,"minZoom",1e-6);w(this,"maxZoom",1);w(this,"minZoomOverride",null);w(this,"maxZoomOverride",null);w(this,"viewTransitionDurationMs",0);w(this,"viewTransitionEasing",gi);w(this,"viewAnimationState",{animation:null,frame:null});w(this,"pointCount",0);w(this,"usePointIndices",!1);w(this,"pointBuffersDirty",!0);w(this,"pointPaletteSize",1);w(this,"pointSizeStops",vn(En));w(this,"pointStrokeScale",1);w(this,"pointInnerFillOpacity",0);w(this,"imageColorSettings",{brightness:0,contrast:0,saturation:0});w(this,"lastPointData",null);w(this,"lastPointPalette",null);w(this,"zeroFillModes",new Uint8Array(0));w(this,"cache",new Map);w(this,"boundPointerDown");w(this,"boundPointerMove");w(this,"boundPointerUp");w(this,"boundWheel");w(this,"boundDoubleClick");w(this,"boundContextMenu");w(this,"boundContextLost");w(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):In,this.pointSizeStops=Ir(r.pointSizeByZoom),this.pointStrokeScale=Pr(r.pointStrokeScale),this.pointInnerFillOpacity=Er(r.pointInnerFillOpacity),this.imageColorSettings=vr(r.imageColorSettings),this.minZoomOverride=jt(r.minZoom),this.maxZoomOverride=jt(r.maxZoom),this.viewTransitionDurationMs=xn(r.viewTransition?.duration),this.viewTransitionEasing=Sn(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=_r(this.gl),this.pointProgram=Fr(this.gl),this.tileScheduler=new hi({authToken:this.authToken,maxConcurrency:r.tileScheduler?.maxConcurrency??12,maxRetries:r.tileScheduler?.maxRetries??2,retryBaseDelayMs:r.tileScheduler?.retryBaseDelayMs??120,retryMaxDelayMs:r.tileScheduler?.retryMaxDelayMs??1200,onTileLoad:(s,a)=>Aa({gl:this.gl,cache:this.cache,tile:s,bitmap:a,frameSerial:this.frameSerial,maxCacheTiles:this.maxCacheTiles,destroyed:this.destroyed,contextLost:this.contextLost,requestRender:()=>this.requestRender()}),onTileError:(s,a,c)=>{this.onTileError?.({tile:s,error:a,attemptCount:c}),console.warn("tile load failed",s.url,a)}}),this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(t);const o=Sa({canvas:this.canvas,state:this.interactionState,getInteractionLocked:()=>this.interactionLocked,getCtrlDragRotate:()=>this.ctrlDragRotate,getRotationDragSensitivityDegPerPixel:()=>this.rotationDragSensitivityDegPerPixel,cancelViewAnimation:()=>this.cancelViewAnimation(),camera:this.camera,source:this.source,emitViewState:()=>this.onViewStateChange?.(this.camera.getViewState()),requestRender:()=>this.requestRender(),zoomBy:(s,a,c)=>this.zoomBy(s,a,c)});this.boundPointerDown=o.pointerDown,this.boundPointerMove=o.pointerMove,this.boundPointerUp=o.pointerUp,this.boundWheel=o.wheel,this.boundDoubleClick=o.doubleClick,this.boundContextMenu=o.contextMenu,this.boundContextLost=s=>this.onWebGlContextLost(s),this.boundContextRestored=s=>this.onWebGlContextRestored(s),qs(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=Na(this.fitZoom,this.minZoomOverride,this.maxZoomOverride);this.minZoom=t.minZoom,this.maxZoom=t.maxZoom}resolveTargetViewState(t){return ka(this.camera,this.minZoom,this.maxZoom,t,()=>_n(this.camera,this.source))}cancelViewAnimation(){wi(this.viewAnimationState)}startViewAnimation(t,n,r){Ba({state:this.viewAnimationState,camera:this.camera,target:t,durationMs:n,easing:r,onUpdate:()=>{_n(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=jt(t),i=jt(n);if(this.minZoomOverride===r&&this.maxZoomOverride===i)return;this.minZoomOverride=r,this.maxZoomOverride=i,this.applyZoomBounds();const o=this.resolveTargetViewState({}),s=this.camera.getViewState();Cn(s,o)||this.applyViewStateAndRender(o)}setViewTransition(t){this.viewTransitionDurationMs=xn(t?.duration),this.viewTransitionEasing=Sn(t?.easing)}setViewState(t,n){const r=this.resolveTargetViewState(t),i=this.camera.getViewState();if(Cn(i,r))return;const o=xn(n?.duration??this.viewTransitionDurationMs),s=Sn(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=va(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,t);this.applyPointBufferRuntime(n),!(!t||t.length===0)&&this.requestRender()}setPointData(t){const n=_a(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=Ir(t);ra(this.pointSizeStops,n)||(this.pointSizeStops=n,this.requestRender())}setPointStrokeScale(t){const n=Pr(t);this.pointStrokeScale!==n&&(this.pointStrokeScale=n,this.requestRender())}setPointInnerFillOpacity(t){const n=Er(t);this.pointInnerFillOpacity!==n&&(this.pointInnerFillOpacity=n,this.requestRender())}setImageColorSettings(t){const n=vr(t),r=this.imageColorSettings;r.brightness===n.brightness&&r.contrast===n.contrast&&r.saturation===n.saturation||(this.imageColorSettings=n,this.requestRender())}cancelDrag(){xa(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=ia(n,this.pointSizeStops);return L(r,Pn,$s)}fitToImage(t){const n=this.canvas.getBoundingClientRect(),r=Math.max(1,n.width||1),i=Math.max(1,n.height||1),o=La(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=za(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=Fa({gl:this.gl,camera:this.camera,source:this.source,cache:this.cache,frameSerial:this.frameSerial,tileProgram:this.tileProgram,pointProgram:this.pointProgram,imageColorSettings:this.imageColorSettings,pointCount:this.pointCount,usePointIndices:this.usePointIndices,pointPaletteSize:this.pointPaletteSize,pointStrokeScale:this.pointStrokeScale,pointInnerFillOpacity:this.pointInnerFillOpacity,pointSizePx:this.getPointSizeByZoom()*Math.max(1,window.devicePixelRatio||1),tileScheduler:this.tileScheduler,getVisibleTiles:()=>ha(this.camera,this.source),getVisibleTilesForTier:r=>yi(this.camera,this.source,r),getViewBounds:()=>Dn(this.camera),intersectsBounds:da});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(){Zs(this.canvas,this.gl,this.camera),this.requestRender()}onWebGlContextLost(t){const n=Ta({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=_r(this.gl),this.pointProgram=Fr(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=Ia({destroyed:this.destroyed,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),resizeObserver:this.resizeObserver,removeCanvasEventListeners:()=>Hs(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 Da=6;function Fn(e,t){return e.id??t}function Oa(e,t,n,r,i,o){const s=i-n,a=o-r,c=s*s+a*a;if(c<=1e-12){const p=e-n,S=t-r;return p*p+S*S}const l=L(((e-n)*s+(t-r)*a)/c,0,1),u=n+s*l,f=r+a*l,d=e-u,g=t-f;return d*d+g*g}function Br(e,t,n,r){for(let i=1;i<n.length;i+=1){const o=n[i-1],s=n[i];if(Oa(e,t,o[0],o[1],s[0],s[1])<=r)return!0}return!1}function Ya(e,t,n,r){if(e<n.minX-r||e>n.maxX+r||t<n.minY-r||t>n.maxY+r)return!1;const i=r*r;if(Br(e,t,n.outer,i))return!0;for(const o of n.holes)if(Br(e,t,o,i))return!0;return!1}function Xa(e,t,n,r,i,o,s){if(!e.label||!e.labelAnchor)return!1;const a=rn(n.worldToScreen(e.labelAnchor[0],e.labelAnchor[1]));if(!a)return!1;const l=kn(e.label,r)+r.paddingX*2,u=r.fontSize+r.paddingY*2,f=a[0],d=a[1]-r.offsetY,g=s?L(f,l*.5+1,i-l*.5-1):f,p=s?L(d,u*.5+1,o-u*.5-1):d,S=g-l*.5,x=g+l*.5,M=p-u*.5,R=p+u*.5;return t[0]>=S&&t[0]<=x&&t[1]>=M&&t[1]<=R}function Wa(e,t="top-center"){const n=[];for(let r=0;r<e.length;r+=1){const i=e[r],o=vt([Et(i?.coordinates)]);if(o.length===0)continue;const s=typeof i?.label=="string"?i.label.trim():"";n.push({region:i,regionIndex:r,regionId:Fn(i,r),polygons:o,label:s,labelAnchor:s?Jr(o,t):null})}return n}function Va(e,t,n,r,i,o,s,a,c,l=!0){const u=e[0],f=e[1],d=Math.max(1e-6,r.getViewState().zoom),g=Math.max(0,s),p=Da/d;for(let S=n.length-1;S>=0;S-=1){const x=n[S];for(const R of x.polygons)if(Ya(u,f,R,p))return{region:x.region,regionIndex:x.regionIndex,regionId:x.regionId};let M=Qr(i,o?.({region:x.region,regionId:x.regionId,regionIndex:x.regionIndex,zoom:d}));if(g>0&&(M={...M,offsetY:M.offsetY+g}),!!Xa(x,t,r,M,a,c,l))return{region:x.region,regionIndex:x.regionIndex,regionId:x.regionId}}return null}const Mn=[],Ga=[],qa={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)},Ha=.65,Za=4,$a=180,Ur=20;function Ka(e){const t=L(e,0,1);return t*t*(3-2*t)}function ja({source:e,viewState:t,imageColorSettings:n=null,onViewStateChange:r,onStats:i,onTileError:o,onContextLost:s,onContextRestored:a,debugOverlay:c=!1,debugOverlayStyle:l,fitNonce:u=0,rotationResetNonce:f=0,authToken:d="",ctrlDragRotate:g=!0,pointData:p=null,pointPalette:S=null,pointSizeByZoom:x,pointStrokeScale:M,pointInnerFillOpacity:R,minZoom:V,maxZoom:T,viewTransition:F,roiRegions:G,roiPolygons:J,clipPointsToRois:j=!1,clipMode:Q="worker",onClipStats:se,onRoiPointGroups:pe,roiPaletteIndexToTermId:Re,interactionLock:B=!1,drawTool:k="cursor",stampOptions:O,brushOptions:U,drawFillColor:ee,regionStrokeStyle:Ne,regionStrokeHoverStyle:ue,regionStrokeActiveStyle:Oe,patchStrokeStyle:Be,resolveRegionStrokeStyle:Ye,resolveRegionLabelStyle:P,overlayShapes:C,customLayers:D,patchRegions:ae,regionLabelStyle:Z,regionLabelAnchor:le="top-center",drawAreaTooltip:de,autoLiftRegionLabelAtMaxZoom:we=!1,clampRegionLabelToViewport:te=!0,onPointerWorldMove:he,onPointHover:re,onPointClick:ne,onRegionHover:K,onRegionClick:Me,activeRegionId:H,onActiveRegionChange:xe,getCellByCoordinatesRef:be,onDrawComplete:Se,onPatchComplete:ke,overviewMapConfig:Ce,className:Ee,style:Te}){const ct=Ce?.show??!1,ut=Ce?.options,Y=h.useRef(null),X=h.useRef(null),ie=h.useRef(null),ye=h.useRef(null),bt=h.useRef(r),yt=h.useRef(i),Qe=h.useRef(o),_t=h.useRef(s),Ft=h.useRef(a),wt=h.useRef(c),[Bt,m]=h.useState(null),[y,A]=h.useState(()=>H??null),I=H!==void 0,v=I?H??null:y,[me,q]=h.useState(null),[W,oe]=h.useState(null),[ce,Ae]=h.useState(0),ge=h.useRef(null),Ie=h.useRef(null),Ve=h.useRef(null),qe=h.useRef(0),et=h.useRef({rafId:null,startMs:0,from:0,to:0}),Ut=h.useRef(0),tt=G??Mn,Mi=ae??Mn,sn=J??Ga,Nt=(D?.length??0)>0,Ci=h.useMemo(()=>({position:"relative",width:"100%",height:"100%",...Te}),[Te]),Ai=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)",...l}),[l]),Xe=h.useMemo(()=>tt.length>0?tt:sn.length===0?Mn:sn.map((b,E)=>({id:E,coordinates:b})),[tt,sn]),He=h.useMemo(()=>Wa(Xe,le),[Xe,le]),On=h.useMemo(()=>Ln(Z),[Z]),lt=h.useCallback(b=>{const E=L(b,0,Ur);Math.abs(qe.current-E)<1e-4||(qe.current=E,Ae(E))},[]),nt=h.useCallback(()=>{const b=et.current;b.rafId!==null&&(cancelAnimationFrame(b.rafId),b.rafId=null)},[]),an=h.useCallback(b=>{const E=L(b,0,Ur),_=et.current,N=qe.current;if(Math.abs(N-E)<1e-4){nt(),_.to=E,lt(E);return}nt(),_.startMs=performance.now(),_.from=N,_.to=E;const z=$=>{const ve=et.current,Le=Math.max(0,$-ve.startMs),ht=L(Le/$a,0,1),cn=Ka(ht),un=ve.from+(ve.to-ve.from)*cn;if(lt(un),ie.current?.(),ht>=1){ve.rafId=null,lt(ve.to);return}ve.rafId=requestAnimationFrame(z)};_.rafId=requestAnimationFrame(z)},[lt,nt]),Ze=h.useCallback(b=>{const E=X.current;if(!E||typeof b!="number"||!Number.isFinite(b)){an(0);return}const _=ei(we,b,E.getZoomRange());an(_)},[we,an]),rt=h.useMemo(()=>Xe.map(b=>Et(b.coordinates)).filter(b=>b!=null),[Xe]),[it,kt]=h.useState(p);h.useEffect(()=>{const b=++Ut.current;let E=!1;if(!j)return kt(p),()=>{E=!0};if(!p||!p.count||!p.positions||!p.paletteIndices)return kt(null),()=>{E=!0};if(rt.length===0)return kt(qa),se?.({mode:Q,durationMs:0,inputCount:p.count,outputCount:0,polygonCount:0}),()=>{E=!0};const _=(z,$)=>{if(E||b!==Ut.current)return;const ve=p.count,Le=z?.drawIndices?z.drawIndices.length:z?.count??0;kt(z),se?.({mode:$.mode,durationMs:$.durationMs,inputCount:ve,outputCount:Le,polygonCount:rt.length,usedWebGpu:$.usedWebGpu,candidateCount:$.candidateCount,bridgedToDraw:$.bridgedToDraw})};return(async()=>{if(Q==="sync"){const z=performance.now(),$=It(p,rt);_($,{mode:"sync",durationMs:performance.now()-z});return}if(Q==="hybrid-webgpu"){const z=await ai(p,rt,{bridgeToDraw:!0});_(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 ui(p,rt);_(z.data,{mode:z.meta.mode,durationMs:z.meta.durationMs})}catch{const z=performance.now(),$=It(p,rt);_($,{mode:"sync",durationMs:performance.now()-z})}})(),()=>{E=!0}},[j,Q,p,rt,se]);const Yn=!!(re||ne||be),[Ge,Xn]=h.useState(null);h.useEffect(()=>{if(!Yn||!it){Xn(null);return}let b=!1;return fi(it,e).then(E=>{b||Xn(E)}),()=>{b=!0}},[Yn,it,e]);const ot=h.useCallback(b=>{const E=X.current;if(!E||!Ge)return null;const _=Number(b[0]),N=Number(b[1]);if(!Number.isFinite(_)||!Number.isFinite(N))return null;const z=Math.max(1e-6,E.getViewState().zoom),$=E.getPointSizeByZoom(),Le=Math.max(Za,$*Ha)/z;if(!Number.isFinite(Le)||Le<=0)return null;const{cellSize:ht,cellOffsets:cn,cellLengths:un,pointIndices:_i,positions:$n,safeCount:Fi}=Ge,Kn=Math.floor(_/ht),jn=Math.floor(N/ht),Dt=Math.max(1,Math.ceil(Le/ht)),Bi=Le*Le;let Ot=-1,Jn=Bi,Qn=0,er=0;for(let ln=Kn-Dt;ln<=Kn+Dt;ln+=1)for(let fn=jn-Dt;fn<=jn+Dt;fn+=1){const dn=li(Ge,ln,fn);if(dn<0)continue;const tr=cn[dn],Ni=tr+un[dn];for(let hn=tr;hn<Ni;hn+=1){const Yt=_i[hn];if(Yt>=Fi)continue;const nr=$n[Yt*2],rr=$n[Yt*2+1],ir=nr-_,or=rr-N,sr=ir*ir+or*or;sr>Jn||(Jn=sr,Ot=Yt,Qn=nr,er=rr)}}if(Ot<0)return null;const Ui=Ge.ids?Number(Ge.ids[Ot]):null;return{index:Ot,id:Ui,coordinate:[_,N],pointCoordinate:[Qn,er]}},[Ge]),ft=h.useCallback((b,E)=>{if(!re)return;const _=b?.index??null,N=b?.id??null;Ie.current===_&&Ve.current===N||(Ie.current=_,Ve.current=N,re({index:_,id:N,coordinate:E,pointCoordinate:b?.pointCoordinate??null}))},[re]),Lt=h.useCallback((b,E)=>{if(!ne)return;const _=ot(b);_&&ne({..._,button:E})},[ne,ot]);h.useEffect(()=>{if(be)return be.current=ot,()=>{be.current===ot&&(be.current=null)}},[be,ot]),h.useEffect(()=>{I&&A(H??null)},[I,H]);const $e=h.useCallback(b=>{String(v)!==String(b)&&(I||A(b),xe?.(b))},[v,I,xe]);h.useEffect(()=>{bt.current=r},[r]),h.useEffect(()=>{yt.current=i},[i]),h.useEffect(()=>{Qe.current=o},[o]),h.useEffect(()=>{_t.current=s},[s]),h.useEffect(()=>{Ft.current=a},[a]),h.useEffect(()=>{wt.current=c,c||oe(null)},[c]),h.useEffect(()=>()=>{nt()},[nt]);const Wn=h.useCallback(b=>{yt.current?.(b),wt.current&&oe(b)},[]),Ri=h.useMemo(()=>W?[`tier ${W.tier} | frame ${W.frameMs?.toFixed(2)??"-"} ms | drawCalls ${W.drawCalls??"-"}`,`tiles visible ${W.visible} | rendered ${W.rendered} | fallback ${W.fallback}`,`cache size ${W.cache} | hit ${W.cacheHits??"-"} | miss ${W.cacheMisses??"-"}`,`queue inflight ${W.inflight} | queued ${W.queued??"-"} | retries ${W.retries??"-"} | failed ${W.failed??"-"} | aborted ${W.aborted??"-"}`,`points ${W.points}`].join(`
|
|
162
|
-
`):"stats: waiting for first frame...",[W]);h.useEffect(()=>{!(v===null?!0:Xe.some((N,z)=>String(Fn(N,z))===String(v)))&&v!==null&&$e(null);const E=ge.current;!(E===null?!0:Xe.some((N,z)=>String(Fn(N,z))===String(E)))&&E!==null&&(ge.current=null,m(null),K?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[Xe,v,K,$e]),h.useEffect(()=>{const b=Ie.current;b!==null&&(Ge&&b<Ge.safeCount||(Ie.current=null,Ve.current=null,re?.({index:null,id:null,coordinate:null,pointCoordinate:null})))},[Ge,re]);const Vn=h.useCallback(b=>{Ze(b.zoom),Nt&&q(b);const E=bt.current;E&&E(b),ie.current?.(),ye.current?.()},[Nt,Ze]);h.useEffect(()=>{const b=X.current;b&&Ze(b.getViewState().zoom)},[Ze,V,T]),h.useEffect(()=>{k!=="cursor"&&ge.current!==null&&(ge.current=null,m(null),K?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[k,K]),h.useEffect(()=>{k!=="cursor"&&Ie.current!==null&&(Ie.current=null,Ve.current=null,re?.({index:null,id:null,coordinate:null,pointCoordinate:null}))},[k,re]);const Ke=h.useCallback((b,E)=>{const _=X.current;if(!_)return null;const N=_.screenToWorld(b,E);if(!Array.isArray(N)||N.length<2)return null;const z=Number(N[0]),$=Number(N[1]);return!Number.isFinite(z)||!Number.isFinite($)?null:[z,$]},[]),Gn=h.useCallback((b,E)=>{const _=X.current;if(!_)return null;const N=_.worldToScreen(b,E);return rn(N)},[]),zt=h.useCallback((b,E)=>{const _=Y.current;if(!_)return null;const N=_.getBoundingClientRect();if(!Number.isFinite(N.width)||!Number.isFinite(N.height)||N.width<=0||N.height<=0)return null;const z=b-N.left,$=E-N.top;return!Number.isFinite(z)||!Number.isFinite($)?null:{screenCoord:[z,$],canvasWidth:Math.max(1,N.width),canvasHeight:Math.max(1,N.height)}},[]),dt=h.useCallback((b,E,_,N)=>{const z=X.current;return z?Va(b,E,He,z,On,P,ce,_,N,te):null},[He,On,P,ce,te]),qn=h.useCallback(()=>{X.current?.requestRender(),ie.current?.(),ye.current?.()},[]),Hn=h.useMemo(()=>me??X.current?.getViewState()??null,[me]),Zn=h.useMemo(()=>{if(!e)return null;const b=Hn;return b?{source:e,viewState:b,drawTool:k,interactionLock:B,worldToScreen:Gn,screenToWorld:Ke,requestRedraw:qn}:null},[e,Hn,k,B,Gn,Ke,qn]),Ti=h.useCallback(b=>{const E=b.target===Y.current,_=Ke(b.clientX,b.clientY);if(he){const Le=!!_&&_[0]>=0&&_[1]>=0&&!!e&&_[0]<=e.width&&_[1]<=e.height;he({coordinate:_,clientX:b.clientX,clientY:b.clientY,insideImage:Le})}if(k!=="cursor")return;if(!E){ft(null,null),ge.current!==null&&(ge.current=null,m(null),K?.({region:null,regionId:null,regionIndex:-1,coordinate:null}));return}if(!_){ft(null,null);return}if(re&&ft(ot(_),_),!He.length)return;const N=zt(b.clientX,b.clientY);if(!N)return;const z=dt(_,N.screenCoord,N.canvasWidth,N.canvasHeight),$=z?.regionId??null,ve=ge.current;String(ve)!==String($)&&(ge.current=$,m($),K?.({region:z?.region??null,regionId:$,regionIndex:z?.regionIndex??-1,coordinate:_}))},[k,He,Ke,K,he,e,ft,ot,re,zt,dt]),Ii=h.useCallback(()=>{he?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1}),ft(null,null),ge.current!==null&&(ge.current=null,m(null),K?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[K,he,ft]),Pi=h.useCallback(b=>{if(k!=="cursor"||b.target!==Y.current)return;const E=Ke(b.clientX,b.clientY);if(!E)return;if(Lt(E,b.button),!He.length){$e(null);return}const _=zt(b.clientX,b.clientY);if(!_)return;const N=dt(E,_.screenCoord,_.canvasWidth,_.canvasHeight);if(!N){$e(null);return}const z=v!==null&&String(v)===String(N.regionId)?null:N.regionId;$e(z),Me?.({region:N.region,regionId:N.regionId,regionIndex:N.regionIndex,coordinate:E})},[k,He,Ke,Me,v,$e,Lt,zt,dt]),Ei=h.useCallback(b=>{if(k!=="brush"||U?.clickSelectRoi!==!0||!He.length)return!1;const E=X.current,_=Y.current;if(!E||!_)return!1;const N=_.getBoundingClientRect();if(N.width<=0||N.height<=0)return!1;const z=rn(E.worldToScreen(b[0],b[1]));if(!z)return!1;const $=dt(b,z,N.width,N.height);if(!$)return!1;const ve=v!==null&&String(v)===String($.regionId)?null:$.regionId;return $e(ve),Me?.({region:$.region,regionId:$.regionId,regionIndex:$.regionIndex,coordinate:b}),!0},[k,U?.clickSelectRoi,He,v,$e,Me,dt]),vi=h.useCallback(b=>{if(!ne||k!=="cursor"||b.target!==Y.current)return;b.preventDefault();const E=Ke(b.clientX,b.clientY);E&&Lt(E,b.button)},[k,Ke,Lt,ne]);return h.useEffect(()=>{const b=Y.current;if(!b||!e)return;const E=new xi(b,e,{onViewStateChange:Vn,onStats:Wn,onTileError:_=>{Qe.current?.(_)},onContextLost:()=>{_t.current?.()},onContextRestored:()=>{Ft.current?.()},authToken:d,imageColorSettings:n,ctrlDragRotate:g,pointSizeByZoom:x,pointStrokeScale:M,pointInnerFillOpacity:R,minZoom:V,maxZoom:T,viewTransition:F});return X.current=E,t&&E.setViewState(t),Ze(E.getViewState().zoom),E.setInteractionLock(B),Nt&&q(E.getViewState()),()=>{nt(),lt(0),E.destroy(),X.current=null}},[e,Wn,d,g,Vn,Nt,Ze,nt,lt]),h.useEffect(()=>{const b=X.current;!b||!t||b.setViewState(t)},[t]),h.useEffect(()=>{const b=X.current;b&&b.fitToImage()},[u]),h.useEffect(()=>{const b=X.current;b&&b.resetRotation()},[f]),h.useEffect(()=>{const b=X.current;!b||!S||b.setPointPalette(S)},[S]),h.useEffect(()=>{const b=X.current;b&&b.setPointSizeByZoom(x)},[x]),h.useEffect(()=>{const b=X.current;b&&b.setPointStrokeScale(M)},[M]),h.useEffect(()=>{const b=X.current;b&&b.setPointInnerFillOpacity(R)},[R]),h.useEffect(()=>{const b=X.current;b&&(b.setZoomRange(V,T),Ze(b.getViewState().zoom))},[V,T,Ze]),h.useEffect(()=>{const b=X.current;b&&b.setViewTransition(F)},[F]),h.useEffect(()=>{const b=X.current;b&&b.setImageColorSettings(n)},[n]),h.useEffect(()=>{const b=X.current;b&&b.setPointData(it)},[it]),h.useEffect(()=>{if(!pe)return;const E=di(j?it:p,Xe,{paletteIndexToTermId:Re,includeEmptyRegions:!0});pe(E)},[pe,j,p,it,Xe,Re]),h.useEffect(()=>{const b=X.current;b&&b.setInteractionLock(B)},[B]),De.jsxs("div",{className:Ee,style:Ci,onPointerMove:Ti,onPointerLeave:Ii,onClick:Pi,onContextMenu:vi,children:[De.jsx("canvas",{ref:Y,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none",cursor:k==="cursor"&&Bt!==null?"pointer":B?"crosshair":"grab"}}),e&&Zn&&Array.isArray(D)&&D.length>0?D.map((b,E)=>De.jsx("div",{className:b.className,style:{position:"absolute",inset:0,zIndex:b.zIndex??3,pointerEvents:b.pointerEvents??"none",...b.style},children:b.render(Zn)},b.id??E)):null,e?De.jsx(ti,{tool:k,enabled:k!=="cursor",imageWidth:e.width,imageHeight:e.height,imageMpp:e.mpp,imageZoom:e.maxTierZoom,stampOptions:O,brushOptions:U,drawFillColor:ee,projectorRef:X,onBrushTap:Ei,viewStateSignal:t,persistedRegions:Xe,patchRegions:Mi,regionStrokeStyle:Ne,regionStrokeHoverStyle:ue,regionStrokeActiveStyle:Oe,patchStrokeStyle:Be,resolveRegionStrokeStyle:Ye,resolveRegionLabelStyle:P,overlayShapes:C,hoveredRegionId:Bt,activeRegionId:v,regionLabelStyle:Z,regionLabelAnchor:le,drawAreaTooltip:de,autoLiftRegionLabelAtMaxZoom:we,clampRegionLabelToViewport:te,regionLabelAutoLiftOffsetPx:ce,invalidateRef:ie,onDrawComplete:Se,onPatchComplete:ke}):null,c?De.jsx("pre",{"data-open-plant-debug-overlay":!0,style:Ai,children:Ri}):null,e&&ct&&De.jsx(ri,{source:e,projectorRef:X,authToken:d,options:ut,invalidateRef:ye,className:Ce?.className,style:Ce?.style})]})}function Nr(e,t,n,r){return[Math.min(e,n),Math.min(t,r),Math.max(e,n),Math.max(t,r)]}function kr(e,t){return!(e[2]<t[0]||e[0]>t[2]||e[3]<t[1]||e[1]>t[3])}class Ja{constructor(t=16){w(this,"targetNodeSize");w(this,"items",[]);w(this,"globalBounds",[0,0,0,0]);w(this,"gridSize",1);w(this,"cellWidth",1);w(this,"cellHeight",1);w(this,"buckets",[]);w(this,"visited",new Uint32Array(0));w(this,"querySerial",1);const n=Number.isFinite(t)?Math.floor(t):16;this.targetNodeSize=Math.max(1,n)}load(t){if(!Array.isArray(t)||t.length===0){this.items=[],this.globalBounds=[0,0,0,0],this.gridSize=1,this.cellWidth=1,this.cellHeight=1,this.buckets=[],this.visited=new Uint32Array(0),this.querySerial=1;return}const n=[];let r=1/0,i=1/0,o=-1/0,s=-1/0;for(const u of t){if(!u||!Number.isFinite(u.minX)||!Number.isFinite(u.minY)||!Number.isFinite(u.maxX)||!Number.isFinite(u.maxY))continue;const f=Nr(u.minX,u.minY,u.maxX,u.maxY);r=Math.min(r,f[0]),i=Math.min(i,f[1]),o=Math.max(o,f[2]),s=Math.max(s,f[3]),n.push({minX:f[0],minY:f[1],maxX:f[2],maxY:f[3],value:u.value})}if(this.items=n,this.visited=new Uint32Array(n.length),this.querySerial=1,n.length===0||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(o)||!Number.isFinite(s)){this.globalBounds=[0,0,0,0],this.gridSize=1,this.cellWidth=1,this.cellHeight=1,this.buckets=[];return}this.globalBounds=[r,i,o,s],this.gridSize=Math.max(1,Math.ceil(Math.sqrt(n.length/this.targetNodeSize)));const a=Math.max(0,o-r),c=Math.max(0,s-i);this.cellWidth=a>0?a/this.gridSize:1,this.cellHeight=c>0?c/this.gridSize:1;const l=this.gridSize*this.gridSize;this.buckets=Array.from({length:l},()=>[]);for(let u=0;u<n.length;u+=1){const f=n[u],d=this.toCellX(f.minX),g=this.toCellX(f.maxX),p=this.toCellY(f.minY),S=this.toCellY(f.maxY);for(let x=p;x<=S;x+=1)for(let M=d;M<=g;M+=1)this.buckets[x*this.gridSize+M].push(u)}}search(t){if(this.items.length===0)return[];if(!Array.isArray(t)||t.length<4)return[];const n=Nr(t[0],t[1],t[2],t[3]);if(!kr(n,this.globalBounds))return[];const r=this.toCellX(n[0]),i=this.toCellX(n[2]),o=this.toCellY(n[1]),s=this.toCellY(n[3]),a=this.nextSerial(),c=[];for(let l=o;l<=s;l+=1)for(let u=r;u<=i;u+=1){const f=this.buckets[l*this.gridSize+u];if(!(!f||f.length===0))for(const d of f){if(this.visited[d]===a)continue;this.visited[d]=a;const g=this.items[d];kr(n,[g.minX,g.minY,g.maxX,g.maxY])&&c.push(g)}}return c}nextSerial(){return this.querySerial+=1,this.querySerial===4294967295&&(this.visited.fill(0),this.querySerial=1),this.querySerial}toCellX(t){const n=this.globalBounds[0],r=this.globalBounds[2];if(this.gridSize<=1||r<=n)return 0;const i=(t-n)/this.cellWidth;return!Number.isFinite(i)||i<=0?0:i>=this.gridSize-1?this.gridSize-1:Math.max(0,Math.min(this.gridSize-1,Math.floor(i)))}toCellY(t){const n=this.globalBounds[1],r=this.globalBounds[3];if(this.gridSize<=1||r<=n)return 0;const i=(t-n)/this.cellHeight;return!Number.isFinite(i)||i<=0?0:i>=this.gridSize-1?this.gridSize-1:Math.max(0,Math.min(this.gridSize-1,Math.floor(i)))}}function Qa(e){return new Ja(e)}function ec(e){return e.replace(/^\s*SRID\s*=\s*\d+\s*;\s*/i,"")}function tc(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function nc(e){return e>="0"&&e<="9"}function Lr(e){return e==="+"||e==="-"||e==="."||nc(e)}class rc{constructor(t){w(this,"text");w(this,"index",0);this.text=ec(t.trim())}parse(){if(!this.text)return null;const t=this.readWord();if(!t)return null;const n=t.toUpperCase();if(n!=="POLYGON"&&n!=="MULTIPOLYGON")return null;this.skipWhitespace();const r=this.peekWord();if(r){const s=r.toUpperCase();(s==="Z"||s==="M"||s==="ZM")&&(this.readWord(),this.skipWhitespace())}if(this.consumeWordIf("EMPTY"))return this.skipWhitespace(),this.isEof()?n==="POLYGON"?{type:"Polygon",coordinates:[]}:{type:"MultiPolygon",coordinates:[]}:null;let i;try{i=this.parseNestedList()}catch{return null}if(this.skipWhitespace(),!this.isEof())return null;if(n==="POLYGON"){const s=Si(i);return s?{type:"Polygon",coordinates:s}:null}const o=oc(i);return o?{type:"MultiPolygon",coordinates:o}:null}isEof(){return this.index>=this.text.length}currentChar(){return this.text[this.index]??""}skipWhitespace(){for(;!this.isEof()&&/\s/.test(this.currentChar());)this.index+=1}readWord(){if(this.skipWhitespace(),this.isEof())return null;const t=this.index;for(;!this.isEof()&&tc(this.currentChar());)this.index+=1;return this.index===t?null:this.text.slice(t,this.index)}peekWord(){const t=this.index,n=this.readWord();return this.index=t,n}consumeWordIf(t){const n=this.index,r=this.readWord();return!r||r.toUpperCase()!==t.toUpperCase()?(this.index=n,!1):!0}parseNestedList(){if(this.skipWhitespace(),this.currentChar()!=="(")throw new Error("Expected '('");this.index+=1;const t=[];for(;;){this.skipWhitespace(),this.currentChar()==="("?t.push(this.parseNestedList()):t.push(this.parseCoordinateTuple()),this.skipWhitespace();const n=this.currentChar();if(n===","){this.index+=1;continue}if(n===")"){this.index+=1;break}throw new Error("Expected ',' or ')'")}return t}parseCoordinateTuple(){this.skipWhitespace();const t=[];for(;;){this.skipWhitespace();const n=this.currentChar();if(!n||!Lr(n))break;const r=this.readNumber();if(r===null)break;t.push(r),this.skipWhitespace();const i=this.currentChar();if(!i||i===","||i===")")break;if(!Lr(i))throw new Error("Invalid coordinate")}if(t.length<2)throw new Error("Coordinate requires at least x y");return[t[0],t[1]]}readNumber(){if(this.skipWhitespace(),this.isEof())return null;const n=this.text.slice(this.index).match(/^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/);if(!n)return null;const r=Number(n[0]);return Number.isFinite(r)?(this.index+=n[0].length,r):null}}function ic(e){return Array.isArray(e)&&e.length>=2&&typeof e[0]=="number"&&Number.isFinite(e[0])&&typeof e[1]=="number"&&Number.isFinite(e[1])}function Si(e){if(!Array.isArray(e))return null;const t=[];for(const n of e){if(!Array.isArray(n))return null;const r=[];for(const i of n){if(!ic(i))return null;r.push([i[0],i[1]])}t.push(r)}return t}function oc(e){if(!Array.isArray(e))return null;const t=[];for(const n of e){const r=Si(n);if(!r)return null;t.push(r)}return t}function sc(e){return typeof e!="string"?null:new rc(e).parse()}exports.DEFAULT_POINT_COLOR=Un;exports.DrawLayer=ti;exports.M1TileRenderer=Dr;exports.OverviewMap=ri;exports.TileScheduler=hi;exports.TileViewerCanvas=xs;exports.WsiTileRenderer=xi;exports.WsiViewerCanvas=ja;exports.buildPointSpatialIndexAsync=fi;exports.buildTermPalette=Vi;exports.calcScaleLength=Xi;exports.calcScaleResolution=Nn;exports.clamp=L;exports.closeRing=Fe;exports.computeRoiPointGroups=di;exports.createCircle=Rn;exports.createRectangle=on;exports.createSpatialIndex=Qa;exports.filterPointDataByPolygons=It;exports.filterPointDataByPolygonsHybrid=ai;exports.filterPointDataByPolygonsInWorker=ui;exports.filterPointIndicesByPolygons=ii;exports.filterPointIndicesByPolygonsInWorker=vs;exports.getWebGpuCapabilities=Is;exports.hexToRgba=Vr;exports.isSameViewState=Cn;exports.lookupCellIndex=li;exports.normalizeImageInfo=ys;exports.parseWkt=sc;exports.prefilterPointsByBoundsWebGpu=si;exports.terminatePointHitIndexWorker=zs;exports.terminateRoiClipWorker=Es;exports.toBearerToken=Wi;exports.toRoiGeometry=Et;exports.toTileUrl=zn;
|
|
162
|
+
}`),i=Tt(t,r,"uCamera"),o=Tt(t,r,"uPointSize"),s=Tt(t,r,"uPointStrokeScale"),a=Tt(t,r,"uPointInnerFillAlpha"),u=Tt(t,r,"uPalette"),c=Tt(t,r,"uPaletteSize"),f=t.createVertexArray(),l=t.createBuffer(),h=t.createBuffer(),d=t.createBuffer(),m=t.createBuffer(),p=t.createTexture();if(!f||!l||!h||!d||!m||!p)throw new Error("point buffer allocation failed");t.bindVertexArray(f),t.bindBuffer(t.ARRAY_BUFFER,l),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const x=t.getAttribLocation(r,"aPosition");if(x<0)throw new Error("point position attribute not found");t.enableVertexAttribArray(x),t.vertexAttribPointer(x,2,t.FLOAT,!1,0,0),t.bindBuffer(t.ARRAY_BUFFER,h),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const w=t.getAttribLocation(r,"aTerm");if(w<0)throw new Error("point term attribute not found");t.enableVertexAttribArray(w),t.vertexAttribIPointer(w,1,t.UNSIGNED_SHORT,0,0),t.bindBuffer(t.ARRAY_BUFFER,d),t.bufferData(t.ARRAY_BUFFER,0,t.DYNAMIC_DRAW);const M=t.getAttribLocation(r,"aFillMode");if(M<0)throw new Error("point fill mode attribute not found");return t.enableVertexAttribArray(M),t.vertexAttribIPointer(M,1,t.UNSIGNED_BYTE,0,0),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,m),t.bufferData(t.ELEMENT_ARRAY_BUFFER,0,t.DYNAMIC_DRAW),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null),t.bindTexture(t.TEXTURE_2D,p),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,new Uint8Array([160,160,160,255])),t.bindTexture(t.TEXTURE_2D,null),{program:r,vao:f,posBuffer:l,termBuffer:h,fillModeBuffer:d,indexBuffer:m,paletteTexture:p,uCamera:i,uPointSize:o,uPointStrokeScale:s,uPointInnerFillAlpha:a,uPalette:u,uPaletteSize:c}}function ro(t){t.animation=null,t.frame!==null&&(cancelAnimationFrame(t.frame),t.frame=null)}function Dl(t){const{state:e,camera:n,target:r,durationMs:i,easing:o,onUpdate:s}=t,a=n.getViewState();ro(e),e.animation={startMs:mt(),durationMs:Math.max(0,i),from:a,to:r,easing:o};const u=()=>{const c=e.animation;if(!c)return;const f=Math.max(0,mt()-c.startMs),l=c.durationMs<=0?1:D(f/c.durationMs,0,1);let h=l;try{h=c.easing(l)}catch{h=l}if(Number.isFinite(h)||(h=l),h=D(h,0,1),n.setViewState({zoom:c.from.zoom+(c.to.zoom-c.from.zoom)*h,offsetX:c.from.offsetX+(c.to.offsetX-c.from.offsetX)*h,offsetY:c.from.offsetY+(c.to.offsetY-c.from.offsetY)*h,rotationDeg:c.from.rotationDeg+(c.to.rotationDeg-c.from.rotationDeg)*h}),s(),l>=1){e.animation=null,e.frame=null;return}e.frame=requestAnimationFrame(u)};e.frame=requestAnimationFrame(u)}function Ol(t){const e=Math.max(t*.5,1e-6),n=Math.max(1,t*8);return{minZoom:e,maxZoom:Math.max(e,n)}}function Yl(t,e,n){const r=Ol(t);let i=e??r.minZoom,o=n??r.maxZoom;return i=Math.max(1e-6,i),o=Math.max(1e-6,o),i>o&&(i=o),{minZoom:i,maxZoom:o}}function Xl(t,e,n,r,i){const o=t.getViewState(),s={zoom:typeof r.zoom=="number"&&Number.isFinite(r.zoom)?D(r.zoom,e,n):o.zoom,offsetX:typeof r.offsetX=="number"&&Number.isFinite(r.offsetX)?r.offsetX:o.offsetX,offsetY:typeof r.offsetY=="number"&&Number.isFinite(r.offsetY)?r.offsetY:o.offsetY,rotationDeg:typeof r.rotationDeg=="number"&&Number.isFinite(r.rotationDeg)?r.rotationDeg:o.rotationDeg};t.setViewState(s),i();const a=t.getViewState();return t.setViewState(o),a}function Wl(t,e,n,r,i){const o=Math.min(e/t.width,n/t.height),s=Number.isFinite(o)&&o>0?o:1,a=D(s,r,i),u=e/a,c=n/a;return{fitZoom:s,target:{zoom:a,offsetX:(t.width-u)*.5,offsetY:(t.height-c)*.5,rotationDeg:0}}}function Vl(t,e,n,r,i,o){const s=t.getViewState(),a=D(s.zoom*r,e,n);if(a===s.zoom)return null;const[u,c]=t.screenToWorld(i,o),f=t.getViewportSize(),l=i-f.width*.5,h=o-f.height*.5,d=Qi(s.rotationDeg),m=Math.cos(d),p=Math.sin(d),x=l/a*m-h/a*p,w=l/a*p+h/a*m,M=u-x,N=c-w;return{zoom:a,offsetX:M-f.width/(2*a),offsetY:N-f.height/(2*a)}}class io{constructor(e,n,r={}){E(this,"canvas");E(this,"source");E(this,"gl");E(this,"camera",new Ei);E(this,"onViewStateChange");E(this,"onStats");E(this,"onTileError");E(this,"onContextLost");E(this,"onContextRestored");E(this,"resizeObserver");E(this,"tileProgram");E(this,"pointProgram");E(this,"tileScheduler");E(this,"authToken");E(this,"destroyed",!1);E(this,"contextLost",!1);E(this,"frame",null);E(this,"frameSerial",0);E(this,"interactionState",{dragging:!1,mode:"none",rotateLastAngleRad:null,pointerId:null,lastPointerX:0,lastPointerY:0});E(this,"interactionLocked",!1);E(this,"ctrlDragRotate",!0);E(this,"rotationDragSensitivityDegPerPixel",Zn);E(this,"maxCacheTiles");E(this,"fitZoom",1);E(this,"minZoom",1e-6);E(this,"maxZoom",1);E(this,"minZoomOverride",null);E(this,"maxZoomOverride",null);E(this,"viewTransitionDurationMs",0);E(this,"viewTransitionEasing",Ji);E(this,"viewAnimationState",{animation:null,frame:null});E(this,"pointCount",0);E(this,"usePointIndices",!1);E(this,"pointBuffersDirty",!0);E(this,"pointPaletteSize",1);E(this,"pointSizeStops",Qn(jn));E(this,"pointStrokeScale",1);E(this,"pointInnerFillOpacity",0);E(this,"imageColorSettings",{brightness:0,contrast:0,saturation:0});E(this,"lastPointData",null);E(this,"lastPointPalette",null);E(this,"zeroFillModes",new Uint8Array(0));E(this,"cache",new Map);E(this,"boundPointerDown");E(this,"boundPointerMove");E(this,"boundPointerUp");E(this,"boundWheel");E(this,"boundDoubleClick");E(this,"boundContextMenu");E(this,"boundContextLost");E(this,"boundContextRestored");this.canvas=e,this.source=n,this.onViewStateChange=r.onViewStateChange,this.onStats=r.onStats,this.onTileError=r.onTileError,this.onContextLost=r.onContextLost,this.onContextRestored=r.onContextRestored,this.authToken=r.authToken??"",this.maxCacheTiles=Math.max(32,Math.floor(r.maxCacheTiles??320)),this.ctrlDragRotate=r.ctrlDragRotate??!0,this.rotationDragSensitivityDegPerPixel=typeof r.rotationDragSensitivityDegPerPixel=="number"&&Number.isFinite(r.rotationDragSensitivityDegPerPixel)?Math.max(0,r.rotationDragSensitivityDegPerPixel):Zn,this.pointSizeStops=fi(r.pointSizeByZoom),this.pointStrokeScale=hi(r.pointStrokeScale),this.pointInnerFillOpacity=di(r.pointInnerFillOpacity),this.imageColorSettings=mi(r.imageColorSettings),this.minZoomOverride=cn(r.minZoom),this.maxZoomOverride=cn(r.maxZoom),this.viewTransitionDurationMs=Un(r.viewTransition?.duration),this.viewTransitionEasing=zn(r.viewTransition?.easing);const i=e.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,stencil:!1,powerPreference:"high-performance"});if(!i)throw new Error("WebGL2 not supported");this.gl=i,this.tileProgram=gi(this.gl),this.pointProgram=pi(this.gl),this.tileScheduler=new ji({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)=>Tl({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,u)=>{this.onTileError?.({tile:s,error:a,attemptCount:u}),console.warn("tile load failed",s.url,a)}}),this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(e);const o=Il({canvas:this.canvas,state:this.interactionState,getInteractionLocked:()=>this.interactionLocked,getCtrlDragRotate:()=>this.ctrlDragRotate,getRotationDragSensitivityDegPerPixel:()=>this.rotationDragSensitivityDegPerPixel,cancelViewAnimation:()=>this.cancelViewAnimation(),camera:this.camera,source:this.source,emitViewState:()=>this.onViewStateChange?.(this.camera.getViewState()),requestRender:()=>this.requestRender(),zoomBy:(s,a,u)=>this.zoomBy(s,a,u)});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),Qa(e,this.getCanvasHandlers()),this.fitToImage({duration:0}),this.resize()}getCanvasHandlers(){return{pointerDown:this.boundPointerDown,pointerMove:this.boundPointerMove,pointerUp:this.boundPointerUp,wheel:this.boundWheel,doubleClick:this.boundDoubleClick,contextMenu:this.boundContextMenu,contextLost:this.boundContextLost,contextRestored:this.boundContextRestored}}applyZoomBounds(){const e=Yl(this.fitZoom,this.minZoomOverride,this.maxZoomOverride);this.minZoom=e.minZoom,this.maxZoom=e.maxZoom}resolveTargetViewState(e){return Xl(this.camera,this.minZoom,this.maxZoom,e,()=>Jn(this.camera,this.source))}cancelViewAnimation(){ro(this.viewAnimationState)}startViewAnimation(e,n,r){Dl({state:this.viewAnimationState,camera:this.camera,target:e,durationMs:n,easing:r,onUpdate:()=>{Jn(this.camera,this.source),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}})}getPointBufferRuntime(){return{pointCount:this.pointCount,usePointIndices:this.usePointIndices,pointBuffersDirty:this.pointBuffersDirty,lastPointData:this.lastPointData,zeroFillModes:this.zeroFillModes,lastPointPalette:this.lastPointPalette,pointPaletteSize:this.pointPaletteSize}}applyPointBufferRuntime(e){this.pointCount=e.pointCount,this.usePointIndices=e.usePointIndices,this.pointBuffersDirty=e.pointBuffersDirty,this.lastPointData=e.lastPointData,this.zeroFillModes=e.zeroFillModes,this.lastPointPalette=e.lastPointPalette,this.pointPaletteSize=e.pointPaletteSize}applyViewStateAndRender(e,n=!0){n&&this.cancelViewAnimation(),this.camera.setViewState(e),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}setAuthToken(e){this.authToken=String(e??""),this.tileScheduler.setAuthToken(this.authToken)}setZoomRange(e,n){const r=cn(e),i=cn(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(e){this.viewTransitionDurationMs=Un(e?.duration),this.viewTransitionEasing=zn(e?.easing)}setViewState(e,n){const r=this.resolveTargetViewState(e),i=this.camera.getViewState();if(Gn(i,r))return;const o=Un(n?.duration??this.viewTransitionDurationMs),s=zn(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(e){const n=Bl(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,e);this.applyPointBufferRuntime(n),!(!e||e.length===0)&&this.requestRender()}setPointData(e){const n=Ul(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,e);this.applyPointBufferRuntime(n),this.requestRender()}setInteractionLock(e){const n=!!e;this.interactionLocked!==n&&(this.interactionLocked=n,n&&this.cancelDrag())}setPointSizeByZoom(e){const n=fi(e);ul(this.pointSizeStops,n)||(this.pointSizeStops=n,this.requestRender())}setPointStrokeScale(e){const n=hi(e);this.pointStrokeScale!==n&&(this.pointStrokeScale=n,this.requestRender())}setPointInnerFillOpacity(e){const n=di(e);this.pointInnerFillOpacity!==n&&(this.pointInnerFillOpacity=n,this.requestRender())}setImageColorSettings(e){const n=mi(e),r=this.imageColorSettings;r.brightness===n.brightness&&r.contrast===n.contrast&&r.saturation===n.saturation||(this.imageColorSettings=n,this.requestRender())}cancelDrag(){Cl(this.canvas,this.interactionState)}screenToWorld(e,n){const r=this.canvas.getBoundingClientRect(),i=e-r.left,o=n-r.top;return this.camera.screenToWorld(i,o)}worldToScreen(e,n){return this.camera.worldToScreen(e,n)}setViewCenter(e,n,r){if(!Number.isFinite(e)||!Number.isFinite(n))return;const i=this.camera.getViewState(),o=Math.max(1e-6,i.zoom),s=this.camera.getViewportSize();this.setViewState({offsetX:e-s.width/(2*o),offsetY:n-s.height/(2*o)},r)}getViewCorners(){return this.camera.getViewCorners()}resetRotation(e){const n=this.camera.getViewState();Math.abs(n.rotationDeg)<1e-6||this.setViewState({rotationDeg:0},e)}getPointSizeByZoom(){const e=Math.max(1e-6,this.camera.getViewState().zoom),n=this.source.maxTierZoom+Math.log2(e),r=cl(n,this.pointSizeStops);return D(r,Kn,el)}fitToImage(e){const n=this.canvas.getBoundingClientRect(),r=Math.max(1,n.width||1),i=Math.max(1,n.height||1),o=Wl(this.source,r,i,this.minZoom,this.maxZoom);this.fitZoom=o.fitZoom,this.applyZoomBounds(),this.setViewState(o.target,e)}zoomBy(e,n,r,i){const o=Vl(this.camera,this.minZoom,this.maxZoom,e,n,r);o&&this.setViewState(o,i)}render(){if(this.destroyed||this.contextLost||this.gl.isContextLost())return;const e=this.onStats?mt():0;this.frameSerial+=1;const n=zl({gl:this.gl,camera:this.camera,source:this.source,cache:this.cache,frameSerial:this.frameSerial,tileProgram:this.tileProgram,pointProgram:this.pointProgram,imageColorSettings:this.imageColorSettings,pointCount:this.pointCount,usePointIndices:this.usePointIndices,pointPaletteSize:this.pointPaletteSize,pointStrokeScale:this.pointStrokeScale,pointInnerFillOpacity:this.pointInnerFillOpacity,pointSizePx:this.getPointSizeByZoom()*Math.max(1,window.devicePixelRatio||1),tileScheduler:this.tileScheduler,getVisibleTiles:()=>xl(this.camera,this.source),getVisibleTilesForTier:r=>no(this.camera,this.source,r),getViewBounds:()=>lr(this.camera),intersectsBounds:bl});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:mt()-e})}}requestRender(){this.frame!==null||this.destroyed||this.contextLost||this.gl.isContextLost()||(this.frame=requestAnimationFrame(()=>{this.frame=null,this.render()}))}resize(){tl(this.canvas,this.gl,this.camera),this.requestRender()}onWebGlContextLost(e){const n=Fl({event:e,destroyed:this.destroyed,contextLost:this.contextLost,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,cache:this.cache,onContextLost:this.onContextLost});n.handled&&(this.frame=n.frame,this.contextLost=!0,this.pointBuffersDirty=!0)}onWebGlContextRestored(e){this.destroyed||(this.contextLost=!1,this.cache.clear(),this.tileProgram=gi(this.gl),this.pointProgram=pi(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 e=Nl({destroyed:this.destroyed,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),resizeObserver:this.resizeObserver,removeCanvasEventListeners:()=>Ja(this.canvas,this.getCanvasHandlers()),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,contextLost:this.contextLost,gl:this.gl,cache:this.cache,tileProgram:this.tileProgram,pointProgram:this.pointProgram});e.didDestroy&&(this.destroyed=!0,this.frame=e.frame)}}const Gl=6;function tr(t,e){return t.id??e}function ql(t,e,n,r,i,o){const s=i-n,a=o-r,u=s*s+a*a;if(u<=1e-12){const m=t-n,p=e-r;return m*m+p*p}const c=D(((t-n)*s+(e-r)*a)/u,0,1),f=n+s*c,l=r+a*c,h=t-f,d=e-l;return h*h+d*d}function yi(t,e,n,r){for(let i=1;i<n.length;i+=1){const o=n[i-1],s=n[i];if(ql(t,e,o[0],o[1],s[0],s[1])<=r)return!0}return!1}function Hl(t,e,n,r){if(t<n.minX-r||t>n.maxX+r||e<n.minY-r||e>n.maxY+r)return!1;const i=r*r;if(yi(t,e,n.outer,i))return!0;for(const o of n.holes)if(yi(t,e,o,i))return!0;return!1}function $l(t,e,n,r,i,o,s){if(!t.label||!t.labelAnchor)return!1;const a=wn(n.worldToScreen(t.labelAnchor[0],t.labelAnchor[1]));if(!a)return!1;const c=or(t.label,r)+r.paddingX*2,f=r.fontSize+r.paddingY*2,l=a[0],h=a[1]-r.offsetY,d=s?D(l,c*.5+1,i-c*.5-1):l,m=s?D(h,f*.5+1,o-f*.5-1):h,p=d-c*.5,x=d+c*.5,w=m-f*.5,M=m+f*.5;return e[0]>=p&&e[0]<=x&&e[1]>=w&&e[1]<=M}function Zl(t,e="top-center"){const n=[];for(let r=0;r<t.length;r+=1){const i=t[r],o=Ye([Oe(i?.coordinates)]);if(o.length===0)continue;const s=typeof i?.label=="string"?i.label.trim():"";n.push({region:i,regionIndex:r,regionId:tr(i,r),polygons:o,label:s,labelAnchor:s?Bi(o,e):null})}return n}function Kl(t,e,n,r,i,o,s,a,u,c=!0){const f=t[0],l=t[1],h=Math.max(1e-6,r.getViewState().zoom),d=Math.max(0,s),m=Gl/h;for(let p=n.length-1;p>=0;p-=1){const x=n[p];for(const M of x.polygons)if(Hl(f,l,M,m))return{region:x.region,regionIndex:x.regionIndex,regionId:x.regionId};let w=Ui(i,o?.({region:x.region,regionId:x.regionId,regionIndex:x.regionIndex,zoom:h}));if(d>0&&(w={...w,offsetY:w.offsetY+d}),!!$l(x,e,r,w,a,u,c))return{region:x.region,regionIndex:x.regionIndex,regionId:x.regionId}}return null}const Dn=[],jl=[],Ql={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)},Jl=.65,tu=4,eu=180,bi=20;function nu(t){const e=D(t,0,1);return e*e*(3-2*e)}function ru({source:t,viewState:e,imageColorSettings:n=null,onViewStateChange:r,onStats:i,onTileError:o,onContextLost:s,onContextRestored:a,debugOverlay:u=!1,debugOverlayStyle:c,fitNonce:f=0,rotationResetNonce:l=0,authToken:h="",ctrlDragRotate:d=!0,pointData:m=null,pointPalette:p=null,pointSizeByZoom:x,pointStrokeScale:w,pointInnerFillOpacity:M,minZoom:N,maxZoom:A,viewTransition:C,roiRegions:U,roiPolygons:H,clipPointsToRois:O=!1,clipMode:$="worker",onClipStats:Z,onRoiPointGroups:Q,roiPaletteIndexToTermId:rt,interactionLock:_=!1,drawTool:k="cursor",stampOptions:Y,brushOptions:B,drawFillColor:nt,regionStrokeStyle:zt,regionStrokeHoverStyle:ft,regionStrokeActiveStyle:Vt,patchStrokeStyle:Bt,resolveRegionStrokeStyle:Gt,resolveRegionLabelStyle:v,overlayShapes:R,customLayers:W,patchRegions:ut,regionLabelStyle:J,regionLabelAnchor:ht="top-center",drawAreaTooltip:gt,autoLiftRegionLabelAtMaxZoom:wt=!1,clampRegionLabelToViewport:it=!0,onPointerWorldMove:pt,onPointHover:st,onPointClick:ot,onRegionHover:et,onRegionClick:Mt,activeRegionId:K,onActiveRegionChange:St,getCellByCoordinatesRef:bt,onDrawComplete:Et,onPatchComplete:Dt,overviewMapConfig:At,className:_t,style:It}){const ye=At?.show??!1,be=At?.options,G=g.useRef(null),q=g.useRef(null),at=g.useRef(null),xt=g.useRef(null),Ie=g.useRef(r),Pe=g.useRef(i),le=g.useRef(o),Xe=g.useRef(s),We=g.useRef(a),ve=g.useRef(u),[Ve,y]=g.useState(null),[S,I]=g.useState(()=>K??null),P=K!==void 0,L=P?K??null:S,[dt,j]=g.useState(null),[V,lt]=g.useState(null),[ct,Rt]=g.useState(0),yt=g.useRef(null),Pt=g.useRef(null),$t=g.useRef(null),jt=g.useRef(0),ue=g.useRef({rafId:null,startMs:0,from:0,to:0}),Ge=g.useRef(0),ce=U??Dn,so=ut??Dn,En=H??jl,qe=(W?.length??0)>0,ao=g.useMemo(()=>({position:"relative",width:"100%",height:"100%",...It}),[It]),lo=g.useMemo(()=>({position:"absolute",top:8,left:8,zIndex:7,margin:0,padding:"8px 10px",maxWidth:"min(420px, 80%)",pointerEvents:"none",whiteSpace:"pre-wrap",lineHeight:1.35,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:11,color:"#cde6ff",background:"rgba(6, 12, 20, 0.82)",border:"1px solid rgba(173, 216, 255, 0.28)",borderRadius:8,boxShadow:"0 8px 22px rgba(0,0,0,0.35)",...c}),[c]),qt=g.useMemo(()=>ce.length>0?ce:En.length===0?Dn:En.map((b,T)=>({id:T,coordinates:b})),[ce,En]),Qt=g.useMemo(()=>Zl(qt,ht),[qt,ht]),ur=g.useMemo(()=>sr(J),[J]),xe=g.useCallback(b=>{const T=D(b,0,bi);Math.abs(jt.current-T)<1e-4||(jt.current=T,Rt(T))},[]),fe=g.useCallback(()=>{const b=ue.current;b.rafId!==null&&(cancelAnimationFrame(b.rafId),b.rafId=null)},[]),Mn=g.useCallback(b=>{const T=D(b,0,bi),F=ue.current,z=jt.current;if(Math.abs(z-T)<1e-4){fe(),F.to=T,xe(T);return}fe(),F.startMs=performance.now(),F.from=z,F.to=T;const X=tt=>{const Ft=ue.current,Ot=Math.max(0,tt-Ft.startMs),Ee=D(Ot/eu,0,1),An=nu(Ee),Rn=Ft.from+(Ft.to-Ft.from)*An;if(xe(Rn),at.current?.(),Ee>=1){Ft.rafId=null,xe(Ft.to);return}Ft.rafId=requestAnimationFrame(X)};F.rafId=requestAnimationFrame(X)},[xe,fe]),Jt=g.useCallback(b=>{const T=q.current;if(!T||typeof b!="number"||!Number.isFinite(b)){Mn(0);return}const F=zi(wt,b,T.getZoomRange());Mn(F)},[wt,Mn]),he=g.useMemo(()=>qt.map(b=>Oe(b.coordinates)).filter(b=>b!=null),[qt]),[de,He]=g.useState(m);g.useEffect(()=>{const b=++Ge.current;let T=!1;if(!O)return He(m),()=>{T=!0};if(!m||!m.count||!m.positions||!m.paletteIndices)return He(null),()=>{T=!0};if(he.length===0)return He(Ql),Z?.({mode:$,durationMs:0,inputCount:m.count,outputCount:0,polygonCount:0}),()=>{T=!0};const F=(X,tt)=>{if(T||b!==Ge.current)return;const Ft=m.count,Ot=X?.drawIndices?X.drawIndices.length:X?.count??0;He(X),Z?.({mode:tt.mode,durationMs:tt.durationMs,inputCount:Ft,outputCount:Ot,polygonCount:he.length,usedWebGpu:tt.usedWebGpu,candidateCount:tt.candidateCount,bridgedToDraw:tt.bridgedToDraw})};return(async()=>{if($==="sync"){const X=performance.now(),tt=Ue(m,he);F(tt,{mode:"sync",durationMs:performance.now()-X});return}if($==="hybrid-webgpu"){const X=await Gi(m,he,{bridgeToDraw:!0});F(X.data,{mode:X.meta.mode,durationMs:X.meta.durationMs,usedWebGpu:X.meta.usedWebGpu,candidateCount:X.meta.candidateCount,bridgedToDraw:X.meta.bridgedToDraw});return}try{const X=await Hi(m,he);F(X.data,{mode:X.meta.mode,durationMs:X.meta.durationMs})}catch{const X=performance.now(),tt=Ue(m,he);F(tt,{mode:"sync",durationMs:performance.now()-X})}})(),()=>{T=!0}},[O,$,m,he,Z]);const cr=!!(st||ot||bt),[Zt,fr]=g.useState(null);g.useEffect(()=>{if(!cr||!de){fr(null);return}let b=!1;return Zi(de,t).then(T=>{b||fr(T)}),()=>{b=!0}},[cr,de,t]);const me=g.useCallback(b=>{const T=q.current;if(!T||!Zt)return null;const F=Number(b[0]),z=Number(b[1]);if(!Number.isFinite(F)||!Number.isFinite(z))return null;const X=Math.max(1e-6,T.getViewState().zoom),tt=T.getPointSizeByZoom(),Ot=Math.max(tu,tt*Jl)/X;if(!Number.isFinite(Ot)||Ot<=0)return null;const{cellSize:Ee,cellOffsets:An,cellLengths:Rn,pointIndices:po,positions:br,safeCount:yo}=Zt,xr=Math.floor(F/Ee),wr=Math.floor(z/Ee),Ke=Math.max(1,Math.ceil(Ot/Ee)),bo=Ot*Ot;let je=-1,Sr=bo,Er=0,Mr=0;for(let Cn=xr-Ke;Cn<=xr+Ke;Cn+=1)for(let In=wr-Ke;In<=wr+Ke;In+=1){const Pn=$i(Zt,Cn,In);if(Pn<0)continue;const Ar=An[Pn],wo=Ar+Rn[Pn];for(let vn=Ar;vn<wo;vn+=1){const Qe=po[vn];if(Qe>=yo)continue;const Rr=br[Qe*2],Cr=br[Qe*2+1],Ir=Rr-F,Pr=Cr-z,vr=Ir*Ir+Pr*Pr;vr>Sr||(Sr=vr,je=Qe,Er=Rr,Mr=Cr)}}if(je<0)return null;const xo=Zt.ids?Number(Zt.ids[je]):null;return{index:je,id:xo,coordinate:[F,z],pointCoordinate:[Er,Mr]}},[Zt]),we=g.useCallback((b,T)=>{if(!st)return;const F=b?.index??null,z=b?.id??null;Pt.current===F&&$t.current===z||(Pt.current=F,$t.current=z,st({index:F,id:z,coordinate:T,pointCoordinate:b?.pointCoordinate??null}))},[st]),$e=g.useCallback((b,T)=>{if(!ot)return;const F=me(b);F&&ot({...F,button:T})},[ot,me]);g.useEffect(()=>{if(bt)return bt.current=me,()=>{bt.current===me&&(bt.current=null)}},[bt,me]),g.useEffect(()=>{P&&I(K??null)},[P,K]);const te=g.useCallback(b=>{String(L)!==String(b)&&(P||I(b),St?.(b))},[L,P,St]);g.useEffect(()=>{Ie.current=r},[r]),g.useEffect(()=>{Pe.current=i},[i]),g.useEffect(()=>{le.current=o},[o]),g.useEffect(()=>{Xe.current=s},[s]),g.useEffect(()=>{We.current=a},[a]),g.useEffect(()=>{ve.current=u,u||lt(null)},[u]),g.useEffect(()=>()=>{fe()},[fe]);const hr=g.useCallback(b=>{Pe.current?.(b),ve.current&<(b)},[]),uo=g.useMemo(()=>V?[`tier ${V.tier} | frame ${V.frameMs?.toFixed(2)??"-"} ms | drawCalls ${V.drawCalls??"-"}`,`tiles visible ${V.visible} | rendered ${V.rendered} | fallback ${V.fallback}`,`cache size ${V.cache} | hit ${V.cacheHits??"-"} | miss ${V.cacheMisses??"-"}`,`queue inflight ${V.inflight} | queued ${V.queued??"-"} | retries ${V.retries??"-"} | failed ${V.failed??"-"} | aborted ${V.aborted??"-"}`,`points ${V.points}`].join(`
|
|
163
|
+
`):"stats: waiting for first frame...",[V]);g.useEffect(()=>{!(L===null?!0:qt.some((z,X)=>String(tr(z,X))===String(L)))&&L!==null&&te(null);const T=yt.current;!(T===null?!0:qt.some((z,X)=>String(tr(z,X))===String(T)))&&T!==null&&(yt.current=null,y(null),et?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[qt,L,et,te]),g.useEffect(()=>{const b=Pt.current;b!==null&&(Zt&&b<Zt.safeCount||(Pt.current=null,$t.current=null,st?.({index:null,id:null,coordinate:null,pointCoordinate:null})))},[Zt,st]);const dr=g.useCallback(b=>{Jt(b.zoom),qe&&j(b);const T=Ie.current;T&&T(b),at.current?.(),xt.current?.()},[qe,Jt]);g.useEffect(()=>{const b=q.current;b&&Jt(b.getViewState().zoom)},[Jt,N,A]),g.useEffect(()=>{k!=="cursor"&&yt.current!==null&&(yt.current=null,y(null),et?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[k,et]),g.useEffect(()=>{k!=="cursor"&&Pt.current!==null&&(Pt.current=null,$t.current=null,st?.({index:null,id:null,coordinate:null,pointCoordinate:null}))},[k,st]);const ee=g.useCallback((b,T)=>{const F=q.current;if(!F)return null;const z=F.screenToWorld(b,T);if(!Array.isArray(z)||z.length<2)return null;const X=Number(z[0]),tt=Number(z[1]);return!Number.isFinite(X)||!Number.isFinite(tt)?null:[X,tt]},[]),mr=g.useCallback((b,T)=>{const F=q.current;if(!F)return null;const z=F.worldToScreen(b,T);return wn(z)},[]),Ze=g.useCallback((b,T)=>{const F=G.current;if(!F)return null;const z=F.getBoundingClientRect();if(!Number.isFinite(z.width)||!Number.isFinite(z.height)||z.width<=0||z.height<=0)return null;const X=b-z.left,tt=T-z.top;return!Number.isFinite(X)||!Number.isFinite(tt)?null:{screenCoord:[X,tt],canvasWidth:Math.max(1,z.width),canvasHeight:Math.max(1,z.height)}},[]),Se=g.useCallback((b,T,F,z)=>{const X=q.current;return X?Kl(b,T,Qt,X,ur,v,ct,F,z,it):null},[Qt,ur,v,ct,it]),gr=g.useCallback(()=>{q.current?.requestRender(),at.current?.(),xt.current?.()},[]),pr=g.useMemo(()=>dt??q.current?.getViewState()??null,[dt]),yr=g.useMemo(()=>{if(!t)return null;const b=pr;return b?{source:t,viewState:b,drawTool:k,interactionLock:_,worldToScreen:mr,screenToWorld:ee,requestRedraw:gr}:null},[t,pr,k,_,mr,ee,gr]),co=g.useCallback(b=>{const T=b.target===G.current,F=ee(b.clientX,b.clientY);if(pt){const Ot=!!F&&F[0]>=0&&F[1]>=0&&!!t&&F[0]<=t.width&&F[1]<=t.height;pt({coordinate:F,clientX:b.clientX,clientY:b.clientY,insideImage:Ot})}if(k!=="cursor")return;if(!T){we(null,null),yt.current!==null&&(yt.current=null,y(null),et?.({region:null,regionId:null,regionIndex:-1,coordinate:null}));return}if(!F){we(null,null);return}if(st&&we(me(F),F),!Qt.length)return;const z=Ze(b.clientX,b.clientY);if(!z)return;const X=Se(F,z.screenCoord,z.canvasWidth,z.canvasHeight),tt=X?.regionId??null,Ft=yt.current;String(Ft)!==String(tt)&&(yt.current=tt,y(tt),et?.({region:X?.region??null,regionId:tt,regionIndex:X?.regionIndex??-1,coordinate:F}))},[k,Qt,ee,et,pt,t,we,me,st,Ze,Se]),fo=g.useCallback(()=>{pt?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1}),we(null,null),yt.current!==null&&(yt.current=null,y(null),et?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[et,pt,we]),ho=g.useCallback(b=>{if(k!=="cursor"||b.target!==G.current)return;const T=ee(b.clientX,b.clientY);if(!T)return;if($e(T,b.button),!Qt.length){te(null);return}const F=Ze(b.clientX,b.clientY);if(!F)return;const z=Se(T,F.screenCoord,F.canvasWidth,F.canvasHeight);if(!z){te(null);return}const X=L!==null&&String(L)===String(z.regionId)?null:z.regionId;te(X),Mt?.({region:z.region,regionId:z.regionId,regionIndex:z.regionIndex,coordinate:T})},[k,Qt,ee,Mt,L,te,$e,Ze,Se]),mo=g.useCallback(b=>{if(k!=="brush"||B?.clickSelectRoi!==!0||!Qt.length)return!1;const T=q.current,F=G.current;if(!T||!F)return!1;const z=F.getBoundingClientRect();if(z.width<=0||z.height<=0)return!1;const X=wn(T.worldToScreen(b[0],b[1]));if(!X)return!1;const tt=Se(b,X,z.width,z.height);if(!tt)return!1;const Ft=L!==null&&String(L)===String(tt.regionId)?null:tt.regionId;return te(Ft),Mt?.({region:tt.region,regionId:tt.regionId,regionIndex:tt.regionIndex,coordinate:b}),!0},[k,B?.clickSelectRoi,Qt,L,te,Mt,Se]),go=g.useCallback(b=>{if(!ot||k!=="cursor"||b.target!==G.current)return;b.preventDefault();const T=ee(b.clientX,b.clientY);T&&$e(T,b.button)},[k,ee,$e,ot]);return g.useEffect(()=>{const b=G.current;if(!b||!t)return;const T=new io(b,t,{onViewStateChange:dr,onStats:hr,onTileError:F=>{le.current?.(F)},onContextLost:()=>{Xe.current?.()},onContextRestored:()=>{We.current?.()},authToken:h,imageColorSettings:n,ctrlDragRotate:d,pointSizeByZoom:x,pointStrokeScale:w,pointInnerFillOpacity:M,minZoom:N,maxZoom:A,viewTransition:C});return q.current=T,e&&T.setViewState(e),Jt(T.getViewState().zoom),T.setInteractionLock(_),qe&&j(T.getViewState()),()=>{fe(),xe(0),T.destroy(),q.current=null}},[t,hr,h,d,dr,qe,Jt,fe,xe]),g.useEffect(()=>{const b=q.current;!b||!e||b.setViewState(e)},[e]),g.useEffect(()=>{const b=q.current;b&&b.fitToImage()},[f]),g.useEffect(()=>{const b=q.current;b&&b.resetRotation()},[l]),g.useEffect(()=>{const b=q.current;!b||!p||b.setPointPalette(p)},[p]),g.useEffect(()=>{const b=q.current;b&&b.setPointSizeByZoom(x)},[x]),g.useEffect(()=>{const b=q.current;b&&b.setPointStrokeScale(w)},[w]),g.useEffect(()=>{const b=q.current;b&&b.setPointInnerFillOpacity(M)},[M]),g.useEffect(()=>{const b=q.current;b&&(b.setZoomRange(N,A),Jt(b.getViewState().zoom))},[N,A,Jt]),g.useEffect(()=>{const b=q.current;b&&b.setViewTransition(C)},[C]),g.useEffect(()=>{const b=q.current;b&&b.setImageColorSettings(n)},[n]),g.useEffect(()=>{const b=q.current;b&&b.setPointData(de)},[de]),g.useEffect(()=>{if(!Q)return;const T=Ki(O?de:m,qt,{paletteIndexToTermId:rt,includeEmptyRegions:!0});Q(T)},[Q,O,m,de,qt,rt]),g.useEffect(()=>{const b=q.current;b&&b.setInteractionLock(_)},[_]),Xt.jsxs("div",{className:_t,style:ao,onPointerMove:co,onPointerLeave:fo,onClick:ho,onContextMenu:go,children:[Xt.jsx("canvas",{ref:G,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none",cursor:k==="cursor"&&Ve!==null?"pointer":_?"crosshair":"grab"}}),t&&yr&&Array.isArray(W)&&W.length>0?W.map((b,T)=>Xt.jsx("div",{className:b.className,style:{position:"absolute",inset:0,zIndex:b.zIndex??3,pointerEvents:b.pointerEvents??"none",...b.style},children:b.render(yr)},b.id??T)):null,t?Xt.jsx(Di,{tool:k,enabled:k!=="cursor",imageWidth:t.width,imageHeight:t.height,imageMpp:t.mpp,imageZoom:t.maxTierZoom,stampOptions:Y,brushOptions:B,drawFillColor:nt,projectorRef:q,onBrushTap:mo,viewStateSignal:e,persistedRegions:qt,patchRegions:so,regionStrokeStyle:zt,regionStrokeHoverStyle:ft,regionStrokeActiveStyle:Vt,patchStrokeStyle:Bt,resolveRegionStrokeStyle:Gt,resolveRegionLabelStyle:v,overlayShapes:R,hoveredRegionId:Ve,activeRegionId:L,regionLabelStyle:J,regionLabelAnchor:ht,drawAreaTooltip:gt,autoLiftRegionLabelAtMaxZoom:wt,clampRegionLabelToViewport:it,regionLabelAutoLiftOffsetPx:ct,invalidateRef:at,onDrawComplete:Et,onPatchComplete:Dt}):null,u?Xt.jsx("pre",{"data-open-plant-debug-overlay":!0,style:lo,children:uo}):null,t&&ye&&Xt.jsx(Yi,{source:t,projectorRef:q,authToken:h,options:be,invalidateRef:xt,className:At?.className,style:At?.style})]})}function xi(t,e,n,r){return[Math.min(t,n),Math.min(e,r),Math.max(t,n),Math.max(e,r)]}function wi(t,e){return!(t[2]<e[0]||t[0]>e[2]||t[3]<e[1]||t[1]>e[3])}class iu{constructor(e=16){E(this,"targetNodeSize");E(this,"items",[]);E(this,"globalBounds",[0,0,0,0]);E(this,"gridSize",1);E(this,"cellWidth",1);E(this,"cellHeight",1);E(this,"buckets",[]);E(this,"visited",new Uint32Array(0));E(this,"querySerial",1);const n=Number.isFinite(e)?Math.floor(e):16;this.targetNodeSize=Math.max(1,n)}load(e){if(!Array.isArray(e)||e.length===0){this.items=[],this.globalBounds=[0,0,0,0],this.gridSize=1,this.cellWidth=1,this.cellHeight=1,this.buckets=[],this.visited=new Uint32Array(0),this.querySerial=1;return}const n=[];let r=1/0,i=1/0,o=-1/0,s=-1/0;for(const f of e){if(!f||!Number.isFinite(f.minX)||!Number.isFinite(f.minY)||!Number.isFinite(f.maxX)||!Number.isFinite(f.maxY))continue;const l=xi(f.minX,f.minY,f.maxX,f.maxY);r=Math.min(r,l[0]),i=Math.min(i,l[1]),o=Math.max(o,l[2]),s=Math.max(s,l[3]),n.push({minX:l[0],minY:l[1],maxX:l[2],maxY:l[3],value:f.value})}if(this.items=n,this.visited=new Uint32Array(n.length),this.querySerial=1,n.length===0||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(o)||!Number.isFinite(s)){this.globalBounds=[0,0,0,0],this.gridSize=1,this.cellWidth=1,this.cellHeight=1,this.buckets=[];return}this.globalBounds=[r,i,o,s],this.gridSize=Math.max(1,Math.ceil(Math.sqrt(n.length/this.targetNodeSize)));const a=Math.max(0,o-r),u=Math.max(0,s-i);this.cellWidth=a>0?a/this.gridSize:1,this.cellHeight=u>0?u/this.gridSize:1;const c=this.gridSize*this.gridSize;this.buckets=Array.from({length:c},()=>[]);for(let f=0;f<n.length;f+=1){const l=n[f],h=this.toCellX(l.minX),d=this.toCellX(l.maxX),m=this.toCellY(l.minY),p=this.toCellY(l.maxY);for(let x=m;x<=p;x+=1)for(let w=h;w<=d;w+=1)this.buckets[x*this.gridSize+w].push(f)}}search(e){if(this.items.length===0)return[];if(!Array.isArray(e)||e.length<4)return[];const n=xi(e[0],e[1],e[2],e[3]);if(!wi(n,this.globalBounds))return[];const r=this.toCellX(n[0]),i=this.toCellX(n[2]),o=this.toCellY(n[1]),s=this.toCellY(n[3]),a=this.nextSerial(),u=[];for(let c=o;c<=s;c+=1)for(let f=r;f<=i;f+=1){const l=this.buckets[c*this.gridSize+f];if(!(!l||l.length===0))for(const h of l){if(this.visited[h]===a)continue;this.visited[h]=a;const d=this.items[h];wi(n,[d.minX,d.minY,d.maxX,d.maxY])&&u.push(d)}}return u}nextSerial(){return this.querySerial+=1,this.querySerial===4294967295&&(this.visited.fill(0),this.querySerial=1),this.querySerial}toCellX(e){const n=this.globalBounds[0],r=this.globalBounds[2];if(this.gridSize<=1||r<=n)return 0;const i=(e-n)/this.cellWidth;return!Number.isFinite(i)||i<=0?0:i>=this.gridSize-1?this.gridSize-1:Math.max(0,Math.min(this.gridSize-1,Math.floor(i)))}toCellY(e){const n=this.globalBounds[1],r=this.globalBounds[3];if(this.gridSize<=1||r<=n)return 0;const i=(e-n)/this.cellHeight;return!Number.isFinite(i)||i<=0?0:i>=this.gridSize-1?this.gridSize-1:Math.max(0,Math.min(this.gridSize-1,Math.floor(i)))}}function ou(t){return new iu(t)}function su(t){return t.replace(/^\s*SRID\s*=\s*\d+\s*;\s*/i,"")}function au(t){return t>="A"&&t<="Z"||t>="a"&&t<="z"}function lu(t){return t>="0"&&t<="9"}function Si(t){return t==="+"||t==="-"||t==="."||lu(t)}class uu{constructor(e){E(this,"text");E(this,"index",0);this.text=su(e.trim())}parse(){if(!this.text)return null;const e=this.readWord();if(!e)return null;const n=e.toUpperCase();if(n!=="POLYGON"&&n!=="MULTIPOLYGON")return null;this.skipWhitespace();const r=this.peekWord();if(r){const s=r.toUpperCase();(s==="Z"||s==="M"||s==="ZM")&&(this.readWord(),this.skipWhitespace())}if(this.consumeWordIf("EMPTY"))return this.skipWhitespace(),this.isEof()?n==="POLYGON"?{type:"Polygon",coordinates:[]}:{type:"MultiPolygon",coordinates:[]}:null;let i;try{i=this.parseNestedList()}catch{return null}if(this.skipWhitespace(),!this.isEof())return null;if(n==="POLYGON"){const s=oo(i);return s?{type:"Polygon",coordinates:s}:null}const o=fu(i);return o?{type:"MultiPolygon",coordinates:o}:null}isEof(){return this.index>=this.text.length}currentChar(){return this.text[this.index]??""}skipWhitespace(){for(;!this.isEof()&&/\s/.test(this.currentChar());)this.index+=1}readWord(){if(this.skipWhitespace(),this.isEof())return null;const e=this.index;for(;!this.isEof()&&au(this.currentChar());)this.index+=1;return this.index===e?null:this.text.slice(e,this.index)}peekWord(){const e=this.index,n=this.readWord();return this.index=e,n}consumeWordIf(e){const n=this.index,r=this.readWord();return!r||r.toUpperCase()!==e.toUpperCase()?(this.index=n,!1):!0}parseNestedList(){if(this.skipWhitespace(),this.currentChar()!=="(")throw new Error("Expected '('");this.index+=1;const e=[];for(;;){this.skipWhitespace(),this.currentChar()==="("?e.push(this.parseNestedList()):e.push(this.parseCoordinateTuple()),this.skipWhitespace();const n=this.currentChar();if(n===","){this.index+=1;continue}if(n===")"){this.index+=1;break}throw new Error("Expected ',' or ')'")}return e}parseCoordinateTuple(){this.skipWhitespace();const e=[];for(;;){this.skipWhitespace();const n=this.currentChar();if(!n||!Si(n))break;const r=this.readNumber();if(r===null)break;e.push(r),this.skipWhitespace();const i=this.currentChar();if(!i||i===","||i===")")break;if(!Si(i))throw new Error("Invalid coordinate")}if(e.length<2)throw new Error("Coordinate requires at least x y");return[e[0],e[1]]}readNumber(){if(this.skipWhitespace(),this.isEof())return null;const n=this.text.slice(this.index).match(/^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/);if(!n)return null;const r=Number(n[0]);return Number.isFinite(r)?(this.index+=n[0].length,r):null}}function cu(t){return Array.isArray(t)&&t.length>=2&&typeof t[0]=="number"&&Number.isFinite(t[0])&&typeof t[1]=="number"&&Number.isFinite(t[1])}function oo(t){if(!Array.isArray(t))return null;const e=[];for(const n of t){if(!Array.isArray(n))return null;const r=[];for(const i of n){if(!cu(i))return null;r.push([i[0],i[1]])}e.push(r)}return e}function fu(t){if(!Array.isArray(t))return null;const e=[];for(const n of t){const r=oo(n);if(!r)return null;e.push(r)}return e}function hu(t){return typeof t!="string"?null:new uu(t).parse()}exports.DEFAULT_POINT_COLOR=rr;exports.DrawLayer=Di;exports.M1TileRenderer=Mi;exports.OverviewMap=Yi;exports.TileScheduler=ji;exports.TileViewerCanvas=Ca;exports.WsiTileRenderer=io;exports.WsiViewerCanvas=ru;exports.buildPointSpatialIndexAsync=Zi;exports.buildTermPalette=rs;exports.calcScaleLength=es;exports.calcScaleResolution=ir;exports.clamp=D;exports.closeRing=kt;exports.computeRoiPointGroups=Ki;exports.createCircle=Hn;exports.createRectangle=Sn;exports.createSpatialIndex=ou;exports.filterPointDataByPolygons=Ue;exports.filterPointDataByPolygonsHybrid=Gi;exports.filterPointDataByPolygonsInWorker=Hi;exports.filterPointIndicesByPolygons=Xi;exports.filterPointIndicesByPolygonsInWorker=Ba;exports.getWebGpuCapabilities=Na;exports.hexToRgba=vi;exports.isSameViewState=Gn;exports.lookupCellIndex=$i;exports.normalizeImageInfo=Aa;exports.parseWkt=hu;exports.prefilterPointsByBoundsWebGpu=Vi;exports.terminatePointHitIndexWorker=Va;exports.terminateRoiClipWorker=La;exports.toBearerToken=ns;exports.toRoiGeometry=Oe;exports.toTileUrl=ar;
|
|
163
164
|
//# sourceMappingURL=index.cjs.map
|