open-plant 1.2.13 → 1.2.15

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 CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var xr=Object.defineProperty;var Ar=(t,e,n)=>e in t?xr(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var M=(t,e,n)=>Ar(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ae=require("react/jsx-runtime"),d=require("react");var Bt=typeof document<"u"?document.currentScript:null;function An(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 Rr(t,e,n){const r=An(t,t.VERTEX_SHADER,e),i=An(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 s=t.getProgramInfoLog(o)??"unknown link error";throw t.deleteProgram(o),new Error(s)}return o}function Lt(t,e,n){const r=t.getUniformLocation(e,n);if(!r)throw new Error(`Failed to get uniform location: ${n}`);return r}function Er(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}let Tr=class{constructor(){M(this,"viewportWidth",1);M(this,"viewportHeight",1);M(this,"viewState",{offsetX:0,offsetY:0,zoom:1})}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))}getViewState(){return{...this.viewState}}getMatrix(){const e=this.viewportWidth/this.viewState.zoom,n=this.viewportHeight/this.viewState.zoom,r=2/e,i=-2/n,o=-1-this.viewState.offsetX*r,a=1-this.viewState.offsetY*i;return new Float32Array([r,0,0,0,i,0,o,a,1])}};const Pr=`#version 300 es
1
+ "use strict";var xr=Object.defineProperty;var Ar=(t,e,n)=>e in t?xr(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var w=(t,e,n)=>Ar(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Be=require("react/jsx-runtime"),d=require("react");var Ut=typeof document<"u"?document.currentScript:null;function Sn(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 Rr(t,e,n){const r=Sn(t,t.VERTEX_SHADER,e),i=Sn(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 Bt(t,e,n){const r=t.getUniformLocation(e,n);if(!r)throw new Error(`Failed to get uniform location: ${n}`);return r}function Tr(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}let Er=class{constructor(){w(this,"viewportWidth",1);w(this,"viewportHeight",1);w(this,"viewState",{offsetX:0,offsetY:0,zoom:1})}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))}getViewState(){return{...this.viewState}}getMatrix(){const e=this.viewportWidth/this.viewState.zoom,n=this.viewportHeight/this.viewState.zoom,r=2/e,i=-2/n,o=-1-this.viewState.offsetX*r,s=1-this.viewState.offsetY*i;return new Float32Array([r,0,0,0,i,0,o,s,1])}};const Pr=`#version 300 es
2
2
  precision highp float;
3
3
 
4
4
  in vec2 aUnit;
@@ -29,7 +29,7 @@ out vec4 outColor;
29
29
  void main() {
30
30
  outColor = texture(uTexture, vUv);
31
31
  }
