open-plant 1.2.15 → 1.2.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +7 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1760 -1630
- package/dist/index.js.map +1 -1
- package/dist/types/react/draw-layer.d.ts +1 -0
- package/dist/types/react/draw-layer.d.ts.map +1 -1
- package/dist/types/react/wsi-viewer-canvas.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var vr=Object.defineProperty;var _r=(t,e,n)=>e in t?vr(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var M=(t,e,n)=>_r(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ue=require("react/jsx-runtime"),m=require("react");var zt=typeof document<"u"?document.currentScript:null;function En(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 Fr(t,e,n){const r=En(t,t.VERTEX_SHADER,e),i=En(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 kt(t,e,n){const r=t.getUniformLocation(e,n);if(!r)throw new Error(`Failed to get uniform location: ${n}`);return r}function Ur(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 Br=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,s=1-this.viewState.offsetY*i;return new Float32Array([r,0,0,0,i,0,o,s,1])}};const Lr=`#version 300 es
|
|
2
2
|
precision highp float;
|
|
3
3
|
|
|
4
4
|
in vec2 aUnit;
|
|
@@ -18,7 +18,7 @@ void main() {
|
|
|
18
18
|
gl_Position = vec4(clip.xy, 0.0, 1.0);
|
|
19
19
|
vUv = aUv;
|
|
20
20
|
}
|
|
21
|
-
`,
|
|
21
|
+
`,Nr=`#version 300 es
|
|
22
22
|
precision highp float;
|
|
23
23
|
|
|
24
24
|
in vec2 vUv;
|
|
@@ -29,7 +29,7 @@ out vec4 outColor;
|
|
|
29
29
|
void main() {
|
|
30
30
|
outColor = texture(uTexture, vUv);
|
|
31
31
|
}
|
|
32
|
-
`;class 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=`
|
|
32
|
+
`;class Zn{constructor(e){M(this,"canvas");M(this,"gl");M(this,"camera",new Br);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=Ur(this.canvas),this.program=Fr(this.gl,Lr,Nr);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=kt(this.gl,this.program,"uCamera"),this.uBoundsLocation=kt(this.gl,this.program,"uBounds"),this.uTextureLocation=kt(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 zr=.1,kr=4e6,Dr=4096,Or=64,Xr=1,Wr=4,Kn=1e-6,Yr=24;function _t(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 Vr(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 Gr(t,e,n){if(e<=Kn||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 Dt(t,e){if(!t.length)return[];let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,c]of t)a<n&&(n=a),a>i&&(i=a),c<r&&(r=c),c>o&&(o=c);if(!Number.isFinite(n)||!Number.isFinite(r))return[];const s=Math.max(e,1);return ze([[n-s,r-s],[i+s,r-s],[i+s,o+s],[n-s,o+s]])}function qr(t,e){let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,c]of t)a<n&&(n=a),a>i&&(i=a),c<r&&(r=c),c>o&&(o=c);const s=Math.max(e,1);return[n-s,r-s,i+s,o+s]}function Hr(t,e,n){const r=Math.max(zr,Number(n.minRasterStep)||0),i=Math.max(32768,Math.floor(n.maxRasterPixels||kr)),o=Math.max(256,Math.floor(n.maxRasterSize||Dr)),s=Math.max(.001,t[2]-t[0]),a=Math.max(.001,t[3]-t[1]);let c=Math.max(r,Number.EPSILON),l=3,f=Math.ceil(s/c)+l*2+1,p=Math.ceil(a/c)+l*2+1;for(;(f>o||p>o||f*p>i)&&(c*=1.15,f=Math.ceil(s/c)+l*2+1,p=Math.ceil(a/c)+l*2+1,!(c>Math.max(s,a))););return f=Math.max(8,f),p=Math.max(8,p),{minX:t[0],minY:t[1],step:c,padding:l,width:f,height:p}}function $r(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 Zr(t,e){return[(t[0]-e.minX)/e.step+e.padding,(t[1]-e.minY)/e.step+e.padding]}function Kr(t,e,n){const r=$r(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=>Zr(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]>=Yr?1:0;return s}function jr(t,e,n){const r=[],i=e+1,o=(a,c)=>c*i+a,s=(a,c)=>a>=0&&c>=0&&a<e&&c<n&&t[c*e+a]>0;for(let a=0;a<n;a+=1)for(let c=0;c<e;c+=1)s(c,a)&&(s(c,a-1)||r.push({start:o(c,a),end:o(c+1,a),dir:0}),s(c+1,a)||r.push({start:o(c+1,a),end:o(c+1,a+1),dir:1}),s(c,a+1)||r.push({start:o(c+1,a+1),end:o(c,a+1),dir:2}),s(c-1,a)||r.push({start:o(c,a+1),end:o(c,a),dir:3}));return r}function Jr(t,e){const n=(e-t+4)%4;return n===1?0:n===0?1:n===3?2:3}function Qr(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,c=o.dir;const l=[o.start,o.end];n[i]=1;let f=0;const p=t.length*3;for(;a!==s&&f<p;){const d=e.get(a);if(!d||d.length===0)break;let b=-1,g=1/0;for(const T of d){if(n[T])continue;const L=t[T],D=Jr(c,L.dir);D<g&&(g=D,b=T)}if(b<0)break;n[b]=1;const S=t[b];a=S.end,c=S.dir,l.push(a),f+=1}l.length>=4&&l[0]===l[l.length-1]&&r.push(l)}return r}function ei(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 ti(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 ni(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],c=(s[0]-o[0])*(a[1]-s[1])-(s[1]-o[1])*(a[0]-s[0]);Math.abs(c)<=e||r.push(s)}return r.push(r[0]),ze(r)}function ri(t,e,n){const r=n[0]-e[0],i=n[1]-e[1],o=r*r+i*i;if(o<=1e-12){const p=t[0]-e[0],d=t[1]-e[1];return p*p+d*d}const s=_t(((t[0]-e[0])*r+(t[1]-e[1])*i)/o,0,1),a=e[0]+r*s,c=e[1]+i*s,l=t[0]-a,f=t[1]-c;return l*l+f*f}function ii(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,c]=s;if(c-a<=1)continue;let l=0,f=-1;for(let p=a+1;p<c;p+=1){const d=ri(t[p],t[a],t[c]);d>l&&(l=d,f=p)}f>=0&&l>r&&(n[f]=1,i.push([a,f],[f,c]))}const o=[];for(let s=0;s<t.length;s+=1)n[s]&&o.push(t[s]);return o}function oi(t,e){const n=ze(t);if(n.length<5||e<=0)return n;const r=n.slice(0,-1),i=ii(r,e);return i.length<3?n:ze(i)}function si(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],c=i[(s+1)%i.length];o.push([a[0]*.75+c[0]*.25,a[1]*.75+c[1]*.25],[a[0]*.25+c[0]*.75,a[1]*.25+c[1]*.75])}n=ze(o)}return n}function st(t,e){return e?ze(t.map(([n,r])=>[_t(n,e[0],e[2]),_t(r,e[1],e[3])])):t}function ai(t,e){const n=Vr(t),r=Math.max(Kn,Number(e.radius)||0);if(n.length===0||!Number.isFinite(r))return[];const i=Math.max(12,Math.floor(e.circleSides||Or));if(n.length===1)return st(Gr(n[0],r,i),e.clipBounds);const o=qr(n,r),s=Hr(o,r,e),a=Kr(n,r,s);if(!a.length)return st(Dt(n,r),e.clipBounds);const c=jr(a,s.width,s.height),l=Qr(c);if(!l.length)return st(Dt(n,r),e.clipBounds);let f=[],p=0;for(const S of l){const T=ei(S,s.width,s),L=Math.abs(ti(T));L<=p||(p=L,f=T)}if(!f.length)return st(Dt(n,r),e.clipBounds);const d=typeof e.simplifyTolerance=="number"&&Number.isFinite(e.simplifyTolerance)?Math.max(0,e.simplifyTolerance):s.step*.2,b=typeof e.smoothingPasses=="number"&&Number.isFinite(e.smoothingPasses)?Math.round(_t(e.smoothingPasses,0,Wr)):Xr,g=oi(si(ni(f,s.step*.001),b),d);return st(g,e.clipBounds)}function Cn(t){return typeof t=="number"&&Number.isFinite(t)}function ci(t){return Array.isArray(t)&&t.length>=2&&Cn(t[0])&&Cn(t[1])}function jn(t){return Array.isArray(t)&&t.length>0&&t.every(e=>ci(e))}function Jn(t){return Array.isArray(t)&&t.length>0&&t.every(e=>jn(e))}function ui(t){return Array.isArray(t)&&t.length>0&&t.every(e=>Jn(e))}function li(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 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 e*.5}function Ot(t){if(!Array.isArray(t)||t.length===0)return[];const e=[];for(const o of t){const s=li(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(Vt(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 Qn(t){if(!t)return[];if(jn(t)){const e=Ot([t]);return e.length>0?[e]:[]}if(Jn(t)){const e=Ot(t);return e.length>0?[e]:[]}if(ui(t)){const e=[];for(const n of t){const r=Ot(n);r.length>0&&e.push(r)}return e}return[]}function Pn(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],c=n[o][0],l=n[o][1];a>e!=l>e&&t<(c-s)*(e-a)/(l-a||Number.EPSILON)+s&&(r=!r)}return r}function dt(t){const e=[];for(const n of t??[]){const r=Qn(n);for(const i of r){const o=i[0];if(!o||o.length<4)continue;let s=1/0,a=1/0,c=-1/0,l=-1/0;for(const[p,d]of o)p<s&&(s=p),p>c&&(c=p),d<a&&(a=d),d>l&&(l=d);if(!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(c)||!Number.isFinite(l))continue;let f=Math.abs(Vt(o));for(let p=1;p<i.length;p+=1)f-=Math.abs(Vt(i[p]));e.push({outer:o,holes:i.slice(1),minX:s,minY:a,maxX:c,maxY:l,area:Math.max(1e-6,f)})}}return e}function er(t,e,n){if(t<n.minX||t>n.maxX||e<n.minY||e>n.maxY||!Pn(t,e,n.outer))return!1;for(const r of n.holes)if(Pn(t,e,r))return!1;return!0}function Ft(t,e,n){for(const r of n)if(er(t,e,r))return!0;return!1}const nn=[160,160,160,255];function te(t,e,n){return Math.max(e,Math.min(n,t))}function rn(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 fi(t,e,n){let i=100*rn(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 hi(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 di(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 tr(t){const n=String(t??"").trim().match(/^#?([0-9a-fA-F]{6})$/);if(!n)return[...nn];const r=Number.parseInt(n[1],16);return[r>>16&255,r>>8&255,r&255,255]}function mi(t){const e=[[...nn]],n=new Map;for(const i of t??[]){const o=String(i?.termId??"");!o||n.has(o)||(n.set(o,e.length),e.push(tr(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 In(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 gi="rgba(255, 77, 79, 0.16)",pi=3,bi=2,nr=96,wi=1,vn=[],ft=[],_n=1e3,rr=2,ir=2,yi=4096,Mi=.2,Si=1.12,xi=.89,Ai=32,Ri="#000000",Ti=.1,Ei="#FFCF00",Ci="#FF0000",Pi=1.5,Fn=[2,2],Ii=1,vi=.25,_i=4,Fi=1,Ui=0,Bi=4,Li=.05,Ni=256,Un=1.5,He={color:"#ff4d4f",width:2,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},zi={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},ki="rgba(23, 23, 25, 0.1)",Di=6,_e={fontFamily:"Pretendard, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:11,fontWeight:600,textColor:"#171719",backgroundColor:"#FFCC00",borderColor:"rgba(0, 0, 0, 0)",borderWidth:0,paddingX:8,paddingY:4,offsetY:10,borderRadius:4};function Ye(t,e,n){return Math.max(e,Math.min(n,t))}function Mt(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 ut(t,e){return typeof t!="number"||!Number.isFinite(t)||t<=0?e:t}function Oi(t){return{rectangleAreaMm2:ut(t?.rectangleAreaMm2,rr),circleAreaMm2:ut(t?.circleAreaMm2,ir),rectanglePixelSize:ut(t?.rectanglePixelSize,yi)}}function Xi(t,e){return typeof t!="number"||!Number.isFinite(t)?e:Ye(t,0,1)}function Wi(t){if(!Array.isArray(t))return Fn;const e=t.filter(n=>Number.isFinite(n)&&n>=0);return e.length>0?e:Fn}function Yi(t){return typeof t!="number"||!Number.isFinite(t)?Ii:Ye(t,vi,_i)}function Vi(t){return typeof t!="number"||!Number.isFinite(t)?Fi:Math.round(Ye(t,Ui,Bi))}function Gi(t){const e=ut(t?.radius,Ai),n=ut(t?.cursorLineWidth,Pi),r=Yi(t?.edgeDetail),i=Vi(t?.edgeSmoothing);return{radius:e,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:t?.clickSelectRoi===!0,fillColor:t?.fillColor||Ri,fillOpacity:Xi(t?.fillOpacity,Ti),cursorColor:t?.cursorColor||Ei,cursorActiveColor:t?.cursorActiveColor||Ci,cursorLineWidth:n,cursorLineDash:Wi(t?.cursorLineDash)}}function qi(t){return t*_n*_n}function Bn(t,e){return!t||!Number.isFinite(e)||e<=0?[]:Ne([[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 Hi(t,e,n=nr){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 Ne(r)}function Ne(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 Gt(t,e){return!t||!e?[]:Ne([[t[0],t[1]],[e[0],t[1]],[e[0],e[1]],[t[0],e[1]]])}function qt(t,e,n=nr){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 c=a/n*Math.PI*2;s.push([r+Math.cos(c)*o,i+Math.sin(c)*o])}return Ne(s)}function Ht(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 Ln(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 Nn(t){return Array.isArray(t)&&t.length>=4&&Ht(t)>wi}function $t(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 Le(t,e,n,r=!1,i=!1){e.length!==0&&(t.beginPath(),$t(t,e,r),i&&r&&(t.fillStyle=gi,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(ft),t.shadowColor="rgba(0, 0, 0, 0)",t.shadowBlur=0,t.shadowOffsetX=0,t.shadowOffsetY=0)}function or(t){const e=Array.isArray(t?.lineDash)?t.lineDash.filter(s=>Number.isFinite(s)&&s>=0):ft,n=typeof t?.width=="number"&&Number.isFinite(t.width)?Math.max(0,t.width):He.width,r=typeof t?.shadowBlur=="number"&&Number.isFinite(t.shadowBlur)?Math.max(0,t.shadowBlur):He.shadowBlur,i=typeof t?.shadowOffsetX=="number"&&Number.isFinite(t.shadowOffsetX)?t.shadowOffsetX:He.shadowOffsetX,o=typeof t?.shadowOffsetY=="number"&&Number.isFinite(t.shadowOffsetY)?t.shadowOffsetY:He.shadowOffsetY;return{color:t?.color||He.color,width:n,lineDash:e.length?e:ft,lineJoin:t?.lineJoin||He.lineJoin,lineCap:t?.lineCap||He.lineCap,shadowColor:t?.shadowColor||He.shadowColor,shadowBlur:r,shadowOffsetX:i,shadowOffsetY:o}}function at(t,e){return e?or({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 zn(t,e){return t==null||e===null||e===void 0?!1:String(t)===String(e)}function $i(t){const e=t[0];return Array.isArray(e)&&Array.isArray(e[0])}function kn(t){return typeof t=="number"&&Number.isFinite(t)}function Zi(t){return Array.isArray(t)&&t.length>=2&&kn(t[0])&&kn(t[1])}function Ki(t){return Array.isArray(t)&&t.length>=2&&t.every(e=>Zi(e))}function sr(t,e){if(!(!Array.isArray(t)||t.length===0)){if(Ki(t)){e.push(t.map(([n,r])=>[n,r]));return}for(const n of t)sr(n,e)}}function Dn(t,e){const n=[];sr(t,n);const r=[];for(const i of n){if(i.length<2)continue;const o=e?Ne(i):i;o.length>=(e?4:2)&&r.push(o)}return r}function ji(t,e,n,r){if(!(e.length<4||n.length===0)){t.save(),t.beginPath(),$t(t,e,!0);for(const i of n)i.length<4||$t(t,i,!0);t.fillStyle=r,t.fill("evenodd"),t.restore()}}function ar(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 Ji(t){return{color:ki,width:Di,lineDash:ft,lineJoin:t.lineJoin,lineCap:t.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function Qi(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 eo(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 to(t){let e=null;for(const n of t){const r=eo(n.outer);r&&(!e||r[1]<e[1]||r[1]===e[1]&&r[0]<e[0])&&(e=r)}return e}function On(t){const e=Qn(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,c])=>[a,c]),s=[];for(let a=1;a<r.length;a+=1){const c=r[a];!c||c.length<4||s.push(c.map(([l,f])=>[l,f]))}n.push({outer:o,holes:s})}return n}function no(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 c=t.measureText(s).width+o.paddingX*2,l=o.fontSize+o.paddingY*2,f=Ye(n[0],c*.5+1,r-c*.5-1),p=Ye(n[1]-o.offsetY,l*.5+1,i-l*.5-1),d=f-c*.5,b=p-l*.5;t.fillStyle=o.backgroundColor,t.strokeStyle=o.borderColor,t.lineWidth=o.borderWidth,Qi(t,d,b,c,l,o.borderRadius),t.fill(),o.borderWidth>0&&t.stroke(),t.fillStyle=o.textColor,t.fillText(s,f,p+.5),t.restore()}function St(t,e,n){return[Ye(t[0],0,e),Ye(t[1],0,n)]}function ct(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 cr({tool:t,imageWidth:e,imageHeight:n,imageMpp:r,imageZoom:i,stampOptions:o,brushOptions:s,projectorRef:a,onBrushTap:c,onDrawComplete:l,onPatchComplete:f,enabled:p,viewStateSignal:d,persistedRegions:b,patchRegions:g,persistedPolygons:S,regionStrokeStyle:T,regionStrokeHoverStyle:L,regionStrokeActiveStyle:D,patchStrokeStyle:O,resolveRegionStrokeStyle:Y,overlayShapes:P,hoveredRegionId:X=null,activeRegionId:Q=null,regionLabelStyle:ce,invalidateRef:J,className:Z,style:Pe}){const he=m.useRef(null),Ke=m.useRef(!1),je=m.useRef(new Map),et=m.useRef(t),pe=m.useRef({isDrawing:!1,pointerId:null,start:null,current:null,cursor:null,cursorScreen:null,points:[],screenPoints:[],stampCenter:null}),V=p??t!=="cursor",ve=m.useMemo(()=>b&&b.length>0?b:!S||S.length===0?vn:S.map((u,h)=>({id:h,coordinates:u})),[b,S]),Te=m.useMemo(()=>g??vn,[g]),ke=m.useMemo(()=>{const u=[];for(let h=0;h<ve.length;h+=1){const w=ve[h],x=On(w.coordinates);x.length!==0&&u.push({region:w,regionIndex:h,regionKey:w.id??h,polygons:x})}return u},[ve]),De=m.useMemo(()=>{const u=[];for(let h=0;h<Te.length;h+=1){const w=Te[h],x=On(w.coordinates);x.length!==0&&u.push({region:w,regionIndex:h,regionKey:w.id??h,polygons:x})}return u},[Te]),se=m.useMemo(()=>or(T),[T]),A=m.useMemo(()=>at(se,L),[se,L]),C=m.useMemo(()=>at(se,D),[se,D]),I=m.useMemo(()=>at(zi,O),[O]),j=m.useMemo(()=>ar(ce),[ce]),q=m.useMemo(()=>Oi(o),[o]),F=m.useMemo(()=>Gi(s),[s]),Ee=m.useMemo(()=>({position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",touchAction:"none",pointerEvents:V?"auto":"none",cursor:V?t==="brush"?"none":"crosshair":"default",...Pe}),[V,t,Pe]),ne=m.useCallback(()=>{const u=he.current;if(!u)return;const h=u.getBoundingClientRect(),w=Math.max(1,window.devicePixelRatio||1),x=Math.max(1,Math.round(h.width*w)),R=Math.max(1,Math.round(h.height*w));(u.width!==x||u.height!==R)&&(u.width=x,u.height=R)},[]),N=m.useCallback(u=>{const h=a.current;if(!h||u.length===0)return[];const w=new Array(u.length);for(let x=0;x<u.length;x+=1){const R=ct(h.worldToScreen(u[x][0],u[x][1]));if(!R)return[];w[x]=R}return w},[a]),de=m.useCallback(u=>{const h=a.current,w=he.current;if(!h||!w)return null;const x=w.getBoundingClientRect(),R=ct(h.screenToWorld(x.left+u[0],x.top+u[1]));return R?St(R,e,n):null},[a,e,n]),me=m.useCallback(u=>{if(!Number.isFinite(u)||u<=0)return 0;const h=typeof r=="number"&&Number.isFinite(r)&&r>0?r:1,w=typeof i=="number"&&Number.isFinite(i)?i:0,x=a.current?.getViewState?.().zoom,R=typeof x=="number"&&Number.isFinite(x)&&x>0?x:1,z=w+Math.log2(R),G=Math.max(1e-9,rn(h,w,z));return u/G/R},[r,i,a]),ee=m.useCallback((u,h)=>{if(!h)return[];let w=0;if(u==="stamp-rectangle-4096px"){const z=q.rectanglePixelSize*.5;return Bn(h,z).map(K=>St(K,e,n))}if(u==="stamp-rectangle"||u==="stamp-rectangle-2mm2"?w=u==="stamp-rectangle-2mm2"?rr:q.rectangleAreaMm2:(u==="stamp-circle"||u==="stamp-circle-2mm2"||u==="stamp-circle-hpf-0.2mm2")&&(w=u==="stamp-circle-hpf-0.2mm2"?Mi:u==="stamp-circle-2mm2"?ir:q.circleAreaMm2),!Number.isFinite(w)||w<=0)return[];const x=qi(w);let R=[];if(u==="stamp-rectangle"||u==="stamp-rectangle-2mm2"){const z=me(Math.sqrt(x)*.5);R=Bn(h,z)}else if(u==="stamp-circle"||u==="stamp-circle-2mm2"||u==="stamp-circle-hpf-0.2mm2"){const z=me(Math.sqrt(x/Math.PI));R=Hi(h,z)}return R.length?R.map(z=>St(z,e,n)):[]},[me,e,n,q]),ue=m.useCallback(()=>{const u=pe.current;return Mt(t)?ee(t,u.stampCenter):t==="brush"?[]:u.isDrawing?t==="freehand"?u.points:t==="rectangle"?Gt(u.start,u.current):t==="circular"?qt(u.start,u.current):[]:[]},[t,ee]),re=m.useCallback(u=>{const h=pe.current;if(!h.isDrawing||h.screenPoints.length===0)return;const w=h.screenPoints;if(w.length===0)return;const x=F.radius;if(!(!Number.isFinite(x)||x<=0)){if(u.save(),u.globalAlpha=F.fillOpacity,u.fillStyle=F.fillColor,u.strokeStyle=F.fillColor,u.lineCap="round",u.lineJoin="round",u.lineWidth=x*2,w.length===1)u.beginPath(),u.arc(w[0][0],w[0][1],x,0,Math.PI*2),u.fill();else{u.beginPath(),u.moveTo(w[0][0],w[0][1]);for(let R=1;R<w.length;R+=1)u.lineTo(w[R][0],w[R][1]);u.stroke()}u.restore()}},[F]),k=m.useCallback(u=>{const h=pe.current,w=h.cursor;if(!w)return;const x=h.cursorScreen??ct(a.current?.worldToScreen(w[0],w[1])??[]);if(!x)return;const R=F.radius;!Number.isFinite(R)||R<=0||(u.save(),u.beginPath(),u.arc(x[0],x[1],R,0,Math.PI*2),u.strokeStyle=h.isDrawing?F.cursorActiveColor:F.cursorColor,u.lineWidth=F.cursorLineWidth,u.setLineDash(F.cursorLineDash),u.stroke(),u.setLineDash(ft),u.restore())},[a,F]),ie=m.useCallback(()=>{ne();const u=he.current;if(!u)return;const h=u.getContext("2d");if(!h)return;const w=Math.max(1,window.devicePixelRatio||1),x=u.width/w,R=u.height/w;if(h.setTransform(1,0,0,1,0,0),h.clearRect(0,0,u.width,u.height),h.setTransform(w,0,0,w,0,0),ke.length>0)for(const z of ke){const{region:G,polygons:K,regionIndex:H,regionKey:ge}=z,Xe=zn(Q,ge)?"active":zn(X,ge)?"hover":"default";let fe=Xe==="active"?C:Xe==="hover"?A:se;if(Y){const xe=Y({region:G,regionId:ge,regionIndex:H,state:Xe});fe=at(fe,xe||void 0)}const oe=Xe==="default"?null:Ji(fe);for(const xe of K){const we=N(xe.outer);we.length>=4&&(oe&&Le(h,we,oe,!0,!1),Le(h,we,fe,!0,!1));for(const Ae of xe.holes){const Ve=N(Ae);Ve.length>=4&&(oe&&Le(h,Ve,oe,!0,!1),Le(h,Ve,fe,!0,!1))}}}if(De.length>0)for(const z of De)for(const G of z.polygons){const K=N(G.outer);K.length>=4&&Le(h,K,I,!0,!1);for(const H of G.holes){const ge=N(H);ge.length>=4&&Le(h,ge,I,!0,!1)}}if(Array.isArray(P)&&P.length>0){const z=!!globalThis.__OPEN_PLANT_DEBUG_OVERLAY__,G=N(Ne([[0,0],[e,0],[e,n],[0,n]]));for(let K=0;K<P.length;K+=1){const H=P[K];if(!H?.coordinates?.length||H.visible===!1)continue;const ge=H.closed??$i(H.coordinates),Xe=Dn(H.coordinates,ge);if(H.invertedFill?.fillColor){const oe=[],xe=Dn(H.coordinates,!0);for(const we of xe){const Ae=N(we);Ae.length>=4&&oe.push(Ae)}if(z){const we=String(H.id??K),Ae=`${G.length}|${xe.length}|${oe.length}|${H.invertedFill.fillColor}`;je.current.get(we)!==Ae&&(je.current.set(we,Ae),console.debug("[open-plant] invertedFill",{id:H.id??K,outerRingPoints:G.length,sourceRingCount:xe.length,holeRingCount:oe.length,fillColor:H.invertedFill.fillColor}))}ji(h,G,oe,H.invertedFill.fillColor)}if(Xe.length===0)continue;const fe=at(se,H.stroke??H.strokeStyle);for(const oe of Xe){const xe=N(oe);xe.length<2||Le(h,xe,fe,ge,H.fill??!1)}}}if(V)if(t==="brush")re(h),k(h);else{const z=ue();if(z.length>0)if(t==="freehand"){const G=N(z);G.length>=2&&Le(h,G,se,!1,!1),G.length>=3&&Le(h,N(Ne(z)),se,!0,!0)}else{const G=N(z);G.length>=4&&Le(h,G,se,!0,!0)}}if(ke.length>0)for(const z of ke){if(!z.region.label)continue;const G=to(z.polygons);if(!G)continue;const K=ct(a.current?.worldToScreen(G[0],G[1])??[]);K&&no(h,z.region.label,K,x,R,j)}},[V,t,ue,re,k,ne,N,e,n,a,ke,P,X,Q,se,A,C,De,I,Y,j]),B=m.useCallback(()=>{Ke.current||(Ke.current=!0,requestAnimationFrame(()=>{Ke.current=!1,ie()}))},[ie]),ae=m.useCallback((u=!1)=>{const h=pe.current,w=he.current;if(w&&h.pointerId!==null&&w.hasPointerCapture(h.pointerId))try{w.releasePointerCapture(h.pointerId)}catch{}h.isDrawing=!1,h.pointerId=null,h.start=null,h.current=null,h.points=[],h.screenPoints=[],h.stampCenter=null,u||(h.cursor=null,h.cursorScreen=null)},[]),ye=m.useCallback(u=>{const h=a.current;if(!h||e<=0||n<=0)return null;const w=ct(h.screenToWorld(u.clientX,u.clientY));return w?St(w,e,n):null},[a,e,n]),Se=m.useCallback(u=>{const h=he.current;if(!h)return null;const w=h.getBoundingClientRect(),x=Ye(u.clientX-w.left,0,w.width),R=Ye(u.clientY-w.top,0,w.height);return!Number.isFinite(x)||!Number.isFinite(R)?null:[x,R]},[]),Me=m.useCallback(()=>{const u=pe.current;if(!u.isDrawing){ae(!0),B();return}let h=[];if(t==="freehand")u.points.length>=pi&&(h=Ne(u.points));else if(t==="rectangle")h=Gt(u.start,u.current);else if(t==="circular")h=qt(u.start,u.current);else if(t==="brush"){const w=u.points[u.points.length-1]??u.current??u.start;if(F.clickSelectRoi&&w&&u.points.length<=1&&c?.(w)){ae(!0),B();return}const x=F.edgeDetail,R=Math.max(Li,F.radius*2/(Ni*x)),z=u.screenPoints.length>0?u.screenPoints:N(u.points),G=ai(z,{radius:F.radius,minRasterStep:R,circleSides:Math.max(24,Math.round(64*x)),simplifyTolerance:R*.25,smoothingPasses:F.edgeSmoothing}),K=[];for(const H of G){const ge=de(H);ge&&K.push(ge)}h=Ne(K)}(t==="freehand"||t==="rectangle"||t==="circular"||t==="brush")&&Nn(h)&&l&&l({tool:t,intent:t==="brush"?"brush":"roi",coordinates:h,bbox:Ln(h),areaPx:Ht(h)}),ae(!0),B()},[t,l,ae,B,N,de,F.radius,F.edgeDetail,F.edgeSmoothing,F.clickSelectRoi,c]),be=m.useCallback((u,h)=>{const w=ee(u,h);if(!Nn(w))return;const x=u==="stamp-rectangle-4096px"?"patch":"roi",R={tool:u,intent:x,coordinates:w,bbox:Ln(w),areaPx:Ht(w)};l?.(R),x==="patch"&&f&&f(R)},[ee,l,f]),le=m.useCallback((u,h,w)=>{const x=Un*Un,R=u.screenPoints[u.screenPoints.length-1];if(!R){u.points.push(h),u.screenPoints.push(w),u.current=h;return}const z=w[0]-R[0],G=w[1]-R[1];z*z+G*G>=x?(u.points.push(h),u.screenPoints.push(w)):(u.points[u.points.length-1]=h,u.screenPoints[u.screenPoints.length-1]=w),u.current=h},[]),ot=m.useCallback(u=>{if(!V||t==="cursor"||u.button!==0)return;const h=ye(u);if(!h)return;const w=t==="brush"?Se(u):null;if(t==="brush"&&!w)return;if(u.preventDefault(),u.stopPropagation(),Mt(t)){const z=pe.current;z.stampCenter=h,be(t,h),B();return}const x=he.current;x&&x.setPointerCapture(u.pointerId);const R=pe.current;R.isDrawing=!0,R.pointerId=u.pointerId,R.start=h,R.current=h,R.cursor=h,R.cursorScreen=w,R.points=t==="freehand"||t==="brush"?[h]:[],R.screenPoints=t==="brush"&&w?[w]:[],B()},[V,t,ye,Se,be,B]),Oe=m.useCallback(u=>{if(!V||t==="cursor")return;const h=ye(u);if(!h)return;if(Mt(t)){const x=pe.current;x.stampCenter=h,u.preventDefault(),u.stopPropagation(),B();return}const w=pe.current;if(t==="brush"){const x=Se(u);if(!x)return;if(w.cursor=h,w.cursorScreen=x,!w.isDrawing||w.pointerId!==u.pointerId){B();return}u.preventDefault(),u.stopPropagation(),le(w,h,x),B();return}if(!(!w.isDrawing||w.pointerId!==u.pointerId)){if(u.preventDefault(),u.stopPropagation(),t==="freehand"){const x=a.current,R=Math.max(1e-6,x?.getViewState?.().zoom??1),z=bi/R,G=z*z,K=w.points[w.points.length-1];if(!K)w.points.push(h);else{const H=h[0]-K[0],ge=h[1]-K[1];H*H+ge*ge>=G&&w.points.push(h)}}else w.current=h;B()}},[V,t,ye,Se,B,a,le]),Be=m.useCallback(u=>{const h=pe.current;if(!h.isDrawing||h.pointerId!==u.pointerId)return;u.preventDefault(),u.stopPropagation();const w=ye(u),x=t==="brush"?Se(u):null;w&&(h.cursor=w,t==="brush"?x&&(h.cursorScreen=x,le(h,w,x)):h.current=w);const R=he.current;if(R&&R.hasPointerCapture(u.pointerId))try{R.releasePointerCapture(u.pointerId)}catch{}Me()},[Me,ye,Se,t,le]),W=m.useCallback(()=>{const u=pe.current;let h=!1;t==="brush"&&!u.isDrawing&&u.cursor&&(u.cursor=null,u.cursorScreen=null,h=!0),Mt(t)&&u.stampCenter&&(u.stampCenter=null,h=!0),h&&B()},[t,B]);return m.useEffect(()=>{ne(),B();const u=he.current;if(!u)return;const h=new ResizeObserver(()=>{ne(),B()});return h.observe(u),()=>{h.disconnect()}},[ne,B]),m.useEffect(()=>{V||ae(),B()},[V,B,ae]),m.useEffect(()=>{et.current!==t&&(et.current=t,ae(),B())},[t,ae,B]),m.useEffect(()=>{B()},[d,ve,P,B]),m.useEffect(()=>{if(J)return J.current=B,()=>{J.current===B&&(J.current=null)}},[J,B]),m.useEffect(()=>{if(!V)return;const u=h=>{h.key==="Escape"&&(ae(),B())};return window.addEventListener("keydown",u),()=>{window.removeEventListener("keydown",u)}},[V,ae,B]),Ue.jsx("canvas",{ref:he,className:Z,style:Ee,onPointerDown:ot,onPointerMove:Oe,onPointerUp:Be,onPointerCancel:Be,onPointerLeave:W,onContextMenu:u=>{V&&u.preventDefault()},onWheel:u=>{if(!V)return;const h=he.current,w=a.current;if(!h||typeof w?.zoomBy!="function")return;u.preventDefault(),u.stopPropagation();const x=h.getBoundingClientRect(),R=u.clientX-x.left,z=u.clientY-x.top;w.zoomBy(u.deltaY<0?Si:xi,R,z),B()}})}function Xn(t){return String(t??"").replace(/\/+$/,"")}function ur(t){const e=String(t??"");return e.startsWith("/")?e:`/${e}`}function ro(t){const e=Xn(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=Xn(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 io(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),c=String(n.path??t?.path??""),l=Number(n.mpp??t?.mpp??0);if(!i||!o||!s||!c)throw new Error("이미지 메타데이터가 불완전합니다. width/height/tileSize/path 확인 필요");const f=Array.isArray(t?.terms)?t.terms.map(g=>({termId:String(g?.termId??""),termName:String(g?.termName??""),termColor:String(g?.termColor??"")})):[],p=ur(c),d=ro(e),b=r?(g,S,T)=>`${d}${p}/${g}/${T}_${S}.webp`:void 0;return{id:t?._id||"unknown",name:t?.name||"unknown",width:i,height:o,mpp:Number.isFinite(l)&&l>0?l:void 0,tileSize:s,maxTierZoom:Number.isFinite(a)?Math.max(0,Math.floor(a)):0,tilePath:c,tileBaseUrl:e,terms:f,tileUrlBuilder:b}}function on(t,e,n,r){if(t.tileUrlBuilder)return t.tileUrlBuilder(e,n,r);const i=ur(t.tilePath);return`${t.tileBaseUrl}${i}/${e}/${r}_${n}.webp`}const Re={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 Wn(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],c=Math.hypot(a[0]-s[0],a[1]-s[1]);if(c<1e-6)continue;const l=Math.max(1,Math.round((c+r)/(n+r))),f=l*n+(l-1)*r,p=c/Math.max(1e-6,f),d=n*p,b=r*p;t.beginPath(),t.moveTo(s[0],s[1]),t.lineTo(a[0],a[1]),t.setLineDash([d,b]),t.lineDashOffset=0,t.stroke()}t.setLineDash([]),t.lineDashOffset=0}}function it(t,e,n=1){return typeof t!="number"||!Number.isFinite(t)?e:Math.max(n,t)}function xt(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 oo={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 lr({source:t,projectorRef:e,authToken:n="",options:r,invalidateRef:i,className:o,style:s}){const a=m.useRef(null),c=m.useRef(null),l=m.useRef(null),f=m.useRef({active:!1,pointerId:null}),p=m.useRef(null),d=m.useRef(!1),b=it(r?.width,Re.width,64),g=it(r?.height,Re.height,48),S=m.useMemo(()=>{const A=Math.max(1,t.width),C=Math.max(1,t.height),I=A/C,j=b/g;let q,F;return I>j?(q=b,F=b/I):(F=g,q=g*I),{x:(b-q)/2,y:(g-F)/2,w:q,h:F}},[t.width,t.height,b,g]),T=it(r?.margin,Re.margin,0),L=it(r?.borderRadius,Re.borderRadius,0),D=it(r?.borderWidth,Re.borderWidth,0),O=Math.max(1,Math.round(it(r?.maxThumbnailTiles,Re.maxThumbnailTiles,1))),Y=r?.backgroundColor||Re.backgroundColor,P=r?.borderColor||Re.borderColor,X=r?.viewportBorderColor||Re.viewportBorderColor,Q=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:Re.viewportBorderStyle,ce=r?.viewportFillColor??Re.viewportFillColor,J=r?.interactive??Re.interactive,Z=r?.showThumbnail??Re.showThumbnail,Pe=r?.position||Re.position,he=r?.onClose,Ke=r?.closeIcon,je=r?.closeButtonStyle,et=m.useMemo(()=>{const A={};return Pe==="top-left"||Pe==="bottom-left"?A.left=T:A.right=T,Pe==="top-left"||Pe==="top-right"?A.top=T:A.bottom=T,{position:"absolute",...A,width:b,height:g,borderRadius:L,overflow:"hidden",zIndex:4,pointerEvents:J?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[T,Pe,b,g,L,J,s]),pe=m.useCallback(()=>{const A=a.current;if(!A)return;const C=A.getContext("2d");if(!C)return;const I=b,j=g,q=Math.max(1,window.devicePixelRatio||1),F=Math.max(1,Math.round(I*q)),Ee=Math.max(1,Math.round(j*q));(A.width!==F||A.height!==Ee)&&(A.width=F,A.height=Ee),C.setTransform(1,0,0,1,0,0),C.clearRect(0,0,A.width,A.height),C.setTransform(q,0,0,q,0,0),C.fillStyle=Y,C.fillRect(0,0,I,j);const{x:ne,y:N,w:de,h:me}=S,ee=c.current;ee&&C.drawImage(ee,ne,N,de,me),C.strokeStyle=P,C.lineWidth=D,C.strokeRect(D*.5,D*.5,I-D,j-D);const ue=e.current,re=ue?.getViewBounds?.(),k=ue?.getViewCorners?.(),ie=xt(re)?re:xt(l.current)?l.current:null;if(!ie)return;l.current=ie;const B=de/Math.max(1,t.width),ae=me/Math.max(1,t.height),ye=Array.isArray(k)&&k.length>=4&&k.every(W=>Array.isArray(W)&&W.length>=2&&Number.isFinite(W[0])&&Number.isFinite(W[1]))?k:null,Se=Q==="dash";if(ye){const W=[];for(let u=0;u<ye.length;u+=1){const h=ye[u];W.push([te(ne+h[0]*B,ne,ne+de),te(N+h[1]*ae,N,N+me)])}C.beginPath();for(let u=0;u<W.length;u+=1)u===0?C.moveTo(W[u][0],W[u][1]):C.lineTo(W[u][0],W[u][1]);C.closePath(),C.fillStyle=ce,C.fill(),C.strokeStyle=X,C.lineWidth=2.25,Se?Wn(C,W,4,3):C.stroke();return}const Me=te(ne+ie[0]*B,ne,ne+de),be=te(N+ie[1]*ae,N,N+me),le=te(ne+ie[2]*B,ne,ne+de),ot=te(N+ie[3]*ae,N,N+me),Oe=Math.max(1,le-Me),Be=Math.max(1,ot-be);if(C.fillStyle=ce,C.fillRect(Me,be,Oe,Be),C.strokeStyle=X,C.lineWidth=2.25,Se){const W=[[Me+.5,be+.5],[Me+.5+Math.max(1,Oe-1),be+.5],[Me+.5+Math.max(1,Oe-1),be+.5+Math.max(1,Be-1)],[Me+.5,be+.5+Math.max(1,Be-1)]];Wn(C,W,4,3)}else C.strokeRect(Me+.5,be+.5,Math.max(1,Oe-1),Math.max(1,Be-1))},[b,g,S,Y,P,D,e,t.width,t.height,ce,X,Q]),V=m.useCallback(()=>{d.current||(d.current=!0,p.current=requestAnimationFrame(()=>{d.current=!1,p.current=null,pe()}))},[pe]),ve=m.useCallback((A,C)=>{const I=a.current;if(!I)return null;const j=I.getBoundingClientRect();if(!j.width||!j.height)return null;const q=j.width/b,F=j.height/g,Ee=S.x*q,ne=S.y*F,N=S.w*q,de=S.h*F,me=te((A-j.left-Ee)/N,0,1),ee=te((C-j.top-ne)/de,0,1);return[me*t.width,ee*t.height]},[t.width,t.height,b,g,S]),Te=m.useCallback((A,C)=>{const I=e.current;if(!I)return;if(I.setViewCenter){I.setViewCenter(A,C),V();return}const j=I.getViewBounds?.(),q=xt(j)?j:xt(l.current)?l.current:null;if(!q)return;const F=Math.max(1e-6,q[2]-q[0]),Ee=Math.max(1e-6,q[3]-q[1]);I.setViewState({offsetX:A-F*.5,offsetY:C-Ee*.5}),V()},[e,V]),ke=m.useCallback(A=>{if(!J||A.button!==0)return;const C=a.current;if(!C)return;const I=ve(A.clientX,A.clientY);I&&(A.preventDefault(),A.stopPropagation(),C.setPointerCapture(A.pointerId),f.current={active:!0,pointerId:A.pointerId},Te(I[0],I[1]))},[J,ve,Te]),De=m.useCallback(A=>{const C=f.current;if(!C.active||C.pointerId!==A.pointerId)return;const I=ve(A.clientX,A.clientY);I&&(A.preventDefault(),A.stopPropagation(),Te(I[0],I[1]))},[ve,Te]),se=m.useCallback(A=>{const C=f.current;if(!C.active||C.pointerId!==A.pointerId)return;const I=a.current;if(I&&I.hasPointerCapture(A.pointerId))try{I.releasePointerCapture(A.pointerId)}catch{}f.current={active:!1,pointerId:null},V()},[V]);return m.useEffect(()=>{let A=!1;c.current=null,V();const C=0,I=2**(t.maxTierZoom-C),j=Math.ceil(t.width/I),q=Math.ceil(t.height/I),F=Math.max(1,Math.ceil(j/t.tileSize)),Ee=Math.max(1,Math.ceil(q/t.tileSize)),ne=F*Ee;if(!Z||ne>O)return;const N=document.createElement("canvas");N.width=Math.max(1,Math.round(S.w)),N.height=Math.max(1,Math.round(S.h));const de=N.getContext("2d");if(!de)return;de.fillStyle=Y,de.fillRect(0,0,N.width,N.height);const me=[];for(let ee=0;ee<Ee;ee+=1)for(let ue=0;ue<F;ue+=1){const re=ue*t.tileSize*I,k=ee*t.tileSize*I,ie=Math.min((ue+1)*t.tileSize,j)*I,B=Math.min((ee+1)*t.tileSize,q)*I;me.push({url:on(t,C,ue,ee),bounds:[re,k,ie,B]})}return Promise.allSettled(me.map(async ee=>{const ue=!!n,re=await fetch(ee.url,{headers:ue?{Authorization:n}:void 0});if(!re.ok)throw new Error(`HTTP ${re.status}`);const k=await createImageBitmap(await re.blob());return{tile:ee,bitmap:k}})).then(ee=>{if(A){for(const k of ee)k.status==="fulfilled"&&k.value.bitmap.close();return}const ue=N.width/Math.max(1,t.width),re=N.height/Math.max(1,t.height);for(const k of ee){if(k.status!=="fulfilled")continue;const{tile:{bounds:ie},bitmap:B}=k.value,ae=ie[0]*ue,ye=ie[1]*re,Se=Math.max(1,(ie[2]-ie[0])*ue),Me=Math.max(1,(ie[3]-ie[1])*re);de.drawImage(B,ae,ye,Se,Me),B.close()}c.current=N,V()}),()=>{A=!0}},[t,n,S,Y,Z,O,V]),m.useEffect(()=>{V()},[V]),m.useEffect(()=>{if(i)return i.current=V,()=>{i.current===V&&(i.current=null)}},[i,V]),m.useEffect(()=>()=>{f.current={active:!1,pointerId:null},p.current!==null&&(cancelAnimationFrame(p.current),p.current=null),d.current=!1},[]),Ue.jsxs("div",{className:o,style:et,children:[Ue.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:ke,onPointerMove:De,onPointerUp:se,onPointerCancel:se,onContextMenu:A=>{A.preventDefault()},onWheel:A=>{A.preventDefault(),A.stopPropagation()}}),he&&Ue.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:A=>{A.stopPropagation(),he()},style:je?{...je}:{...oo},children:Ke??"×"})]})}function so({imageWidth:t,imageHeight:e,tiles:n,viewState:r,className:i,style:o}){const s=m.useRef(null),a=m.useRef(null),c=m.useMemo(()=>({width:"100%",height:"100%",display:"block",...o}),[o]);return m.useEffect(()=>{const l=s.current;if(!l)return;const f=new Zn({canvas:l,imageWidth:t,imageHeight:e,initialViewState:r});return a.current=f,f.setTiles(n),()=>{f.destroy(),a.current=null}},[t,e]),m.useEffect(()=>{const l=a.current;l&&l.setTiles(n)},[n]),m.useEffect(()=>{const l=a.current;!l||!r||l.setViewState(r)},[r]),Ue.jsx("canvas",{ref:s,className:i,style:c})}function fr(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 ht(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return null;const n=dt(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=fr(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,c=new Float32Array(r*2),l=new Uint16Array(r),f=s?new Uint8Array(r):null,p=a?new Uint32Array(r):null;let d=0;for(let g=0;g<r;g+=1){const S=i[g*2],T=i[g*2+1];Ft(S,T,n)&&(c[d*2]=S,c[d*2+1]=T,l[d]=o[g],f&&(f[d]=s[g]),p&&(p[d]=a[g]),d+=1)}const b={count:d,positions:c.subarray(0,d*2),paletteIndices:l.subarray(0,d)};return f&&(b.fillModes=f.subarray(0,d)),p&&(b.ids=p.subarray(0,d)),b}function hr(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return new Uint32Array(0);const n=dt(e??[]);if(n.length===0)return new Uint32Array(0);const r=fr(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 c=i[a*2],l=i[a*2+1];Ft(c,l,n)&&(o[s]=a,s+=1)}return o.subarray(0,s)}let At=null;const ao=`
|
|
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 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
|
|
63
|
+
`;function co(){if(typeof navigator>"u")return!1;const t=navigator;return typeof t.gpu=="object"&&t.gpu!==null}function dr(){if(!co())return null;const e=navigator.gpu;if(!e||typeof e!="object")return null;const n=e;return typeof n.requestAdapter!="function"?null:n}const Rt=globalThis.GPUShaderStage?.COMPUTE??4,Xt=globalThis.GPUBufferUsage?.STORAGE??128,Tt=globalThis.GPUBufferUsage?.COPY_DST??8,uo=globalThis.GPUBufferUsage?.COPY_SRC??4,lo=globalThis.GPUBufferUsage?.UNIFORM??64,fo=globalThis.GPUBufferUsage?.MAP_READ??1,ho=globalThis.GPUMapMode?.READ??1;async function mo(){const t=dr();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 go(){return At||(At=(async()=>{const t=dr();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:Rt,buffer:{type:"read-only-storage"}},{binding:1,visibility:Rt,buffer:{type:"read-only-storage"}},{binding:2,visibility:Rt,buffer:{type:"storage"}},{binding:3,visibility:Rt,buffer:{type:"uniform"}}]}),i=n.createComputePipeline({layout:n.createPipelineLayout({bindGroupLayouts:[r]}),compute:{module:n.createShaderModule({code:ao}),entryPoint:"main"}});return{device:n,pipeline:i,bindGroupLayout:r}})(),At)}function Et(t,e){return Math.ceil(t/e)*e}async function mr(t,e,n){const r=await go();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,c=o*4*Float32Array.BYTES_PER_ELEMENT,l=s*Uint32Array.BYTES_PER_ELEMENT,f=Number(r.device.limits.maxStorageBufferBindingSize);if(a>f||c>f||l>f)return null;const p=r.device.createBuffer({size:Et(a,4),usage:Xt|Tt}),d=r.device.createBuffer({size:Et(c,4),usage:Xt|Tt}),b=r.device.createBuffer({size:Et(l,4),usage:Xt|uo}),g=r.device.createBuffer({size:16,usage:lo|Tt}),S=r.device.createBuffer({size:Et(l,4),usage:Tt|fo});r.device.queue.writeBuffer(p,0,t.buffer,t.byteOffset,a),r.device.queue.writeBuffer(d,0,n.buffer,n.byteOffset,c),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:p}},{binding:1,resource:{buffer:d}},{binding:2,resource:{buffer:b}},{binding:3,resource:{buffer:g}}]}),L=r.device.createCommandEncoder(),D=L.beginComputePass();D.setPipeline(r.pipeline),D.setBindGroup(0,T),D.dispatchWorkgroups(Math.ceil(s/256)),D.end(),L.copyBufferToBuffer(b,0,S,0,l),r.device.queue.submit([L.finish()]),await S.mapAsync(ho);const O=S.getMappedRange(),Y=new Uint32Array(O.slice(0));return S.unmap(),p.destroy(),d.destroy(),b.destroy(),g.destroy(),S.destroy(),Y}function We(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}async function gr(t,e,n={}){const r=We(),i=n.bridgeToDraw===!0;if(!t||!t.count||!t.positions||!t.paletteIndices)return{data:null,meta:{mode:"hybrid-webgpu",durationMs:We()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}};const o=dt(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:We()-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)),c=t.fillModes instanceof Uint8Array&&t.fillModes.length>=a?t.fillModes:null,l=t.ids instanceof Uint32Array&&t.ids.length>=a?t.ids:null;if(a===0){const P={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return c&&(P.fillModes=new Uint8Array(0)),l&&(P.ids=new Uint32Array(0)),{data:P,meta:{mode:"hybrid-webgpu",durationMs:We()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const f=new Float32Array(o.length*4);for(let P=0;P<o.length;P+=1){const X=P*4,Q=o[P];f[X]=Q.minX,f[X+1]=Q.minY,f[X+2]=Q.maxX,f[X+3]=Q.maxY}let p=null,d=!1;try{p=await mr(t.positions,a,f),d=!!p}catch{p=null,d=!1}if(!p)return{data:ht(t,e),meta:{mode:"hybrid-webgpu",durationMs:We()-r,usedWebGpu:!1,candidateCount:a,bridgedToDraw:!1}};let b=0;for(let P=0;P<a;P+=1)p[P]===1&&(b+=1);const g=new Uint32Array(b);if(b>0){let P=0;for(let X=0;X<a;X+=1)p[X]===1&&(g[P]=X,P+=1)}if(b===0){if(i){const X={count:a,positions:t.positions.subarray(0,a*2),paletteIndices:t.paletteIndices.subarray(0,a),drawIndices:new Uint32Array(0)};return c&&(X.fillModes=c.subarray(0,a)),l&&(X.ids=l.subarray(0,a)),{data:X,meta:{mode:"hybrid-webgpu",durationMs:We()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!0}}}const P={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return c&&(P.fillModes=new Uint8Array(0)),l&&(P.ids=new Uint32Array(0)),{data:P,meta:{mode:"hybrid-webgpu",durationMs:We()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const P=new Uint32Array(b);let X=0;for(let ce=0;ce<b;ce+=1){const J=g[ce]??0,Z=t.positions[J*2],Pe=t.positions[J*2+1];Ft(Z,Pe,o)&&(P[X]=J,X+=1)}const Q={count:a,positions:t.positions.subarray(0,a*2),paletteIndices:t.paletteIndices.subarray(0,a),drawIndices:P.subarray(0,X)};return c&&(Q.fillModes=c.subarray(0,a)),l&&(Q.ids=l.subarray(0,a)),{data:Q,meta:{mode:"hybrid-webgpu",durationMs:We()-r,usedWebGpu:!0,candidateCount:b,bridgedToDraw:!0}}}const S=new Float32Array(b*2),T=new Uint16Array(b),L=c?new Uint8Array(b):null,D=l?new Uint32Array(b):null;let O=0;for(let P=0;P<b;P+=1){const X=g[P]??0,Q=t.positions[X*2],ce=t.positions[X*2+1];Ft(Q,ce,o)&&(S[O*2]=Q,S[O*2+1]=ce,T[O]=t.paletteIndices[X],L&&(L[O]=c[X]),D&&(D[O]=l[X]),O+=1)}const Y={count:O,positions:S.subarray(0,O*2),paletteIndices:T.subarray(0,O)};return L&&(Y.fillModes=L.subarray(0,O)),D&&(Y.ids=D.subarray(0,O)),{data:Y,meta:{mode:"hybrid-webgpu",durationMs:We()-r,usedWebGpu:!0,candidateCount:b,bridgedToDraw:!1}}}let Ce=null,Zt=!0,pr=1;const Ze=new Map;function $e(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function br(){if(!Zt)return null;if(Ce)return Ce;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:zt&&zt.tagName.toUpperCase()==="SCRIPT"&&zt.src||new URL("index.cjs",document.baseURI).href),{type:"module"});return t.addEventListener("message",sn),t.addEventListener("error",an),Ce=t,t}catch{return Zt=!1,null}}function sn(t){const e=t.data;if(!e)return;const n=Ze.get(e.id);if(!n)return;if(Ze.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 l=Math.max(0,Math.floor(e.count)),f=new Uint32Array(e.indices).subarray(0,l);n.resolve({indices:f,meta:{mode:"worker",durationMs:Number.isFinite(e.durationMs)?e.durationMs:$e()-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,c={count:r,positions:i.subarray(0,r*2),paletteIndices:o.subarray(0,r)};s&&(c.fillModes=s.subarray(0,r)),a&&(c.ids=a.subarray(0,r)),n.resolve({data:c,meta:{mode:"worker",durationMs:Number.isFinite(e.durationMs)?e.durationMs:$e()-n.startMs}})}function an(){Zt=!1,Ce&&(Ce.removeEventListener("message",sn),Ce.removeEventListener("error",an),Ce.terminate(),Ce=null);for(const[,t]of Ze)t.reject(new Error("worker crashed"));Ze.clear()}function po(){if(Ce){Ce.removeEventListener("message",sn),Ce.removeEventListener("error",an),Ce.terminate(),Ce=null;for(const[,t]of Ze)t.reject(new Error("worker terminated"));Ze.clear()}}async function wr(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return{data:null,meta:{mode:"worker",durationMs:0}};const n=br();if(!n){const p=$e();return{data:ht(t,e),meta:{mode:"sync",durationMs:$e()-p}}}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,c=t.ids instanceof Uint32Array&&t.ids.length>=i?t.ids.slice(0,i):null,l=pr++,f=$e();return new Promise((p,d)=>{Ze.set(l,{kind:"data",resolve:p,reject:d,startMs:f});const b={type:"roi-clip-request",id:l,count:i,positions:o.buffer,paletteIndices:s.buffer,fillModes:a?.buffer,ids:c?.buffer,polygons:e??[]},g=[o.buffer,s.buffer];a&&g.push(a.buffer),c&&g.push(c.buffer),n.postMessage(b,g)})}async function bo(t,e){if(!t||!t.count||!t.positions||!t.paletteIndices)return{indices:new Uint32Array(0),meta:{mode:"worker",durationMs:0}};const n=br();if(!n){const c=$e();return{indices:hr(t,e),meta:{mode:"sync",durationMs:$e()-c}}}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=pr++,a=$e();return new Promise((c,l)=>{Ze.set(s,{kind:"index",resolve:c,reject:l,startMs:a});const f={type:"roi-clip-index-request",id:s,count:i,positions:o.buffer,polygons:e??[]};n.postMessage(f,[o.buffer])})}function wo(t){const e=[];for(let n=0;n<t.length;n+=1){const r=t[n],i=dt([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 yo(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 yr(t,e,n={}){const r=Math.max(0,Math.min(Math.floor(t?.count??0),Math.floor((t?.positions?.length??0)/2),t?.paletteIndices?.length??0,t?.fillModes instanceof Uint8Array?t.fillModes.length:Number.MAX_SAFE_INTEGER));let i=null;if(t?.drawIndices instanceof Uint32Array){const d=t.drawIndices;let b=d.length;for(let g=0;g<d.length;g+=1)d[g]<r||(b-=1);if(b===d.length)i=d;else if(b>0){const g=new Uint32Array(b);let S=0;for(let T=0;T<d.length;T+=1){const L=d[T];L>=r||(g[S]=L,S+=1)}i=g}else i=new Uint32Array(0)}const o=i?i.length:r,s=wo(e??[]);if(!t||o===0||s.length===0)return{groups:[],inputPointCount:o,pointsInsideAnyRegion:0,unmatchedPointCount:o};const a=new Map,c=new Map;let l=0;for(let d=0;d<o;d+=1){const b=i?i[d]:d,g=t.positions[b*2],S=t.positions[b*2+1];let T=null;for(const O of s){let Y=!1;for(const P of O.polygons)if(er(g,S,P)){Y=!0;break}Y&&(!T||O.area<T.area)&&(T=O)}if(!T)continue;l+=1;const L=t.paletteIndices[b]??0,D=a.get(T.regionIndex)??new Map;D.set(L,(D.get(L)??0)+1),a.set(T.regionIndex,D),c.set(T.regionIndex,(c.get(T.regionIndex)??0)+1)}const f=n.includeEmptyRegions??!1,p=[];for(const d of s){const b=c.get(d.regionIndex)??0;if(!f&&b<=0)continue;const g=a.get(d.regionIndex)??new Map,S=Array.from(g.entries()).map(([T,L])=>({termId:yo(T,n.paletteIndexToTermId),paletteIndex:T,count:L})).sort((T,L)=>L.count-T.count||T.paletteIndex-L.paletteIndex);p.push({regionId:d.regionId,regionIndex:d.regionIndex,totalCount:b,termCounts:S})}return{groups:p,inputPointCount:o,pointsInsideAnyRegion:l,unmatchedPointCount:Math.max(0,o-l)}}function Ct(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Mo(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 Mr{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 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:Ct()};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-Ct());this.timerId=window.setTimeout(()=>{this.timerId=null,this.pump()},n)}takeNextReadyQueueItem(){if(this.queue.length===0)return null;const e=Ct(),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=Mo(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,c=this.getRetryDelay(a),l={tile:e.tile,attempt:a,readyAt:Ct()+c},f=this.queuedByKey.get(e.tile.key);f?(f.tile=l.tile,f.readyAt=Math.min(f.readyAt,l.readyAt),f.attempt=Math.max(f.attempt,l.attempt)):(this.queue.push(l),this.queuedByKey.set(l.tile.key,l)),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 Yn=.35,Kt=.5,So=256,jt=[{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 xo{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,s]=this.getCenter(),a=(e-this.viewportWidth*.5)/i,c=(n-this.viewportHeight*.5)/i,l=lt(r.rotationDeg),f=Math.cos(l),p=Math.sin(l);return[o+a*f-c*p,s+a*p+c*f]}worldToScreen(e,n){const r=this.viewState,i=Math.max(1e-6,r.zoom),[o,s]=this.getCenter(),a=e-o,c=n-s,l=lt(r.rotationDeg),f=Math.cos(l),p=Math.sin(l),d=a*f+c*p,b=-a*p+c*f;return[this.viewportWidth*.5+d*i,this.viewportHeight*.5+b*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=lt(this.viewState.rotationDeg),o=Math.cos(i),s=Math.sin(i),a=2*e*o/this.viewportWidth,c=2*e*s/this.viewportWidth,l=2*e*s/this.viewportHeight,f=-2*e*o/this.viewportHeight,p=-(a*n+c*r),d=-(l*n+f*r);return new Float32Array([a,l,0,c,f,0,p,d,1])}}function lt(t){return t*Math.PI/180}function Vn(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Fe(t,e,n){const r=t.getUniformLocation(e,n);if(!r)throw new Error(`uniform location lookup failed: ${n}`);return r}function Pt(t,e){return!t||!e?t===e:t.buffer===e.buffer&&t.byteOffset===e.byteOffset&&t.byteLength===e.byteLength}function Jt(t){return t.map(e=>({zoom:e.zoom,size:e.size}))}function Gn(t){if(!t)return Jt(jt);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?Jt(jt):Array.from(e.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function Ao(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 Ro(t,e){if(!Number.isFinite(t))return e[0]?.size??Kt;if(e.length===0)return Kt;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],c=e[s];if(t>c.zoom)continue;const l=Math.max(1e-6,c.zoom-a.zoom),f=te((t-a.zoom)/l,0,1);return a.size+(c.size-a.size)*f}const n=e[e.length-1],r=e[e.length-2],i=Math.max(1e-6,n.zoom-r.zoom),o=(n.size-r.size)/i;return n.size+(t-n.zoom)*o}const To=.1,Eo=5;function qn(t){return typeof t!="number"||!Number.isFinite(t)?1:te(t,To,Eo)}const Co=-100,Po=100;function Wt(t){return typeof t!="number"||!Number.isFinite(t)?0:te(t,Co,Po)}function Hn(t){const e=Wt(t?.brightness),n=Wt(t?.contrast),r=Wt(t?.saturation);return{brightness:e/200,contrast:n/100,saturation:r/100}}class Sr{constructor(e,n,r={}){M(this,"canvas");M(this,"source");M(this,"gl");M(this,"camera",new xo);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",Jt(jt));M(this,"pointStrokeScale",1);M(this,"imageColorSettings",{brightness:0,contrast:0,saturation:0});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):Yn,this.pointSizeStops=Gn(r.pointSizeByZoom),this.pointStrokeScale=qn(r.pointStrokeScale),this.imageColorSettings=Hn(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 Mr({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=te(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,c=e.drawIndices instanceof Uint32Array,l=c?this.sanitizeDrawIndices(e.drawIndices,i):null,f=this.lastPointData,p=f?.fillModes instanceof Uint8Array;let d=this.pointBuffersDirty||!f||f.count!==i||!Pt(f.positions,o)||!Pt(f.paletteIndices,s)||p!==r||r&&(!f?.fillModes||!Pt(f.fillModes,a)),b=this.pointBuffersDirty||c&&(!f?.drawIndices||!Pt(f.drawIndices,l))||!c&&!!f?.drawIndices;if(this.lastPointData={count:i,positions:o,paletteIndices:s,fillModes:a,drawIndices:c?l??void 0:void 0},this.contextLost||this.gl.isContextLost())return;const g=this.gl;d&&(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)),c&&b&&(g.bindBuffer(g.ELEMENT_ARRAY_BUFFER,this.pointProgram.indexBuffer),g.bufferData(g.ELEMENT_ARRAY_BUFFER,l??new Uint32Array(0),g.DYNAMIC_DRAW),g.bindBuffer(g.ELEMENT_ARRAY_BUFFER,null)),this.usePointIndices=c,this.pointCount=c?l?.length??0:this.lastPointData.count,(d||b)&&(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=Gn(e);Ao(this.pointSizeStops,n)||(this.pointSizeStops=n,this.requestRender())}setPointStrokeScale(e){const n=qn(e);this.pointStrokeScale!==n&&(this.pointStrokeScale=n,this.requestRender())}setImageColorSettings(e){const n=Hn(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=Ro(n,this.pointSizeStops);return te(r,Kt,So)}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:te(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=te(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 c=this.camera.getViewport(),l=n-c.width*.5,f=r-c.height*.5,p=lt(this.camera.getViewState().rotationDeg),d=Math.cos(p),b=Math.sin(p),g=l/o*d-f/o*b,S=l/o*b+f/o*d;this.camera.setCenter(s-g,a-S),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(),c=n*.5,l=r*.5,f=c-i,p=this.source.width-c+i,d=l-o,b=this.source.height-l+o,g=f<=p?te(s,f,p):this.source.width*.5,S=d<=b?te(a,d,b):this.source.height*.5;this.camera.setCenter(g,S)}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 te(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)),c=n[0],l=n[1],f=n[2],p=n[3],d=te(Math.floor(c/r/this.source.tileSize),0,s-1),b=te(Math.floor((f-1)/r/this.source.tileSize),0,s-1),g=te(Math.floor(l/r/this.source.tileSize),0,a-1),S=te(Math.floor((p-1)/r/this.source.tileSize),0,a-1);if(d>b||g>S)return[];const T=(c+f)*.5/r/this.source.tileSize,L=(l+p)*.5/r/this.source.tileSize,D=[];for(let O=g;O<=S;O+=1)for(let Y=d;Y<=b;Y+=1){const P=Y*this.source.tileSize*r,X=O*this.source.tileSize*r,Q=Math.min((Y+1)*this.source.tileSize,i)*r,ce=Math.min((O+1)*this.source.tileSize,o)*r,J=Y-T,Z=O-L;D.push({key:`${e}/${Y}/${O}`,tier:e,x:Y,y:O,bounds:[P,X,Q,ce],distance2:J*J+Z*Z,url:on(this.source,e,Y,O)})}return D.sort((O,Y)=>O.distance2-Y.distance2),D}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=Vn();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(d=>d.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 c=[];for(const[,d]of this.cache)a.has(d.key)||this.intersectsBounds(d.bounds,s)&&c.push(d);c.sort((d,b)=>d.tier-b.tier);for(const d of c)d.lastUsed=this.frameSerial,n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,d.texture),n.uniform4f(r.uBounds,d.bounds[0],d.bounds[1],d.bounds[2],d.bounds[3]),n.drawArrays(n.TRIANGLE_STRIP,0,4);let l=0;const f=[];for(const d of o){const b=this.cache.get(d.key);if(!b){f.push(d);continue}b.lastUsed=this.frameSerial,n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,b.texture),n.uniform4f(r.uBounds,b.bounds[0],b.bounds[1],b.bounds[2],b.bounds[3]),n.drawArrays(n.TRIANGLE_STRIP,0,4),l+=1}this.tileScheduler.schedule(f),n.bindTexture(n.TEXTURE_2D,null),n.bindVertexArray(null);let p=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),p=this.pointCount),this.onStats){const d=this.tileScheduler.getSnapshot(),b=l,g=f.length,S=c.length+l+(p>0?1:0);this.onStats({tier:this.currentTier,visible:o.length,rendered:l,points:p,fallback:c.length,cache:this.cache.size,inflight:d.inflight,queued:d.queued,retries:d.retries,failed:d.failed,aborted:d.aborted,cacheHits:b,cacheMisses:g,drawCalls:S,frameMs:Vn()-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)),c=this.rotationDragSensitivityDegPerPixel/Yn,l=this.camera.getViewState();this.camera.setViewState({rotationDeg:l.rotationDeg-a*180/Math.PI*c})}}else{const i=this.camera.getViewState(),o=Math.max(1e-6,i.zoom),s=lt(i.rotationDeg),a=Math.cos(s),c=Math.sin(s),l=(n*a-r*c)/o,f=(n*c+r*a)/o;this.camera.setViewState({offsetX:i.offsetX-l,offsetY:i.offsetY-f})}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=In(e,`#version 300 es
|
|
64
64
|
precision highp float;
|
|
65
65
|
in vec2 aUnit;
|
|
66
66
|
in vec2 aUv;
|
|
@@ -105,7 +105,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
105
105
|
|
|
106
106
|
color.rgb = clamp(color.rgb + uBrightness, vec3(0.0), vec3(1.0));
|
|
107
107
|
outColor = color;
|
|
108
|
-
}`),o=
|
|
108
|
+
}`),o=Fe(e,i,"uCamera"),s=Fe(e,i,"uBounds"),a=Fe(e,i,"uTexture"),c=Fe(e,i,"uBrightness"),l=Fe(e,i,"uContrast"),f=Fe(e,i,"uSaturation"),p=e.createVertexArray(),d=e.createBuffer();if(!p||!d)throw new Error("buffer allocation failed");e.bindVertexArray(p),e.bindBuffer(e.ARRAY_BUFFER,d),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,0,0,1,0,1,0,0,1,0,1,1,1,1,1]),e.STATIC_DRAW);const b=e.getAttribLocation(i,"aUnit"),g=e.getAttribLocation(i,"aUv");if(b<0||g<0)throw new Error("tile attribute lookup failed");return e.enableVertexAttribArray(b),e.enableVertexAttribArray(g),e.vertexAttribPointer(b,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:p,vbo:d,uCamera:o,uBounds:s,uTexture:a,uBrightness:c,uContrast:l,uSaturation:f}}initPointProgram(){const e=this.gl,i=In(e,`#version 300 es
|
|
109
109
|
precision highp float;
|
|
110
110
|
in vec2 aPosition;
|
|
111
111
|
in uint aTerm;
|
|
@@ -154,6 +154,6 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
154
154
|
if (alpha <= 0.001) discard;
|
|
155
155
|
|
|
156
156
|
outColor = vec4(color.rgb * alpha, alpha);
|
|
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...",[
|
|
157
|
+
}`),o=Fe(e,i,"uCamera"),s=Fe(e,i,"uPointSize"),a=Fe(e,i,"uPointStrokeScale"),c=Fe(e,i,"uPalette"),l=Fe(e,i,"uPaletteSize"),f=e.createVertexArray(),p=e.createBuffer(),d=e.createBuffer(),b=e.createBuffer(),g=e.createBuffer(),S=e.createTexture();if(!f||!p||!d||!b||!g||!S)throw new Error("point buffer allocation failed");e.bindVertexArray(f),e.bindBuffer(e.ARRAY_BUFFER,p),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,d),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const L=e.getAttribLocation(i,"aTerm");if(L<0)throw new Error("point term attribute not found");e.enableVertexAttribArray(L),e.vertexAttribIPointer(L,1,e.UNSIGNED_SHORT,0,0),e.bindBuffer(e.ARRAY_BUFFER,b),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const D=e.getAttribLocation(i,"aFillMode");if(D<0)throw new Error("point fill mode attribute not found");return e.enableVertexAttribArray(D),e.vertexAttribIPointer(D,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,S),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([160,160,160,255])),e.bindTexture(e.TEXTURE_2D,null),{program:i,vao:f,posBuffer:p,termBuffer:d,fillModeBuffer:b,indexBuffer:g,paletteTexture:S,uCamera:o,uPointSize:s,uPointStrokeScale:a,uPalette:c,uPaletteSize:l}}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 Yt=[],Io=[],vo={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)},_o=.65,Fo=4,Uo=24,Bo=1024,Lo=4,No=6,zo=.5,ko=.58,Do=4096;let It=null;const vt=new Map;function Oo(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 Xo(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 Wo(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))*Lo;return Math.max(Uo,Math.min(Bo,i))}function Yo(t,e){if(!t||!t.positions||!t.paletteIndices)return null;const n=Oo(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=Xo(t.drawIndices,n),s=o?o.length:n;if(s===0)return null;const a=Wo(e,s),c=new Map,l=f=>{const p=r[f*2],d=r[f*2+1];if(!Number.isFinite(p)||!Number.isFinite(d))return;const b=Math.floor(p/a),g=Math.floor(d/a);let S=c.get(b);S||(S=new Map,c.set(b,S));const T=S.get(g);T?T.push(f):S.set(g,[f])};if(o)for(let f=0;f<o.length;f+=1)l(o[f]??0);else for(let f=0;f<n;f+=1)l(f);return c.size===0?null:{cellSize:a,safeCount:n,positions:r,ids:i,buckets:c}}function Qt(t,e){return t.id??e}function en(t,e,n){return Math.max(e,Math.min(n,t))}function tn(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 Vo(t){if(t.length===0)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)>zo||(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 Go(t){let e=null;for(const n of t){const r=Vo(n.outer);r&&(!e||r[1]<e[1]||r[1]===e[1]&&r[0]<e[0])&&(e=r)}return e}function qo(t,e,n,r,i,o){const s=i-n,a=o-r,c=s*s+a*a;if(c<=1e-12){const g=t-n,S=e-r;return g*g+S*S}const l=en(((t-n)*s+(e-r)*a)/c,0,1),f=n+s*l,p=r+a*l,d=t-f,b=e-p;return d*d+b*b}function $n(t,e,n,r){for(let i=1;i<n.length;i+=1){const o=n[i-1],s=n[i];if(qo(t,e,o[0],o[1],s[0],s[1])<=r)return!0}return!1}function Ho(t,e,n,r){if(t<n.minX-r||t>n.maxX+r||e<n.minY-r||e>n.maxY+r)return!1;const i=r*r;if($n(t,e,n.outer,i))return!0;for(const o of n.holes)if($n(t,e,o,i))return!0;return!1}function $o(){if(It)return It;if(typeof document>"u")return null;const e=document.createElement("canvas").getContext("2d");return e?(It=e,It):null}function Zo(t,e){const n=`${e.fontWeight}|${e.fontSize}|${e.fontFamily}|${t}`,r=vt.get(n);if(r!==void 0)return r;const i=t.length*e.fontSize*ko,o=$o();let s=i;if(o){o.font=`${e.fontWeight} ${e.fontSize}px ${e.fontFamily}`;const a=o.measureText(t).width;Number.isFinite(a)&&a>=0&&(s=a)}return vt.size>Do&&vt.clear(),vt.set(n,s),s}function Ko(t,e,n,r,i,o){if(!t.label||!t.labelAnchor)return!1;const s=tn(n.worldToScreen(t.labelAnchor[0],t.labelAnchor[1]));if(!s)return!1;const c=Zo(t.label,r)+r.paddingX*2,l=r.fontSize+r.paddingY*2,f=en(s[0],c*.5+1,i-c*.5-1),p=en(s[1]-r.offsetY,l*.5+1,o-l*.5-1),d=f-c*.5,b=f+c*.5,g=p-l*.5,S=p+l*.5;return e[0]>=d&&e[0]<=b&&e[1]>=g&&e[1]<=S}function jo(t){const e=[];for(let n=0;n<t.length;n+=1){const r=t[n],i=dt([r?.coordinates]);if(i.length===0)continue;const o=typeof r?.label=="string"?r.label.trim():"";e.push({region:r,regionIndex:n,regionId:Qt(r,n),polygons:i,label:o,labelAnchor:o?Go(i):null})}return e}function Jo(t,e,n,r,i,o,s){const a=t[0],c=t[1],l=Math.max(1e-6,r.getViewState().zoom),f=No/l;for(let p=n.length-1;p>=0;p-=1){const d=n[p];for(const b of d.polygons)if(Ho(a,c,b,f))return{region:d.region,regionIndex:d.regionIndex,regionId:d.regionId};if(Ko(d,e,r,i,o,s))return{region:d.region,regionIndex:d.regionIndex,regionId:d.regionId}}return null}function Qo({source:t,viewState:e,imageColorSettings:n=null,onViewStateChange:r,onStats:i,onTileError:o,onContextLost:s,onContextRestored:a,debugOverlay:c=!1,debugOverlayStyle:l,fitNonce:f=0,rotationResetNonce:p=0,authToken:d="",ctrlDragRotate:b=!0,pointData:g=null,pointPalette:S=null,pointSizeByZoom:T,pointStrokeScale:L,roiRegions:D,roiPolygons:O,clipPointsToRois:Y=!1,clipMode:P="worker",onClipStats:X,onRoiPointGroups:Q,roiPaletteIndexToTermId:ce,interactionLock:J=!1,drawTool:Z="cursor",stampOptions:Pe,brushOptions:he,regionStrokeStyle:Ke,regionStrokeHoverStyle:je,regionStrokeActiveStyle:et,patchStrokeStyle:pe,resolveRegionStrokeStyle:V,overlayShapes:ve,customLayers:Te,patchRegions:ke,regionLabelStyle:De,onPointerWorldMove:se,onPointHover:A,onPointClick:C,onRegionHover:I,onRegionClick:j,onActiveRegionChange:q,getCellByCoordinatesRef:F,onDrawComplete:Ee,onPatchComplete:ne,overviewMapConfig:N,className:de,style:me}){const ee=N?.show??!1,ue=N?.options,re=m.useRef(null),k=m.useRef(null),ie=m.useRef(null),B=m.useRef(null),ae=m.useRef(r),ye=m.useRef(i),Se=m.useRef(c),[Me,be]=m.useState(null),[le,ot]=m.useState(null),[Oe,Be]=m.useState(null),[W,u]=m.useState(null),h=m.useRef(null),w=m.useRef(null),x=m.useRef(null),R=m.useRef(0),z=D??Yt,G=ke??Yt,K=O??Io,H=(Te?.length??0)>0,ge=m.useMemo(()=>({position:"relative",width:"100%",height:"100%",...me}),[me]),Xe=m.useMemo(()=>({position:"absolute",top:8,left:8,zIndex:7,margin:0,padding:"8px 10px",maxWidth:"min(420px, 80%)",pointerEvents:"none",whiteSpace:"pre-wrap",lineHeight:1.35,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:11,color:"#cde6ff",background:"rgba(6, 12, 20, 0.82)",border:"1px solid rgba(173, 216, 255, 0.28)",borderRadius:8,boxShadow:"0 8px 22px rgba(0,0,0,0.35)",...l}),[l]),fe=m.useMemo(()=>z.length>0?z:K.length===0?Yt:K.map((y,E)=>({id:E,coordinates:y})),[z,K]),oe=m.useMemo(()=>jo(fe),[fe]),xe=m.useMemo(()=>ar(De),[De]),we=m.useMemo(()=>fe.map(y=>y.coordinates),[fe]),[Ae,Ve]=m.useState(g);m.useEffect(()=>{const y=++R.current;let E=!1;if(!Y)return Ve(g),()=>{E=!0};if(!g||!g.count||!g.positions||!g.paletteIndices)return Ve(null),()=>{E=!0};if(we.length===0)return Ve(vo),X?.({mode:P,durationMs:0,inputCount:g.count,outputCount:0,polygonCount:0}),()=>{E=!0};const v=(U,$)=>{if(E||y!==R.current)return;const rt=U?.drawIndices?U.drawIndices.length:U?.count??0;Ve(U),X?.({mode:$.mode,durationMs:$.durationMs,inputCount:g.count,outputCount:rt,polygonCount:we.length,usedWebGpu:$.usedWebGpu,candidateCount:$.candidateCount,bridgedToDraw:$.bridgedToDraw})};return(async()=>{if(P==="sync"){const U=performance.now(),$=ht(g,we);v($,{mode:"sync",durationMs:performance.now()-U});return}if(P==="hybrid-webgpu"){const U=await gr(g,we,{bridgeToDraw:!0});v(U.data,{mode:U.meta.mode,durationMs:U.meta.durationMs,usedWebGpu:U.meta.usedWebGpu,candidateCount:U.meta.candidateCount,bridgedToDraw:U.meta.bridgedToDraw});return}try{const U=await wr(g,we);v(U.data,{mode:U.meta.mode,durationMs:U.meta.durationMs})}catch{const U=performance.now(),$=ht(g,we);v($,{mode:"sync",durationMs:performance.now()-U})}})(),()=>{E=!0}},[Y,P,g,we,X]);const cn=!!(A||C||F),Ie=m.useMemo(()=>cn?Yo(Ae,t):null,[cn,Ae,t]),Je=m.useCallback(y=>{const E=k.current;if(!E||!Ie)return null;const v=Number(y[0]),_=Number(y[1]);if(!Number.isFinite(v)||!Number.isFinite(_))return null;const U=Math.max(1e-6,E.getViewState().zoom),$=E.getPointSizeByZoom(),Qe=Math.max(Fo,$*_o)/U;if(!Number.isFinite(Qe)||Qe<=0)return null;const Ut=Ie.cellSize,gn=Math.floor(v/Ut),pn=Math.floor(_/Ut),pt=Math.max(1,Math.ceil(Qe/Ut)),Pr=Qe*Qe;let bt=-1,bn=Pr,wn=0,yn=0;for(let Bt=gn-pt;Bt<=gn+pt;Bt+=1){const Mn=Ie.buckets.get(Bt);if(Mn)for(let Lt=pn-pt;Lt<=pn+pt;Lt+=1){const wt=Mn.get(Lt);if(!(!wt||wt.length===0))for(let Nt=0;Nt<wt.length;Nt+=1){const yt=wt[Nt];if(yt>=Ie.safeCount)continue;const Sn=Ie.positions[yt*2],xn=Ie.positions[yt*2+1],An=Sn-v,Rn=xn-_,Tn=An*An+Rn*Rn;Tn>bn||(bn=Tn,bt=yt,wn=Sn,yn=xn)}}}if(bt<0)return null;const Ir=Ie.ids?Number(Ie.ids[bt]):null;return{index:bt,id:Ir,coordinate:[v,_],pointCoordinate:[wn,yn]}},[Ie]),tt=m.useCallback((y,E)=>{if(!A)return;const v=y?.index??null,_=y?.id??null;w.current===v&&x.current===_||(w.current=v,x.current=_,A({index:v,id:_,coordinate:E,pointCoordinate:y?.pointCoordinate??null}))},[A]),mt=m.useCallback((y,E)=>{if(!C)return;const v=Je(y);v&&C({...v,button:E})},[C,Je]);m.useEffect(()=>{if(F)return F.current=Je,()=>{F.current===Je&&(F.current=null)}},[F,Je]);const Ge=m.useCallback(y=>{ot(E=>String(E)===String(y)?E:(q?.(y),y))},[q]);m.useEffect(()=>{ae.current=r},[r]),m.useEffect(()=>{ye.current=i},[i]),m.useEffect(()=>{Se.current=c,c||u(null)},[c]);const un=m.useCallback(y=>{ye.current?.(y),Se.current&&u(y)},[]),xr=m.useMemo(()=>W?[`tier ${W.tier} | frame ${W.frameMs?.toFixed(2)??"-"} ms | drawCalls ${W.drawCalls??"-"}`,`tiles visible ${W.visible} | rendered ${W.rendered} | fallback ${W.fallback}`,`cache size ${W.cache} | hit ${W.cacheHits??"-"} | miss ${W.cacheMisses??"-"}`,`queue inflight ${W.inflight} | queued ${W.queued??"-"} | retries ${W.retries??"-"} | failed ${W.failed??"-"} | aborted ${W.aborted??"-"}`,`points ${W.points}`].join(`
|
|
158
|
+
`):"stats: waiting for first frame...",[W]);m.useEffect(()=>{!(le===null?!0:fe.some((_,U)=>String(Qt(_,U))===String(le)))&&le!==null&&Ge(null);const E=h.current;!(E===null?!0:fe.some((_,U)=>String(Qt(_,U))===String(E)))&&E!==null&&(h.current=null,be(null),I?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[fe,le,I,Ge]),m.useEffect(()=>{const y=w.current;y!==null&&(Ie&&y<Ie.safeCount||(w.current=null,x.current=null,A?.({index:null,id:null,coordinate:null,pointCoordinate:null})))},[Ie,A]);const ln=m.useCallback(y=>{H&&Be(y);const E=ae.current;E&&E(y),ie.current?.(),B.current?.()},[H]);m.useEffect(()=>{Z!=="cursor"&&h.current!==null&&(h.current=null,be(null),I?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[Z,I]),m.useEffect(()=>{Z!=="cursor"&&w.current!==null&&(w.current=null,x.current=null,A?.({index:null,id:null,coordinate:null,pointCoordinate:null}))},[Z,A]);const qe=m.useCallback((y,E)=>{const v=k.current;if(!v)return null;const _=v.screenToWorld(y,E);if(!Array.isArray(_)||_.length<2)return null;const U=Number(_[0]),$=Number(_[1]);return!Number.isFinite(U)||!Number.isFinite($)?null:[U,$]},[]),fn=m.useCallback((y,E)=>{const v=k.current;if(!v)return null;const _=v.worldToScreen(y,E);return tn(_)},[]),gt=m.useCallback((y,E)=>{const v=re.current;if(!v)return null;const _=v.getBoundingClientRect();if(!Number.isFinite(_.width)||!Number.isFinite(_.height)||_.width<=0||_.height<=0)return null;const U=y-_.left,$=E-_.top;return!Number.isFinite(U)||!Number.isFinite($)?null:{screenCoord:[U,$],canvasWidth:Math.max(1,_.width),canvasHeight:Math.max(1,_.height)}},[]),nt=m.useCallback((y,E,v,_)=>{const U=k.current;return U?Jo(y,E,oe,U,xe,v,_):null},[oe,xe]),hn=m.useCallback(()=>{k.current?.requestRender(),ie.current?.(),B.current?.()},[]),dn=m.useMemo(()=>Oe??k.current?.getViewState()??null,[Oe]),mn=m.useMemo(()=>{if(!t)return null;const y=dn;return y?{source:t,viewState:y,drawTool:Z,interactionLock:J,worldToScreen:fn,screenToWorld:qe,requestRedraw:hn}:null},[t,dn,Z,J,fn,qe,hn]),Ar=m.useCallback(y=>{const E=y.target===re.current,v=qe(y.clientX,y.clientY);if(se){const Qe=!!v&&v[0]>=0&&v[1]>=0&&!!t&&v[0]<=t.width&&v[1]<=t.height;se({coordinate:v,clientX:y.clientX,clientY:y.clientY,insideImage:Qe})}if(Z!=="cursor")return;if(!E){tt(null,null),h.current!==null&&(h.current=null,be(null),I?.({region:null,regionId:null,regionIndex:-1,coordinate:null}));return}if(!v){tt(null,null);return}if(A&&tt(Je(v),v),!oe.length)return;const _=gt(y.clientX,y.clientY);if(!_)return;const U=nt(v,_.screenCoord,_.canvasWidth,_.canvasHeight),$=U?.regionId??null,rt=h.current;String(rt)!==String($)&&(h.current=$,be($),I?.({region:U?.region??null,regionId:$,regionIndex:U?.regionIndex??-1,coordinate:v}))},[Z,oe,qe,I,se,t,tt,Je,A,gt,nt]),Rr=m.useCallback(()=>{se?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1}),tt(null,null),h.current!==null&&(h.current=null,be(null),I?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[I,se,tt]),Tr=m.useCallback(y=>{if(Z!=="cursor"||y.target!==re.current)return;const E=qe(y.clientX,y.clientY);if(!E)return;if(mt(E,y.button),!oe.length){Ge(null);return}const v=gt(y.clientX,y.clientY);if(!v)return;const _=nt(E,v.screenCoord,v.canvasWidth,v.canvasHeight);if(!_){Ge(null);return}const U=le!==null&&String(le)===String(_.regionId)?null:_.regionId;Ge(U),j?.({region:_.region,regionId:_.regionId,regionIndex:_.regionIndex,coordinate:E})},[Z,oe,qe,j,le,Ge,mt,gt,nt]),Er=m.useCallback(y=>{if(Z!=="brush"||he?.clickSelectRoi!==!0||!oe.length)return!1;const E=k.current,v=re.current;if(!E||!v)return!1;const _=v.getBoundingClientRect();if(_.width<=0||_.height<=0)return!1;const U=tn(E.worldToScreen(y[0],y[1]));if(!U)return!1;const $=nt(y,U,_.width,_.height);if(!$)return!1;const rt=le!==null&&String(le)===String($.regionId)?null:$.regionId;return Ge(rt),j?.({region:$.region,regionId:$.regionId,regionIndex:$.regionIndex,coordinate:y}),!0},[Z,he?.clickSelectRoi,oe,le,Ge,j,nt]),Cr=m.useCallback(y=>{if(!C||Z!=="cursor"||y.target!==re.current)return;y.preventDefault();const E=qe(y.clientX,y.clientY);E&&mt(E,y.button)},[Z,qe,mt,C]);return m.useEffect(()=>{const y=re.current;if(!y||!t)return;const E=new Sr(y,t,{onViewStateChange:ln,onStats:un,onTileError:o,onContextLost:s,onContextRestored:a,authToken:d,imageColorSettings:n,ctrlDragRotate:b,pointSizeByZoom:T,pointStrokeScale:L});return k.current=E,e&&E.setViewState(e),E.setInteractionLock(J),H&&Be(E.getViewState()),()=>{E.destroy(),k.current=null}},[t,un,o,s,a,d,b,T,L,ln,H]),m.useEffect(()=>{const y=k.current;!y||!e||y.setViewState(e)},[e]),m.useEffect(()=>{const y=k.current;y&&y.fitToImage()},[f]),m.useEffect(()=>{const y=k.current;y&&y.resetRotation()},[p]),m.useEffect(()=>{const y=k.current;!y||!S||y.setPointPalette(S)},[S]),m.useEffect(()=>{const y=k.current;y&&y.setPointSizeByZoom(T)},[T]),m.useEffect(()=>{const y=k.current;y&&y.setPointStrokeScale(L)},[L]),m.useEffect(()=>{const y=k.current;y&&y.setImageColorSettings(n)},[n]),m.useEffect(()=>{const y=k.current;y&&y.setPointData(Ae)},[Ae]),m.useEffect(()=>{if(!Q)return;const E=yr(Y?Ae:g,fe,{paletteIndexToTermId:ce,includeEmptyRegions:!0});Q(E)},[Q,Y,g,Ae,fe,ce]),m.useEffect(()=>{const y=k.current;y&&y.setInteractionLock(J)},[J]),Ue.jsxs("div",{className:de,style:ge,onPointerMove:Ar,onPointerLeave:Rr,onClick:Tr,onContextMenu:Cr,children:[Ue.jsx("canvas",{ref:re,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none",cursor:Z==="cursor"&&Me!==null?"pointer":J?"crosshair":"grab"}}),t&&mn&&Array.isArray(Te)&&Te.length>0?Te.map((y,E)=>Ue.jsx("div",{className:y.className,style:{position:"absolute",inset:0,zIndex:y.zIndex??3,pointerEvents:y.pointerEvents??"none",...y.style},children:y.render(mn)},y.id??E)):null,t?Ue.jsx(cr,{tool:Z,enabled:Z!=="cursor",imageWidth:t.width,imageHeight:t.height,imageMpp:t.mpp,imageZoom:t.maxTierZoom,stampOptions:Pe,brushOptions:he,projectorRef:k,onBrushTap:Er,viewStateSignal:e,persistedRegions:fe,patchRegions:G,regionStrokeStyle:Ke,regionStrokeHoverStyle:je,regionStrokeActiveStyle:et,patchStrokeStyle:pe,resolveRegionStrokeStyle:V,overlayShapes:ve,hoveredRegionId:Me,activeRegionId:le,regionLabelStyle:De,invalidateRef:ie,onDrawComplete:Ee,onPatchComplete:ne}):null,c?Ue.jsx("pre",{"data-open-plant-debug-overlay":!0,style:Xe,children:xr}):null,t&&ee&&Ue.jsx(lr,{source:t,projectorRef:k,authToken:d,options:ue,invalidateRef:B,className:N?.className,style:N?.style})]})}exports.DEFAULT_POINT_COLOR=nn;exports.DrawLayer=cr;exports.M1TileRenderer=Zn;exports.OverviewMap=lr;exports.TileScheduler=Mr;exports.TileViewerCanvas=so;exports.WsiTileRenderer=Sr;exports.WsiViewerCanvas=Qo;exports.buildTermPalette=mi;exports.calcScaleLength=fi;exports.calcScaleResolution=rn;exports.clamp=te;exports.closeRing=Ne;exports.computeRoiPointGroups=yr;exports.createCircle=qt;exports.createRectangle=Gt;exports.filterPointDataByPolygons=ht;exports.filterPointDataByPolygonsHybrid=gr;exports.filterPointDataByPolygonsInWorker=wr;exports.filterPointIndicesByPolygons=hr;exports.filterPointIndicesByPolygonsInWorker=bo;exports.getWebGpuCapabilities=mo;exports.hexToRgba=tr;exports.isSameViewState=hi;exports.normalizeImageInfo=io;exports.prefilterPointsByBoundsWebGpu=mr;exports.terminateRoiClipWorker=po;exports.toBearerToken=di;exports.toTileUrl=on;
|
|
159
159
|
//# sourceMappingURL=index.cjs.map
|