32
- `;class On{constructor(e){M(this,"canvas");M(this,"gl");M(this,"camera",new Tr);M(this,"imageWidth");M(this,"imageHeight");M(this,"clearColor");M(this,"program");M(this,"vao");M(this,"quadBuffer");M(this,"uCameraLocation");M(this,"uBoundsLocation");M(this,"uTextureLocation");M(this,"resizeObserver");M(this,"tiles",[]);M(this,"frameId",null);M(this,"loadVersion",0);M(this,"destroyed",!1);M(this,"fitted",!1);M(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=Er(this.canvas),this.program=Rr(this.gl,Pr,Cr);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"),a=this.gl.getAttribLocation(this.program,"aUv");if(o<0||a<0)throw new Error("Failed to get attribute locations.");const s=4*Float32Array.BYTES_PER_ELEMENT;this.gl.enableVertexAttribArray(o),this.gl.vertexAttribPointer(o,2,this.gl.FLOAT,!1,s,0),this.gl.enableVertexAttribArray(a),this.gl.vertexAttribPointer(a,2,this.gl.FLOAT,!1,s,2*Float32Array.BYTES_PER_ELEMENT),this.gl.bindVertexArray(null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.uCameraLocation=Lt(this.gl,this.program,"uCamera"),this.uBoundsLocation=Lt(this.gl,this.program,"uBounds"),this.uTextureLocation=Lt(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 a=this.gl.createTexture();if(!a)throw o.close(),new Error("Failed to create tile texture.");return this.gl.bindTexture(this.gl.TEXTURE_2D,a),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:a}}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)),a=Math.max(1,Math.round(r*i));(this.canvas.width!==o||this.canvas.height!==a)&&(this.canvas.width=o,this.canvas.height=a),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,a=(this.imageWidth-i)*.5,s=(this.imageHeight-o)*.5;this.camera.setViewState({zoom:r,offsetX:a,offsetY:s})}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)}}const Ir=.1,vr=4e6,_r=4096,Ur=64,Fr=1,Br=4,Vn=1e-6,Lr=24;function Tt(t,e,n){return Math.max(e,Math.min(n,t))}function Le(t){if(!Array.isArray(t)||t.length<3)return[];const e=t.map(([i,o])=>[i,o]),n=e[0],r=e[e.length-1];return!n||!r?[]:((n[0]!==r[0]||n[1]!==r[1])&&e.push([n[0],n[1]]),e)}function zr(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 Nr(t,e,n){if(e<=Vn||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 Le(r)}function zt(t,e){if(!t.length)return[];let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[s,u]of t)s<n&&(n=s),s>i&&(i=s),u<r&&(r=u),u>o&&(o=u);if(!Number.isFinite(n)||!Number.isFinite(r))return[];const a=Math.max(e,1);return Le([[n-a,r-a],[i+a,r-a],[i+a,o+a],[n-a,o+a]])}function kr(t,e){let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[s,u]of t)s<n&&(n=s),s>i&&(i=s),u<r&&(r=u),u>o&&(o=u);const a=Math.max(e,1);return[n-a,r-a,i+a,o+a]}function Dr(t,e,n){const r=Math.max(Ir,Number(n.minRasterStep)||0),i=Math.max(32768,Math.floor(n.maxRasterPixels||vr)),o=Math.max(256,Math.floor(n.maxRasterSize||_r)),a=Math.max(.001,t[2]-t[0]),s=Math.max(.001,t[3]-t[1]);let u=Math.max(r,Number.EPSILON),c=3,h=Math.ceil(a/u)+c*2+1,b=Math.ceil(s/u)+c*2+1;for(;(h>o||b>o||h*b>i)&&(u*=1.15,h=Math.ceil(a/u)+c*2+1,b=Math.ceil(s/u)+c*2+1,!(u>Math.max(a,s))););return h=Math.max(8,h),b=Math.max(8,b),{minX:t[0],minY:t[1],step:u,padding:c,width:h,height:b}}function Xr(t,e){if(typeof OffscreenCanvas<"u"){const r=new OffscreenCanvas(t,e).getContext("2d",{willReadFrequently:!0});if(r)return r}if(typeof document<"u"){const n=document.createElement("canvas");return n.width=t,n.height=e,n.getContext("2d",{willReadFrequently:!0})}return null}function Wr(t,e){return[(t[0]-e.minX)/e.step+e.padding,(t[1]-e.minY)/e.step+e.padding]}function Yr(t,e,n){const r=Xr(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=e*2/n.step;const i=t.map(s=>Wr(s,n));if(i.length<=1){const s=i[0];if(!s)return new Uint8Array(0);r.beginPath(),r.arc(s[0],s[1],e/n.step,0,Math.PI*2),r.fill()}else{r.beginPath(),r.moveTo(i[0][0],i[0][1]);for(let s=1;s<i.length;s+=1)r.lineTo(i[s][0],i[s][1]);r.stroke()}const o=r.getImageData(0,0,n.width,n.height),a=new Uint8Array(n.width*n.height);for(let s=0;s<a.length;s+=1)a[s]=o.data[s*4+3]>=Lr?1:0;return a}function Or(t,e,n){const r=[],i=e+1,o=(s,u)=>u*i+s,a=(s,u)=>s>=0&&u>=0&&s<e&&u<n&&t[u*e+s]>0;for(let s=0;s<n;s+=1)for(let u=0;u<e;u+=1)a(u,s)&&(a(u,s-1)||r.push({start:o(u,s),end:o(u+1,s),dir:0}),a(u+1,s)||r.push({start:o(u+1,s),end:o(u+1,s+1),dir:1}),a(u,s+1)||r.push({start:o(u+1,s+1),end:o(u,s+1),dir:2}),a(u-1,s)||r.push({start:o(u,s+1),end:o(u,s),dir:3}));return r}function Vr(t,e){const n=(e-t+4)%4;return n===1?0:n===0?1:n===3?2:3}function Gr(t){if(!t.length)return[];const e=new Map;for(let i=0;i<t.length;i+=1){const o=e.get(t[i].start);o?o.push(i):e.set(t[i].start,[i])}const n=new Uint8Array(t.length),r=[];for(let i=0;i<t.length;i+=1){if(n[i])continue;const o=t[i],a=o.start;let s=o.end,u=o.dir;const c=[o.start,o.end];n[i]=1;let h=0;const b=t.length*3;for(;s!==a&&h<b;){const m=e.get(s);if(!m||m.length===0)break;let g=-1,y=1/0;for(const E of m){if(n[E])continue;const _=t[E],X=Vr(u,_.dir);X<y&&(y=X,g=E)}if(g<0)break;n[g]=1;const x=t[g];s=x.end,u=x.dir,c.push(s),h+=1}c.length>=4&&c[0]===c[c.length-1]&&r.push(c)}return r}function qr(t,e,n){const r=e+1,i=[];for(const o of t){const a=o%r,s=Math.floor(o/r);i.push([n.minX+(a-n.padding)*n.step,n.minY+(s-n.padding)*n.step])}return Le(i)}function Hr(t){if(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 $r(t,e=1e-9){const n=Le(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],a=n[i],s=n[i+1],u=(a[0]-o[0])*(s[1]-a[1])-(a[1]-o[1])*(s[0]-a[0]);Math.abs(u)<=e||r.push(a)}return r.push(r[0]),Le(r)}function Zr(t,e,n){const r=n[0]-e[0],i=n[1]-e[1],o=r*r+i*i;if(o<=1e-12){const b=t[0]-e[0],m=t[1]-e[1];return b*b+m*m}const a=Tt(((t[0]-e[0])*r+(t[1]-e[1])*i)/o,0,1),s=e[0]+r*a,u=e[1]+i*a,c=t[0]-s,h=t[1]-u;return c*c+h*h}function Kr(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 a=i.pop();if(!a)break;const[s,u]=a;if(u-s<=1)continue;let c=0,h=-1;for(let b=s+1;b<u;b+=1){const m=Zr(t[b],t[s],t[u]);m>c&&(c=m,h=b)}h>=0&&c>r&&(n[h]=1,i.push([s,h],[h,u]))}const o=[];for(let a=0;a<t.length;a+=1)n[a]&&o.push(t[a]);return o}function jr(t,e){const n=Le(t);if(n.length<5||e<=0)return n;const r=n.slice(0,-1),i=Kr(r,e);return i.length<3?n:Le(i)}function Jr(t,e){let n=Le(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 a=0;a<i.length;a+=1){const s=i[a],u=i[(a+1)%i.length];o.push([s[0]*.75+u[0]*.25,s[1]*.75+u[1]*.25],[s[0]*.25+u[0]*.75,s[1]*.25+u[1]*.75])}n=Le(o)}return n}function nt(t,e){return e?Le(t.map(([n,r])=>[Tt(n,e[0],e[2]),Tt(r,e[1],e[3])])):t}function Qr(t,e){const n=zr(t),r=Math.max(Vn,Number(e.radius)||0);if(n.length===0||!Number.isFinite(r))return[];const i=Math.max(12,Math.floor(e.circleSides||Ur));if(n.length===1)return nt(Nr(n[0],r,i),e.clipBounds);const o=kr(n,r),a=Dr(o,r,e),s=Yr(n,r,a);if(!s.length)return nt(zt(n,r),e.clipBounds);const u=Or(s,a.width,a.height),c=Gr(u);if(!c.length)return nt(zt(n,r),e.clipBounds);let h=[],b=0;for(const x of c){const E=qr(x,a.width,a),_=Math.abs(Hr(E));_<=b||(b=_,h=E)}if(!h.length)return nt(zt(n,r),e.clipBounds);const m=typeof e.simplifyTolerance=="number"&&Number.isFinite(e.simplifyTolerance)?Math.max(0,e.simplifyTolerance):a.step*.2,g=typeof e.smoothingPasses=="number"&&Number.isFinite(e.smoothingPasses)?Math.round(Tt(e.smoothingPasses,0,Br)):Fr,y=jr(Jr($r(h,a.step*.001),g),m);return nt(y,e.clipBounds)}function Rn(t){return typeof t=="number"&&Number.isFinite(t)}function ei(t){return Array.isArray(t)&&t.length>=2&&Rn(t[0])&&Rn(t[1])}function Gn(t){return Array.isArray(t)&&t.length>0&&t.every(e=>ei(e))}function qn(t){return Array.isArray(t)&&t.length>0&&t.every(e=>Gn(e))}function ti(t){return Array.isArray(t)&&t.length>0&&t.every(e=>qn(e))}function ni(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]),a=Number(i[1]);if(!Number.isFinite(o)||!Number.isFinite(a))continue;const s=e[e.length-1];s&&s[0]===o&&s[1]===a||e.push([o,a])}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 Wt(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 Nt(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const o of t){const a=ni(o);a.length>=4&&e.push(a)}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 a=Math.abs(Wt(e[o]));a<=r||(r=a,n=o)}const i=[e[n]];for(let o=0;o<e.length;o+=1)o!==n&&i.push(e[o]);return i}function Hn(t){if(!t)return[];if(Gn(t)){const e=Nt([t]);return e.length>0?[e]:[]}if(qn(t)){const e=Nt(t);return e.length>0?[e]:[]}if(ti(t)){const e=[];for(const n of t){const r=Nt(n);r.length>0&&e.push(r)}return e}return[]}function En(t,e,n){let r=!1;for(let i=0,o=n.length-1;i<n.length;o=i,i+=1){const a=n[i][0],s=n[i][1],u=n[o][0],c=n[o][1];s>e!=c>e&&t<(u-a)*(e-s)/(c-s||Number.EPSILON)+a&&(r=!r)}return r}function ut(t){const e=[];for(const n of t??[]){const r=Hn(n);for(const i of r){const o=i[0];if(!o||o.length<4)continue;let a=1/0,s=1/0,u=-1/0,c=-1/0;for(const[b,m]of o)b<a&&(a=b),b>u&&(u=b),m<s&&(s=m),m>c&&(c=m);if(!Number.isFinite(a)||!Number.isFinite(s)||!Number.isFinite(u)||!Number.isFinite(c))continue;let h=Math.abs(Wt(o));for(let b=1;b<i.length;b+=1)h-=Math.abs(Wt(i[b]));e.push({outer:o,holes:i.slice(1),minX:a,minY:s,maxX:u,maxY:c,area:Math.max(1e-6,h)})}}return e}function jt(t,e,n){if(t<n.minX||t>n.maxX||e<n.minY||e>n.maxY||!En(t,e,n.outer))return!1;for(const r of n.holes)if(En(t,e,r))return!1;return!0}function Pt(t,e,n){for(const r of n)if(jt(t,e,r))return!0;return!1}const Jt=[160,160,160,255];function Q(t,e,n){return Math.max(e,Math.min(n,t))}function Qt(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 ri(t,e,n){let i=100*Qt(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 ii(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 oi(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 $n(t){const n=String(t??"").trim().match(/^#?([0-9a-fA-F]{6})$/);if(!n)return[...Jt];const r=Number.parseInt(n[1],16);return[r>>16&255,r>>8&255,r&255,255]}function si(t){const e=[[...Jt]],n=new Map;for(const i of t??[]){const o=String(i?.termId??"");!o||n.has(o)||(n.set(o,e.length),e.push($n(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}}function Tn(t,e,n){const r=t.createShader(t.VERTEX_SHADER),i=t.createShader(t.FRAGMENT_SHADER);if(!r||!i)throw new Error("Shader allocation failed");if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error(t.getShaderInfoLog(r)||"vertex compile failed");if(t.shaderSource(i,n),t.compileShader(i),!t.getShaderParameter(i,t.COMPILE_STATUS))throw new Error(t.getShaderInfoLog(i)||"fragment compile failed");const o=t.createProgram();if(!o)throw new Error("Program allocation failed");if(t.attachShader(o,r),t.attachShader(o,i),t.linkProgram(o),t.deleteShader(r),t.deleteShader(i),!t.getProgramParameter(o,t.LINK_STATUS))throw new Error(t.getProgramInfoLog(o)||"program link failed");return o}const ai="rgba(255, 77, 79, 0.16)",ui=3,li=2,Zn=96,ci=1,Pn=[],Ct=[],Cn=1e3,Kn=2,jn=2,fi=4096,hi=.2,di=1.12,mi=.89,gi=32,pi="#000000",bi=.1,yi="#FFCF00",wi="#FF0000",Mi=1.5,In=[2,2],Si=1,xi=.25,Ai=4,Ri=1,Ei=0,Ti=4,Pi=.05,Ci=256,vn=1.5,Ve={color:"#ff4d4f",width:2,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},Ii={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},Ie={fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:12,fontWeight:500,textColor:"#ffffff",backgroundColor:"rgba(8, 14, 22, 0.88)",borderColor:"rgba(255, 77, 79, 0.85)",borderWidth:1,paddingX:6,paddingY:4,offsetY:10,borderRadius:3};function ke(t,e,n){return Math.max(e,Math.min(n,t))}function bt(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 ot(t,e){return typeof t!="number"||!Number.isFinite(t)||t<=0?e:t}function vi(t){return{rectangleAreaMm2:ot(t?.rectangleAreaMm2,Kn),circleAreaMm2:ot(t?.circleAreaMm2,jn),rectanglePixelSize:ot(t?.rectanglePixelSize,fi)}}function _i(t,e){return typeof t!="number"||!Number.isFinite(t)?e:ke(t,0,1)}function Ui(t){if(!Array.isArray(t))return In;const e=t.filter(n=>Number.isFinite(n)&&n>=0);return e.length>0?e:In}function Fi(t){return typeof t!="number"||!Number.isFinite(t)?Si:ke(t,xi,Ai)}function Bi(t){return typeof t!="number"||!Number.isFinite(t)?Ri:Math.round(ke(t,Ei,Ti))}function Li(t){const e=ot(t?.radius,gi),n=ot(t?.cursorLineWidth,Mi),r=Fi(t?.edgeDetail),i=Bi(t?.edgeSmoothing);return{radius:e,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:t?.clickSelectRoi===!0,fillColor:t?.fillColor||pi,fillOpacity:_i(t?.fillOpacity,bi),cursorColor:t?.cursorColor||yi,cursorActiveColor:t?.cursorActiveColor||wi,cursorLineWidth:n,cursorLineDash:Ui(t?.cursorLineDash)}}function zi(t){return t*Cn*Cn}function _n(t,e){return!t||!Number.isFinite(e)||e<=0?[]:Be([[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 Ni(t,e,n=Zn){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 Be(r)}function Be(t){if(!Array.isArray(t)||t.length<3)return[];const e=t.map(([i,o])=>[i,o]),n=e[0],r=e[e.length-1];return!n||!r?[]:((n[0]!==r[0]||n[1]!==r[1])&&e.push([n[0],n[1]]),e)}function Yt(t,e){return!t||!e?[]:Be([[t[0],t[1]],[e[0],t[1]],[e[0],e[1]],[t[0],e[1]]])}function Ot(t,e,n=Zn){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 a=[];for(let s=0;s<=n;s+=1){const u=s/n*Math.PI*2;a.push([r+Math.cos(u)*o,i+Math.sin(u)*o])}return Be(a)}function Vt(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 Math.abs(e*.5)}function Un(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,a]of t)o<e&&(e=o),o>r&&(r=o),a<n&&(n=a),a>i&&(i=a);return[e,n,r,i]}function Fn(t){return Array.isArray(t)&&t.length>=4&&Vt(t)>ci}function Gt(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 Ge(t,e,n,r=!1,i=!1){e.length!==0&&(t.beginPath(),Gt(t,e,r),i&&r&&(t.fillStyle=ai,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(Ct),t.shadowColor="rgba(0, 0, 0, 0)",t.shadowBlur=0,t.shadowOffsetX=0,t.shadowOffsetY=0)}function Jn(t){const e=Array.isArray(t?.lineDash)?t.lineDash.filter(a=>Number.isFinite(a)&&a>=0):Ct,n=typeof t?.width=="number"&&Number.isFinite(t.width)?Math.max(0,t.width):Ve.width,r=typeof t?.shadowBlur=="number"&&Number.isFinite(t.shadowBlur)?Math.max(0,t.shadowBlur):Ve.shadowBlur,i=typeof t?.shadowOffsetX=="number"&&Number.isFinite(t.shadowOffsetX)?t.shadowOffsetX:Ve.shadowOffsetX,o=typeof t?.shadowOffsetY=="number"&&Number.isFinite(t.shadowOffsetY)?t.shadowOffsetY:Ve.shadowOffsetY;return{color:t?.color||Ve.color,width:n,lineDash:e.length?e:Ct,lineJoin:t?.lineJoin||Ve.lineJoin,lineCap:t?.lineCap||Ve.lineCap,shadowColor:t?.shadowColor||Ve.shadowColor,shadowBlur:r,shadowOffsetX:i,shadowOffsetY:o}}function rt(t,e){return e?Jn({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 Bn(t,e){return t==null||e===null||e===void 0?!1:String(t)===String(e)}function ki(t){const e=t[0];return Array.isArray(e)&&Array.isArray(e[0])}function Ln(t){return typeof t=="number"&&Number.isFinite(t)}function Di(t){return Array.isArray(t)&&t.length>=2&&Ln(t[0])&&Ln(t[1])}function Xi(t){return Array.isArray(t)&&t.length>=2&&t.every(e=>Di(e))}function Qn(t,e){if(!(!Array.isArray(t)||t.length===0)){if(Xi(t)){e.push(t.map(([n,r])=>[n,r]));return}for(const n of t)Qn(n,e)}}function zn(t,e){const n=[];Qn(t,n);const r=[];for(const i of n){if(i.length<2)continue;const o=e?Be(i):i;o.length>=(e?4:2)&&r.push(o)}return r}function Wi(t,e,n,r){if(!(e.length<4||n.length===0)){t.save(),t.beginPath(),Gt(t,e,!0);for(const i of n)i.length<4||Gt(t,i,!0);t.fillStyle=r,t.fill("evenodd"),t.restore()}}function Yi(t){const e=typeof t?.paddingX=="number"&&Number.isFinite(t.paddingX)?Math.max(0,t.paddingX):Ie.paddingX,n=typeof t?.paddingY=="number"&&Number.isFinite(t.paddingY)?Math.max(0,t.paddingY):Ie.paddingY,r=typeof t?.fontSize=="number"&&Number.isFinite(t.fontSize)?Math.max(8,t.fontSize):Ie.fontSize,i=typeof t?.borderWidth=="number"&&Number.isFinite(t.borderWidth)?Math.max(0,t.borderWidth):Ie.borderWidth,o=typeof t?.offsetY=="number"&&Number.isFinite(t.offsetY)?t.offsetY:Ie.offsetY,a=typeof t?.borderRadius=="number"&&Number.isFinite(t.borderRadius)?Math.max(0,t.borderRadius):Ie.borderRadius;return{fontFamily:t?.fontFamily||Ie.fontFamily,fontSize:r,fontWeight:t?.fontWeight||Ie.fontWeight,textColor:t?.textColor||Ie.textColor,backgroundColor:t?.backgroundColor||Ie.backgroundColor,borderColor:t?.borderColor||Ie.borderColor,borderWidth:i,paddingX:e,paddingY:n,offsetY:o,borderRadius:a}}function Oi(t,e,n,r,i,o){const a=Math.max(0,Math.min(o,r*.5,i*.5));t.beginPath(),t.moveTo(e+a,n),t.lineTo(e+r-a,n),t.quadraticCurveTo(e+r,n,e+r,n+a),t.lineTo(e+r,n+i-a),t.quadraticCurveTo(e+r,n+i,e+r-a,n+i),t.lineTo(e+a,n+i),t.quadraticCurveTo(e,n+i,e,n+i-a),t.lineTo(e,n+a),t.quadraticCurveTo(e,n,e+a,n),t.closePath()}function Vi(t){if(!t.length)return null;let e=1/0;for(const i of t)i[1]<e&&(e=i[1]);if(!Number.isFinite(e))return null;let n=1/0,r=-1/0;for(const i of t)Math.abs(i[1]-e)>.5||(i[0]<n&&(n=i[0]),i[0]>r&&(r=i[0]));return!Number.isFinite(n)||!Number.isFinite(r)?null:[(n+r)*.5,e]}function Gi(t){let e=null;for(const n of t){const r=Vi(n.outer);r&&(!e||r[1]<e[1]||r[1]===e[1]&&r[0]<e[0])&&(e=r)}return e}function Nn(t){const e=Hn(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(([s,u])=>[s,u]),a=[];for(let s=1;s<r.length;s+=1){const u=r[s];!u||u.length<4||a.push(u.map(([c,h])=>[c,h]))}n.push({outer:o,holes:a})}return n}function qi(t,e,n,r,i,o){const a=e.trim();if(!a)return;t.save(),t.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,t.textAlign="center",t.textBaseline="middle";const u=t.measureText(a).width+o.paddingX*2,c=o.fontSize+o.paddingY*2,h=ke(n[0],u*.5+1,r-u*.5-1),b=ke(n[1]-o.offsetY,c*.5+1,i-c*.5-1),m=h-u*.5,g=b-c*.5;t.fillStyle=o.backgroundColor,t.strokeStyle=o.borderColor,t.lineWidth=o.borderWidth,Oi(t,m,g,u,c,o.borderRadius),t.fill(),o.borderWidth>0&&t.stroke(),t.fillStyle=o.textColor,t.fillText(a,h,b+.5),t.restore()}function yt(t,e,n){return[ke(t[0],0,e),ke(t[1],0,n)]}function it(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]}function er({tool:t,imageWidth:e,imageHeight:n,imageMpp:r,imageZoom:i,stampOptions:o,brushOptions:a,projectorRef:s,onBrushTap:u,onDrawComplete:c,onPatchComplete:h,enabled:b,viewStateSignal:m,persistedRegions:g,patchRegions:y,persistedPolygons:x,regionStrokeStyle:E,regionStrokeHoverStyle:_,regionStrokeActiveStyle:X,patchStrokeStyle:F,resolveRegionStrokeStyle:W,overlayShapes:P,hoveredRegionId:z=null,activeRegionId:Z=null,regionLabelStyle:ee,invalidateRef:N,className:ve,style:Te}){const $=d.useRef(null),_e=d.useRef(!1),ze=d.useRef(new Map),Ke=d.useRef(t),be=d.useRef({isDrawing:!1,pointerId:null,start:null,current:null,cursor:null,cursorScreen:null,points:[],screenPoints:[],stampCenter:null}),ne=b??t!=="cursor",T=d.useMemo(()=>g&&g.length>0?g:!x||x.length===0?Pn:x.map((l,f)=>({id:f,coordinates:l})),[g,x]),C=d.useMemo(()=>y??Pn,[y]),I=d.useMemo(()=>{const l=[];for(let f=0;f<T.length;f+=1){const p=T[f],S=Nn(p.coordinates);S.length!==0&&l.push({region:p,regionIndex:f,regionKey:p.id??f,polygons:S})}return l},[T]),Y=d.useMemo(()=>{const l=[];for(let f=0;f<C.length;f+=1){const p=C[f],S=Nn(p.coordinates);S.length!==0&&l.push({region:p,regionIndex:f,regionKey:p.id??f,polygons:S})}return l},[C]),L=d.useMemo(()=>Jn(E),[E]),ie=d.useMemo(()=>rt(L,_),[L,_]),re=d.useMemo(()=>rt(L,X),[L,X]),we=d.useMemo(()=>rt(Ii,F),[F]),fe=d.useMemo(()=>Yi(ee),[ee]),oe=d.useMemo(()=>vi(o),[o]),V=d.useMemo(()=>Li(a),[a]),J=d.useMemo(()=>({position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",touchAction:"none",pointerEvents:ne?"auto":"none",cursor:ne?t==="brush"?"none":"crosshair":"default",...Te}),[ne,t,Te]),K=d.useCallback(()=>{const l=$.current;if(!l)return;const f=l.getBoundingClientRect(),p=Math.max(1,window.devicePixelRatio||1),S=Math.max(1,Math.round(f.width*p)),A=Math.max(1,Math.round(f.height*p));(l.width!==S||l.height!==A)&&(l.width=S,l.height=A)},[]),D=d.useCallback(l=>{const f=s.current;if(!f||l.length===0)return[];const p=new Array(l.length);for(let S=0;S<l.length;S+=1){const A=it(f.worldToScreen(l[S][0],l[S][1]));if(!A)return[];p[S]=A}return p},[s]),ce=d.useCallback(l=>{const f=s.current,p=$.current;if(!f||!p)return null;const S=p.getBoundingClientRect(),A=it(f.screenToWorld(S.left+l[0],S.top+l[1]));return A?yt(A,e,n):null},[s,e,n]),se=d.useCallback(l=>{if(!Number.isFinite(l)||l<=0)return 0;const f=typeof r=="number"&&Number.isFinite(r)&&r>0?r:1,p=typeof i=="number"&&Number.isFinite(i)?i:0,S=s.current?.getViewState?.().zoom,A=typeof S=="number"&&Number.isFinite(S)&&S>0?S:1,B=p+Math.log2(A),O=Math.max(1e-9,Qt(f,p,B));return l/O/A},[r,i,s]),ae=d.useCallback((l,f)=>{if(!f)return[];let p=0;if(l==="stamp-rectangle-4096px"){const B=oe.rectanglePixelSize*.5;return _n(f,B).map(H=>yt(H,e,n))}if(l==="stamp-rectangle"||l==="stamp-rectangle-2mm2"?p=l==="stamp-rectangle-2mm2"?Kn:oe.rectangleAreaMm2:(l==="stamp-circle"||l==="stamp-circle-2mm2"||l==="stamp-circle-hpf-0.2mm2")&&(p=l==="stamp-circle-hpf-0.2mm2"?hi:l==="stamp-circle-2mm2"?jn:oe.circleAreaMm2),!Number.isFinite(p)||p<=0)return[];const S=zi(p);let A=[];if(l==="stamp-rectangle"||l==="stamp-rectangle-2mm2"){const B=se(Math.sqrt(S)*.5);A=_n(f,B)}else if(l==="stamp-circle"||l==="stamp-circle-2mm2"||l==="stamp-circle-hpf-0.2mm2"){const B=se(Math.sqrt(S/Math.PI));A=Ni(f,B)}return A.length?A.map(B=>yt(B,e,n)):[]},[se,e,n,oe]),j=d.useCallback(()=>{const l=be.current;return bt(t)?ae(t,l.stampCenter):t==="brush"?[]:l.isDrawing?t==="freehand"?l.points:t==="rectangle"?Yt(l.start,l.current):t==="circular"?Ot(l.start,l.current):[]:[]},[t,ae]),Ue=d.useCallback(l=>{const f=be.current;if(!f.isDrawing||f.screenPoints.length===0)return;const p=f.screenPoints;if(p.length===0)return;const S=V.radius;if(!(!Number.isFinite(S)||S<=0)){if(l.save(),l.globalAlpha=V.fillOpacity,l.fillStyle=V.fillColor,l.strokeStyle=V.fillColor,l.lineCap="round",l.lineJoin="round",l.lineWidth=S*2,p.length===1)l.beginPath(),l.arc(p[0][0],p[0][1],S,0,Math.PI*2),l.fill();else{l.beginPath(),l.moveTo(p[0][0],p[0][1]);for(let A=1;A<p.length;A+=1)l.lineTo(p[A][0],p[A][1]);l.stroke()}l.restore()}},[V]),Pe=d.useCallback(l=>{const f=be.current,p=f.cursor;if(!p)return;const S=f.cursorScreen??it(s.current?.worldToScreen(p[0],p[1])??[]);if(!S)return;const A=V.radius;!Number.isFinite(A)||A<=0||(l.save(),l.beginPath(),l.arc(S[0],S[1],A,0,Math.PI*2),l.strokeStyle=f.isDrawing?V.cursorActiveColor:V.cursorColor,l.lineWidth=V.cursorLineWidth,l.setLineDash(V.cursorLineDash),l.stroke(),l.setLineDash(Ct),l.restore())},[s,V]),Fe=d.useCallback(()=>{K();const l=$.current;if(!l)return;const f=l.getContext("2d");if(!f)return;const p=Math.max(1,window.devicePixelRatio||1),S=l.width/p,A=l.height/p;if(f.setTransform(1,0,0,1,0,0),f.clearRect(0,0,l.width,l.height),f.setTransform(p,0,0,p,0,0),I.length>0)for(const B of I){const{region:O,polygons:H,regionIndex:G,regionKey:he}=B,Xe=Bn(Z,he)?"active":Bn(z,he)?"hover":"default";let de=Xe==="active"?re:Xe==="hover"?ie:L;if(W){const te=W({region:O,regionId:he,regionIndex:G,state:Xe});de=rt(de,te||void 0)}for(const te of H){const me=D(te.outer);me.length>=4&&Ge(f,me,de,!0,!1);for(const Me of te.holes){const Se=D(Me);Se.length>=4&&Ge(f,Se,de,!0,!1)}}}if(Y.length>0)for(const B of Y)for(const O of B.polygons){const H=D(O.outer);H.length>=4&&Ge(f,H,we,!0,!1);for(const G of O.holes){const he=D(G);he.length>=4&&Ge(f,he,we,!0,!1)}}if(Array.isArray(P)&&P.length>0){const B=!!globalThis.__OPEN_PLANT_DEBUG_OVERLAY__,O=D(Be([[0,0],[e,0],[e,n],[0,n]]));for(let H=0;H<P.length;H+=1){const G=P[H];if(!G?.coordinates?.length||G.visible===!1)continue;const he=G.closed??ki(G.coordinates),Xe=zn(G.coordinates,he);if(G.invertedFill?.fillColor){const te=[],me=zn(G.coordinates,!0);for(const Me of me){const Se=D(Me);Se.length>=4&&te.push(Se)}if(B){const Me=String(G.id??H),Se=`${O.length}|${me.length}|${te.length}|${G.invertedFill.fillColor}`;ze.current.get(Me)!==Se&&(ze.current.set(Me,Se),console.debug("[open-plant] invertedFill",{id:G.id??H,outerRingPoints:O.length,sourceRingCount:me.length,holeRingCount:te.length,fillColor:G.invertedFill.fillColor}))}Wi(f,O,te,G.invertedFill.fillColor)}if(Xe.length===0)continue;const de=rt(L,G.stroke??G.strokeStyle);for(const te of Xe){const me=D(te);me.length<2||Ge(f,me,de,he,G.fill??!1)}}}if(ne)if(t==="brush")Ue(f),Pe(f);else{const B=j();if(B.length>0)if(t==="freehand"){const O=D(B);O.length>=2&&Ge(f,O,L,!1,!1),O.length>=3&&Ge(f,D(Be(B)),L,!0,!0)}else{const O=D(B);O.length>=4&&Ge(f,O,L,!0,!0)}}if(I.length>0)for(const B of I){if(!B.region.label)continue;const O=Gi(B.polygons);if(!O)continue;const H=it(s.current?.worldToScreen(O[0],O[1])??[]);H&&qi(f,B.region.label,H,S,A,fe)}},[ne,t,j,Ue,Pe,K,D,e,n,s,I,P,z,Z,L,ie,re,Y,we,W,fe]),U=d.useCallback(()=>{_e.current||(_e.current=!0,requestAnimationFrame(()=>{_e.current=!1,Fe()}))},[Fe]),ge=d.useCallback((l=!1)=>{const f=be.current,p=$.current;if(p&&f.pointerId!==null&&p.hasPointerCapture(f.pointerId))try{p.releasePointerCapture(f.pointerId)}catch{}f.isDrawing=!1,f.pointerId=null,f.start=null,f.current=null,f.points=[],f.screenPoints=[],f.stampCenter=null,l||(f.cursor=null,f.cursorScreen=null)},[]),Ce=d.useCallback(l=>{const f=s.current;if(!f||e<=0||n<=0)return null;const p=it(f.screenToWorld(l.clientX,l.clientY));return p?yt(p,e,n):null},[s,e,n]),ye=d.useCallback(l=>{const f=$.current;if(!f)return null;const p=f.getBoundingClientRect(),S=ke(l.clientX-p.left,0,p.width),A=ke(l.clientY-p.top,0,p.height);return!Number.isFinite(S)||!Number.isFinite(A)?null:[S,A]},[]),Qe=d.useCallback(()=>{const l=be.current;if(!l.isDrawing){ge(!0),U();return}let f=[];if(t==="freehand")l.points.length>=ui&&(f=Be(l.points));else if(t==="rectangle")f=Yt(l.start,l.current);else if(t==="circular")f=Ot(l.start,l.current);else if(t==="brush"){const p=l.points[l.points.length-1]??l.current??l.start;if(V.clickSelectRoi&&p&&l.points.length<=1&&u?.(p)){ge(!0),U();return}const S=V.edgeDetail,A=Math.max(Pi,V.radius*2/(Ci*S)),B=l.screenPoints.length>0?l.screenPoints:D(l.points),O=Qr(B,{radius:V.radius,minRasterStep:A,circleSides:Math.max(24,Math.round(64*S)),simplifyTolerance:A*.25,smoothingPasses:V.edgeSmoothing}),H=[];for(const G of O){const he=ce(G);he&&H.push(he)}f=Be(H)}(t==="freehand"||t==="rectangle"||t==="circular"||t==="brush")&&Fn(f)&&c&&c({tool:t,intent:t==="brush"?"brush":"roi",coordinates:f,bbox:Un(f),areaPx:Vt(f)}),ge(!0),U()},[t,c,ge,U,D,ce,V.radius,V.edgeDetail,V.edgeSmoothing,V.clickSelectRoi,u]),De=d.useCallback((l,f)=>{const p=ae(l,f);if(!Fn(p))return;const S=l==="stamp-rectangle-4096px"?"patch":"roi",A={tool:l,intent:S,coordinates:p,bbox:Un(p),areaPx:Vt(p)};c?.(A),S==="patch"&&h&&h(A)},[ae,c,h]),pe=d.useCallback((l,f,p)=>{const S=vn*vn,A=l.screenPoints[l.screenPoints.length-1];if(!A){l.points.push(f),l.screenPoints.push(p),l.current=f;return}const B=p[0]-A[0],O=p[1]-A[1];B*B+O*O>=S?(l.points.push(f),l.screenPoints.push(p)):(l.points[l.points.length-1]=f,l.screenPoints[l.screenPoints.length-1]=p),l.current=f},[]),It=d.useCallback(l=>{if(!ne||t==="cursor"||l.button!==0)return;const f=Ce(l);if(!f)return;const p=t==="brush"?ye(l):null;if(t==="brush"&&!p)return;if(l.preventDefault(),l.stopPropagation(),bt(t)){const B=be.current;B.stampCenter=f,De(t,f),U();return}const S=$.current;S&&S.setPointerCapture(l.pointerId);const A=be.current;A.isDrawing=!0,A.pointerId=l.pointerId,A.start=f,A.current=f,A.cursor=f,A.cursorScreen=p,A.points=t==="freehand"||t==="brush"?[f]:[],A.screenPoints=t==="brush"&&p?[p]:[],U()},[ne,t,Ce,ye,De,U]),lt=d.useCallback(l=>{if(!ne||t==="cursor")return;const f=Ce(l);if(!f)return;if(bt(t)){const S=be.current;S.stampCenter=f,l.preventDefault(),l.stopPropagation(),U();return}const p=be.current;if(t==="brush"){const S=ye(l);if(!S)return;if(p.cursor=f,p.cursorScreen=S,!p.isDrawing||p.pointerId!==l.pointerId){U();return}l.preventDefault(),l.stopPropagation(),pe(p,f,S),U();return}if(!(!p.isDrawing||p.pointerId!==l.pointerId)){if(l.preventDefault(),l.stopPropagation(),t==="freehand"){const S=s.current,A=Math.max(1e-6,S?.getViewState?.().zoom??1),B=li/A,O=B*B,H=p.points[p.points.length-1];if(!H)p.points.push(f);else{const G=f[0]-H[0],he=f[1]-H[1];G*G+he*he>=O&&p.points.push(f)}}else p.current=f;U()}},[ne,t,Ce,ye,U,s,pe]),et=d.useCallback(l=>{const f=be.current;if(!f.isDrawing||f.pointerId!==l.pointerId)return;l.preventDefault(),l.stopPropagation();const p=Ce(l),S=t==="brush"?ye(l):null;p&&(f.cursor=p,t==="brush"?S&&(f.cursorScreen=S,pe(f,p,S)):f.current=p);const A=$.current;if(A&&A.hasPointerCapture(l.pointerId))try{A.releasePointerCapture(l.pointerId)}catch{}Qe()},[Qe,Ce,ye,t,pe]),ue=d.useCallback(()=>{const l=be.current;let f=!1;t==="brush"&&!l.isDrawing&&l.cursor&&(l.cursor=null,l.cursorScreen=null,f=!0),bt(t)&&l.stampCenter&&(l.stampCenter=null,f=!0),f&&U()},[t,U]);return d.useEffect(()=>{K(),U();const l=$.current;if(!l)return;const f=new ResizeObserver(()=>{K(),U()});return f.observe(l),()=>{f.disconnect()}},[K,U]),d.useEffect(()=>{ne||ge(),U()},[ne,U,ge]),d.useEffect(()=>{Ke.current!==t&&(Ke.current=t,ge(),U())},[t,ge,U]),d.useEffect(()=>{U()},[m,T,P,U]),d.useEffect(()=>{if(N)return N.current=U,()=>{N.current===U&&(N.current=null)}},[N,U]),d.useEffect(()=>{if(!ne)return;const l=f=>{f.key==="Escape"&&(ge(),U())};return window.addEventListener("keydown",l),()=>{window.removeEventListener("keydown",l)}},[ne,ge,U]),Ae.jsx("canvas",{ref:$,className:ve,style:J,onPointerDown:It,onPointerMove:lt,onPointerUp:et,onPointerCancel:et,onPointerLeave:ue,onContextMenu:l=>{ne&&l.preventDefault()},onWheel:l=>{if(!ne)return;const f=$.current,p=s.current;if(!f||typeof p?.zoomBy!="function")return;l.preventDefault(),l.stopPropagation();const S=f.getBoundingClientRect(),A=l.clientX-S.left,B=l.clientY-S.top;p.zoomBy(l.deltaY<0?di:mi,A,B),U()}})}function kn(t){return String(t??"").replace(/\/+$/,"")}function tr(t){const e=String(t??"");return e.startsWith("/")?e:`/${e}`}function Hi(t){const e=kn(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=kn(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 $i(t,e){const n=t?.imsInfo||{},r=!!t?.imsInfo,i=Number(n.width??t?.width??0),o=Number(n.height??t?.height??0),a=Number(n.tileSize??t?.tileSize??0),s=Number(n.zoom??t?.zoom??0),u=String(n.path??t?.path??""),c=Number(n.mpp??t?.mpp??0);if(!i||!o||!a||!u)throw new Error("이미지 메타데이터가 불완전합니다. width/height/tileSize/path 확인 필요");const h=Array.isArray(t?.terms)?t.terms.map(y=>({termId:String(y?.termId??""),termName:String(y?.termName??""),termColor:String(y?.termColor??"")})):[],b=tr(u),m=Hi(e),g=r?(y,x,E)=>`${m}${b}/${y}/${E}_${x}.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:a,maxTierZoom:Number.isFinite(s)?Math.max(0,Math.floor(s)):0,tilePath:u,tileBaseUrl:e,terms:h,tileUrlBuilder:g}}function en(t,e,n,r){if(t.tileUrlBuilder)return t.tileUrlBuilder(e,n,r);const i=tr(t.tilePath);return`${t.tileBaseUrl}${i}/${e}/${r}_${n}.webp`}const xe={width:220,height:140,margin:16,position:"bottom-right",borderRadius:10,borderWidth:1.5,backgroundColor:"rgba(4, 10, 18, 0.88)",borderColor:"rgba(230, 244, 255, 0.35)",viewportStrokeColor:"rgba(255, 106, 61, 0.95)",viewportFillColor:"rgba(255, 106, 61, 0.2)",interactive:!0,showThumbnail:!0,maxThumbnailTiles:16};function Je(t,e,n=1){return typeof t!="number"||!Number.isFinite(t)?e:Math.max(n,t)}function wt(t){return Array.isArray(t)&&t.length===4&&Number.isFinite(t[0])&&Number.isFinite(t[1])&&Number.isFinite(t[2])&&Number.isFinite(t[3])}function nr({source:t,projectorRef:e,authToken:n="",options:r,invalidateRef:i,className:o,style:a}){const s=d.useRef(null),u=d.useRef(null),c=d.useRef(null),h=d.useRef({active:!1,pointerId:null}),b=d.useRef(null),m=d.useRef(!1),g=Je(r?.width,xe.width,64),y=Je(r?.height,xe.height,48),x=Je(r?.margin,xe.margin,0),E=Je(r?.borderRadius,xe.borderRadius,0),_=Je(r?.borderWidth,xe.borderWidth,0),X=Math.max(1,Math.round(Je(r?.maxThumbnailTiles,xe.maxThumbnailTiles,1))),F=r?.backgroundColor||xe.backgroundColor,W=r?.borderColor||xe.borderColor,P=r?.viewportStrokeColor||xe.viewportStrokeColor,z=r?.viewportFillColor||xe.viewportFillColor,Z=r?.interactive??xe.interactive,ee=r?.showThumbnail??xe.showThumbnail,N=r?.position||xe.position,ve=d.useMemo(()=>{const T={};return N==="top-left"||N==="bottom-left"?T.left=x:T.right=x,N==="top-left"||N==="top-right"?T.top=x:T.bottom=x,{position:"absolute",...T,width:g,height:y,borderRadius:E,overflow:"hidden",zIndex:4,pointerEvents:Z?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...a}},[x,N,g,y,E,Z,a]),Te=d.useCallback(()=>{const T=s.current;if(!T)return;const C=T.getContext("2d");if(!C)return;const I=g,Y=y,L=Math.max(1,window.devicePixelRatio||1),ie=Math.max(1,Math.round(I*L)),re=Math.max(1,Math.round(Y*L));(T.width!==ie||T.height!==re)&&(T.width=ie,T.height=re),C.setTransform(1,0,0,1,0,0),C.clearRect(0,0,T.width,T.height),C.setTransform(L,0,0,L,0,0),C.fillStyle=F,C.fillRect(0,0,I,Y);const we=u.current;we&&C.drawImage(we,0,0,I,Y),C.strokeStyle=W,C.lineWidth=_,C.strokeRect(_*.5,_*.5,I-_,Y-_);const fe=e.current,oe=fe?.getViewBounds?.(),V=fe?.getViewCorners?.(),J=wt(oe)?oe:wt(c.current)?c.current:null;if(!J)return;c.current=J;const K=I/Math.max(1,t.width),D=Y/Math.max(1,t.height),ce=Array.isArray(V)&&V.length>=4&&V.every(U=>Array.isArray(U)&&U.length>=2&&Number.isFinite(U[0])&&Number.isFinite(U[1]))?V:null;if(ce){C.beginPath();for(let U=0;U<ce.length;U+=1){const ge=ce[U],Ce=Q(ge[0]*K,0,I),ye=Q(ge[1]*D,0,Y);U===0?C.moveTo(Ce,ye):C.lineTo(Ce,ye)}C.closePath(),C.fillStyle=z,C.fill(),C.strokeStyle=P,C.lineWidth=1.5,C.stroke();return}const se=Q(J[0]*K,0,I),ae=Q(J[1]*D,0,Y),j=Q(J[2]*K,0,I),Ue=Q(J[3]*D,0,Y),Pe=Math.max(1,j-se),Fe=Math.max(1,Ue-ae);C.fillStyle=z,C.fillRect(se,ae,Pe,Fe),C.strokeStyle=P,C.lineWidth=1.5,C.strokeRect(se+.5,ae+.5,Math.max(1,Pe-1),Math.max(1,Fe-1))},[g,y,F,W,_,e,t.width,t.height,z,P]),$=d.useCallback(()=>{m.current||(m.current=!0,b.current=requestAnimationFrame(()=>{m.current=!1,b.current=null,Te()}))},[Te]),_e=d.useCallback((T,C)=>{const I=s.current;if(!I)return null;const Y=I.getBoundingClientRect();if(!Y.width||!Y.height)return null;const L=Q((T-Y.left)/Y.width,0,1),ie=Q((C-Y.top)/Y.height,0,1);return[L*t.width,ie*t.height]},[t.width,t.height]),ze=d.useCallback((T,C)=>{const I=e.current;if(!I)return;if(I.setViewCenter){I.setViewCenter(T,C),$();return}const Y=I.getViewBounds?.(),L=wt(Y)?Y:wt(c.current)?c.current:null;if(!L)return;const ie=Math.max(1e-6,L[2]-L[0]),re=Math.max(1e-6,L[3]-L[1]);I.setViewState({offsetX:T-ie*.5,offsetY:C-re*.5}),$()},[e,$]),Ke=d.useCallback(T=>{if(!Z||T.button!==0)return;const C=s.current;if(!C)return;const I=_e(T.clientX,T.clientY);I&&(T.preventDefault(),T.stopPropagation(),C.setPointerCapture(T.pointerId),h.current={active:!0,pointerId:T.pointerId},ze(I[0],I[1]))},[Z,_e,ze]),be=d.useCallback(T=>{const C=h.current;if(!C.active||C.pointerId!==T.pointerId)return;const I=_e(T.clientX,T.clientY);I&&(T.preventDefault(),T.stopPropagation(),ze(I[0],I[1]))},[_e,ze]),ne=d.useCallback(T=>{const C=h.current;if(!C.active||C.pointerId!==T.pointerId)return;const I=s.current;if(I&&I.hasPointerCapture(T.pointerId))try{I.releasePointerCapture(T.pointerId)}catch{}h.current={active:!1,pointerId:null},$()},[$]);return d.useEffect(()=>{let T=!1;u.current=null,$();const C=0,I=2**(t.maxTierZoom-C),Y=Math.ceil(t.width/I),L=Math.ceil(t.height/I),ie=Math.max(1,Math.ceil(Y/t.tileSize)),re=Math.max(1,Math.ceil(L/t.tileSize)),we=ie*re;if(!ee||we>X)return;const fe=document.createElement("canvas");fe.width=Math.max(1,Math.round(g)),fe.height=Math.max(1,Math.round(y));const oe=fe.getContext("2d");if(!oe)return;oe.fillStyle=F,oe.fillRect(0,0,fe.width,fe.height);const V=[];for(let J=0;J<re;J+=1)for(let K=0;K<ie;K+=1){const D=K*t.tileSize*I,ce=J*t.tileSize*I,se=Math.min((K+1)*t.tileSize,Y)*I,ae=Math.min((J+1)*t.tileSize,L)*I;V.push({url:en(t,C,K,J),bounds:[D,ce,se,ae]})}return Promise.allSettled(V.map(async J=>{const K=!!n,D=await fetch(J.url,{headers:K?{Authorization:n}:void 0});if(!D.ok)throw new Error(`HTTP ${D.status}`);const ce=await createImageBitmap(await D.blob());return{tile:J,bitmap:ce}})).then(J=>{if(T){for(const ce of J)ce.status==="fulfilled"&&ce.value.bitmap.close();return}const K=fe.width/Math.max(1,t.width),D=fe.height/Math.max(1,t.height);for(const ce of J){if(ce.status!=="fulfilled")continue;const{tile:{bounds:se},bitmap:ae}=ce.value,j=se[0]*K,Ue=se[1]*D,Pe=Math.max(1,(se[2]-se[0])*K),Fe=Math.max(1,(se[3]-se[1])*D);oe.drawImage(ae,j,Ue,Pe,Fe),ae.close()}u.current=fe,$()}),()=>{T=!0}},[t,n,g,y,F,ee,X,$]),d.useEffect(()=>{$()},[$]),d.useEffect(()=>{if(i)return i.current=$,()=>{i.current===$&&(i.current=null)}},[i,$]),d.useEffect(()=>()=>{h.current={active:!1,pointerId:null},b.current!==null&&(cancelAnimationFrame(b.current),b.current=null),m.current=!1},[]),Ae.jsx("canvas",{ref:s,className:o,style:ve,onPointerDown:Ke,onPointerMove:be,onPointerUp:ne,onPointerCancel:ne,onContextMenu:T=>{T.preventDefault()},onWheel:T=>{T.preventDefault(),T.stopPropagation()}})}function Zi({imageWidth:t,imageHeight:e,tiles:n,viewState:r,className:i,style:o}){const a=d.useRef(null),s=d.useRef(null),u=d.useMemo(()=>({width:"100%",height:"100%",display:"block",...o}),[o]);return d.useEffect(()=>{const c=a.current;if(!c)return;const h=new On({canvas:c,imageWidth:t,imageHeight:e,initialViewState:r});return s.current=h,h.setTiles(n),()=>{h.destroy(),s.current=null}},[t,e]),d.useEffect(()=>{const c=s.current;c&&c.setTiles(n)},[n]),d.useEffect(()=>{const c=s.current;!c||!r||c.setViewState(r)},[r]),Ae.jsx("canvas",{ref:a,className:i,style:u})}function rr(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 at(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return null;const n=ut(e??[]);if(n.length===0){const y={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return t.fillModes instanceof Uint8Array&&(y.fillModes=new Uint8Array(0)),t.ids instanceof Uint32Array&&(y.ids=new Uint32Array(0)),y}const r=rr(t),i=t.positions,o=t.paletteIndices,a=t.fillModes instanceof Uint8Array&&t.fillModes.length>=r?t.fillModes:null,s=t.ids instanceof Uint32Array&&t.ids.length>=r?t.ids:null,u=new Float32Array(r*2),c=new Uint16Array(r),h=a?new Uint8Array(r):null,b=s?new Uint32Array(r):null;let m=0;for(let y=0;y<r;y+=1){const x=i[y*2],E=i[y*2+1];Pt(x,E,n)&&(u[m*2]=x,u[m*2+1]=E,c[m]=o[y],h&&(h[m]=a[y]),b&&(b[m]=s[y]),m+=1)}const g={count:m,positions:u.subarray(0,m*2),paletteIndices:c.subarray(0,m)};return h&&(g.fillModes=h.subarray(0,m)),b&&(g.ids=b.subarray(0,m)),g}function ir(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return new Uint32Array(0);const n=ut(e??[]);if(n.length===0)return new Uint32Array(0);const r=rr(t);if(r===0)return new Uint32Array(0);const i=t.positions,o=new Uint32Array(r);let a=0;for(let s=0;s<r;s+=1){const u=i[s*2],c=i[s*2+1];Pt(u,c,n)&&(o[a]=s,a+=1)}return o.subarray(0,a)}let Mt=null;const Ki=`
32
+ `;class Wn{constructor(e){w(this,"canvas");w(this,"gl");w(this,"camera",new Er);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=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=Tr(this.canvas),this.program=Rr(this.gl,Pr,Cr);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=Bt(this.gl,this.program,"uCamera"),this.uBoundsLocation=Bt(this.gl,this.program,"uBounds"),this.uTextureLocation=Bt(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)}}const vr=.1,Ir=4e6,_r=4096,Ur=64,Br=1,Fr=4,Vn=1e-6,Lr=24;function Tt(t,e,n){return Math.max(e,Math.min(n,t))}function ze(t){if(!Array.isArray(t)||t.length<3)return[];const e=t.map(([i,o])=>[i,o]),n=e[0],r=e[e.length-1];return!n||!r?[]:((n[0]!==r[0]||n[1]!==r[1])&&e.push([n[0],n[1]]),e)}function zr(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 Nr(t,e,n){if(e<=Vn||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 ze(r)}function Ft(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 ze([[n-s,r-s],[i+s,r-s],[i+s,o+s],[n-s,o+s]])}function kr(t,e){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);const s=Math.max(e,1);return[n-s,r-s,i+s,o+s]}function Dr(t,e,n){const r=Math.max(vr,Number(n.minRasterStep)||0),i=Math.max(32768,Math.floor(n.maxRasterPixels||Ir)),o=Math.max(256,Math.floor(n.maxRasterSize||_r)),s=Math.max(.001,t[2]-t[0]),a=Math.max(.001,t[3]-t[1]);let u=Math.max(r,Number.EPSILON),c=3,h=Math.ceil(s/u)+c*2+1,y=Math.ceil(a/u)+c*2+1;for(;(h>o||y>o||h*y>i)&&(u*=1.15,h=Math.ceil(s/u)+c*2+1,y=Math.ceil(a/u)+c*2+1,!(u>Math.max(s,a))););return h=Math.max(8,h),y=Math.max(8,y),{minX:t[0],minY:t[1],step:u,padding:c,width:h,height:y}}function Or(t,e){if(typeof OffscreenCanvas<"u"){const r=new OffscreenCanvas(t,e).getContext("2d",{willReadFrequently:!0});if(r)return r}if(typeof document<"u"){const n=document.createElement("canvas");return n.width=t,n.height=e,n.getContext("2d",{willReadFrequently:!0})}return null}function Xr(t,e){return[(t[0]-e.minX)/e.step+e.padding,(t[1]-e.minY)/e.step+e.padding]}function Yr(t,e,n){const r=Or(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=e*2/n.step;const i=t.map(a=>Xr(a,n));if(i.length<=1){const a=i[0];if(!a)return new Uint8Array(0);r.beginPath(),r.arc(a[0],a[1],e/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]>=Lr?1:0;return s}function Wr(t,e,n){const r=[],i=e+1,o=(a,u)=>u*i+a,s=(a,u)=>a>=0&&u>=0&&a<e&&u<n&&t[u*e+a]>0;for(let a=0;a<n;a+=1)for(let u=0;u<e;u+=1)s(u,a)&&(s(u,a-1)||r.push({start:o(u,a),end:o(u+1,a),dir:0}),s(u+1,a)||r.push({start:o(u+1,a),end:o(u+1,a+1),dir:1}),s(u,a+1)||r.push({start:o(u+1,a+1),end:o(u,a+1),dir:2}),s(u-1,a)||r.push({start:o(u,a+1),end:o(u,a),dir:3}));return r}function Vr(t,e){const n=(e-t+4)%4;return n===1?0:n===0?1:n===3?2:3}function Gr(t){if(!t.length)return[];const e=new Map;for(let i=0;i<t.length;i+=1){const o=e.get(t[i].start);o?o.push(i):e.set(t[i].start,[i])}const n=new Uint8Array(t.length),r=[];for(let i=0;i<t.length;i+=1){if(n[i])continue;const o=t[i],s=o.start;let a=o.end,u=o.dir;const c=[o.start,o.end];n[i]=1;let h=0;const y=t.length*3;for(;a!==s&&h<y;){const m=e.get(a);if(!m||m.length===0)break;let p=-1,g=1/0;for(const T of m){if(n[T])continue;const B=t[T],z=Vr(u,B.dir);z<g&&(g=z,p=T)}if(p<0)break;n[p]=1;const x=t[p];a=x.end,u=x.dir,c.push(a),h+=1}c.length>=4&&c[0]===c[c.length-1]&&r.push(c)}return r}function qr(t,e,n){const r=e+1,i=[];for(const o of t){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 ze(i)}function Hr(t){if(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 $r(t,e=1e-9){const n=ze(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]),ze(r)}function Zr(t,e,n){const r=n[0]-e[0],i=n[1]-e[1],o=r*r+i*i;if(o<=1e-12){const y=t[0]-e[0],m=t[1]-e[1];return y*y+m*m}const s=Tt(((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,h=t[1]-u;return c*c+h*h}function Kr(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,h=-1;for(let y=a+1;y<u;y+=1){const m=Zr(t[y],t[a],t[u]);m>c&&(c=m,h=y)}h>=0&&c>r&&(n[h]=1,i.push([a,h],[h,u]))}const o=[];for(let s=0;s<t.length;s+=1)n[s]&&o.push(t[s]);return o}function jr(t,e){const n=ze(t);if(n.length<5||e<=0)return n;const r=n.slice(0,-1),i=Kr(r,e);return i.length<3?n:ze(i)}function Jr(t,e){let n=ze(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=ze(o)}return n}function rt(t,e){return e?ze(t.map(([n,r])=>[Tt(n,e[0],e[2]),Tt(r,e[1],e[3])])):t}function Qr(t,e){const n=zr(t),r=Math.max(Vn,Number(e.radius)||0);if(n.length===0||!Number.isFinite(r))return[];const i=Math.max(12,Math.floor(e.circleSides||Ur));if(n.length===1)return rt(Nr(n[0],r,i),e.clipBounds);const o=kr(n,r),s=Dr(o,r,e),a=Yr(n,r,s);if(!a.length)return rt(Ft(n,r),e.clipBounds);const u=Wr(a,s.width,s.height),c=Gr(u);if(!c.length)return rt(Ft(n,r),e.clipBounds);let h=[],y=0;for(const x of c){const T=qr(x,s.width,s),B=Math.abs(Hr(T));B<=y||(y=B,h=T)}if(!h.length)return rt(Ft(n,r),e.clipBounds);const m=typeof e.simplifyTolerance=="number"&&Number.isFinite(e.simplifyTolerance)?Math.max(0,e.simplifyTolerance):s.step*.2,p=typeof e.smoothingPasses=="number"&&Number.isFinite(e.smoothingPasses)?Math.round(Tt(e.smoothingPasses,0,Fr)):Br,g=jr(Jr($r(h,s.step*.001),p),m);return rt(g,e.clipBounds)}function xn(t){return typeof t=="number"&&Number.isFinite(t)}function ei(t){return Array.isArray(t)&&t.length>=2&&xn(t[0])&&xn(t[1])}function Gn(t){return Array.isArray(t)&&t.length>0&&t.every(e=>ei(e))}function qn(t){return Array.isArray(t)&&t.length>0&&t.every(e=>Gn(e))}function ti(t){return Array.isArray(t)&&t.length>0&&t.every(e=>qn(e))}function ni(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 Ot(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 Lt(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const o of t){const s=ni(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(Ot(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 Hn(t){if(!t)return[];if(Gn(t)){const e=Lt([t]);return e.length>0?[e]:[]}if(qn(t)){const e=Lt(t);return e.length>0?[e]:[]}if(ti(t)){const e=[];for(const n of t){const r=Lt(n);r.length>0&&e.push(r)}return e}return[]}function An(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];a>e!=c>e&&t<(u-s)*(e-a)/(c-a||Number.EPSILON)+s&&(r=!r)}return r}function lt(t){const e=[];for(const n of t??[]){const r=Hn(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[y,m]of o)y<s&&(s=y),y>u&&(u=y),m<a&&(a=m),m>c&&(c=m);if(!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(u)||!Number.isFinite(c))continue;let h=Math.abs(Ot(o));for(let y=1;y<i.length;y+=1)h-=Math.abs(Ot(i[y]));e.push({outer:o,holes:i.slice(1),minX:s,minY:a,maxX:u,maxY:c,area:Math.max(1e-6,h)})}}return e}function Kt(t,e,n){if(t<n.minX||t>n.maxX||e<n.minY||e>n.maxY||!An(t,e,n.outer))return!1;for(const r of n.holes)if(An(t,e,r))return!1;return!0}function Et(t,e,n){for(const r of n)if(Kt(t,e,r))return!0;return!1}const jt=[160,160,160,255];function ee(t,e,n){return Math.max(e,Math.min(n,t))}function Jt(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 ri(t,e,n){let i=100*Jt(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 ii(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 oi(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 $n(t){const n=String(t??"").trim().match(/^#?([0-9a-fA-F]{6})$/);if(!n)return[...jt];const r=Number.parseInt(n[1],16);return[r>>16&255,r>>8&255,r&255,255]}function si(t){const e=[[...jt]],n=new Map;for(const i of t??[]){const o=String(i?.termId??"");!o||n.has(o)||(n.set(o,e.length),e.push($n(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}}function Rn(t,e,n){const r=t.createShader(t.VERTEX_SHADER),i=t.createShader(t.FRAGMENT_SHADER);if(!r||!i)throw new Error("Shader allocation failed");if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error(t.getShaderInfoLog(r)||"vertex compile failed");if(t.shaderSource(i,n),t.compileShader(i),!t.getShaderParameter(i,t.COMPILE_STATUS))throw new Error(t.getShaderInfoLog(i)||"fragment compile failed");const o=t.createProgram();if(!o)throw new Error("Program allocation failed");if(t.attachShader(o,r),t.attachShader(o,i),t.linkProgram(o),t.deleteShader(r),t.deleteShader(i),!t.getProgramParameter(o,t.LINK_STATUS))throw new Error(t.getProgramInfoLog(o)||"program link failed");return o}const ai="rgba(255, 77, 79, 0.16)",ui=3,li=2,Zn=96,ci=1,Tn=[],Pt=[],En=1e3,Kn=2,jn=2,fi=4096,hi=.2,di=1.12,mi=.89,gi=32,pi="#000000",bi=.1,yi="#FFCF00",wi="#FF0000",Mi=1.5,Pn=[2,2],Si=1,xi=.25,Ai=4,Ri=1,Ti=0,Ei=4,Pi=.05,Ci=256,Cn=1.5,Ve={color:"#ff4d4f",width:2,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},vi={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},_e={fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:12,fontWeight:500,textColor:"#ffffff",backgroundColor:"rgba(8, 14, 22, 0.88)",borderColor:"rgba(255, 77, 79, 0.85)",borderWidth:1,paddingX:6,paddingY:4,offsetY:10,borderRadius:3};function Oe(t,e,n){return Math.max(e,Math.min(n,t))}function pt(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 st(t,e){return typeof t!="number"||!Number.isFinite(t)||t<=0?e:t}function Ii(t){return{rectangleAreaMm2:st(t?.rectangleAreaMm2,Kn),circleAreaMm2:st(t?.circleAreaMm2,jn),rectanglePixelSize:st(t?.rectanglePixelSize,fi)}}function _i(t,e){return typeof t!="number"||!Number.isFinite(t)?e:Oe(t,0,1)}function Ui(t){if(!Array.isArray(t))return Pn;const e=t.filter(n=>Number.isFinite(n)&&n>=0);return e.length>0?e:Pn}function Bi(t){return typeof t!="number"||!Number.isFinite(t)?Si:Oe(t,xi,Ai)}function Fi(t){return typeof t!="number"||!Number.isFinite(t)?Ri:Math.round(Oe(t,Ti,Ei))}function Li(t){const e=st(t?.radius,gi),n=st(t?.cursorLineWidth,Mi),r=Bi(t?.edgeDetail),i=Fi(t?.edgeSmoothing);return{radius:e,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:t?.clickSelectRoi===!0,fillColor:t?.fillColor||pi,fillOpacity:_i(t?.fillOpacity,bi),cursorColor:t?.cursorColor||yi,cursorActiveColor:t?.cursorActiveColor||wi,cursorLineWidth:n,cursorLineDash:Ui(t?.cursorLineDash)}}function zi(t){return t*En*En}function vn(t,e){return!t||!Number.isFinite(e)||e<=0?[]:Le([[t[0]-e,t[1]-e],[t[0]+e,t[1]-e],[t[0]+e,t[1]+e],[t[0]-e,t[1]+e]])}function Ni(t,e,n=Zn){if(!t||!Number.isFinite(e)||e<=0)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([t[0]+Math.cos(o)*e,t[1]+Math.sin(o)*e])}return Le(r)}function Le(t){if(!Array.isArray(t)||t.length<3)return[];const e=t.map(([i,o])=>[i,o]),n=e[0],r=e[e.length-1];return!n||!r?[]:((n[0]!==r[0]||n[1]!==r[1])&&e.push([n[0],n[1]]),e)}function Xt(t,e){return!t||!e?[]:Le([[t[0],t[1]],[e[0],t[1]],[e[0],e[1]],[t[0],e[1]]])}function Yt(t,e,n=Zn){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 Le(s)}function Wt(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 Math.abs(e*.5)}function In(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 _n(t){return Array.isArray(t)&&t.length>=4&&Wt(t)>ci}function Vt(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 Ge(t,e,n,r=!1,i=!1){e.length!==0&&(t.beginPath(),Vt(t,e,r),i&&r&&(t.fillStyle=ai,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(Pt),t.shadowColor="rgba(0, 0, 0, 0)",t.shadowBlur=0,t.shadowOffsetX=0,t.shadowOffsetY=0)}function Jn(t){const e=Array.isArray(t?.lineDash)?t.lineDash.filter(s=>Number.isFinite(s)&&s>=0):Pt,n=typeof t?.width=="number"&&Number.isFinite(t.width)?Math.max(0,t.width):Ve.width,r=typeof t?.shadowBlur=="number"&&Number.isFinite(t.shadowBlur)?Math.max(0,t.shadowBlur):Ve.shadowBlur,i=typeof t?.shadowOffsetX=="number"&&Number.isFinite(t.shadowOffsetX)?t.shadowOffsetX:Ve.shadowOffsetX,o=typeof t?.shadowOffsetY=="number"&&Number.isFinite(t.shadowOffsetY)?t.shadowOffsetY:Ve.shadowOffsetY;return{color:t?.color||Ve.color,width:n,lineDash:e.length?e:Pt,lineJoin:t?.lineJoin||Ve.lineJoin,lineCap:t?.lineCap||Ve.lineCap,shadowColor:t?.shadowColor||Ve.shadowColor,shadowBlur:r,shadowOffsetX:i,shadowOffsetY:o}}function it(t,e){return e?Jn({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 Un(t,e){return t==null||e===null||e===void 0?!1:String(t)===String(e)}function ki(t){const e=t[0];return Array.isArray(e)&&Array.isArray(e[0])}function Bn(t){return typeof t=="number"&&Number.isFinite(t)}function Di(t){return Array.isArray(t)&&t.length>=2&&Bn(t[0])&&Bn(t[1])}function Oi(t){return Array.isArray(t)&&t.length>=2&&t.every(e=>Di(e))}function Qn(t,e){if(!(!Array.isArray(t)||t.length===0)){if(Oi(t)){e.push(t.map(([n,r])=>[n,r]));return}for(const n of t)Qn(n,e)}}function Fn(t,e){const n=[];Qn(t,n);const r=[];for(const i of n){if(i.length<2)continue;const o=e?Le(i):i;o.length>=(e?4:2)&&r.push(o)}return r}function Xi(t,e,n,r){if(!(e.length<4||n.length===0)){t.save(),t.beginPath(),Vt(t,e,!0);for(const i of n)i.length<4||Vt(t,i,!0);t.fillStyle=r,t.fill("evenodd"),t.restore()}}function Yi(t){const e=typeof t?.paddingX=="number"&&Number.isFinite(t.paddingX)?Math.max(0,t.paddingX):_e.paddingX,n=typeof t?.paddingY=="number"&&Number.isFinite(t.paddingY)?Math.max(0,t.paddingY):_e.paddingY,r=typeof t?.fontSize=="number"&&Number.isFinite(t.fontSize)?Math.max(8,t.fontSize):_e.fontSize,i=typeof t?.borderWidth=="number"&&Number.isFinite(t.borderWidth)?Math.max(0,t.borderWidth):_e.borderWidth,o=typeof t?.offsetY=="number"&&Number.isFinite(t.offsetY)?t.offsetY:_e.offsetY,s=typeof t?.borderRadius=="number"&&Number.isFinite(t.borderRadius)?Math.max(0,t.borderRadius):_e.borderRadius;return{fontFamily:t?.fontFamily||_e.fontFamily,fontSize:r,fontWeight:t?.fontWeight||_e.fontWeight,textColor:t?.textColor||_e.textColor,backgroundColor:t?.backgroundColor||_e.backgroundColor,borderColor:t?.borderColor||_e.borderColor,borderWidth:i,paddingX:e,paddingY:n,offsetY:o,borderRadius:s}}function Wi(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 Vi(t){if(!t.length)return null;let e=1/0;for(const i of t)i[1]<e&&(e=i[1]);if(!Number.isFinite(e))return null;let n=1/0,r=-1/0;for(const i of t)Math.abs(i[1]-e)>.5||(i[0]<n&&(n=i[0]),i[0]>r&&(r=i[0]));return!Number.isFinite(n)||!Number.isFinite(r)?null:[(n+r)*.5,e]}function Gi(t){let e=null;for(const n of t){const r=Vi(n.outer);r&&(!e||r[1]<e[1]||r[1]===e[1]&&r[0]<e[0])&&(e=r)}return e}function Ln(t){const e=Hn(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,h])=>[c,h]))}n.push({outer:o,holes:s})}return n}function qi(t,e,n,r,i,o){const s=e.trim();if(!s)return;t.save(),t.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,t.textAlign="center",t.textBaseline="middle";const u=t.measureText(s).width+o.paddingX*2,c=o.fontSize+o.paddingY*2,h=Oe(n[0],u*.5+1,r-u*.5-1),y=Oe(n[1]-o.offsetY,c*.5+1,i-c*.5-1),m=h-u*.5,p=y-c*.5;t.fillStyle=o.backgroundColor,t.strokeStyle=o.borderColor,t.lineWidth=o.borderWidth,Wi(t,m,p,u,c,o.borderRadius),t.fill(),o.borderWidth>0&&t.stroke(),t.fillStyle=o.textColor,t.fillText(s,h,y+.5),t.restore()}function bt(t,e,n){return[Oe(t[0],0,e),Oe(t[1],0,n)]}function ot(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]}function er({tool:t,imageWidth:e,imageHeight:n,imageMpp:r,imageZoom:i,stampOptions:o,brushOptions:s,projectorRef:a,onBrushTap:u,onDrawComplete:c,onPatchComplete:h,enabled:y,viewStateSignal:m,persistedRegions:p,patchRegions:g,persistedPolygons:x,regionStrokeStyle:T,regionStrokeHoverStyle:B,regionStrokeActiveStyle:z,patchStrokeStyle:N,resolveRegionStrokeStyle:Y,overlayShapes:C,hoveredRegionId:k=null,activeRegionId:J=null,regionLabelStyle:ue,invalidateRef:j,className:$,style:Ce}){const fe=d.useRef(null),$e=d.useRef(!1),Ze=d.useRef(new Map),Je=d.useRef(t),be=d.useRef({isDrawing:!1,pointerId:null,start:null,current:null,cursor:null,cursorScreen:null,points:[],screenPoints:[],stampCenter:null}),W=y??t!=="cursor",Ie=d.useMemo(()=>p&&p.length>0?p:!x||x.length===0?Tn:x.map((l,f)=>({id:f,coordinates:l})),[p,x]),Ae=d.useMemo(()=>g??Tn,[g]),Ne=d.useMemo(()=>{const l=[];for(let f=0;f<Ie.length;f+=1){const b=Ie[f],S=Ln(b.coordinates);S.length!==0&&l.push({region:b,regionIndex:f,regionKey:b.id??f,polygons:S})}return l},[Ie]),Ke=d.useMemo(()=>{const l=[];for(let f=0;f<Ae.length;f+=1){const b=Ae[f],S=Ln(b.coordinates);S.length!==0&&l.push({region:b,regionIndex:f,regionKey:b.id??f,polygons:S})}return l},[Ae]),oe=d.useMemo(()=>Jn(T),[T]),A=d.useMemo(()=>it(oe,B),[oe,B]),P=d.useMemo(()=>it(oe,z),[oe,z]),v=d.useMemo(()=>it(vi,N),[N]),K=d.useMemo(()=>Yi(ue),[ue]),G=d.useMemo(()=>Ii(o),[o]),_=d.useMemo(()=>Li(s),[s]),Re=d.useMemo(()=>({position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",touchAction:"none",pointerEvents:W?"auto":"none",cursor:W?t==="brush"?"none":"crosshair":"default",...Ce}),[W,t,Ce]),te=d.useCallback(()=>{const l=fe.current;if(!l)return;const f=l.getBoundingClientRect(),b=Math.max(1,window.devicePixelRatio||1),S=Math.max(1,Math.round(f.width*b)),R=Math.max(1,Math.round(f.height*b));(l.width!==S||l.height!==R)&&(l.width=S,l.height=R)},[]),F=d.useCallback(l=>{const f=a.current;if(!f||l.length===0)return[];const b=new Array(l.length);for(let S=0;S<l.length;S+=1){const R=ot(f.worldToScreen(l[S][0],l[S][1]));if(!R)return[];b[S]=R}return b},[a]),he=d.useCallback(l=>{const f=a.current,b=fe.current;if(!f||!b)return null;const S=b.getBoundingClientRect(),R=ot(f.screenToWorld(S.left+l[0],S.top+l[1]));return R?bt(R,e,n):null},[a,e,n]),de=d.useCallback(l=>{if(!Number.isFinite(l)||l<=0)return 0;const f=typeof r=="number"&&Number.isFinite(r)&&r>0?r:1,b=typeof i=="number"&&Number.isFinite(i)?i:0,S=a.current?.getViewState?.().zoom,R=typeof S=="number"&&Number.isFinite(S)&&S>0?S:1,L=b+Math.log2(R),V=Math.max(1e-9,Jt(f,b,L));return l/V/R},[r,i,a]),Q=d.useCallback((l,f)=>{if(!f)return[];let b=0;if(l==="stamp-rectangle-4096px"){const L=G.rectanglePixelSize*.5;return vn(f,L).map(Z=>bt(Z,e,n))}if(l==="stamp-rectangle"||l==="stamp-rectangle-2mm2"?b=l==="stamp-rectangle-2mm2"?Kn:G.rectangleAreaMm2:(l==="stamp-circle"||l==="stamp-circle-2mm2"||l==="stamp-circle-hpf-0.2mm2")&&(b=l==="stamp-circle-hpf-0.2mm2"?hi:l==="stamp-circle-2mm2"?jn:G.circleAreaMm2),!Number.isFinite(b)||b<=0)return[];const S=zi(b);let R=[];if(l==="stamp-rectangle"||l==="stamp-rectangle-2mm2"){const L=de(Math.sqrt(S)*.5);R=vn(f,L)}else if(l==="stamp-circle"||l==="stamp-circle-2mm2"||l==="stamp-circle-hpf-0.2mm2"){const L=de(Math.sqrt(S/Math.PI));R=Ni(f,L)}return R.length?R.map(L=>bt(L,e,n)):[]},[de,e,n,G]),le=d.useCallback(()=>{const l=be.current;return pt(t)?Q(t,l.stampCenter):t==="brush"?[]:l.isDrawing?t==="freehand"?l.points:t==="rectangle"?Xt(l.start,l.current):t==="circular"?Yt(l.start,l.current):[]:[]},[t,Q]),ie=d.useCallback(l=>{const f=be.current;if(!f.isDrawing||f.screenPoints.length===0)return;const b=f.screenPoints;if(b.length===0)return;const S=_.radius;if(!(!Number.isFinite(S)||S<=0)){if(l.save(),l.globalAlpha=_.fillOpacity,l.fillStyle=_.fillColor,l.strokeStyle=_.fillColor,l.lineCap="round",l.lineJoin="round",l.lineWidth=S*2,b.length===1)l.beginPath(),l.arc(b[0][0],b[0][1],S,0,Math.PI*2),l.fill();else{l.beginPath(),l.moveTo(b[0][0],b[0][1]);for(let R=1;R<b.length;R+=1)l.lineTo(b[R][0],b[R][1]);l.stroke()}l.restore()}},[_]),D=d.useCallback(l=>{const f=be.current,b=f.cursor;if(!b)return;const S=f.cursorScreen??ot(a.current?.worldToScreen(b[0],b[1])??[]);if(!S)return;const R=_.radius;!Number.isFinite(R)||R<=0||(l.save(),l.beginPath(),l.arc(S[0],S[1],R,0,Math.PI*2),l.strokeStyle=f.isDrawing?_.cursorActiveColor:_.cursorColor,l.lineWidth=_.cursorLineWidth,l.setLineDash(_.cursorLineDash),l.stroke(),l.setLineDash(Pt),l.restore())},[a,_]),ne=d.useCallback(()=>{te();const l=fe.current;if(!l)return;const f=l.getContext("2d");if(!f)return;const b=Math.max(1,window.devicePixelRatio||1),S=l.width/b,R=l.height/b;if(f.setTransform(1,0,0,1,0,0),f.clearRect(0,0,l.width,l.height),f.setTransform(b,0,0,b,0,0),Ne.length>0)for(const L of Ne){const{region:V,polygons:Z,regionIndex:q,regionKey:me}=L,Xe=Un(J,me)?"active":Un(k,me)?"hover":"default";let ge=Xe==="active"?P:Xe==="hover"?A:oe;if(Y){const re=Y({region:V,regionId:me,regionIndex:q,state:Xe});ge=it(ge,re||void 0)}for(const re of Z){const pe=F(re.outer);pe.length>=4&&Ge(f,pe,ge,!0,!1);for(const Te of re.holes){const Ee=F(Te);Ee.length>=4&&Ge(f,Ee,ge,!0,!1)}}}if(Ke.length>0)for(const L of Ke)for(const V of L.polygons){const Z=F(V.outer);Z.length>=4&&Ge(f,Z,v,!0,!1);for(const q of V.holes){const me=F(q);me.length>=4&&Ge(f,me,v,!0,!1)}}if(Array.isArray(C)&&C.length>0){const L=!!globalThis.__OPEN_PLANT_DEBUG_OVERLAY__,V=F(Le([[0,0],[e,0],[e,n],[0,n]]));for(let Z=0;Z<C.length;Z+=1){const q=C[Z];if(!q?.coordinates?.length||q.visible===!1)continue;const me=q.closed??ki(q.coordinates),Xe=Fn(q.coordinates,me);if(q.invertedFill?.fillColor){const re=[],pe=Fn(q.coordinates,!0);for(const Te of pe){const Ee=F(Te);Ee.length>=4&&re.push(Ee)}if(L){const Te=String(q.id??Z),Ee=`${V.length}|${pe.length}|${re.length}|${q.invertedFill.fillColor}`;Ze.current.get(Te)!==Ee&&(Ze.current.set(Te,Ee),console.debug("[open-plant] invertedFill",{id:q.id??Z,outerRingPoints:V.length,sourceRingCount:pe.length,holeRingCount:re.length,fillColor:q.invertedFill.fillColor}))}Xi(f,V,re,q.invertedFill.fillColor)}if(Xe.length===0)continue;const ge=it(oe,q.stroke??q.strokeStyle);for(const re of Xe){const pe=F(re);pe.length<2||Ge(f,pe,ge,me,q.fill??!1)}}}if(W)if(t==="brush")ie(f),D(f);else{const L=le();if(L.length>0)if(t==="freehand"){const V=F(L);V.length>=2&&Ge(f,V,oe,!1,!1),V.length>=3&&Ge(f,F(Le(L)),oe,!0,!0)}else{const V=F(L);V.length>=4&&Ge(f,V,oe,!0,!0)}}if(Ne.length>0)for(const L of Ne){if(!L.region.label)continue;const V=Gi(L.polygons);if(!V)continue;const Z=ot(a.current?.worldToScreen(V[0],V[1])??[]);Z&&qi(f,L.region.label,Z,S,R,K)}},[W,t,le,ie,D,te,F,e,n,a,Ne,C,k,J,oe,A,P,Ke,v,Y,K]),U=d.useCallback(()=>{$e.current||($e.current=!0,requestAnimationFrame(()=>{$e.current=!1,ne()}))},[ne]),se=d.useCallback((l=!1)=>{const f=be.current,b=fe.current;if(b&&f.pointerId!==null&&b.hasPointerCapture(f.pointerId))try{b.releasePointerCapture(f.pointerId)}catch{}f.isDrawing=!1,f.pointerId=null,f.start=null,f.current=null,f.points=[],f.screenPoints=[],f.stampCenter=null,l||(f.cursor=null,f.cursorScreen=null)},[]),we=d.useCallback(l=>{const f=a.current;if(!f||e<=0||n<=0)return null;const b=ot(f.screenToWorld(l.clientX,l.clientY));return b?bt(b,e,n):null},[a,e,n]),Se=d.useCallback(l=>{const f=fe.current;if(!f)return null;const b=f.getBoundingClientRect(),S=Oe(l.clientX-b.left,0,b.width),R=Oe(l.clientY-b.top,0,b.height);return!Number.isFinite(S)||!Number.isFinite(R)?null:[S,R]},[]),Me=d.useCallback(()=>{const l=be.current;if(!l.isDrawing){se(!0),U();return}let f=[];if(t==="freehand")l.points.length>=ui&&(f=Le(l.points));else if(t==="rectangle")f=Xt(l.start,l.current);else if(t==="circular")f=Yt(l.start,l.current);else if(t==="brush"){const b=l.points[l.points.length-1]??l.current??l.start;if(_.clickSelectRoi&&b&&l.points.length<=1&&u?.(b)){se(!0),U();return}const S=_.edgeDetail,R=Math.max(Pi,_.radius*2/(Ci*S)),L=l.screenPoints.length>0?l.screenPoints:F(l.points),V=Qr(L,{radius:_.radius,minRasterStep:R,circleSides:Math.max(24,Math.round(64*S)),simplifyTolerance:R*.25,smoothingPasses:_.edgeSmoothing}),Z=[];for(const q of V){const me=he(q);me&&Z.push(me)}f=Le(Z)}(t==="freehand"||t==="rectangle"||t==="circular"||t==="brush")&&_n(f)&&c&&c({tool:t,intent:t==="brush"?"brush":"roi",coordinates:f,bbox:In(f),areaPx:Wt(f)}),se(!0),U()},[t,c,se,U,F,he,_.radius,_.edgeDetail,_.edgeSmoothing,_.clickSelectRoi,u]),ye=d.useCallback((l,f)=>{const b=Q(l,f);if(!_n(b))return;const S=l==="stamp-rectangle-4096px"?"patch":"roi",R={tool:l,intent:S,coordinates:b,bbox:In(b),areaPx:Wt(b)};c?.(R),S==="patch"&&h&&h(R)},[Q,c,h]),ce=d.useCallback((l,f,b)=>{const S=Cn*Cn,R=l.screenPoints[l.screenPoints.length-1];if(!R){l.points.push(f),l.screenPoints.push(b),l.current=f;return}const L=b[0]-R[0],V=b[1]-R[1];L*L+V*V>=S?(l.points.push(f),l.screenPoints.push(b)):(l.points[l.points.length-1]=f,l.screenPoints[l.screenPoints.length-1]=b),l.current=f},[]),tt=d.useCallback(l=>{if(!W||t==="cursor"||l.button!==0)return;const f=we(l);if(!f)return;const b=t==="brush"?Se(l):null;if(t==="brush"&&!b)return;if(l.preventDefault(),l.stopPropagation(),pt(t)){const L=be.current;L.stampCenter=f,ye(t,f),U();return}const S=fe.current;S&&S.setPointerCapture(l.pointerId);const R=be.current;R.isDrawing=!0,R.pointerId=l.pointerId,R.start=f,R.current=f,R.cursor=f,R.cursorScreen=b,R.points=t==="freehand"||t==="brush"?[f]:[],R.screenPoints=t==="brush"&&b?[b]:[],U()},[W,t,we,Se,ye,U]),ke=d.useCallback(l=>{if(!W||t==="cursor")return;const f=we(l);if(!f)return;if(pt(t)){const S=be.current;S.stampCenter=f,l.preventDefault(),l.stopPropagation(),U();return}const b=be.current;if(t==="brush"){const S=Se(l);if(!S)return;if(b.cursor=f,b.cursorScreen=S,!b.isDrawing||b.pointerId!==l.pointerId){U();return}l.preventDefault(),l.stopPropagation(),ce(b,f,S),U();return}if(!(!b.isDrawing||b.pointerId!==l.pointerId)){if(l.preventDefault(),l.stopPropagation(),t==="freehand"){const S=a.current,R=Math.max(1e-6,S?.getViewState?.().zoom??1),L=li/R,V=L*L,Z=b.points[b.points.length-1];if(!Z)b.points.push(f);else{const q=f[0]-Z[0],me=f[1]-Z[1];q*q+me*me>=V&&b.points.push(f)}}else b.current=f;U()}},[W,t,we,Se,U,a,ce]),Fe=d.useCallback(l=>{const f=be.current;if(!f.isDrawing||f.pointerId!==l.pointerId)return;l.preventDefault(),l.stopPropagation();const b=we(l),S=t==="brush"?Se(l):null;b&&(f.cursor=b,t==="brush"?S&&(f.cursorScreen=S,ce(f,b,S)):f.current=b);const R=fe.current;if(R&&R.hasPointerCapture(l.pointerId))try{R.releasePointerCapture(l.pointerId)}catch{}Me()},[Me,we,Se,t,ce]),X=d.useCallback(()=>{const l=be.current;let f=!1;t==="brush"&&!l.isDrawing&&l.cursor&&(l.cursor=null,l.cursorScreen=null,f=!0),pt(t)&&l.stampCenter&&(l.stampCenter=null,f=!0),f&&U()},[t,U]);return d.useEffect(()=>{te(),U();const l=fe.current;if(!l)return;const f=new ResizeObserver(()=>{te(),U()});return f.observe(l),()=>{f.disconnect()}},[te,U]),d.useEffect(()=>{W||se(),U()},[W,U,se]),d.useEffect(()=>{Je.current!==t&&(Je.current=t,se(),U())},[t,se,U]),d.useEffect(()=>{U()},[m,Ie,C,U]),d.useEffect(()=>{if(j)return j.current=U,()=>{j.current===U&&(j.current=null)}},[j,U]),d.useEffect(()=>{if(!W)return;const l=f=>{f.key==="Escape"&&(se(),U())};return window.addEventListener("keydown",l),()=>{window.removeEventListener("keydown",l)}},[W,se,U]),Be.jsx("canvas",{ref:fe,className:$,style:Re,onPointerDown:tt,onPointerMove:ke,onPointerUp:Fe,onPointerCancel:Fe,onPointerLeave:X,onContextMenu:l=>{W&&l.preventDefault()},onWheel:l=>{if(!W)return;const f=fe.current,b=a.current;if(!f||typeof b?.zoomBy!="function")return;l.preventDefault(),l.stopPropagation();const S=f.getBoundingClientRect(),R=l.clientX-S.left,L=l.clientY-S.top;b.zoomBy(l.deltaY<0?di:mi,R,L),U()}})}function zn(t){return String(t??"").replace(/\/+$/,"")}function tr(t){const e=String(t??"");return e.startsWith("/")?e:`/${e}`}function Hi(t){const e=zn(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=zn(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 $i(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("이미지 메타데이터가 불완전합니다. width/height/tileSize/path 확인 필요");const h=Array.isArray(t?.terms)?t.terms.map(g=>({termId:String(g?.termId??""),termName:String(g?.termName??""),termColor:String(g?.termColor??"")})):[],y=tr(u),m=Hi(e),p=r?(g,x,T)=>`${m}${y}/${g}/${T}_${x}.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:h,tileUrlBuilder:p}}function Qt(t,e,n,r){if(t.tileUrlBuilder)return t.tileUrlBuilder(e,n,r);const i=tr(t.tilePath);return`${t.tileBaseUrl}${i}/${e}/${r}_${n}.webp`}const xe={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 Nn(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))),h=c*n+(c-1)*r,y=u/Math.max(1e-6,h),m=n*y,p=r*y;t.beginPath(),t.moveTo(s[0],s[1]),t.lineTo(a[0],a[1]),t.setLineDash([m,p]),t.lineDashOffset=0,t.stroke()}t.setLineDash([]),t.lineDashOffset=0}}function et(t,e,n=1){return typeof t!="number"||!Number.isFinite(t)?e:Math.max(n,t)}function yt(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 Zi={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 nr({source:t,projectorRef:e,authToken:n="",options:r,invalidateRef:i,className:o,style:s}){const a=d.useRef(null),u=d.useRef(null),c=d.useRef(null),h=d.useRef({active:!1,pointerId:null}),y=d.useRef(null),m=d.useRef(!1),p=et(r?.width,xe.width,64),g=et(r?.height,xe.height,48),x=d.useMemo(()=>{const A=Math.max(1,t.width),P=Math.max(1,t.height),v=A/P,K=p/g;let G,_;return v>K?(G=p,_=p/v):(_=g,G=g*v),{x:(p-G)/2,y:(g-_)/2,w:G,h:_}},[t.width,t.height,p,g]),T=et(r?.margin,xe.margin,0),B=et(r?.borderRadius,xe.borderRadius,0),z=et(r?.borderWidth,xe.borderWidth,0),N=Math.max(1,Math.round(et(r?.maxThumbnailTiles,xe.maxThumbnailTiles,1))),Y=r?.backgroundColor||xe.backgroundColor,C=r?.borderColor||xe.borderColor,k=r?.viewportBorderColor||xe.viewportBorderColor,J=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:xe.viewportBorderStyle,ue=r?.viewportFillColor??xe.viewportFillColor,j=r?.interactive??xe.interactive,$=r?.showThumbnail??xe.showThumbnail,Ce=r?.position||xe.position,fe=r?.onClose,$e=r?.closeIcon,Ze=r?.closeButtonStyle,Je=d.useMemo(()=>{const A={};return Ce==="top-left"||Ce==="bottom-left"?A.left=T:A.right=T,Ce==="top-left"||Ce==="top-right"?A.top=T:A.bottom=T,{position:"absolute",...A,width:p,height:g,borderRadius:B,overflow:"hidden",zIndex:4,pointerEvents:j?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[T,Ce,p,g,B,j,s]),be=d.useCallback(()=>{const A=a.current;if(!A)return;const P=A.getContext("2d");if(!P)return;const v=p,K=g,G=Math.max(1,window.devicePixelRatio||1),_=Math.max(1,Math.round(v*G)),Re=Math.max(1,Math.round(K*G));(A.width!==_||A.height!==Re)&&(A.width=_,A.height=Re),P.setTransform(1,0,0,1,0,0),P.clearRect(0,0,A.width,A.height),P.setTransform(G,0,0,G,0,0),P.fillStyle=Y,P.fillRect(0,0,v,K);const{x:te,y:F,w:he,h:de}=x,Q=u.current;Q&&P.drawImage(Q,te,F,he,de),P.strokeStyle=C,P.lineWidth=z,P.strokeRect(z*.5,z*.5,v-z,K-z);const le=e.current,ie=le?.getViewBounds?.(),D=le?.getViewCorners?.(),ne=yt(ie)?ie:yt(c.current)?c.current:null;if(!ne)return;c.current=ne;const U=he/Math.max(1,t.width),se=de/Math.max(1,t.height),we=Array.isArray(D)&&D.length>=4&&D.every(X=>Array.isArray(X)&&X.length>=2&&Number.isFinite(X[0])&&Number.isFinite(X[1]))?D:null,Se=J==="dash";if(we){const X=[];for(let l=0;l<we.length;l+=1){const f=we[l];X.push([ee(te+f[0]*U,te,te+he),ee(F+f[1]*se,F,F+de)])}P.beginPath();for(let l=0;l<X.length;l+=1)l===0?P.moveTo(X[l][0],X[l][1]):P.lineTo(X[l][0],X[l][1]);P.closePath(),P.fillStyle=ue,P.fill(),P.strokeStyle=k,P.lineWidth=2.25,Se?Nn(P,X,4,3):P.stroke();return}const Me=ee(te+ne[0]*U,te,te+he),ye=ee(F+ne[1]*se,F,F+de),ce=ee(te+ne[2]*U,te,te+he),tt=ee(F+ne[3]*se,F,F+de),ke=Math.max(1,ce-Me),Fe=Math.max(1,tt-ye);if(P.fillStyle=ue,P.fillRect(Me,ye,ke,Fe),P.strokeStyle=k,P.lineWidth=2.25,Se){const X=[[Me+.5,ye+.5],[Me+.5+Math.max(1,ke-1),ye+.5],[Me+.5+Math.max(1,ke-1),ye+.5+Math.max(1,Fe-1)],[Me+.5,ye+.5+Math.max(1,Fe-1)]];Nn(P,X,4,3)}else P.strokeRect(Me+.5,ye+.5,Math.max(1,ke-1),Math.max(1,Fe-1))},[p,g,x,Y,C,z,e,t.width,t.height,ue,k,J]),W=d.useCallback(()=>{m.current||(m.current=!0,y.current=requestAnimationFrame(()=>{m.current=!1,y.current=null,be()}))},[be]),Ie=d.useCallback((A,P)=>{const v=a.current;if(!v)return null;const K=v.getBoundingClientRect();if(!K.width||!K.height)return null;const G=K.width/p,_=K.height/g,Re=x.x*G,te=x.y*_,F=x.w*G,he=x.h*_,de=ee((A-K.left-Re)/F,0,1),Q=ee((P-K.top-te)/he,0,1);return[de*t.width,Q*t.height]},[t.width,t.height,p,g,x]),Ae=d.useCallback((A,P)=>{const v=e.current;if(!v)return;if(v.setViewCenter){v.setViewCenter(A,P),W();return}const K=v.getViewBounds?.(),G=yt(K)?K:yt(c.current)?c.current:null;if(!G)return;const _=Math.max(1e-6,G[2]-G[0]),Re=Math.max(1e-6,G[3]-G[1]);v.setViewState({offsetX:A-_*.5,offsetY:P-Re*.5}),W()},[e,W]),Ne=d.useCallback(A=>{if(!j||A.button!==0)return;const P=a.current;if(!P)return;const v=Ie(A.clientX,A.clientY);v&&(A.preventDefault(),A.stopPropagation(),P.setPointerCapture(A.pointerId),h.current={active:!0,pointerId:A.pointerId},Ae(v[0],v[1]))},[j,Ie,Ae]),Ke=d.useCallback(A=>{const P=h.current;if(!P.active||P.pointerId!==A.pointerId)return;const v=Ie(A.clientX,A.clientY);v&&(A.preventDefault(),A.stopPropagation(),Ae(v[0],v[1]))},[Ie,Ae]),oe=d.useCallback(A=>{const P=h.current;if(!P.active||P.pointerId!==A.pointerId)return;const v=a.current;if(v&&v.hasPointerCapture(A.pointerId))try{v.releasePointerCapture(A.pointerId)}catch{}h.current={active:!1,pointerId:null},W()},[W]);return d.useEffect(()=>{let A=!1;u.current=null,W();const P=0,v=2**(t.maxTierZoom-P),K=Math.ceil(t.width/v),G=Math.ceil(t.height/v),_=Math.max(1,Math.ceil(K/t.tileSize)),Re=Math.max(1,Math.ceil(G/t.tileSize)),te=_*Re;if(!$||te>N)return;const F=document.createElement("canvas");F.width=Math.max(1,Math.round(x.w)),F.height=Math.max(1,Math.round(x.h));const he=F.getContext("2d");if(!he)return;he.fillStyle=Y,he.fillRect(0,0,F.width,F.height);const de=[];for(let Q=0;Q<Re;Q+=1)for(let le=0;le<_;le+=1){const ie=le*t.tileSize*v,D=Q*t.tileSize*v,ne=Math.min((le+1)*t.tileSize,K)*v,U=Math.min((Q+1)*t.tileSize,G)*v;de.push({url:Qt(t,P,le,Q),bounds:[ie,D,ne,U]})}return Promise.allSettled(de.map(async Q=>{const le=!!n,ie=await fetch(Q.url,{headers:le?{Authorization:n}:void 0});if(!ie.ok)throw new Error(`HTTP ${ie.status}`);const D=await createImageBitmap(await ie.blob());return{tile:Q,bitmap:D}})).then(Q=>{if(A){for(const D of Q)D.status==="fulfilled"&&D.value.bitmap.close();return}const le=F.width/Math.max(1,t.width),ie=F.height/Math.max(1,t.height);for(const D of Q){if(D.status!=="fulfilled")continue;const{tile:{bounds:ne},bitmap:U}=D.value,se=ne[0]*le,we=ne[1]*ie,Se=Math.max(1,(ne[2]-ne[0])*le),Me=Math.max(1,(ne[3]-ne[1])*ie);he.drawImage(U,se,we,Se,Me),U.close()}u.current=F,W()}),()=>{A=!0}},[t,n,x,Y,$,N,W]),d.useEffect(()=>{W()},[W]),d.useEffect(()=>{if(i)return i.current=W,()=>{i.current===W&&(i.current=null)}},[i,W]),d.useEffect(()=>()=>{h.current={active:!1,pointerId:null},y.current!==null&&(cancelAnimationFrame(y.current),y.current=null),m.current=!1},[]),Be.jsxs("div",{className:o,style:Je,children:[Be.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:Ne,onPointerMove:Ke,onPointerUp:oe,onPointerCancel:oe,onContextMenu:A=>{A.preventDefault()},onWheel:A=>{A.preventDefault(),A.stopPropagation()}}),fe&&Be.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:A=>{A.stopPropagation(),fe()},style:Ze?{...Ze}:{...Zi},children:$e??"×"})]})}function Ki({imageWidth:t,imageHeight:e,tiles:n,viewState:r,className:i,style:o}){const s=d.useRef(null),a=d.useRef(null),u=d.useMemo(()=>({width:"100%",height:"100%",display:"block",...o}),[o]);return d.useEffect(()=>{const c=s.current;if(!c)return;const h=new Wn({canvas:c,imageWidth:t,imageHeight:e,initialViewState:r});return a.current=h,h.setTiles(n),()=>{h.destroy(),a.current=null}},[t,e]),d.useEffect(()=>{const c=a.current;c&&c.setTiles(n)},[n]),d.useEffect(()=>{const c=a.current;!c||!r||c.setViewState(r)},[r]),Be.jsx("canvas",{ref:s,className:i,style:u})}function rr(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 ut(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return null;const n=lt(e??[]);if(n.length===0){const g={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return t.fillModes instanceof Uint8Array&&(g.fillModes=new Uint8Array(0)),t.ids instanceof Uint32Array&&(g.ids=new Uint32Array(0)),g}const r=rr(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),h=s?new Uint8Array(r):null,y=a?new Uint32Array(r):null;let m=0;for(let g=0;g<r;g+=1){const x=i[g*2],T=i[g*2+1];Et(x,T,n)&&(u[m*2]=x,u[m*2+1]=T,c[m]=o[g],h&&(h[m]=s[g]),y&&(y[m]=a[g]),m+=1)}const p={count:m,positions:u.subarray(0,m*2),paletteIndices:c.subarray(0,m)};return h&&(p.fillModes=h.subarray(0,m)),y&&(p.ids=y.subarray(0,m)),p}function ir(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return new Uint32Array(0);const n=lt(e??[]);if(n.length===0)return new Uint32Array(0);const r=rr(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];Et(u,c,n)&&(o[s]=a,s+=1)}return o.subarray(0,s)}let wt=null;const ji=`
33
33
  struct Params {
34
34
  pointCount: u32,
35
35
  boundsCount: u32,
@@ -60,7 +60,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
60
60
  }
61
61
  outputMask[i] = inside;
62
62
  }
63
- `;function ji(){if(typeof navigator>"u")return!1;const t=navigator;return typeof t.gpu=="object"&&t.gpu!==null}function or(){if(!ji())return null;const e=navigator.gpu;if(!e||typeof e!="object")return null;const n=e;return typeof n.requestAdapter!="function"?null:n}const St=globalThis.GPUShaderStage?.COMPUTE??4,kt=globalThis.GPUBufferUsage?.STORAGE??128,xt=globalThis.GPUBufferUsage?.COPY_DST??8,Ji=globalThis.GPUBufferUsage?.COPY_SRC??4,Qi=globalThis.GPUBufferUsage?.UNIFORM??64,eo=globalThis.GPUBufferUsage?.MAP_READ??1,to=globalThis.GPUMapMode?.READ??1;async function no(){const t=or();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 ro(){return Mt||(Mt=(async()=>{const t=or();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:St,buffer:{type:"read-only-storage"}},{binding:1,visibility:St,buffer:{type:"read-only-storage"}},{binding:2,visibility:St,buffer:{type:"storage"}},{binding:3,visibility:St,buffer:{type:"uniform"}}]}),i=n.createComputePipeline({layout:n.createPipelineLayout({bindGroupLayouts:[r]}),compute:{module:n.createShaderModule({code:Ki}),entryPoint:"main"}});return{device:n,pipeline:i,bindGroupLayout:r}})(),Mt)}function At(t,e){return Math.ceil(t/e)*e}async function sr(t,e,n){const r=await ro();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 a=Math.min(i,Math.floor(t.length/2));if(a===0)return new Uint32Array(0);const s=a*2*Float32Array.BYTES_PER_ELEMENT,u=o*4*Float32Array.BYTES_PER_ELEMENT,c=a*Uint32Array.BYTES_PER_ELEMENT,h=Number(r.device.limits.maxStorageBufferBindingSize);if(s>h||u>h||c>h)return null;const b=r.device.createBuffer({size:At(s,4),usage:kt|xt}),m=r.device.createBuffer({size:At(u,4),usage:kt|xt}),g=r.device.createBuffer({size:At(c,4),usage:kt|Ji}),y=r.device.createBuffer({size:16,usage:Qi|xt}),x=r.device.createBuffer({size:At(c,4),usage:xt|eo});r.device.queue.writeBuffer(b,0,t.buffer,t.byteOffset,s),r.device.queue.writeBuffer(m,0,n.buffer,n.byteOffset,u),r.device.queue.writeBuffer(y,0,new Uint32Array([a,o,0,0]));const E=r.device.createBindGroup({layout:r.bindGroupLayout,entries:[{binding:0,resource:{buffer:b}},{binding:1,resource:{buffer:m}},{binding:2,resource:{buffer:g}},{binding:3,resource:{buffer:y}}]}),_=r.device.createCommandEncoder(),X=_.beginComputePass();X.setPipeline(r.pipeline),X.setBindGroup(0,E),X.dispatchWorkgroups(Math.ceil(a/256)),X.end(),_.copyBufferToBuffer(g,0,x,0,c),r.device.queue.submit([_.finish()]),await x.mapAsync(to);const F=x.getMappedRange(),W=new Uint32Array(F.slice(0));return x.unmap(),b.destroy(),m.destroy(),g.destroy(),y.destroy(),x.destroy(),W}function Ne(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}async function ar(t,e,n={}){const r=Ne(),i=n.bridgeToDraw===!0;if(!t||!t.count||!t.positions||!t.paletteIndices)return{data:null,meta:{mode:"hybrid-webgpu",durationMs:Ne()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}};const o=ut(e??[]);if(o.length===0){const P={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return t.fillModes instanceof Uint8Array&&(P.fillModes=new Uint8Array(0)),t.ids instanceof Uint32Array&&(P.ids=new Uint32Array(0)),{data:P,meta:{mode:"hybrid-webgpu",durationMs:Ne()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const a=t.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER,s=Math.max(0,Math.min(t.count,Math.floor(t.positions.length/2),t.paletteIndices.length,a)),u=t.fillModes instanceof Uint8Array&&t.fillModes.length>=s?t.fillModes:null,c=t.ids instanceof Uint32Array&&t.ids.length>=s?t.ids:null;if(s===0){const P={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return u&&(P.fillModes=new Uint8Array(0)),c&&(P.ids=new Uint32Array(0)),{data:P,meta:{mode:"hybrid-webgpu",durationMs:Ne()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const h=new Float32Array(o.length*4);for(let P=0;P<o.length;P+=1){const z=P*4,Z=o[P];h[z]=Z.minX,h[z+1]=Z.minY,h[z+2]=Z.maxX,h[z+3]=Z.maxY}let b=null,m=!1;try{b=await sr(t.positions,s,h),m=!!b}catch{b=null,m=!1}if(!b)return{data:at(t,e),meta:{mode:"hybrid-webgpu",durationMs:Ne()-r,usedWebGpu:!1,candidateCount:s,bridgedToDraw:!1}};let g=0;for(let P=0;P<s;P+=1)b[P]===1&&(g+=1);const y=new Uint32Array(g);if(g>0){let P=0;for(let z=0;z<s;z+=1)b[z]===1&&(y[P]=z,P+=1)}if(g===0){if(i){const z={count:s,positions:t.positions.subarray(0,s*2),paletteIndices:t.paletteIndices.subarray(0,s),drawIndices:new Uint32Array(0)};return u&&(z.fillModes=u.subarray(0,s)),c&&(z.ids=c.subarray(0,s)),{data:z,meta:{mode:"hybrid-webgpu",durationMs:Ne()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!0}}}const P={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return u&&(P.fillModes=new Uint8Array(0)),c&&(P.ids=new Uint32Array(0)),{data:P,meta:{mode:"hybrid-webgpu",durationMs:Ne()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const P=new Uint32Array(g);let z=0;for(let ee=0;ee<g;ee+=1){const N=y[ee]??0,ve=t.positions[N*2],Te=t.positions[N*2+1];Pt(ve,Te,o)&&(P[z]=N,z+=1)}const Z={count:s,positions:t.positions.subarray(0,s*2),paletteIndices:t.paletteIndices.subarray(0,s),drawIndices:P.subarray(0,z)};return u&&(Z.fillModes=u.subarray(0,s)),c&&(Z.ids=c.subarray(0,s)),{data:Z,meta:{mode:"hybrid-webgpu",durationMs:Ne()-r,usedWebGpu:!0,candidateCount:g,bridgedToDraw:!0}}}const x=new Float32Array(g*2),E=new Uint16Array(g),_=u?new Uint8Array(g):null,X=c?new Uint32Array(g):null;let F=0;for(let P=0;P<g;P+=1){const z=y[P]??0,Z=t.positions[z*2],ee=t.positions[z*2+1];Pt(Z,ee,o)&&(x[F*2]=Z,x[F*2+1]=ee,E[F]=t.paletteIndices[z],_&&(_[F]=u[z]),X&&(X[F]=c[z]),F+=1)}const W={count:F,positions:x.subarray(0,F*2),paletteIndices:E.subarray(0,F)};return _&&(W.fillModes=_.subarray(0,F)),X&&(W.ids=X.subarray(0,F)),{data:W,meta:{mode:"hybrid-webgpu",durationMs:Ne()-r,usedWebGpu:!0,candidateCount:g,bridgedToDraw:!1}}}let Re=null,qt=!0,ur=1;const $e=new Map;function He(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function lr(){if(!qt)return null;if(Re)return Re;try{const t=new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/roi-clip-worker-BDVQwN2T.js").href:new URL("assets/roi-clip-worker-BDVQwN2T.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:Bt&&Bt.tagName.toUpperCase()==="SCRIPT"&&Bt.src||new URL("index.cjs",document.baseURI).href),{type:"module"});return t.addEventListener("message",tn),t.addEventListener("error",nn),Re=t,t}catch{return qt=!1,null}}function tn(t){const e=t.data;if(!e)return;const n=$e.get(e.id);if(!n)return;if($e.delete(e.id),e.type==="roi-clip-failure"){n.reject(new Error(e.error||"worker clip failed"));return}if(e.type==="roi-clip-index-success"){if(n.kind!=="index"){n.reject(new Error("worker response mismatch: expected point data result"));return}const c=Math.max(0,Math.floor(e.count)),h=new Uint32Array(e.indices).subarray(0,c);n.resolve({indices:h,meta:{mode:"worker",durationMs:Number.isFinite(e.durationMs)?e.durationMs:He()-n.startMs}});return}if(n.kind!=="data"){n.reject(new Error("worker response mismatch: expected index result"));return}const r=Math.max(0,Math.floor(e.count)),i=new Float32Array(e.positions),o=new Uint16Array(e.paletteIndices),a=e.fillModes?new Uint8Array(e.fillModes):null,s=e.ids?new Uint32Array(e.ids):null,u={count:r,positions:i.subarray(0,r*2),paletteIndices:o.subarray(0,r)};a&&(u.fillModes=a.subarray(0,r)),s&&(u.ids=s.subarray(0,r)),n.resolve({data:u,meta:{mode:"worker",durationMs:Number.isFinite(e.durationMs)?e.durationMs:He()-n.startMs}})}function nn(){qt=!1,Re&&(Re.removeEventListener("message",tn),Re.removeEventListener("error",nn),Re.terminate(),Re=null);for(const[,t]of $e)t.reject(new Error("worker crashed"));$e.clear()}function io(){if(Re){Re.removeEventListener("message",tn),Re.removeEventListener("error",nn),Re.terminate(),Re=null;for(const[,t]of $e)t.reject(new Error("worker terminated"));$e.clear()}}async function cr(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return{data:null,meta:{mode:"worker",durationMs:0}};const n=lr();if(!n){const b=He();return{data:at(t,e),meta:{mode:"sync",durationMs:He()-b}}}const r=t.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER,i=Math.max(0,Math.min(t.count,Math.floor(t.positions.length/2),t.paletteIndices.length,r)),o=t.positions.slice(0,i*2),a=t.paletteIndices.slice(0,i),s=t.fillModes instanceof Uint8Array&&t.fillModes.length>=i?t.fillModes.slice(0,i):null,u=t.ids instanceof Uint32Array&&t.ids.length>=i?t.ids.slice(0,i):null,c=ur++,h=He();return new Promise((b,m)=>{$e.set(c,{kind:"data",resolve:b,reject:m,startMs:h});const g={type:"roi-clip-request",id:c,count:i,positions:o.buffer,paletteIndices:a.buffer,fillModes:s?.buffer,ids:u?.buffer,polygons:e??[]},y=[o.buffer,a.buffer];s&&y.push(s.buffer),u&&y.push(u.buffer),n.postMessage(g,y)})}async function oo(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return{indices:new Uint32Array(0),meta:{mode:"worker",durationMs:0}};const n=lr();if(!n){const u=He();return{indices:ir(t,e),meta:{mode:"sync",durationMs:He()-u}}}const r=t.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER,i=Math.max(0,Math.min(t.count,Math.floor(t.positions.length/2),t.paletteIndices.length,r)),o=t.positions.slice(0,i*2),a=ur++,s=He();return new Promise((u,c)=>{$e.set(a,{kind:"index",resolve:u,reject:c,startMs:s});const h={type:"roi-clip-index-request",id:a,count:i,positions:o.buffer,polygons:e??[]};n.postMessage(h,[o.buffer])})}function so(t){const e=[];for(let n=0;n<t.length;n+=1){const r=t[n],i=ut([r?.coordinates]);if(i.length===0)continue;let o=0;for(const a of i)o+=a.area;e.push({regionId:r.id??n,regionIndex:n,polygons:i,area:Math.max(1e-6,o)})}return e}function ao(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 fr(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 m=t.drawIndices;let g=m.length;for(let y=0;y<m.length;y+=1)m[y]<r||(g-=1);if(g===m.length)i=m;else if(g>0){const y=new Uint32Array(g);let x=0;for(let E=0;E<m.length;E+=1){const _=m[E];_>=r||(y[x]=_,x+=1)}i=y}else i=new Uint32Array(0)}const o=i?i.length:r,a=so(e??[]);if(!t||o===0||a.length===0)return{groups:[],inputPointCount:o,pointsInsideAnyRegion:0,unmatchedPointCount:o};const s=new Map,u=new Map;let c=0;for(let m=0;m<o;m+=1){const g=i?i[m]:m,y=t.positions[g*2],x=t.positions[g*2+1];let E=null;for(const F of a){let W=!1;for(const P of F.polygons)if(jt(y,x,P)){W=!0;break}W&&(!E||F.area<E.area)&&(E=F)}if(!E)continue;c+=1;const _=t.paletteIndices[g]??0,X=s.get(E.regionIndex)??new Map;X.set(_,(X.get(_)??0)+1),s.set(E.regionIndex,X),u.set(E.regionIndex,(u.get(E.regionIndex)??0)+1)}const h=n.includeEmptyRegions??!1,b=[];for(const m of a){const g=u.get(m.regionIndex)??0;if(!h&&g<=0)continue;const y=s.get(m.regionIndex)??new Map,x=Array.from(y.entries()).map(([E,_])=>({termId:ao(E,n.paletteIndexToTermId),paletteIndex:E,count:_})).sort((E,_)=>_.count-E.count||E.paletteIndex-_.paletteIndex);b.push({regionId:m.regionId,regionIndex:m.regionIndex,totalCount:g,termCounts:x})}return{groups:b,inputPointCount:o,pointsInsideAnyRegion:c,unmatchedPointCount:Math.max(0,o-c)}}function Rt(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function uo(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 hr{constructor(e){M(this,"maxConcurrency");M(this,"maxRetries");M(this,"retryBaseDelayMs");M(this,"retryMaxDelayMs");M(this,"onTileLoad");M(this,"onTileError");M(this,"onStateChange");M(this,"authToken");M(this,"destroyed",!1);M(this,"queue",[]);M(this,"queuedByKey",new Map);M(this,"inflight",new Map);M(this,"visibleKeys",new Set);M(this,"timerId",null);M(this,"abortedCount",0);M(this,"retryCount",0);M(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 a=this.inflight.get(r.key);a&&(a.tile=r);continue}const i=this.queuedByKey.get(r.key);if(i){i.tile=r;continue}const o={tile:r,attempt:0,readyAt:Rt()};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-Rt());this.timerId=window.setTimeout(()=>{this.timerId=null,this.pump()},n)}takeNextReadyQueueItem(){if(this.queue.length===0)return null;const e=Rt(),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=uo(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 s=e.attempt+1,u=this.getRetryDelay(s),c={tile:e.tile,attempt:s,readyAt:Rt()+u},h=this.queuedByKey.get(e.tile.key);h?(h.tile=c.tile,h.readyAt=Math.min(h.readyAt,c.readyAt),h.attempt=Math.max(h.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&&(window.clearTimeout(this.timerId),this.timerId=null)}emitStateChange(){this.onStateChange?.(this.getSnapshot())}}const Dn=.35,Ht=.5,lo=256,$t=[{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}];class co{constructor(){M(this,"viewportWidth",1);M(this,"viewportHeight",1);M(this,"viewState",{zoom:1,offsetX:0,offsetY:0,rotationDeg:0})}setViewport(e,n){this.viewportWidth=Math.max(1,e),this.viewportHeight=Math.max(1,n)}getViewport(){return{width:this.viewportWidth,height:this.viewportHeight}}setViewState(e){typeof e.zoom=="number"&&(this.viewState.zoom=Math.max(1e-4,e.zoom)),typeof e.offsetX=="number"&&(this.viewState.offsetX=e.offsetX),typeof e.offsetY=="number"&&(this.viewState.offsetY=e.offsetY),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=this.viewState,i=Math.max(1e-6,r.zoom),[o,a]=this.getCenter(),s=(e-this.viewportWidth*.5)/i,u=(n-this.viewportHeight*.5)/i,c=st(r.rotationDeg),h=Math.cos(c),b=Math.sin(c);return[o+s*h-u*b,a+s*b+u*h]}worldToScreen(e,n){const r=this.viewState,i=Math.max(1e-6,r.zoom),[o,a]=this.getCenter(),s=e-o,u=n-a,c=st(r.rotationDeg),h=Math.cos(c),b=Math.sin(c),m=s*h+u*b,g=-s*b+u*h;return[this.viewportWidth*.5+m*i,this.viewportHeight*.5+g*i]}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,r]=this.getCenter(),i=st(this.viewState.rotationDeg),o=Math.cos(i),a=Math.sin(i),s=2*e*o/this.viewportWidth,u=2*e*a/this.viewportWidth,c=2*e*a/this.viewportHeight,h=-2*e*o/this.viewportHeight,b=-(s*n+u*r),m=-(c*n+h*r);return new Float32Array([s,c,0,u,h,0,b,m,1])}}function st(t){return t*Math.PI/180}function Xn(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function qe(t,e,n){const r=t.getUniformLocation(e,n);if(!r)throw new Error(`uniform location lookup failed: ${n}`);return r}function Et(t,e){return!t||!e?t===e:t.buffer===e.buffer&&t.byteOffset===e.byteOffset&&t.byteLength===e.byteLength}function Zt(t){return t.map(e=>({zoom:e.zoom,size:e.size}))}function Wn(t){if(!t)return Zt($t);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?Zt($t):Array.from(e.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function fo(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 ho(t,e){if(!Number.isFinite(t))return e[0]?.size??Ht;if(e.length===0)return Ht;if(e.length===1||t<=e[0].zoom)return e[0].size;for(let a=1;a<e.length;a+=1){const s=e[a-1],u=e[a];if(t>u.zoom)continue;const c=Math.max(1e-6,u.zoom-s.zoom),h=Q((t-s.zoom)/c,0,1);return s.size+(u.size-s.size)*h}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}const mo=.1,go=5;function Yn(t){return typeof t!="number"||!Number.isFinite(t)?1:Q(t,mo,go)}class dr{constructor(e,n,r={}){M(this,"canvas");M(this,"source");M(this,"gl");M(this,"camera",new co);M(this,"onViewStateChange");M(this,"onStats");M(this,"onTileError");M(this,"onContextLost");M(this,"onContextRestored");M(this,"resizeObserver");M(this,"tileProgram");M(this,"pointProgram");M(this,"tileScheduler");M(this,"authToken");M(this,"destroyed",!1);M(this,"contextLost",!1);M(this,"frame",null);M(this,"frameSerial",0);M(this,"dragging",!1);M(this,"interactionMode","none");M(this,"rotateLastAngleRad",null);M(this,"pointerId",null);M(this,"lastPointerX",0);M(this,"lastPointerY",0);M(this,"interactionLocked",!1);M(this,"ctrlDragRotate",!0);M(this,"rotationDragSensitivityDegPerPixel",.35);M(this,"maxCacheTiles");M(this,"fitZoom",1);M(this,"minZoom",1e-6);M(this,"maxZoom",1);M(this,"currentTier",0);M(this,"pointCount",0);M(this,"usePointIndices",!1);M(this,"pointBuffersDirty",!0);M(this,"pointPaletteSize",1);M(this,"pointSizeStops",Zt($t));M(this,"pointStrokeScale",1);M(this,"lastPointData",null);M(this,"lastPointPalette",null);M(this,"zeroFillModes",new Uint8Array(0));M(this,"cache",new Map);M(this,"boundPointerDown");M(this,"boundPointerMove");M(this,"boundPointerUp");M(this,"boundWheel");M(this,"boundDoubleClick");M(this,"boundContextMenu");M(this,"boundContextLost");M(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):Dn,this.pointSizeStops=Wn(r.pointSizeByZoom),this.pointStrokeScale=Yn(r.pointStrokeScale);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=this.initTileProgram(),this.pointProgram=this.initPointProgram(),this.tileScheduler=new hr({authToken:this.authToken,maxConcurrency:r.tileScheduler?.maxConcurrency??12,maxRetries:r.tileScheduler?.maxRetries??2,retryBaseDelayMs:r.tileScheduler?.retryBaseDelayMs??120,retryMaxDelayMs:r.tileScheduler?.retryMaxDelayMs??1200,onTileLoad:(o,a)=>this.handleTileLoaded(o,a),onTileError:(o,a,s)=>{this.onTileError?.({tile:o,error:a,attemptCount:s}),console.warn("tile load failed",o.url,a)}}),this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(e),this.boundPointerDown=o=>this.onPointerDown(o),this.boundPointerMove=o=>this.onPointerMove(o),this.boundPointerUp=o=>this.onPointerUp(o),this.boundWheel=o=>this.onWheel(o),this.boundDoubleClick=o=>this.onDoubleClick(o),this.boundContextMenu=o=>this.onContextMenu(o),this.boundContextLost=o=>this.onWebGlContextLost(o),this.boundContextRestored=o=>this.onWebGlContextRestored(o),e.addEventListener("pointerdown",this.boundPointerDown),e.addEventListener("pointermove",this.boundPointerMove),e.addEventListener("pointerup",this.boundPointerUp),e.addEventListener("pointercancel",this.boundPointerUp),e.addEventListener("wheel",this.boundWheel,{passive:!1}),e.addEventListener("dblclick",this.boundDoubleClick),e.addEventListener("contextmenu",this.boundContextMenu),e.addEventListener("webglcontextlost",this.boundContextLost),e.addEventListener("webglcontextrestored",this.boundContextRestored),this.fitToImage(),this.resize()}setAuthToken(e){this.authToken=String(e??""),this.tileScheduler.setAuthToken(this.authToken)}setViewState(e){const n={...e};typeof n.zoom=="number"&&(n.zoom=Q(n.zoom,this.minZoom,this.maxZoom)),this.camera.setViewState(n),this.clampViewState(),this.emitViewState(),this.requestRender()}getViewState(){return this.camera.getViewState()}setPointPalette(e){if(!e||e.length===0){this.lastPointPalette=null;return}if(this.lastPointPalette=new Uint8Array(e),this.contextLost||this.gl.isContextLost())return;const n=this.gl,r=Math.max(1,Math.floor(this.lastPointPalette.length/4));this.pointPaletteSize=r,n.bindTexture(n.TEXTURE_2D,this.pointProgram.paletteTexture),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,r,1,0,n.RGBA,n.UNSIGNED_BYTE,this.lastPointPalette),n.bindTexture(n.TEXTURE_2D,null),this.requestRender()}setPointData(e){if(!e||!e.count||!e.positions||!e.paletteIndices){this.lastPointData=null,this.pointCount=0,this.usePointIndices=!1,this.requestRender();return}const n=e.fillModes instanceof Uint8Array?e.fillModes:null,r=n!==null,i=Math.max(0,Math.min(e.count,Math.floor(e.positions.length/2),e.paletteIndices.length,r?n.length:Number.MAX_SAFE_INTEGER)),o=e.positions.subarray(0,i*2),a=e.paletteIndices.subarray(0,i),s=r?n.subarray(0,i):void 0,u=e.drawIndices instanceof Uint32Array,c=u?this.sanitizeDrawIndices(e.drawIndices,i):null,h=this.lastPointData,b=h?.fillModes instanceof Uint8Array;let m=this.pointBuffersDirty||!h||h.count!==i||!Et(h.positions,o)||!Et(h.paletteIndices,a)||b!==r||r&&(!h?.fillModes||!Et(h.fillModes,s)),g=this.pointBuffersDirty||u&&(!h?.drawIndices||!Et(h.drawIndices,c))||!u&&!!h?.drawIndices;if(this.lastPointData={count:i,positions:o,paletteIndices:a,fillModes:s,drawIndices:u?c??void 0:void 0},this.contextLost||this.gl.isContextLost())return;const y=this.gl;m&&(y.bindBuffer(y.ARRAY_BUFFER,this.pointProgram.posBuffer),y.bufferData(y.ARRAY_BUFFER,this.lastPointData.positions,y.STATIC_DRAW),y.bindBuffer(y.ARRAY_BUFFER,this.pointProgram.termBuffer),y.bufferData(y.ARRAY_BUFFER,this.lastPointData.paletteIndices,y.STATIC_DRAW),y.bindBuffer(y.ARRAY_BUFFER,this.pointProgram.fillModeBuffer),y.bufferData(y.ARRAY_BUFFER,this.lastPointData.fillModes??this.getZeroFillModes(i),y.STATIC_DRAW),y.bindBuffer(y.ARRAY_BUFFER,null)),u&&g&&(y.bindBuffer(y.ELEMENT_ARRAY_BUFFER,this.pointProgram.indexBuffer),y.bufferData(y.ELEMENT_ARRAY_BUFFER,c??new Uint32Array(0),y.DYNAMIC_DRAW),y.bindBuffer(y.ELEMENT_ARRAY_BUFFER,null)),this.usePointIndices=u,this.pointCount=u?c?.length??0:this.lastPointData.count,(m||g)&&(this.pointBuffersDirty=!1),this.requestRender()}sanitizeDrawIndices(e,n){if(n<=0||e.length===0)return new Uint32Array(0);let r=e.length;for(let a=0;a<e.length;a+=1)e[a]<n||(r-=1);if(r===e.length)return e;if(r<=0)return new Uint32Array(0);const i=new Uint32Array(r);let o=0;for(let a=0;a<e.length;a+=1){const s=e[a];s>=n||(i[o]=s,o+=1)}return i}getZeroFillModes(e){return e<=0?new Uint8Array(0):(this.zeroFillModes.length<e&&(this.zeroFillModes=new Uint8Array(e)),this.zeroFillModes.subarray(0,e))}setInteractionLock(e){const n=!!e;this.interactionLocked!==n&&(this.interactionLocked=n,n&&this.cancelDrag())}setPointSizeByZoom(e){const n=Wn(e);fo(this.pointSizeStops,n)||(this.pointSizeStops=n,this.requestRender())}setPointStrokeScale(e){const n=Yn(e);this.pointStrokeScale!==n&&(this.pointStrokeScale=n,this.requestRender())}cancelDrag(){if(this.pointerId!==null&&this.canvas.hasPointerCapture(this.pointerId))try{this.canvas.releasePointerCapture(this.pointerId)}catch{}this.dragging=!1,this.interactionMode="none",this.rotateLastAngleRad=null,this.pointerId=null,this.canvas.classList.remove("dragging")}getPointerAngleRad(e,n){const r=this.canvas.getBoundingClientRect(),i=e-r.left-r.width*.5,o=n-r.top-r.height*.5;return Math.atan2(o,i)}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){!Number.isFinite(e)||!Number.isFinite(n)||(this.camera.setCenter(e,n),this.clampViewState(),this.emitViewState(),this.requestRender())}getViewCorners(){return this.camera.getViewCorners()}resetRotation(){const e=this.camera.getViewState();Math.abs(e.rotationDeg)<1e-6||(this.camera.setViewState({rotationDeg:0}),this.clampViewState(),this.emitViewState(),this.requestRender())}getPointSizeByZoom(){const e=Math.max(1e-6,this.camera.getViewState().zoom),n=this.source.maxTierZoom+Math.log2(e),r=ho(n,this.pointSizeStops);return Q(r,Ht,lo)}fitToImage(){const e=this.canvas.getBoundingClientRect(),n=Math.max(1,e.width||1),r=Math.max(1,e.height||1),i=Math.min(n/this.source.width,r/this.source.height),o=Number.isFinite(i)&&i>0?i:1;this.fitZoom=o,this.minZoom=Math.max(this.fitZoom*.5,1e-6),this.maxZoom=Math.max(1,this.fitZoom*8),this.minZoom>this.maxZoom&&(this.minZoom=this.maxZoom);const a=n/o,s=r/o;this.camera.setViewState({zoom:Q(o,this.minZoom,this.maxZoom),offsetX:(this.source.width-a)*.5,offsetY:(this.source.height-s)*.5,rotationDeg:0}),this.clampViewState(),this.emitViewState(),this.requestRender()}zoomBy(e,n,r){const i=this.camera.getViewState(),o=Q(i.zoom*e,this.minZoom,this.maxZoom);if(o===i.zoom)return;const[a,s]=this.camera.screenToWorld(n,r);this.camera.setViewState({zoom:o});const u=this.camera.getViewport(),c=n-u.width*.5,h=r-u.height*.5,b=st(this.camera.getViewState().rotationDeg),m=Math.cos(b),g=Math.sin(b),y=c/o*m-h/o*g,x=c/o*g+h/o*m;this.camera.setCenter(a-y,s-x),this.clampViewState(),this.emitViewState(),this.requestRender()}clampViewState(){const e=this.getViewBounds(),n=Math.max(1e-6,e[2]-e[0]),r=Math.max(1e-6,e[3]-e[1]),i=n*.2,o=r*.2,[a,s]=this.camera.getCenter(),u=n*.5,c=r*.5,h=u-i,b=this.source.width-u+i,m=c-o,g=this.source.height-c+o,y=h<=b?Q(a,h,b):this.source.width*.5,x=m<=g?Q(s,m,g):this.source.height*.5;this.camera.setCenter(y,x)}emitViewState(){this.onViewStateChange?.(this.camera.getViewState())}selectTier(){const e=Math.max(1e-6,this.camera.getViewState().zoom),n=this.source.maxTierZoom+Math.log2(e);return Q(Math.floor(n),0,this.source.maxTierZoom)}getViewBounds(){const e=this.camera.getViewCorners();let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,s]of e)a<n&&(n=a),a>i&&(i=a),s<r&&(r=s),s>o&&(o=s);return[n,r,i,o]}intersectsBounds(e,n){return!(e[2]<=n[0]||e[0]>=n[2]||e[3]<=n[1]||e[1]>=n[3])}getVisibleTiles(){const e=this.selectTier();this.currentTier=e;const n=this.getViewBounds(),r=Math.pow(2,this.source.maxTierZoom-e),i=Math.ceil(this.source.width/r),o=Math.ceil(this.source.height/r),a=Math.max(1,Math.ceil(i/this.source.tileSize)),s=Math.max(1,Math.ceil(o/this.source.tileSize)),u=n[0],c=n[1],h=n[2],b=n[3],m=Q(Math.floor(u/r/this.source.tileSize),0,a-1),g=Q(Math.floor((h-1)/r/this.source.tileSize),0,a-1),y=Q(Math.floor(c/r/this.source.tileSize),0,s-1),x=Q(Math.floor((b-1)/r/this.source.tileSize),0,s-1);if(m>g||y>x)return[];const E=(u+h)*.5/r/this.source.tileSize,_=(c+b)*.5/r/this.source.tileSize,X=[];for(let F=y;F<=x;F+=1)for(let W=m;W<=g;W+=1){const P=W*this.source.tileSize*r,z=F*this.source.tileSize*r,Z=Math.min((W+1)*this.source.tileSize,i)*r,ee=Math.min((F+1)*this.source.tileSize,o)*r,N=W-E,ve=F-_;X.push({key:`${e}/${W}/${F}`,tier:e,x:W,y:F,bounds:[P,z,Z,ee],distance2:N*N+ve*ve,url:en(this.source,e,W,F)})}return X.sort((F,W)=>F.distance2-W.distance2),X}trimCache(){if(this.cache.size<=this.maxCacheTiles)return;const e=Array.from(this.cache.entries());e.sort((r,i)=>r[1].lastUsed-i[1].lastUsed);const n=this.cache.size-this.maxCacheTiles;for(let r=0;r<n;r+=1){const[i,o]=e[r];this.gl.deleteTexture(o.texture),this.cache.delete(i)}}render(){if(this.destroyed||this.contextLost||this.gl.isContextLost())return;const e=Xn();this.frameSerial+=1;const n=this.gl,r=this.tileProgram,i=this.pointProgram;n.clearColor(.03,.06,.1,1),n.clear(n.COLOR_BUFFER_BIT);const o=this.getVisibleTiles(),a=this.getViewBounds(),s=new Set(o.map(m=>m.key));n.useProgram(r.program),n.bindVertexArray(r.vao),n.uniformMatrix3fv(r.uCamera,!1,this.camera.getMatrix()),n.uniform1i(r.uTexture,0);const u=[];for(const[,m]of this.cache)s.has(m.key)||this.intersectsBounds(m.bounds,a)&&u.push(m);u.sort((m,g)=>m.tier-g.tier);for(const m of u)m.lastUsed=this.frameSerial,n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,m.texture),n.uniform4f(r.uBounds,m.bounds[0],m.bounds[1],m.bounds[2],m.bounds[3]),n.drawArrays(n.TRIANGLE_STRIP,0,4);let c=0;const h=[];for(const m of o){const g=this.cache.get(m.key);if(!g){h.push(m);continue}g.lastUsed=this.frameSerial,n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,g.texture),n.uniform4f(r.uBounds,g.bounds[0],g.bounds[1],g.bounds[2],g.bounds[3]),n.drawArrays(n.TRIANGLE_STRIP,0,4),c+=1}this.tileScheduler.schedule(h),n.bindTexture(n.TEXTURE_2D,null),n.bindVertexArray(null);let b=0;if(this.pointCount>0&&(n.enable(n.BLEND),n.blendFunc(n.ONE,n.ONE_MINUS_SRC_ALPHA),n.useProgram(i.program),n.bindVertexArray(i.vao),n.uniformMatrix3fv(i.uCamera,!1,this.camera.getMatrix()),n.uniform1f(i.uPointSize,this.getPointSizeByZoom()),n.uniform1f(i.uPointStrokeScale,this.pointStrokeScale),n.uniform1f(i.uPaletteSize,this.pointPaletteSize),n.uniform1i(i.uPalette,1),n.activeTexture(n.TEXTURE1),n.bindTexture(n.TEXTURE_2D,i.paletteTexture),this.usePointIndices?n.drawElements(n.POINTS,this.pointCount,n.UNSIGNED_INT,0):n.drawArrays(n.POINTS,0,this.pointCount),n.bindTexture(n.TEXTURE_2D,null),n.bindVertexArray(null),b=this.pointCount),this.onStats){const m=this.tileScheduler.getSnapshot(),g=c,y=h.length,x=u.length+c+(b>0?1:0);this.onStats({tier:this.currentTier,visible:o.length,rendered:c,points:b,fallback:u.length,cache:this.cache.size,inflight:m.inflight,queued:m.queued,retries:m.retries,failed:m.failed,aborted:m.aborted,cacheHits:g,cacheMisses:y,drawCalls:x,frameMs:Xn()-e})}}requestRender(){this.frame!==null||this.destroyed||this.contextLost||this.gl.isContextLost()||(this.frame=requestAnimationFrame(()=>{this.frame=null,this.render()}))}resize(){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)),a=Math.max(1,Math.round(r*i));(this.canvas.width!==o||this.canvas.height!==a)&&(this.canvas.width=o,this.canvas.height=a),this.camera.setViewport(n,r),this.gl.viewport(0,0,o,a),this.requestRender()}onPointerDown(e){if(this.interactionLocked)return;const n=this.ctrlDragRotate&&(e.ctrlKey||e.metaKey);(e.button===0||n&&e.button===2)&&(n&&e.preventDefault(),this.dragging=!0,this.interactionMode=n?"rotate":"pan",this.pointerId=e.pointerId,this.lastPointerX=e.clientX,this.lastPointerY=e.clientY,this.rotateLastAngleRad=this.interactionMode==="rotate"?this.getPointerAngleRad(e.clientX,e.clientY):null,this.canvas.classList.add("dragging"),this.canvas.setPointerCapture(e.pointerId))}onPointerMove(e){if(this.interactionLocked||!this.dragging||e.pointerId!==this.pointerId)return;const n=e.clientX-this.lastPointerX,r=e.clientY-this.lastPointerY;if(this.lastPointerX=e.clientX,this.lastPointerY=e.clientY,this.interactionMode==="rotate"){const i=this.getPointerAngleRad(e.clientX,e.clientY),o=this.rotateLastAngleRad;if(this.rotateLastAngleRad=i,o!==null){const a=i-o,s=Math.atan2(Math.sin(a),Math.cos(a)),u=this.rotationDragSensitivityDegPerPixel/Dn,c=this.camera.getViewState();this.camera.setViewState({rotationDeg:c.rotationDeg-s*180/Math.PI*u})}}else{const i=this.camera.getViewState(),o=Math.max(1e-6,i.zoom),a=st(i.rotationDeg),s=Math.cos(a),u=Math.sin(a),c=(n*s-r*u)/o,h=(n*u+r*s)/o;this.camera.setViewState({offsetX:i.offsetX-c,offsetY:i.offsetY-h})}this.clampViewState(),this.emitViewState(),this.requestRender()}onPointerUp(e){this.interactionLocked||e.pointerId===this.pointerId&&this.cancelDrag()}onWheel(e){if(this.interactionLocked){e.preventDefault();return}e.preventDefault();const n=this.canvas.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top,o=e.deltaY<0?1.12:.89;this.zoomBy(o,r,i)}onDoubleClick(e){if(this.interactionLocked)return;const n=this.canvas.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top;this.zoomBy(e.shiftKey?.8:1.25,r,i)}onContextMenu(e){(this.dragging||e.ctrlKey||e.metaKey)&&e.preventDefault()}onWebGlContextLost(e){e.preventDefault(),!(this.destroyed||this.contextLost)&&(this.contextLost=!0,this.pointBuffersDirty=!0,this.frame!==null&&(cancelAnimationFrame(this.frame),this.frame=null),this.cancelDrag(),this.tileScheduler.clear(),this.cache.clear(),this.onContextLost?.())}onWebGlContextRestored(e){this.destroyed||(this.contextLost=!1,this.cache.clear(),this.tileProgram=this.initTileProgram(),this.pointProgram=this.initPointProgram(),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(){if(!this.destroyed){if(this.destroyed=!0,this.frame!==null&&(cancelAnimationFrame(this.frame),this.frame=null),this.resizeObserver.disconnect(),this.canvas.removeEventListener("pointerdown",this.boundPointerDown),this.canvas.removeEventListener("pointermove",this.boundPointerMove),this.canvas.removeEventListener("pointerup",this.boundPointerUp),this.canvas.removeEventListener("pointercancel",this.boundPointerUp),this.canvas.removeEventListener("wheel",this.boundWheel),this.canvas.removeEventListener("dblclick",this.boundDoubleClick),this.canvas.removeEventListener("contextmenu",this.boundContextMenu),this.canvas.removeEventListener("webglcontextlost",this.boundContextLost),this.canvas.removeEventListener("webglcontextrestored",this.boundContextRestored),this.cancelDrag(),this.tileScheduler.destroy(),!this.contextLost&&!this.gl.isContextLost()){for(const[,e]of this.cache)this.gl.deleteTexture(e.texture);this.gl.deleteBuffer(this.tileProgram.vbo),this.gl.deleteVertexArray(this.tileProgram.vao),this.gl.deleteProgram(this.tileProgram.program),this.gl.deleteBuffer(this.pointProgram.posBuffer),this.gl.deleteBuffer(this.pointProgram.termBuffer),this.gl.deleteBuffer(this.pointProgram.fillModeBuffer),this.gl.deleteBuffer(this.pointProgram.indexBuffer),this.gl.deleteTexture(this.pointProgram.paletteTexture),this.gl.deleteVertexArray(this.pointProgram.vao),this.gl.deleteProgram(this.pointProgram.program)}this.cache.clear()}}initTileProgram(){const e=this.gl,i=Tn(e,`#version 300 es
63
+ `;function Ji(){if(typeof navigator>"u")return!1;const t=navigator;return typeof t.gpu=="object"&&t.gpu!==null}function or(){if(!Ji())return null;const e=navigator.gpu;if(!e||typeof e!="object")return null;const n=e;return typeof n.requestAdapter!="function"?null:n}const Mt=globalThis.GPUShaderStage?.COMPUTE??4,zt=globalThis.GPUBufferUsage?.STORAGE??128,St=globalThis.GPUBufferUsage?.COPY_DST??8,Qi=globalThis.GPUBufferUsage?.COPY_SRC??4,eo=globalThis.GPUBufferUsage?.UNIFORM??64,to=globalThis.GPUBufferUsage?.MAP_READ??1,no=globalThis.GPUMapMode?.READ??1;async function ro(){const t=or();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 io(){return wt||(wt=(async()=>{const t=or();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:Mt,buffer:{type:"read-only-storage"}},{binding:1,visibility:Mt,buffer:{type:"read-only-storage"}},{binding:2,visibility:Mt,buffer:{type:"storage"}},{binding:3,visibility:Mt,buffer:{type:"uniform"}}]}),i=n.createComputePipeline({layout:n.createPipelineLayout({bindGroupLayouts:[r]}),compute:{module:n.createShaderModule({code:ji}),entryPoint:"main"}});return{device:n,pipeline:i,bindGroupLayout:r}})(),wt)}function xt(t,e){return Math.ceil(t/e)*e}async function sr(t,e,n){const r=await io();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,h=Number(r.device.limits.maxStorageBufferBindingSize);if(a>h||u>h||c>h)return null;const y=r.device.createBuffer({size:xt(a,4),usage:zt|St}),m=r.device.createBuffer({size:xt(u,4),usage:zt|St}),p=r.device.createBuffer({size:xt(c,4),usage:zt|Qi}),g=r.device.createBuffer({size:16,usage:eo|St}),x=r.device.createBuffer({size:xt(c,4),usage:St|to});r.device.queue.writeBuffer(y,0,t.buffer,t.byteOffset,a),r.device.queue.writeBuffer(m,0,n.buffer,n.byteOffset,u),r.device.queue.writeBuffer(g,0,new Uint32Array([s,o,0,0]));const T=r.device.createBindGroup({layout:r.bindGroupLayout,entries:[{binding:0,resource:{buffer:y}},{binding:1,resource:{buffer:m}},{binding:2,resource:{buffer:p}},{binding:3,resource:{buffer:g}}]}),B=r.device.createCommandEncoder(),z=B.beginComputePass();z.setPipeline(r.pipeline),z.setBindGroup(0,T),z.dispatchWorkgroups(Math.ceil(s/256)),z.end(),B.copyBufferToBuffer(p,0,x,0,c),r.device.queue.submit([B.finish()]),await x.mapAsync(no);const N=x.getMappedRange(),Y=new Uint32Array(N.slice(0));return x.unmap(),y.destroy(),m.destroy(),p.destroy(),g.destroy(),x.destroy(),Y}function De(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}async function ar(t,e,n={}){const r=De(),i=n.bridgeToDraw===!0;if(!t||!t.count||!t.positions||!t.paletteIndices)return{data:null,meta:{mode:"hybrid-webgpu",durationMs:De()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}};const o=lt(e??[]);if(o.length===0){const C={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return t.fillModes instanceof Uint8Array&&(C.fillModes=new Uint8Array(0)),t.ids instanceof Uint32Array&&(C.ids=new Uint32Array(0)),{data:C,meta:{mode:"hybrid-webgpu",durationMs:De()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const s=t.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER,a=Math.max(0,Math.min(t.count,Math.floor(t.positions.length/2),t.paletteIndices.length,s)),u=t.fillModes instanceof Uint8Array&&t.fillModes.length>=a?t.fillModes:null,c=t.ids instanceof Uint32Array&&t.ids.length>=a?t.ids:null;if(a===0){const C={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return u&&(C.fillModes=new Uint8Array(0)),c&&(C.ids=new Uint32Array(0)),{data:C,meta:{mode:"hybrid-webgpu",durationMs:De()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const h=new Float32Array(o.length*4);for(let C=0;C<o.length;C+=1){const k=C*4,J=o[C];h[k]=J.minX,h[k+1]=J.minY,h[k+2]=J.maxX,h[k+3]=J.maxY}let y=null,m=!1;try{y=await sr(t.positions,a,h),m=!!y}catch{y=null,m=!1}if(!y)return{data:ut(t,e),meta:{mode:"hybrid-webgpu",durationMs:De()-r,usedWebGpu:!1,candidateCount:a,bridgedToDraw:!1}};let p=0;for(let C=0;C<a;C+=1)y[C]===1&&(p+=1);const g=new Uint32Array(p);if(p>0){let C=0;for(let k=0;k<a;k+=1)y[k]===1&&(g[C]=k,C+=1)}if(p===0){if(i){const k={count:a,positions:t.positions.subarray(0,a*2),paletteIndices:t.paletteIndices.subarray(0,a),drawIndices:new Uint32Array(0)};return u&&(k.fillModes=u.subarray(0,a)),c&&(k.ids=c.subarray(0,a)),{data:k,meta:{mode:"hybrid-webgpu",durationMs:De()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!0}}}const C={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return u&&(C.fillModes=new Uint8Array(0)),c&&(C.ids=new Uint32Array(0)),{data:C,meta:{mode:"hybrid-webgpu",durationMs:De()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const C=new Uint32Array(p);let k=0;for(let ue=0;ue<p;ue+=1){const j=g[ue]??0,$=t.positions[j*2],Ce=t.positions[j*2+1];Et($,Ce,o)&&(C[k]=j,k+=1)}const J={count:a,positions:t.positions.subarray(0,a*2),paletteIndices:t.paletteIndices.subarray(0,a),drawIndices:C.subarray(0,k)};return u&&(J.fillModes=u.subarray(0,a)),c&&(J.ids=c.subarray(0,a)),{data:J,meta:{mode:"hybrid-webgpu",durationMs:De()-r,usedWebGpu:!0,candidateCount:p,bridgedToDraw:!0}}}const x=new Float32Array(p*2),T=new Uint16Array(p),B=u?new Uint8Array(p):null,z=c?new Uint32Array(p):null;let N=0;for(let C=0;C<p;C+=1){const k=g[C]??0,J=t.positions[k*2],ue=t.positions[k*2+1];Et(J,ue,o)&&(x[N*2]=J,x[N*2+1]=ue,T[N]=t.paletteIndices[k],B&&(B[N]=u[k]),z&&(z[N]=c[k]),N+=1)}const Y={count:N,positions:x.subarray(0,N*2),paletteIndices:T.subarray(0,N)};return B&&(Y.fillModes=B.subarray(0,N)),z&&(Y.ids=z.subarray(0,N)),{data:Y,meta:{mode:"hybrid-webgpu",durationMs:De()-r,usedWebGpu:!0,candidateCount:p,bridgedToDraw:!1}}}let Pe=null,Gt=!0,ur=1;const He=new Map;function qe(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function lr(){if(!Gt)return null;if(Pe)return Pe;try{const t=new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/roi-clip-worker-BDVQwN2T.js").href:new URL("assets/roi-clip-worker-BDVQwN2T.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:Ut&&Ut.tagName.toUpperCase()==="SCRIPT"&&Ut.src||new URL("index.cjs",document.baseURI).href),{type:"module"});return t.addEventListener("message",en),t.addEventListener("error",tn),Pe=t,t}catch{return Gt=!1,null}}function en(t){const e=t.data;if(!e)return;const n=He.get(e.id);if(!n)return;if(He.delete(e.id),e.type==="roi-clip-failure"){n.reject(new Error(e.error||"worker clip failed"));return}if(e.type==="roi-clip-index-success"){if(n.kind!=="index"){n.reject(new Error("worker response mismatch: expected point data result"));return}const c=Math.max(0,Math.floor(e.count)),h=new Uint32Array(e.indices).subarray(0,c);n.resolve({indices:h,meta:{mode:"worker",durationMs:Number.isFinite(e.durationMs)?e.durationMs:qe()-n.startMs}});return}if(n.kind!=="data"){n.reject(new Error("worker response mismatch: expected index result"));return}const r=Math.max(0,Math.floor(e.count)),i=new Float32Array(e.positions),o=new Uint16Array(e.paletteIndices),s=e.fillModes?new Uint8Array(e.fillModes):null,a=e.ids?new Uint32Array(e.ids):null,u={count:r,positions:i.subarray(0,r*2),paletteIndices:o.subarray(0,r)};s&&(u.fillModes=s.subarray(0,r)),a&&(u.ids=a.subarray(0,r)),n.resolve({data:u,meta:{mode:"worker",durationMs:Number.isFinite(e.durationMs)?e.durationMs:qe()-n.startMs}})}function tn(){Gt=!1,Pe&&(Pe.removeEventListener("message",en),Pe.removeEventListener("error",tn),Pe.terminate(),Pe=null);for(const[,t]of He)t.reject(new Error("worker crashed"));He.clear()}function oo(){if(Pe){Pe.removeEventListener("message",en),Pe.removeEventListener("error",tn),Pe.terminate(),Pe=null;for(const[,t]of He)t.reject(new Error("worker terminated"));He.clear()}}async function cr(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return{data:null,meta:{mode:"worker",durationMs:0}};const n=lr();if(!n){const y=qe();return{data:ut(t,e),meta:{mode:"sync",durationMs:qe()-y}}}const r=t.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER,i=Math.max(0,Math.min(t.count,Math.floor(t.positions.length/2),t.paletteIndices.length,r)),o=t.positions.slice(0,i*2),s=t.paletteIndices.slice(0,i),a=t.fillModes instanceof Uint8Array&&t.fillModes.length>=i?t.fillModes.slice(0,i):null,u=t.ids instanceof Uint32Array&&t.ids.length>=i?t.ids.slice(0,i):null,c=ur++,h=qe();return new Promise((y,m)=>{He.set(c,{kind:"data",resolve:y,reject:m,startMs:h});const p={type:"roi-clip-request",id:c,count:i,positions:o.buffer,paletteIndices:s.buffer,fillModes:a?.buffer,ids:u?.buffer,polygons:e??[]},g=[o.buffer,s.buffer];a&&g.push(a.buffer),u&&g.push(u.buffer),n.postMessage(p,g)})}async function so(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return{indices:new Uint32Array(0),meta:{mode:"worker",durationMs:0}};const n=lr();if(!n){const u=qe();return{indices:ir(t,e),meta:{mode:"sync",durationMs:qe()-u}}}const r=t.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER,i=Math.max(0,Math.min(t.count,Math.floor(t.positions.length/2),t.paletteIndices.length,r)),o=t.positions.slice(0,i*2),s=ur++,a=qe();return new Promise((u,c)=>{He.set(s,{kind:"index",resolve:u,reject:c,startMs:a});const h={type:"roi-clip-index-request",id:s,count:i,positions:o.buffer,polygons:e??[]};n.postMessage(h,[o.buffer])})}function ao(t){const e=[];for(let n=0;n<t.length;n+=1){const r=t[n],i=lt([r?.coordinates]);if(i.length===0)continue;let o=0;for(const s of i)o+=s.area;e.push({regionId:r.id??n,regionIndex:n,polygons:i,area:Math.max(1e-6,o)})}return e}function uo(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 fr(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 m=t.drawIndices;let p=m.length;for(let g=0;g<m.length;g+=1)m[g]<r||(p-=1);if(p===m.length)i=m;else if(p>0){const g=new Uint32Array(p);let x=0;for(let T=0;T<m.length;T+=1){const B=m[T];B>=r||(g[x]=B,x+=1)}i=g}else i=new Uint32Array(0)}const o=i?i.length:r,s=ao(e??[]);if(!t||o===0||s.length===0)return{groups:[],inputPointCount:o,pointsInsideAnyRegion:0,unmatchedPointCount:o};const a=new Map,u=new Map;let c=0;for(let m=0;m<o;m+=1){const p=i?i[m]:m,g=t.positions[p*2],x=t.positions[p*2+1];let T=null;for(const N of s){let Y=!1;for(const C of N.polygons)if(Kt(g,x,C)){Y=!0;break}Y&&(!T||N.area<T.area)&&(T=N)}if(!T)continue;c+=1;const B=t.paletteIndices[p]??0,z=a.get(T.regionIndex)??new Map;z.set(B,(z.get(B)??0)+1),a.set(T.regionIndex,z),u.set(T.regionIndex,(u.get(T.regionIndex)??0)+1)}const h=n.includeEmptyRegions??!1,y=[];for(const m of s){const p=u.get(m.regionIndex)??0;if(!h&&p<=0)continue;const g=a.get(m.regionIndex)??new Map,x=Array.from(g.entries()).map(([T,B])=>({termId:uo(T,n.paletteIndexToTermId),paletteIndex:T,count:B})).sort((T,B)=>B.count-T.count||T.paletteIndex-B.paletteIndex);y.push({regionId:m.regionId,regionIndex:m.regionIndex,totalCount:p,termCounts:x})}return{groups:y,inputPointCount:o,pointsInsideAnyRegion:c,unmatchedPointCount:Math.max(0,o-c)}}function At(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function lo(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 hr{constructor(e){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(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:At()};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-At());this.timerId=window.setTimeout(()=>{this.timerId=null,this.pump()},n)}takeNextReadyQueueItem(){if(this.queue.length===0)return null;const e=At(),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=lo(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:At()+u},h=this.queuedByKey.get(e.tile.key);h?(h.tile=c.tile,h.readyAt=Math.min(h.readyAt,c.readyAt),h.attempt=Math.max(h.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&&(window.clearTimeout(this.timerId),this.timerId=null)}emitStateChange(){this.onStateChange?.(this.getSnapshot())}}const kn=.35,qt=.5,co=256,Ht=[{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}];class fo{constructor(){w(this,"viewportWidth",1);w(this,"viewportHeight",1);w(this,"viewState",{zoom:1,offsetX:0,offsetY:0,rotationDeg:0})}setViewport(e,n){this.viewportWidth=Math.max(1,e),this.viewportHeight=Math.max(1,n)}getViewport(){return{width:this.viewportWidth,height:this.viewportHeight}}setViewState(e){typeof e.zoom=="number"&&(this.viewState.zoom=Math.max(1e-4,e.zoom)),typeof e.offsetX=="number"&&(this.viewState.offsetX=e.offsetX),typeof e.offsetY=="number"&&(this.viewState.offsetY=e.offsetY),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=this.viewState,i=Math.max(1e-6,r.zoom),[o,s]=this.getCenter(),a=(e-this.viewportWidth*.5)/i,u=(n-this.viewportHeight*.5)/i,c=at(r.rotationDeg),h=Math.cos(c),y=Math.sin(c);return[o+a*h-u*y,s+a*y+u*h]}worldToScreen(e,n){const r=this.viewState,i=Math.max(1e-6,r.zoom),[o,s]=this.getCenter(),a=e-o,u=n-s,c=at(r.rotationDeg),h=Math.cos(c),y=Math.sin(c),m=a*h+u*y,p=-a*y+u*h;return[this.viewportWidth*.5+m*i,this.viewportHeight*.5+p*i]}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,r]=this.getCenter(),i=at(this.viewState.rotationDeg),o=Math.cos(i),s=Math.sin(i),a=2*e*o/this.viewportWidth,u=2*e*s/this.viewportWidth,c=2*e*s/this.viewportHeight,h=-2*e*o/this.viewportHeight,y=-(a*n+u*r),m=-(c*n+h*r);return new Float32Array([a,c,0,u,h,0,y,m,1])}}function at(t){return t*Math.PI/180}function Dn(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Ue(t,e,n){const r=t.getUniformLocation(e,n);if(!r)throw new Error(`uniform location lookup failed: ${n}`);return r}function Rt(t,e){return!t||!e?t===e:t.buffer===e.buffer&&t.byteOffset===e.byteOffset&&t.byteLength===e.byteLength}function $t(t){return t.map(e=>({zoom:e.zoom,size:e.size}))}function On(t){if(!t)return $t(Ht);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?$t(Ht):Array.from(e.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function ho(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 mo(t,e){if(!Number.isFinite(t))return e[0]?.size??qt;if(e.length===0)return qt;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),h=ee((t-a.zoom)/c,0,1);return a.size+(u.size-a.size)*h}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}const go=.1,po=5;function Xn(t){return typeof t!="number"||!Number.isFinite(t)?1:ee(t,go,po)}const bo=-100,yo=100;function Nt(t){return typeof t!="number"||!Number.isFinite(t)?0:ee(t,bo,yo)}function Yn(t){const e=Nt(t?.brightness),n=Nt(t?.contrast),r=Nt(t?.saturation);return{brightness:e/200,contrast:n/100,saturation:r/100}}class dr{constructor(e,n,r={}){w(this,"canvas");w(this,"source");w(this,"gl");w(this,"camera",new fo);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,"dragging",!1);w(this,"interactionMode","none");w(this,"rotateLastAngleRad",null);w(this,"pointerId",null);w(this,"lastPointerX",0);w(this,"lastPointerY",0);w(this,"interactionLocked",!1);w(this,"ctrlDragRotate",!0);w(this,"rotationDragSensitivityDegPerPixel",.35);w(this,"maxCacheTiles");w(this,"fitZoom",1);w(this,"minZoom",1e-6);w(this,"maxZoom",1);w(this,"currentTier",0);w(this,"pointCount",0);w(this,"usePointIndices",!1);w(this,"pointBuffersDirty",!0);w(this,"pointPaletteSize",1);w(this,"pointSizeStops",$t(Ht));w(this,"pointStrokeScale",1);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=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):kn,this.pointSizeStops=On(r.pointSizeByZoom),this.pointStrokeScale=Xn(r.pointStrokeScale),this.imageColorSettings=Yn(r.imageColorSettings);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=this.initTileProgram(),this.pointProgram=this.initPointProgram(),this.tileScheduler=new hr({authToken:this.authToken,maxConcurrency:r.tileScheduler?.maxConcurrency??12,maxRetries:r.tileScheduler?.maxRetries??2,retryBaseDelayMs:r.tileScheduler?.retryBaseDelayMs??120,retryMaxDelayMs:r.tileScheduler?.retryMaxDelayMs??1200,onTileLoad:(o,s)=>this.handleTileLoaded(o,s),onTileError:(o,s,a)=>{this.onTileError?.({tile:o,error:s,attemptCount:a}),console.warn("tile load failed",o.url,s)}}),this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(e),this.boundPointerDown=o=>this.onPointerDown(o),this.boundPointerMove=o=>this.onPointerMove(o),this.boundPointerUp=o=>this.onPointerUp(o),this.boundWheel=o=>this.onWheel(o),this.boundDoubleClick=o=>this.onDoubleClick(o),this.boundContextMenu=o=>this.onContextMenu(o),this.boundContextLost=o=>this.onWebGlContextLost(o),this.boundContextRestored=o=>this.onWebGlContextRestored(o),e.addEventListener("pointerdown",this.boundPointerDown),e.addEventListener("pointermove",this.boundPointerMove),e.addEventListener("pointerup",this.boundPointerUp),e.addEventListener("pointercancel",this.boundPointerUp),e.addEventListener("wheel",this.boundWheel,{passive:!1}),e.addEventListener("dblclick",this.boundDoubleClick),e.addEventListener("contextmenu",this.boundContextMenu),e.addEventListener("webglcontextlost",this.boundContextLost),e.addEventListener("webglcontextrestored",this.boundContextRestored),this.fitToImage(),this.resize()}setAuthToken(e){this.authToken=String(e??""),this.tileScheduler.setAuthToken(this.authToken)}setViewState(e){const n={...e};typeof n.zoom=="number"&&(n.zoom=ee(n.zoom,this.minZoom,this.maxZoom)),this.camera.setViewState(n),this.clampViewState(),this.emitViewState(),this.requestRender()}getViewState(){return this.camera.getViewState()}setPointPalette(e){if(!e||e.length===0){this.lastPointPalette=null;return}if(this.lastPointPalette=new Uint8Array(e),this.contextLost||this.gl.isContextLost())return;const n=this.gl,r=Math.max(1,Math.floor(this.lastPointPalette.length/4));this.pointPaletteSize=r,n.bindTexture(n.TEXTURE_2D,this.pointProgram.paletteTexture),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,r,1,0,n.RGBA,n.UNSIGNED_BYTE,this.lastPointPalette),n.bindTexture(n.TEXTURE_2D,null),this.requestRender()}setPointData(e){if(!e||!e.count||!e.positions||!e.paletteIndices){this.lastPointData=null,this.pointCount=0,this.usePointIndices=!1,this.requestRender();return}const n=e.fillModes instanceof Uint8Array?e.fillModes:null,r=n!==null,i=Math.max(0,Math.min(e.count,Math.floor(e.positions.length/2),e.paletteIndices.length,r?n.length:Number.MAX_SAFE_INTEGER)),o=e.positions.subarray(0,i*2),s=e.paletteIndices.subarray(0,i),a=r?n.subarray(0,i):void 0,u=e.drawIndices instanceof Uint32Array,c=u?this.sanitizeDrawIndices(e.drawIndices,i):null,h=this.lastPointData,y=h?.fillModes instanceof Uint8Array;let m=this.pointBuffersDirty||!h||h.count!==i||!Rt(h.positions,o)||!Rt(h.paletteIndices,s)||y!==r||r&&(!h?.fillModes||!Rt(h.fillModes,a)),p=this.pointBuffersDirty||u&&(!h?.drawIndices||!Rt(h.drawIndices,c))||!u&&!!h?.drawIndices;if(this.lastPointData={count:i,positions:o,paletteIndices:s,fillModes:a,drawIndices:u?c??void 0:void 0},this.contextLost||this.gl.isContextLost())return;const g=this.gl;m&&(g.bindBuffer(g.ARRAY_BUFFER,this.pointProgram.posBuffer),g.bufferData(g.ARRAY_BUFFER,this.lastPointData.positions,g.STATIC_DRAW),g.bindBuffer(g.ARRAY_BUFFER,this.pointProgram.termBuffer),g.bufferData(g.ARRAY_BUFFER,this.lastPointData.paletteIndices,g.STATIC_DRAW),g.bindBuffer(g.ARRAY_BUFFER,this.pointProgram.fillModeBuffer),g.bufferData(g.ARRAY_BUFFER,this.lastPointData.fillModes??this.getZeroFillModes(i),g.STATIC_DRAW),g.bindBuffer(g.ARRAY_BUFFER,null)),u&&p&&(g.bindBuffer(g.ELEMENT_ARRAY_BUFFER,this.pointProgram.indexBuffer),g.bufferData(g.ELEMENT_ARRAY_BUFFER,c??new Uint32Array(0),g.DYNAMIC_DRAW),g.bindBuffer(g.ELEMENT_ARRAY_BUFFER,null)),this.usePointIndices=u,this.pointCount=u?c?.length??0:this.lastPointData.count,(m||p)&&(this.pointBuffersDirty=!1),this.requestRender()}sanitizeDrawIndices(e,n){if(n<=0||e.length===0)return new Uint32Array(0);let r=e.length;for(let s=0;s<e.length;s+=1)e[s]<n||(r-=1);if(r===e.length)return e;if(r<=0)return new Uint32Array(0);const i=new Uint32Array(r);let o=0;for(let s=0;s<e.length;s+=1){const a=e[s];a>=n||(i[o]=a,o+=1)}return i}getZeroFillModes(e){return e<=0?new Uint8Array(0):(this.zeroFillModes.length<e&&(this.zeroFillModes=new Uint8Array(e)),this.zeroFillModes.subarray(0,e))}setInteractionLock(e){const n=!!e;this.interactionLocked!==n&&(this.interactionLocked=n,n&&this.cancelDrag())}setPointSizeByZoom(e){const n=On(e);ho(this.pointSizeStops,n)||(this.pointSizeStops=n,this.requestRender())}setPointStrokeScale(e){const n=Xn(e);this.pointStrokeScale!==n&&(this.pointStrokeScale=n,this.requestRender())}setImageColorSettings(e){const n=Yn(e),r=this.imageColorSettings;r.brightness===n.brightness&&r.contrast===n.contrast&&r.saturation===n.saturation||(this.imageColorSettings=n,this.requestRender())}cancelDrag(){if(this.pointerId!==null&&this.canvas.hasPointerCapture(this.pointerId))try{this.canvas.releasePointerCapture(this.pointerId)}catch{}this.dragging=!1,this.interactionMode="none",this.rotateLastAngleRad=null,this.pointerId=null,this.canvas.classList.remove("dragging")}getPointerAngleRad(e,n){const r=this.canvas.getBoundingClientRect(),i=e-r.left-r.width*.5,o=n-r.top-r.height*.5;return Math.atan2(o,i)}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){!Number.isFinite(e)||!Number.isFinite(n)||(this.camera.setCenter(e,n),this.clampViewState(),this.emitViewState(),this.requestRender())}getViewCorners(){return this.camera.getViewCorners()}resetRotation(){const e=this.camera.getViewState();Math.abs(e.rotationDeg)<1e-6||(this.camera.setViewState({rotationDeg:0}),this.clampViewState(),this.emitViewState(),this.requestRender())}getPointSizeByZoom(){const e=Math.max(1e-6,this.camera.getViewState().zoom),n=this.source.maxTierZoom+Math.log2(e),r=mo(n,this.pointSizeStops);return ee(r,qt,co)}fitToImage(){const e=this.canvas.getBoundingClientRect(),n=Math.max(1,e.width||1),r=Math.max(1,e.height||1),i=Math.min(n/this.source.width,r/this.source.height),o=Number.isFinite(i)&&i>0?i:1;this.fitZoom=o,this.minZoom=Math.max(this.fitZoom*.5,1e-6),this.maxZoom=Math.max(1,this.fitZoom*8),this.minZoom>this.maxZoom&&(this.minZoom=this.maxZoom);const s=n/o,a=r/o;this.camera.setViewState({zoom:ee(o,this.minZoom,this.maxZoom),offsetX:(this.source.width-s)*.5,offsetY:(this.source.height-a)*.5,rotationDeg:0}),this.clampViewState(),this.emitViewState(),this.requestRender()}zoomBy(e,n,r){const i=this.camera.getViewState(),o=ee(i.zoom*e,this.minZoom,this.maxZoom);if(o===i.zoom)return;const[s,a]=this.camera.screenToWorld(n,r);this.camera.setViewState({zoom:o});const u=this.camera.getViewport(),c=n-u.width*.5,h=r-u.height*.5,y=at(this.camera.getViewState().rotationDeg),m=Math.cos(y),p=Math.sin(y),g=c/o*m-h/o*p,x=c/o*p+h/o*m;this.camera.setCenter(s-g,a-x),this.clampViewState(),this.emitViewState(),this.requestRender()}clampViewState(){const e=this.getViewBounds(),n=Math.max(1e-6,e[2]-e[0]),r=Math.max(1e-6,e[3]-e[1]),i=n*.2,o=r*.2,[s,a]=this.camera.getCenter(),u=n*.5,c=r*.5,h=u-i,y=this.source.width-u+i,m=c-o,p=this.source.height-c+o,g=h<=y?ee(s,h,y):this.source.width*.5,x=m<=p?ee(a,m,p):this.source.height*.5;this.camera.setCenter(g,x)}emitViewState(){this.onViewStateChange?.(this.camera.getViewState())}selectTier(){const e=Math.max(1e-6,this.camera.getViewState().zoom),n=this.source.maxTierZoom+Math.log2(e);return ee(Math.floor(n),0,this.source.maxTierZoom)}getViewBounds(){const e=this.camera.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]}intersectsBounds(e,n){return!(e[2]<=n[0]||e[0]>=n[2]||e[3]<=n[1]||e[1]>=n[3])}getVisibleTiles(){const e=this.selectTier();this.currentTier=e;const n=this.getViewBounds(),r=Math.pow(2,this.source.maxTierZoom-e),i=Math.ceil(this.source.width/r),o=Math.ceil(this.source.height/r),s=Math.max(1,Math.ceil(i/this.source.tileSize)),a=Math.max(1,Math.ceil(o/this.source.tileSize)),u=n[0],c=n[1],h=n[2],y=n[3],m=ee(Math.floor(u/r/this.source.tileSize),0,s-1),p=ee(Math.floor((h-1)/r/this.source.tileSize),0,s-1),g=ee(Math.floor(c/r/this.source.tileSize),0,a-1),x=ee(Math.floor((y-1)/r/this.source.tileSize),0,a-1);if(m>p||g>x)return[];const T=(u+h)*.5/r/this.source.tileSize,B=(c+y)*.5/r/this.source.tileSize,z=[];for(let N=g;N<=x;N+=1)for(let Y=m;Y<=p;Y+=1){const C=Y*this.source.tileSize*r,k=N*this.source.tileSize*r,J=Math.min((Y+1)*this.source.tileSize,i)*r,ue=Math.min((N+1)*this.source.tileSize,o)*r,j=Y-T,$=N-B;z.push({key:`${e}/${Y}/${N}`,tier:e,x:Y,y:N,bounds:[C,k,J,ue],distance2:j*j+$*$,url:Qt(this.source,e,Y,N)})}return z.sort((N,Y)=>N.distance2-Y.distance2),z}trimCache(){if(this.cache.size<=this.maxCacheTiles)return;const e=Array.from(this.cache.entries());e.sort((r,i)=>r[1].lastUsed-i[1].lastUsed);const n=this.cache.size-this.maxCacheTiles;for(let r=0;r<n;r+=1){const[i,o]=e[r];this.gl.deleteTexture(o.texture),this.cache.delete(i)}}render(){if(this.destroyed||this.contextLost||this.gl.isContextLost())return;const e=Dn();this.frameSerial+=1;const n=this.gl,r=this.tileProgram,i=this.pointProgram;n.clearColor(.03,.06,.1,1),n.clear(n.COLOR_BUFFER_BIT);const o=this.getVisibleTiles(),s=this.getViewBounds(),a=new Set(o.map(m=>m.key));n.useProgram(r.program),n.bindVertexArray(r.vao),n.uniformMatrix3fv(r.uCamera,!1,this.camera.getMatrix()),n.uniform1i(r.uTexture,0),n.uniform1f(r.uBrightness,this.imageColorSettings.brightness),n.uniform1f(r.uContrast,this.imageColorSettings.contrast),n.uniform1f(r.uSaturation,this.imageColorSettings.saturation);const u=[];for(const[,m]of this.cache)a.has(m.key)||this.intersectsBounds(m.bounds,s)&&u.push(m);u.sort((m,p)=>m.tier-p.tier);for(const m of u)m.lastUsed=this.frameSerial,n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,m.texture),n.uniform4f(r.uBounds,m.bounds[0],m.bounds[1],m.bounds[2],m.bounds[3]),n.drawArrays(n.TRIANGLE_STRIP,0,4);let c=0;const h=[];for(const m of o){const p=this.cache.get(m.key);if(!p){h.push(m);continue}p.lastUsed=this.frameSerial,n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,p.texture),n.uniform4f(r.uBounds,p.bounds[0],p.bounds[1],p.bounds[2],p.bounds[3]),n.drawArrays(n.TRIANGLE_STRIP,0,4),c+=1}this.tileScheduler.schedule(h),n.bindTexture(n.TEXTURE_2D,null),n.bindVertexArray(null);let y=0;if(this.pointCount>0&&(n.enable(n.BLEND),n.blendFunc(n.ONE,n.ONE_MINUS_SRC_ALPHA),n.useProgram(i.program),n.bindVertexArray(i.vao),n.uniformMatrix3fv(i.uCamera,!1,this.camera.getMatrix()),n.uniform1f(i.uPointSize,this.getPointSizeByZoom()),n.uniform1f(i.uPointStrokeScale,this.pointStrokeScale),n.uniform1f(i.uPaletteSize,this.pointPaletteSize),n.uniform1i(i.uPalette,1),n.activeTexture(n.TEXTURE1),n.bindTexture(n.TEXTURE_2D,i.paletteTexture),this.usePointIndices?n.drawElements(n.POINTS,this.pointCount,n.UNSIGNED_INT,0):n.drawArrays(n.POINTS,0,this.pointCount),n.bindTexture(n.TEXTURE_2D,null),n.bindVertexArray(null),y=this.pointCount),this.onStats){const m=this.tileScheduler.getSnapshot(),p=c,g=h.length,x=u.length+c+(y>0?1:0);this.onStats({tier:this.currentTier,visible:o.length,rendered:c,points:y,fallback:u.length,cache:this.cache.size,inflight:m.inflight,queued:m.queued,retries:m.retries,failed:m.failed,aborted:m.aborted,cacheHits:p,cacheMisses:g,drawCalls:x,frameMs:Dn()-e})}}requestRender(){this.frame!==null||this.destroyed||this.contextLost||this.gl.isContextLost()||(this.frame=requestAnimationFrame(()=>{this.frame=null,this.render()}))}resize(){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,o,s),this.requestRender()}onPointerDown(e){if(this.interactionLocked)return;const n=this.ctrlDragRotate&&(e.ctrlKey||e.metaKey);(e.button===0||n&&e.button===2)&&(n&&e.preventDefault(),this.dragging=!0,this.interactionMode=n?"rotate":"pan",this.pointerId=e.pointerId,this.lastPointerX=e.clientX,this.lastPointerY=e.clientY,this.rotateLastAngleRad=this.interactionMode==="rotate"?this.getPointerAngleRad(e.clientX,e.clientY):null,this.canvas.classList.add("dragging"),this.canvas.setPointerCapture(e.pointerId))}onPointerMove(e){if(this.interactionLocked||!this.dragging||e.pointerId!==this.pointerId)return;const n=e.clientX-this.lastPointerX,r=e.clientY-this.lastPointerY;if(this.lastPointerX=e.clientX,this.lastPointerY=e.clientY,this.interactionMode==="rotate"){const i=this.getPointerAngleRad(e.clientX,e.clientY),o=this.rotateLastAngleRad;if(this.rotateLastAngleRad=i,o!==null){const s=i-o,a=Math.atan2(Math.sin(s),Math.cos(s)),u=this.rotationDragSensitivityDegPerPixel/kn,c=this.camera.getViewState();this.camera.setViewState({rotationDeg:c.rotationDeg-a*180/Math.PI*u})}}else{const i=this.camera.getViewState(),o=Math.max(1e-6,i.zoom),s=at(i.rotationDeg),a=Math.cos(s),u=Math.sin(s),c=(n*a-r*u)/o,h=(n*u+r*a)/o;this.camera.setViewState({offsetX:i.offsetX-c,offsetY:i.offsetY-h})}this.clampViewState(),this.emitViewState(),this.requestRender()}onPointerUp(e){this.interactionLocked||e.pointerId===this.pointerId&&this.cancelDrag()}onWheel(e){if(this.interactionLocked){e.preventDefault();return}e.preventDefault();const n=this.canvas.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top,o=e.deltaY<0?1.12:.89;this.zoomBy(o,r,i)}onDoubleClick(e){if(this.interactionLocked)return;const n=this.canvas.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top;this.zoomBy(e.shiftKey?.8:1.25,r,i)}onContextMenu(e){(this.dragging||e.ctrlKey||e.metaKey)&&e.preventDefault()}onWebGlContextLost(e){e.preventDefault(),!(this.destroyed||this.contextLost)&&(this.contextLost=!0,this.pointBuffersDirty=!0,this.frame!==null&&(cancelAnimationFrame(this.frame),this.frame=null),this.cancelDrag(),this.tileScheduler.clear(),this.cache.clear(),this.onContextLost?.())}onWebGlContextRestored(e){this.destroyed||(this.contextLost=!1,this.cache.clear(),this.tileProgram=this.initTileProgram(),this.pointProgram=this.initPointProgram(),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(){if(!this.destroyed){if(this.destroyed=!0,this.frame!==null&&(cancelAnimationFrame(this.frame),this.frame=null),this.resizeObserver.disconnect(),this.canvas.removeEventListener("pointerdown",this.boundPointerDown),this.canvas.removeEventListener("pointermove",this.boundPointerMove),this.canvas.removeEventListener("pointerup",this.boundPointerUp),this.canvas.removeEventListener("pointercancel",this.boundPointerUp),this.canvas.removeEventListener("wheel",this.boundWheel),this.canvas.removeEventListener("dblclick",this.boundDoubleClick),this.canvas.removeEventListener("contextmenu",this.boundContextMenu),this.canvas.removeEventListener("webglcontextlost",this.boundContextLost),this.canvas.removeEventListener("webglcontextrestored",this.boundContextRestored),this.cancelDrag(),this.tileScheduler.destroy(),!this.contextLost&&!this.gl.isContextLost()){for(const[,e]of this.cache)this.gl.deleteTexture(e.texture);this.gl.deleteBuffer(this.tileProgram.vbo),this.gl.deleteVertexArray(this.tileProgram.vao),this.gl.deleteProgram(this.tileProgram.program),this.gl.deleteBuffer(this.pointProgram.posBuffer),this.gl.deleteBuffer(this.pointProgram.termBuffer),this.gl.deleteBuffer(this.pointProgram.fillModeBuffer),this.gl.deleteBuffer(this.pointProgram.indexBuffer),this.gl.deleteTexture(this.pointProgram.paletteTexture),this.gl.deleteVertexArray(this.pointProgram.vao),this.gl.deleteProgram(this.pointProgram.program)}this.cache.clear()}}initTileProgram(){const e=this.gl,i=Rn(e,`#version 300 es
64
64
  precision highp float;
65
65
  in vec2 aUnit;
66
66
  in vec2 aUv;
@@ -79,10 +79,33 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
79
79
  precision highp float;
80
80
  in vec2 vUv;
81
81
  uniform sampler2D uTexture;
82
+ uniform float uBrightness;
83
+ uniform float uContrast;
84
+ uniform float uSaturation;
82
85
  out vec4 outColor;
83
86
  void main() {
84
- outColor = texture(uTexture, vUv);
85
- }`),o=qe(e,i,"uCamera"),a=qe(e,i,"uBounds"),s=qe(e,i,"uTexture"),u=e.createVertexArray(),c=e.createBuffer();if(!u||!c)throw new Error("buffer allocation failed");e.bindVertexArray(u),e.bindBuffer(e.ARRAY_BUFFER,c),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,0,0,1,0,1,0,0,1,0,1,1,1,1,1]),e.STATIC_DRAW);const h=e.getAttribLocation(i,"aUnit"),b=e.getAttribLocation(i,"aUv");if(h<0||b<0)throw new Error("tile attribute lookup failed");return e.enableVertexAttribArray(h),e.enableVertexAttribArray(b),e.vertexAttribPointer(h,2,e.FLOAT,!1,16,0),e.vertexAttribPointer(b,2,e.FLOAT,!1,16,8),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),{program:i,vao:u,vbo:c,uCamera:o,uBounds:a,uTexture:s}}initPointProgram(){const e=this.gl,i=Tn(e,`#version 300 es
87
+ vec4 color = texture(uTexture, vUv);
88
+
89
+ color.rgb = clamp(
90
+ (uContrast + 1.0) * color.rgb - (uContrast / 2.0),
91
+ vec3(0.0),
92
+ vec3(1.0)
93
+ );
94
+
95
+ float saturation = uSaturation + 1.0;
96
+ float sr = (1.0 - saturation) * 0.2126;
97
+ float sg = (1.0 - saturation) * 0.7152;
98
+ float sb = (1.0 - saturation) * 0.0722;
99
+ mat3 saturationMatrix = mat3(
100
+ sr + saturation, sr, sr,
101
+ sg, sg + saturation, sg,
102
+ sb, sb, sb + saturation
103
+ );
104
+ color.rgb = clamp(saturationMatrix * color.rgb, vec3(0.0), vec3(1.0));
105
+
106
+ color.rgb = clamp(color.rgb + uBrightness, vec3(0.0), vec3(1.0));
107
+ outColor = color;
108
+ }`),o=Ue(e,i,"uCamera"),s=Ue(e,i,"uBounds"),a=Ue(e,i,"uTexture"),u=Ue(e,i,"uBrightness"),c=Ue(e,i,"uContrast"),h=Ue(e,i,"uSaturation"),y=e.createVertexArray(),m=e.createBuffer();if(!y||!m)throw new Error("buffer allocation failed");e.bindVertexArray(y),e.bindBuffer(e.ARRAY_BUFFER,m),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,0,0,1,0,1,0,0,1,0,1,1,1,1,1]),e.STATIC_DRAW);const p=e.getAttribLocation(i,"aUnit"),g=e.getAttribLocation(i,"aUv");if(p<0||g<0)throw new Error("tile attribute lookup failed");return e.enableVertexAttribArray(p),e.enableVertexAttribArray(g),e.vertexAttribPointer(p,2,e.FLOAT,!1,16,0),e.vertexAttribPointer(g,2,e.FLOAT,!1,16,8),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),{program:i,vao:y,vbo:m,uCamera:o,uBounds:s,uTexture:a,uBrightness:u,uContrast:c,uSaturation:h}}initPointProgram(){const e=this.gl,i=Rn(e,`#version 300 es
86
109
  precision highp float;
87
110
  in vec2 aPosition;
88
111
  in uint aTerm;
@@ -131,6 +154,6 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
131
154
  if (alpha <= 0.001) discard;
132
155
 
133
156
  outColor = vec4(color.rgb * alpha, alpha);
134
- }`),o=qe(e,i,"uCamera"),a=qe(e,i,"uPointSize"),s=qe(e,i,"uPointStrokeScale"),u=qe(e,i,"uPalette"),c=qe(e,i,"uPaletteSize"),h=e.createVertexArray(),b=e.createBuffer(),m=e.createBuffer(),g=e.createBuffer(),y=e.createBuffer(),x=e.createTexture();if(!h||!b||!m||!g||!y||!x)throw new Error("point buffer allocation failed");e.bindVertexArray(h),e.bindBuffer(e.ARRAY_BUFFER,b),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const E=e.getAttribLocation(i,"aPosition");if(E<0)throw new Error("point position attribute not found");e.enableVertexAttribArray(E),e.vertexAttribPointer(E,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,m),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const _=e.getAttribLocation(i,"aTerm");if(_<0)throw new Error("point term attribute not found");e.enableVertexAttribArray(_),e.vertexAttribIPointer(_,1,e.UNSIGNED_SHORT,0,0),e.bindBuffer(e.ARRAY_BUFFER,g),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const X=e.getAttribLocation(i,"aFillMode");if(X<0)throw new Error("point fill mode attribute not found");return e.enableVertexAttribArray(X),e.vertexAttribIPointer(X,1,e.UNSIGNED_BYTE,0,0),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,y),e.bufferData(e.ELEMENT_ARRAY_BUFFER,0,e.DYNAMIC_DRAW),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),e.bindTexture(e.TEXTURE_2D,x),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([160,160,160,255])),e.bindTexture(e.TEXTURE_2D,null),{program:i,vao:h,posBuffer:b,termBuffer:m,fillModeBuffer:g,indexBuffer:y,paletteTexture:x,uCamera:o,uPointSize:a,uPointStrokeScale:s,uPalette:u,uPaletteSize:c}}handleTileLoaded(e,n){if(this.destroyed||this.contextLost||this.gl.isContextLost()){n.close();return}if(this.cache.has(e.key)){n.close();return}const r=this.createTextureFromBitmap(n);n.close(),r&&(this.cache.set(e.key,{key:e.key,texture:r,bounds:e.bounds,tier:e.tier,lastUsed:this.frameSerial}),this.trimCache(),this.requestRender())}createTextureFromBitmap(e){if(this.contextLost||this.gl.isContextLost())return null;const n=this.gl,r=n.createTexture();return r?(n.bindTexture(n.TEXTURE_2D,r),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,1),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,e),n.bindTexture(n.TEXTURE_2D,null),r):null}}const Dt=[],po=[],bo={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)},yo=.65,wo=4,Mo=24,So=1024,xo=4;function Ao(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 Ro(t,e){if(!(t instanceof Uint32Array)||e<=0||t.length===0)return null;let n=!1;for(let o=0;o<t.length;o+=1)if(!(t[o]<e)){n=!0;break}if(!n)return t;const r=new Uint32Array(t.length);let i=0;for(let o=0;o<t.length;o+=1){const a=t[o];a>=e||(r[i]=a,i+=1)}return r.subarray(0,i)}function Eo(t,e){if(!t||e<=0)return 256;const n=Math.max(1,t.width*t.height),i=Math.sqrt(n/Math.max(1,e))*xo;return Math.max(Mo,Math.min(So,i))}function To(t,e){if(!t||!t.positions||!t.paletteIndices)return null;const n=Ao(t);if(n<=0)return null;const r=t.positions.subarray(0,n*2),i=t.ids instanceof Uint32Array&&t.ids.length>=n?t.ids.subarray(0,n):null,o=Ro(t.drawIndices,n),a=o?o.length:n;if(a===0)return null;const s=Eo(e,a),u=new Map,c=h=>{const b=r[h*2],m=r[h*2+1];if(!Number.isFinite(b)||!Number.isFinite(m))return;const g=Math.floor(b/s),y=Math.floor(m/s);let x=u.get(g);x||(x=new Map,u.set(g,x));const E=x.get(y);E?E.push(h):x.set(y,[h])};if(o)for(let h=0;h<o.length;h+=1)c(o[h]??0);else for(let h=0;h<n;h+=1)c(h);return u.size===0?null:{cellSize:s,safeCount:n,positions:r,ids:i,buckets:u}}function Kt(t,e){return t.id??e}function Po(t){const e=[];for(let n=0;n<t.length;n+=1){const r=t[n],i=ut([r?.coordinates]);i.length!==0&&e.push({region:r,regionIndex:n,regionId:Kt(r,n),polygons:i})}return e}function Xt(t,e){const n=t[0],r=t[1];for(let i=e.length-1;i>=0;i-=1){const o=e[i];for(const a of o.polygons)if(jt(n,r,a))return{region:o.region,regionIndex:o.regionIndex,regionId:o.regionId}}return null}function Co({source:t,viewState:e,onViewStateChange:n,onStats:r,onTileError:i,onContextLost:o,onContextRestored:a,debugOverlay:s=!1,debugOverlayStyle:u,fitNonce:c=0,rotationResetNonce:h=0,authToken:b="",ctrlDragRotate:m=!0,pointData:g=null,pointPalette:y=null,pointSizeByZoom:x,pointStrokeScale:E,roiRegions:_,roiPolygons:X,clipPointsToRois:F=!1,clipMode:W="worker",onClipStats:P,onRoiPointGroups:z,roiPaletteIndexToTermId:Z,interactionLock:ee=!1,drawTool:N="cursor",stampOptions:ve,brushOptions:Te,regionStrokeStyle:$,regionStrokeHoverStyle:_e,regionStrokeActiveStyle:ze,patchStrokeStyle:Ke,resolveRegionStrokeStyle:be,overlayShapes:ne,customLayers:T,patchRegions:C,regionLabelStyle:I,onPointerWorldMove:Y,onPointHover:L,onPointClick:ie,onRegionHover:re,onRegionClick:we,onActiveRegionChange:fe,getCellByCoordinatesRef:oe,onDrawComplete:V,onPatchComplete:J,showOverviewMap:K=!1,overviewMapOptions:D,className:ce,style:se}){const ae=d.useRef(null),j=d.useRef(null),Ue=d.useRef(null),Pe=d.useRef(null),Fe=d.useRef(n),U=d.useRef(r),ge=d.useRef(s),[Ce,ye]=d.useState(!0),[Qe,De]=d.useState(null),[pe,It]=d.useState(null),[lt,et]=d.useState(null),[ue,l]=d.useState(null),f=d.useRef(null),p=d.useRef(null),S=d.useRef(null),A=d.useRef(0),B=_??Dt,O=C??Dt,H=X??po,G=(T?.length??0)>0,he=d.useMemo(()=>({position:"relative",width:"100%",height:"100%",...se}),[se]),Xe=d.useMemo(()=>({position:"absolute",top:8,left:8,zIndex:7,margin:0,padding:"8px 10px",maxWidth:"min(420px, 80%)",pointerEvents:"none",whiteSpace:"pre-wrap",lineHeight:1.35,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:11,color:"#cde6ff",background:"rgba(6, 12, 20, 0.82)",border:"1px solid rgba(173, 216, 255, 0.28)",borderRadius:8,boxShadow:"0 8px 22px rgba(0,0,0,0.35)",...u}),[u]),de=d.useMemo(()=>B.length>0?B:H.length===0?Dt:H.map((w,R)=>({id:R,coordinates:w})),[B,H]),te=d.useMemo(()=>Po(de),[de]),me=d.useMemo(()=>de.map(w=>w.coordinates),[de]),[Me,Se]=d.useState(g);d.useEffect(()=>{const w=++A.current;let R=!1;if(!F)return Se(g),()=>{R=!0};if(!g||!g.count||!g.positions||!g.paletteIndices)return Se(null),()=>{R=!0};if(me.length===0)return Se(bo),P?.({mode:W,durationMs:0,inputCount:g.count,outputCount:0,polygonCount:0}),()=>{R=!0};const v=(k,le)=>{if(R||w!==A.current)return;const ht=k?.drawIndices?k.drawIndices.length:k?.count??0;Se(k),P?.({mode:le.mode,durationMs:le.durationMs,inputCount:g.count,outputCount:ht,polygonCount:me.length,usedWebGpu:le.usedWebGpu,candidateCount:le.candidateCount,bridgedToDraw:le.bridgedToDraw})};return(async()=>{if(W==="sync"){const k=performance.now(),le=at(g,me);v(le,{mode:"sync",durationMs:performance.now()-k});return}if(W==="hybrid-webgpu"){const k=await ar(g,me,{bridgeToDraw:!0});v(k.data,{mode:k.meta.mode,durationMs:k.meta.durationMs,usedWebGpu:k.meta.usedWebGpu,candidateCount:k.meta.candidateCount,bridgedToDraw:k.meta.bridgedToDraw});return}try{const k=await cr(g,me);v(k.data,{mode:k.meta.mode,durationMs:k.meta.durationMs})}catch{const k=performance.now(),le=at(g,me);v(le,{mode:"sync",durationMs:performance.now()-k})}})(),()=>{R=!0}},[F,W,g,me,P]);const rn=!!(L||ie||oe),Ee=d.useMemo(()=>rn?To(Me,t):null,[rn,Me,t]),Ze=d.useCallback(w=>{const R=j.current;if(!R||!Ee)return null;const v=Number(w[0]),q=Number(w[1]);if(!Number.isFinite(v)||!Number.isFinite(q))return null;const k=Math.max(1e-6,R.getViewState().zoom),le=R.getPointSizeByZoom(),tt=Math.max(wo,le*yo)/k;if(!Number.isFinite(tt)||tt<=0)return null;const vt=Ee.cellSize,hn=Math.floor(v/vt),dn=Math.floor(q/vt),dt=Math.max(1,Math.ceil(tt/vt)),Mr=tt*tt;let mt=-1,mn=Mr,gn=0,pn=0;for(let _t=hn-dt;_t<=hn+dt;_t+=1){const bn=Ee.buckets.get(_t);if(bn)for(let Ut=dn-dt;Ut<=dn+dt;Ut+=1){const gt=bn.get(Ut);if(!(!gt||gt.length===0))for(let Ft=0;Ft<gt.length;Ft+=1){const pt=gt[Ft];if(pt>=Ee.safeCount)continue;const yn=Ee.positions[pt*2],wn=Ee.positions[pt*2+1],Mn=yn-v,Sn=wn-q,xn=Mn*Mn+Sn*Sn;xn>mn||(mn=xn,mt=pt,gn=yn,pn=wn)}}}if(mt<0)return null;const Sr=Ee.ids?Number(Ee.ids[mt]):null;return{index:mt,id:Sr,coordinate:[v,q],pointCoordinate:[gn,pn]}},[Ee]),je=d.useCallback((w,R)=>{if(!L)return;const v=w?.index??null,q=w?.id??null;p.current===v&&S.current===q||(p.current=v,S.current=q,L({index:v,id:q,coordinate:R,pointCoordinate:w?.pointCoordinate??null}))},[L]),ct=d.useCallback((w,R)=>{if(!ie)return;const v=Ze(w);v&&ie({...v,button:R})},[ie,Ze]);d.useMemo(()=>{const w=Number(D?.width??220);return Number.isFinite(w)?Math.max(64,w):220},[D?.width]);const on=d.useMemo(()=>{const w=Number(D?.height??140);return Number.isFinite(w)?Math.max(48,w):140},[D?.height]),We=d.useMemo(()=>{const w=Number(D?.margin??16);return Number.isFinite(w)?Math.max(0,w):16},[D?.margin]),ft=D?.position||"bottom-right";d.useEffect(()=>{if(oe)return oe.current=Ze,()=>{oe.current===Ze&&(oe.current=null)}},[oe,Ze]);const Ye=d.useCallback(w=>{It(R=>String(R)===String(w)?R:(fe?.(w),w))},[fe]);d.useEffect(()=>{Fe.current=n},[n]),d.useEffect(()=>{U.current=r},[r]),d.useEffect(()=>{ge.current=s,s||l(null)},[s]);const sn=d.useCallback(w=>{U.current?.(w),ge.current&&l(w)},[]),mr=d.useMemo(()=>ue?[`tier ${ue.tier} | frame ${ue.frameMs?.toFixed(2)??"-"} ms | drawCalls ${ue.drawCalls??"-"}`,`tiles visible ${ue.visible} | rendered ${ue.rendered} | fallback ${ue.fallback}`,`cache size ${ue.cache} | hit ${ue.cacheHits??"-"} | miss ${ue.cacheMisses??"-"}`,`queue inflight ${ue.inflight} | queued ${ue.queued??"-"} | retries ${ue.retries??"-"} | failed ${ue.failed??"-"} | aborted ${ue.aborted??"-"}`,`points ${ue.points}`].join(`
135
- `):"stats: waiting for first frame...",[ue]);d.useEffect(()=>{!(pe===null?!0:de.some((q,k)=>String(Kt(q,k))===String(pe)))&&pe!==null&&Ye(null);const R=f.current;!(R===null?!0:de.some((q,k)=>String(Kt(q,k))===String(R)))&&R!==null&&(f.current=null,De(null),re?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[de,pe,re,Ye]),d.useEffect(()=>{const w=p.current;w!==null&&(Ee&&w<Ee.safeCount||(p.current=null,S.current=null,L?.({index:null,id:null,coordinate:null,pointCoordinate:null})))},[Ee,L]);const an=d.useCallback(w=>{G&&et(w);const R=Fe.current;R&&R(w),Ue.current?.(),Pe.current?.()},[G]);d.useEffect(()=>{if(!K){ye(!1);return}ye(!0)},[K,t?.id]),d.useEffect(()=>{N!=="cursor"&&f.current!==null&&(f.current=null,De(null),re?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[N,re]),d.useEffect(()=>{N!=="cursor"&&p.current!==null&&(p.current=null,S.current=null,L?.({index:null,id:null,coordinate:null,pointCoordinate:null}))},[N,L]);const Oe=d.useCallback((w,R)=>{const v=j.current;if(!v)return null;const q=v.screenToWorld(w,R);if(!Array.isArray(q)||q.length<2)return null;const k=Number(q[0]),le=Number(q[1]);return!Number.isFinite(k)||!Number.isFinite(le)?null:[k,le]},[]),un=d.useCallback((w,R)=>{const v=j.current;if(!v)return null;const q=v.worldToScreen(w,R);if(!Array.isArray(q)||q.length<2)return null;const k=Number(q[0]),le=Number(q[1]);return!Number.isFinite(k)||!Number.isFinite(le)?null:[k,le]},[]),ln=d.useCallback(()=>{j.current?.requestRender(),Ue.current?.(),Pe.current?.()},[]),cn=d.useMemo(()=>lt??j.current?.getViewState()??null,[lt]),fn=d.useMemo(()=>{if(!t)return null;const w=cn;return w?{source:t,viewState:w,drawTool:N,interactionLock:ee,worldToScreen:un,screenToWorld:Oe,requestRedraw:ln}:null},[t,cn,N,ee,un,Oe,ln]),gr=d.useCallback(w=>{const R=w.target===ae.current,v=Oe(w.clientX,w.clientY);if(Y){const ht=!!v&&v[0]>=0&&v[1]>=0&&!!t&&v[0]<=t.width&&v[1]<=t.height;Y({coordinate:v,clientX:w.clientX,clientY:w.clientY,insideImage:ht})}if(N!=="cursor")return;if(!R){je(null,null),f.current!==null&&(f.current=null,De(null),re?.({region:null,regionId:null,regionIndex:-1,coordinate:null}));return}if(!v){je(null,null);return}if(L&&je(Ze(v),v),!te.length)return;const q=Xt(v,te),k=q?.regionId??null,le=f.current;String(le)!==String(k)&&(f.current=k,De(k),re?.({region:q?.region??null,regionId:k,regionIndex:q?.regionIndex??-1,coordinate:v}))},[N,te,Oe,re,Y,t,je,Ze,L]),pr=d.useCallback(()=>{Y?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1}),je(null,null),f.current!==null&&(f.current=null,De(null),re?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[re,Y,je]),br=d.useCallback(w=>{if(N!=="cursor"||w.target!==ae.current)return;const R=Oe(w.clientX,w.clientY);if(!R)return;if(ct(R,w.button),!te.length){Ye(null);return}const v=Xt(R,te);if(!v){Ye(null);return}const q=pe!==null&&String(pe)===String(v.regionId)?null:v.regionId;Ye(q),we?.({region:v.region,regionId:v.regionId,regionIndex:v.regionIndex,coordinate:R})},[N,te,Oe,we,pe,Ye,ct]),yr=d.useCallback(w=>{if(N!=="brush"||Te?.clickSelectRoi!==!0||!te.length)return!1;const R=Xt(w,te);if(!R)return!1;const v=pe!==null&&String(pe)===String(R.regionId)?null:R.regionId;return Ye(v),we?.({region:R.region,regionId:R.regionId,regionIndex:R.regionIndex,coordinate:w}),!0},[N,Te?.clickSelectRoi,te,pe,Ye,we]),wr=d.useCallback(w=>{if(!ie||N!=="cursor"||w.target!==ae.current)return;w.preventDefault();const R=Oe(w.clientX,w.clientY);R&&ct(R,w.button)},[N,Oe,ct,ie]);return d.useEffect(()=>{const w=ae.current;if(!w||!t)return;const R=new dr(w,t,{onViewStateChange:an,onStats:sn,onTileError:i,onContextLost:o,onContextRestored:a,authToken:b,ctrlDragRotate:m,pointSizeByZoom:x,pointStrokeScale:E});return j.current=R,e&&R.setViewState(e),R.setInteractionLock(ee),G&&et(R.getViewState()),()=>{R.destroy(),j.current=null}},[t,sn,i,o,a,b,m,x,E,an,G]),d.useEffect(()=>{const w=j.current;!w||!e||w.setViewState(e)},[e]),d.useEffect(()=>{const w=j.current;w&&w.fitToImage()},[c]),d.useEffect(()=>{const w=j.current;w&&w.resetRotation()},[h]),d.useEffect(()=>{const w=j.current;!w||!y||w.setPointPalette(y)},[y]),d.useEffect(()=>{const w=j.current;w&&w.setPointSizeByZoom(x)},[x]),d.useEffect(()=>{const w=j.current;w&&w.setPointStrokeScale(E)},[E]),d.useEffect(()=>{const w=j.current;w&&w.setPointData(Me)},[Me]),d.useEffect(()=>{if(!z)return;const R=fr(F?Me:g,de,{paletteIndexToTermId:Z,includeEmptyRegions:!0});z(R)},[z,F,g,Me,de,Z]),d.useEffect(()=>{const w=j.current;w&&w.setInteractionLock(ee)},[ee]),Ae.jsxs("div",{className:ce,style:he,onPointerMove:gr,onPointerLeave:pr,onClick:br,onContextMenu:wr,children:[Ae.jsx("canvas",{ref:ae,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none",cursor:N==="cursor"&&Qe!==null?"pointer":ee?"crosshair":"grab"}}),t&&fn&&Array.isArray(T)&&T.length>0?T.map((w,R)=>Ae.jsx("div",{className:w.className,style:{position:"absolute",inset:0,zIndex:w.zIndex??3,pointerEvents:w.pointerEvents??"none",...w.style},children:w.render(fn)},w.id??R)):null,t?Ae.jsx(er,{tool:N,enabled:N!=="cursor",imageWidth:t.width,imageHeight:t.height,imageMpp:t.mpp,imageZoom:t.maxTierZoom,stampOptions:ve,brushOptions:Te,projectorRef:j,onBrushTap:yr,viewStateSignal:e,persistedRegions:de,patchRegions:O,regionStrokeStyle:$,regionStrokeHoverStyle:_e,regionStrokeActiveStyle:ze,patchStrokeStyle:Ke,resolveRegionStrokeStyle:be,overlayShapes:ne,hoveredRegionId:Qe,activeRegionId:pe,regionLabelStyle:I,invalidateRef:Ue,onDrawComplete:V,onPatchComplete:J}):null,s?Ae.jsx("pre",{"data-open-plant-debug-overlay":!0,style:Xe,children:mr}):null,t&&K?Ce?Ae.jsxs(Ae.Fragment,{children:[Ae.jsx(nr,{source:t,projectorRef:j,authToken:b,options:D,invalidateRef:Pe}),Ae.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:()=>ye(!1),style:{position:"absolute",zIndex:6,...ft.includes("left")?{left:We}:{right:We},...ft.includes("top")?{top:We+on+8}:{bottom:We+on+8},width:20,height:20,borderRadius:999,border:"1px solid rgba(255,255,255,0.4)",background:"rgba(8, 14, 22, 0.9)",color:"#fff",fontSize:13,lineHeight:1,cursor:"pointer",padding:0},children:"×"})]}):Ae.jsx("button",{type:"button","aria-label":"Show overview map",onClick:()=>ye(!0),style:{position:"absolute",zIndex:6,...ft.includes("left")?{left:We}:{right:We},...ft.includes("top")?{top:We}:{bottom:We},height:24,minWidth:40,borderRadius:999,border:"1px solid rgba(255,255,255,0.45)",background:"rgba(8, 14, 22, 0.9)",color:"#dff8ff",fontSize:11,fontWeight:700,cursor:"pointer",padding:"0 8px"},children:"Map"}):null]})}exports.DEFAULT_POINT_COLOR=Jt;exports.DrawLayer=er;exports.M1TileRenderer=On;exports.OverviewMap=nr;exports.TileScheduler=hr;exports.TileViewerCanvas=Zi;exports.WsiTileRenderer=dr;exports.WsiViewerCanvas=Co;exports.buildTermPalette=si;exports.calcScaleLength=ri;exports.calcScaleResolution=Qt;exports.clamp=Q;exports.closeRing=Be;exports.computeRoiPointGroups=fr;exports.createCircle=Ot;exports.createRectangle=Yt;exports.filterPointDataByPolygons=at;exports.filterPointDataByPolygonsHybrid=ar;exports.filterPointDataByPolygonsInWorker=cr;exports.filterPointIndicesByPolygons=ir;exports.filterPointIndicesByPolygonsInWorker=oo;exports.getWebGpuCapabilities=no;exports.hexToRgba=$n;exports.isSameViewState=ii;exports.normalizeImageInfo=$i;exports.prefilterPointsByBoundsWebGpu=sr;exports.terminateRoiClipWorker=io;exports.toBearerToken=oi;exports.toTileUrl=en;
157
+ }`),o=Ue(e,i,"uCamera"),s=Ue(e,i,"uPointSize"),a=Ue(e,i,"uPointStrokeScale"),u=Ue(e,i,"uPalette"),c=Ue(e,i,"uPaletteSize"),h=e.createVertexArray(),y=e.createBuffer(),m=e.createBuffer(),p=e.createBuffer(),g=e.createBuffer(),x=e.createTexture();if(!h||!y||!m||!p||!g||!x)throw new Error("point buffer allocation failed");e.bindVertexArray(h),e.bindBuffer(e.ARRAY_BUFFER,y),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const T=e.getAttribLocation(i,"aPosition");if(T<0)throw new Error("point position attribute not found");e.enableVertexAttribArray(T),e.vertexAttribPointer(T,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,m),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const B=e.getAttribLocation(i,"aTerm");if(B<0)throw new Error("point term attribute not found");e.enableVertexAttribArray(B),e.vertexAttribIPointer(B,1,e.UNSIGNED_SHORT,0,0),e.bindBuffer(e.ARRAY_BUFFER,p),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const z=e.getAttribLocation(i,"aFillMode");if(z<0)throw new Error("point fill mode attribute not found");return e.enableVertexAttribArray(z),e.vertexAttribIPointer(z,1,e.UNSIGNED_BYTE,0,0),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,g),e.bufferData(e.ELEMENT_ARRAY_BUFFER,0,e.DYNAMIC_DRAW),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),e.bindTexture(e.TEXTURE_2D,x),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([160,160,160,255])),e.bindTexture(e.TEXTURE_2D,null),{program:i,vao:h,posBuffer:y,termBuffer:m,fillModeBuffer:p,indexBuffer:g,paletteTexture:x,uCamera:o,uPointSize:s,uPointStrokeScale:a,uPalette:u,uPaletteSize:c}}handleTileLoaded(e,n){if(this.destroyed||this.contextLost||this.gl.isContextLost()){n.close();return}if(this.cache.has(e.key)){n.close();return}const r=this.createTextureFromBitmap(n);n.close(),r&&(this.cache.set(e.key,{key:e.key,texture:r,bounds:e.bounds,tier:e.tier,lastUsed:this.frameSerial}),this.trimCache(),this.requestRender())}createTextureFromBitmap(e){if(this.contextLost||this.gl.isContextLost())return null;const n=this.gl,r=n.createTexture();return r?(n.bindTexture(n.TEXTURE_2D,r),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,1),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,e),n.bindTexture(n.TEXTURE_2D,null),r):null}}const kt=[],wo=[],Mo={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)},So=.65,xo=4,Ao=24,Ro=1024,To=4;function Eo(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 Po(t,e){if(!(t instanceof Uint32Array)||e<=0||t.length===0)return null;let n=!1;for(let o=0;o<t.length;o+=1)if(!(t[o]<e)){n=!0;break}if(!n)return t;const r=new Uint32Array(t.length);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.subarray(0,i)}function Co(t,e){if(!t||e<=0)return 256;const n=Math.max(1,t.width*t.height),i=Math.sqrt(n/Math.max(1,e))*To;return Math.max(Ao,Math.min(Ro,i))}function vo(t,e){if(!t||!t.positions||!t.paletteIndices)return null;const n=Eo(t);if(n<=0)return null;const r=t.positions.subarray(0,n*2),i=t.ids instanceof Uint32Array&&t.ids.length>=n?t.ids.subarray(0,n):null,o=Po(t.drawIndices,n),s=o?o.length:n;if(s===0)return null;const a=Co(e,s),u=new Map,c=h=>{const y=r[h*2],m=r[h*2+1];if(!Number.isFinite(y)||!Number.isFinite(m))return;const p=Math.floor(y/a),g=Math.floor(m/a);let x=u.get(p);x||(x=new Map,u.set(p,x));const T=x.get(g);T?T.push(h):x.set(g,[h])};if(o)for(let h=0;h<o.length;h+=1)c(o[h]??0);else for(let h=0;h<n;h+=1)c(h);return u.size===0?null:{cellSize:a,safeCount:n,positions:r,ids:i,buckets:u}}function Zt(t,e){return t.id??e}function Io(t){const e=[];for(let n=0;n<t.length;n+=1){const r=t[n],i=lt([r?.coordinates]);i.length!==0&&e.push({region:r,regionIndex:n,regionId:Zt(r,n),polygons:i})}return e}function Dt(t,e){const n=t[0],r=t[1];for(let i=e.length-1;i>=0;i-=1){const o=e[i];for(const s of o.polygons)if(Kt(n,r,s))return{region:o.region,regionIndex:o.regionIndex,regionId:o.regionId}}return null}function _o({source:t,viewState:e,imageColorSettings:n=null,onViewStateChange:r,onStats:i,onTileError:o,onContextLost:s,onContextRestored:a,debugOverlay:u=!1,debugOverlayStyle:c,fitNonce:h=0,rotationResetNonce:y=0,authToken:m="",ctrlDragRotate:p=!0,pointData:g=null,pointPalette:x=null,pointSizeByZoom:T,pointStrokeScale:B,roiRegions:z,roiPolygons:N,clipPointsToRois:Y=!1,clipMode:C="worker",onClipStats:k,onRoiPointGroups:J,roiPaletteIndexToTermId:ue,interactionLock:j=!1,drawTool:$="cursor",stampOptions:Ce,brushOptions:fe,regionStrokeStyle:$e,regionStrokeHoverStyle:Ze,regionStrokeActiveStyle:Je,patchStrokeStyle:be,resolveRegionStrokeStyle:W,overlayShapes:Ie,customLayers:Ae,patchRegions:Ne,regionLabelStyle:Ke,onPointerWorldMove:oe,onPointHover:A,onPointClick:P,onRegionHover:v,onRegionClick:K,onActiveRegionChange:G,getCellByCoordinatesRef:_,onDrawComplete:Re,onPatchComplete:te,overviewMapConfig:F,className:he,style:de}){const Q=F?.show??!1,le=F?.options,ie=d.useRef(null),D=d.useRef(null),ne=d.useRef(null),U=d.useRef(null),se=d.useRef(r),we=d.useRef(i),Se=d.useRef(u),[Me,ye]=d.useState(null),[ce,tt]=d.useState(null),[ke,Fe]=d.useState(null),[X,l]=d.useState(null),f=d.useRef(null),b=d.useRef(null),S=d.useRef(null),R=d.useRef(0),L=z??kt,V=Ne??kt,Z=N??wo,q=(Ae?.length??0)>0,me=d.useMemo(()=>({position:"relative",width:"100%",height:"100%",...de}),[de]),Xe=d.useMemo(()=>({position:"absolute",top:8,left:8,zIndex:7,margin:0,padding:"8px 10px",maxWidth:"min(420px, 80%)",pointerEvents:"none",whiteSpace:"pre-wrap",lineHeight:1.35,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:11,color:"#cde6ff",background:"rgba(6, 12, 20, 0.82)",border:"1px solid rgba(173, 216, 255, 0.28)",borderRadius:8,boxShadow:"0 8px 22px rgba(0,0,0,0.35)",...c}),[c]),ge=d.useMemo(()=>L.length>0?L:Z.length===0?kt:Z.map((M,E)=>({id:E,coordinates:M})),[L,Z]),re=d.useMemo(()=>Io(ge),[ge]),pe=d.useMemo(()=>ge.map(M=>M.coordinates),[ge]),[Te,Ee]=d.useState(g);d.useEffect(()=>{const M=++R.current;let E=!1;if(!Y)return Ee(g),()=>{E=!0};if(!g||!g.count||!g.positions||!g.paletteIndices)return Ee(null),()=>{E=!0};if(pe.length===0)return Ee(Mo),k?.({mode:C,durationMs:0,inputCount:g.count,outputCount:0,polygonCount:0}),()=>{E=!0};const I=(O,ae)=>{if(E||M!==R.current)return;const ft=O?.drawIndices?O.drawIndices.length:O?.count??0;Ee(O),k?.({mode:ae.mode,durationMs:ae.durationMs,inputCount:g.count,outputCount:ft,polygonCount:pe.length,usedWebGpu:ae.usedWebGpu,candidateCount:ae.candidateCount,bridgedToDraw:ae.bridgedToDraw})};return(async()=>{if(C==="sync"){const O=performance.now(),ae=ut(g,pe);I(ae,{mode:"sync",durationMs:performance.now()-O});return}if(C==="hybrid-webgpu"){const O=await ar(g,pe,{bridgeToDraw:!0});I(O.data,{mode:O.meta.mode,durationMs:O.meta.durationMs,usedWebGpu:O.meta.usedWebGpu,candidateCount:O.meta.candidateCount,bridgedToDraw:O.meta.bridgedToDraw});return}try{const O=await cr(g,pe);I(O.data,{mode:O.meta.mode,durationMs:O.meta.durationMs})}catch{const O=performance.now(),ae=ut(g,pe);I(ae,{mode:"sync",durationMs:performance.now()-O})}})(),()=>{E=!0}},[Y,C,g,pe,k]);const nn=!!(A||P||_),ve=d.useMemo(()=>nn?vo(Te,t):null,[nn,Te,t]),je=d.useCallback(M=>{const E=D.current;if(!E||!ve)return null;const I=Number(M[0]),H=Number(M[1]);if(!Number.isFinite(I)||!Number.isFinite(H))return null;const O=Math.max(1e-6,E.getViewState().zoom),ae=E.getPointSizeByZoom(),nt=Math.max(xo,ae*So)/O;if(!Number.isFinite(nt)||nt<=0)return null;const Ct=ve.cellSize,cn=Math.floor(I/Ct),fn=Math.floor(H/Ct),ht=Math.max(1,Math.ceil(nt/Ct)),Mr=nt*nt;let dt=-1,hn=Mr,dn=0,mn=0;for(let vt=cn-ht;vt<=cn+ht;vt+=1){const gn=ve.buckets.get(vt);if(gn)for(let It=fn-ht;It<=fn+ht;It+=1){const mt=gn.get(It);if(!(!mt||mt.length===0))for(let _t=0;_t<mt.length;_t+=1){const gt=mt[_t];if(gt>=ve.safeCount)continue;const pn=ve.positions[gt*2],bn=ve.positions[gt*2+1],yn=pn-I,wn=bn-H,Mn=yn*yn+wn*wn;Mn>hn||(hn=Mn,dt=gt,dn=pn,mn=bn)}}}if(dt<0)return null;const Sr=ve.ids?Number(ve.ids[dt]):null;return{index:dt,id:Sr,coordinate:[I,H],pointCoordinate:[dn,mn]}},[ve]),Qe=d.useCallback((M,E)=>{if(!A)return;const I=M?.index??null,H=M?.id??null;b.current===I&&S.current===H||(b.current=I,S.current=H,A({index:I,id:H,coordinate:E,pointCoordinate:M?.pointCoordinate??null}))},[A]),ct=d.useCallback((M,E)=>{if(!P)return;const I=je(M);I&&P({...I,button:E})},[P,je]);d.useEffect(()=>{if(_)return _.current=je,()=>{_.current===je&&(_.current=null)}},[_,je]);const Ye=d.useCallback(M=>{tt(E=>String(E)===String(M)?E:(G?.(M),M))},[G]);d.useEffect(()=>{se.current=r},[r]),d.useEffect(()=>{we.current=i},[i]),d.useEffect(()=>{Se.current=u,u||l(null)},[u]);const rn=d.useCallback(M=>{we.current?.(M),Se.current&&l(M)},[]),mr=d.useMemo(()=>X?[`tier ${X.tier} | frame ${X.frameMs?.toFixed(2)??"-"} ms | drawCalls ${X.drawCalls??"-"}`,`tiles visible ${X.visible} | rendered ${X.rendered} | fallback ${X.fallback}`,`cache size ${X.cache} | hit ${X.cacheHits??"-"} | miss ${X.cacheMisses??"-"}`,`queue inflight ${X.inflight} | queued ${X.queued??"-"} | retries ${X.retries??"-"} | failed ${X.failed??"-"} | aborted ${X.aborted??"-"}`,`points ${X.points}`].join(`
158
+ `):"stats: waiting for first frame...",[X]);d.useEffect(()=>{!(ce===null?!0:ge.some((H,O)=>String(Zt(H,O))===String(ce)))&&ce!==null&&Ye(null);const E=f.current;!(E===null?!0:ge.some((H,O)=>String(Zt(H,O))===String(E)))&&E!==null&&(f.current=null,ye(null),v?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[ge,ce,v,Ye]),d.useEffect(()=>{const M=b.current;M!==null&&(ve&&M<ve.safeCount||(b.current=null,S.current=null,A?.({index:null,id:null,coordinate:null,pointCoordinate:null})))},[ve,A]);const on=d.useCallback(M=>{q&&Fe(M);const E=se.current;E&&E(M),ne.current?.(),U.current?.()},[q]);d.useEffect(()=>{$!=="cursor"&&f.current!==null&&(f.current=null,ye(null),v?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[$,v]),d.useEffect(()=>{$!=="cursor"&&b.current!==null&&(b.current=null,S.current=null,A?.({index:null,id:null,coordinate:null,pointCoordinate:null}))},[$,A]);const We=d.useCallback((M,E)=>{const I=D.current;if(!I)return null;const H=I.screenToWorld(M,E);if(!Array.isArray(H)||H.length<2)return null;const O=Number(H[0]),ae=Number(H[1]);return!Number.isFinite(O)||!Number.isFinite(ae)?null:[O,ae]},[]),sn=d.useCallback((M,E)=>{const I=D.current;if(!I)return null;const H=I.worldToScreen(M,E);if(!Array.isArray(H)||H.length<2)return null;const O=Number(H[0]),ae=Number(H[1]);return!Number.isFinite(O)||!Number.isFinite(ae)?null:[O,ae]},[]),an=d.useCallback(()=>{D.current?.requestRender(),ne.current?.(),U.current?.()},[]),un=d.useMemo(()=>ke??D.current?.getViewState()??null,[ke]),ln=d.useMemo(()=>{if(!t)return null;const M=un;return M?{source:t,viewState:M,drawTool:$,interactionLock:j,worldToScreen:sn,screenToWorld:We,requestRedraw:an}:null},[t,un,$,j,sn,We,an]),gr=d.useCallback(M=>{const E=M.target===ie.current,I=We(M.clientX,M.clientY);if(oe){const ft=!!I&&I[0]>=0&&I[1]>=0&&!!t&&I[0]<=t.width&&I[1]<=t.height;oe({coordinate:I,clientX:M.clientX,clientY:M.clientY,insideImage:ft})}if($!=="cursor")return;if(!E){Qe(null,null),f.current!==null&&(f.current=null,ye(null),v?.({region:null,regionId:null,regionIndex:-1,coordinate:null}));return}if(!I){Qe(null,null);return}if(A&&Qe(je(I),I),!re.length)return;const H=Dt(I,re),O=H?.regionId??null,ae=f.current;String(ae)!==String(O)&&(f.current=O,ye(O),v?.({region:H?.region??null,regionId:O,regionIndex:H?.regionIndex??-1,coordinate:I}))},[$,re,We,v,oe,t,Qe,je,A]),pr=d.useCallback(()=>{oe?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1}),Qe(null,null),f.current!==null&&(f.current=null,ye(null),v?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[v,oe,Qe]),br=d.useCallback(M=>{if($!=="cursor"||M.target!==ie.current)return;const E=We(M.clientX,M.clientY);if(!E)return;if(ct(E,M.button),!re.length){Ye(null);return}const I=Dt(E,re);if(!I){Ye(null);return}const H=ce!==null&&String(ce)===String(I.regionId)?null:I.regionId;Ye(H),K?.({region:I.region,regionId:I.regionId,regionIndex:I.regionIndex,coordinate:E})},[$,re,We,K,ce,Ye,ct]),yr=d.useCallback(M=>{if($!=="brush"||fe?.clickSelectRoi!==!0||!re.length)return!1;const E=Dt(M,re);if(!E)return!1;const I=ce!==null&&String(ce)===String(E.regionId)?null:E.regionId;return Ye(I),K?.({region:E.region,regionId:E.regionId,regionIndex:E.regionIndex,coordinate:M}),!0},[$,fe?.clickSelectRoi,re,ce,Ye,K]),wr=d.useCallback(M=>{if(!P||$!=="cursor"||M.target!==ie.current)return;M.preventDefault();const E=We(M.clientX,M.clientY);E&&ct(E,M.button)},[$,We,ct,P]);return d.useEffect(()=>{const M=ie.current;if(!M||!t)return;const E=new dr(M,t,{onViewStateChange:on,onStats:rn,onTileError:o,onContextLost:s,onContextRestored:a,authToken:m,imageColorSettings:n,ctrlDragRotate:p,pointSizeByZoom:T,pointStrokeScale:B});return D.current=E,e&&E.setViewState(e),E.setInteractionLock(j),q&&Fe(E.getViewState()),()=>{E.destroy(),D.current=null}},[t,rn,o,s,a,m,p,T,B,on,q]),d.useEffect(()=>{const M=D.current;!M||!e||M.setViewState(e)},[e]),d.useEffect(()=>{const M=D.current;M&&M.fitToImage()},[h]),d.useEffect(()=>{const M=D.current;M&&M.resetRotation()},[y]),d.useEffect(()=>{const M=D.current;!M||!x||M.setPointPalette(x)},[x]),d.useEffect(()=>{const M=D.current;M&&M.setPointSizeByZoom(T)},[T]),d.useEffect(()=>{const M=D.current;M&&M.setPointStrokeScale(B)},[B]),d.useEffect(()=>{const M=D.current;M&&M.setImageColorSettings(n)},[n]),d.useEffect(()=>{const M=D.current;M&&M.setPointData(Te)},[Te]),d.useEffect(()=>{if(!J)return;const E=fr(Y?Te:g,ge,{paletteIndexToTermId:ue,includeEmptyRegions:!0});J(E)},[J,Y,g,Te,ge,ue]),d.useEffect(()=>{const M=D.current;M&&M.setInteractionLock(j)},[j]),Be.jsxs("div",{className:he,style:me,onPointerMove:gr,onPointerLeave:pr,onClick:br,onContextMenu:wr,children:[Be.jsx("canvas",{ref:ie,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none",cursor:$==="cursor"&&Me!==null?"pointer":j?"crosshair":"grab"}}),t&&ln&&Array.isArray(Ae)&&Ae.length>0?Ae.map((M,E)=>Be.jsx("div",{className:M.className,style:{position:"absolute",inset:0,zIndex:M.zIndex??3,pointerEvents:M.pointerEvents??"none",...M.style},children:M.render(ln)},M.id??E)):null,t?Be.jsx(er,{tool:$,enabled:$!=="cursor",imageWidth:t.width,imageHeight:t.height,imageMpp:t.mpp,imageZoom:t.maxTierZoom,stampOptions:Ce,brushOptions:fe,projectorRef:D,onBrushTap:yr,viewStateSignal:e,persistedRegions:ge,patchRegions:V,regionStrokeStyle:$e,regionStrokeHoverStyle:Ze,regionStrokeActiveStyle:Je,patchStrokeStyle:be,resolveRegionStrokeStyle:W,overlayShapes:Ie,hoveredRegionId:Me,activeRegionId:ce,regionLabelStyle:Ke,invalidateRef:ne,onDrawComplete:Re,onPatchComplete:te}):null,u?Be.jsx("pre",{"data-open-plant-debug-overlay":!0,style:Xe,children:mr}):null,t&&Q&&Be.jsx(nr,{source:t,projectorRef:D,authToken:m,options:le,invalidateRef:U,className:F?.className,style:F?.style})]})}exports.DEFAULT_POINT_COLOR=jt;exports.DrawLayer=er;exports.M1TileRenderer=Wn;exports.OverviewMap=nr;exports.TileScheduler=hr;exports.TileViewerCanvas=Ki;exports.WsiTileRenderer=dr;exports.WsiViewerCanvas=_o;exports.buildTermPalette=si;exports.calcScaleLength=ri;exports.calcScaleResolution=Jt;exports.clamp=ee;exports.closeRing=Le;exports.computeRoiPointGroups=fr;exports.createCircle=Yt;exports.createRectangle=Xt;exports.filterPointDataByPolygons=ut;exports.filterPointDataByPolygonsHybrid=ar;exports.filterPointDataByPolygonsInWorker=cr;exports.filterPointIndicesByPolygons=ir;exports.filterPointIndicesByPolygonsInWorker=so;exports.getWebGpuCapabilities=ro;exports.hexToRgba=$n;exports.isSameViewState=ii;exports.normalizeImageInfo=$i;exports.prefilterPointsByBoundsWebGpu=sr;exports.terminateRoiClipWorker=oo;exports.toBearerToken=oi;exports.toTileUrl=Qt;
136
159
  //# sourceMappingURL=index.cjs.map