open-plant 1.4.2 → 1.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -30,7 +30,7 @@ void main() {
30
30
  outColor = texture(uTexture, vUv);
31
31
  }
32
32
  `;class zr{constructor(t){R(this,"canvas");R(this,"gl");R(this,"camera",new Br);R(this,"imageWidth");R(this,"imageHeight");R(this,"clearColor");R(this,"program");R(this,"vao");R(this,"quadBuffer");R(this,"uCameraLocation");R(this,"uBoundsLocation");R(this,"uTextureLocation");R(this,"resizeObserver");R(this,"tiles",[]);R(this,"frameId",null);R(this,"loadVersion",0);R(this,"destroyed",!1);R(this,"fitted",!1);R(this,"controlledViewState",!1);this.canvas=t.canvas,this.imageWidth=Math.max(1,t.imageWidth),this.imageHeight=Math.max(1,t.imageHeight),this.clearColor=t.clearColor??[.03,.05,.08,1],this.gl=Ei(this.canvas),this.program=bn(this.gl,Ri,Mi);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=_e(this.gl,this.program,"uCamera"),this.uBoundsLocation=_e(this.gl,this.program,"uBounds"),this.uTextureLocation=_e(this.gl,this.program,"uTexture"),t.initialViewState&&(this.controlledViewState=!0,this.camera.setViewState(t.initialViewState)),this.resizeObserver=new ResizeObserver(()=>{this.resize()}),this.resizeObserver.observe(this.canvas),this.resize()}async setTiles(t){if(this.destroyed)return;const n=++this.loadVersion,r=await Promise.all(t.map(async i=>await this.loadTile(i,n)));if(this.destroyed||n!==this.loadVersion){for(const i of r)i&&this.gl.deleteTexture(i.texture);return}this.disposeTiles(this.tiles),this.tiles=r.filter(i=>i!==null),this.requestRender()}setViewState(t){this.controlledViewState=!0,this.camera.setViewState(t),this.requestRender()}getViewState(){return this.camera.getViewState()}destroy(){this.destroyed||(this.destroyed=!0,this.loadVersion+=1,this.frameId!==null&&(cancelAnimationFrame(this.frameId),this.frameId=null),this.resizeObserver.disconnect(),this.disposeTiles(this.tiles),this.tiles=[],this.gl.deleteBuffer(this.quadBuffer),this.gl.deleteVertexArray(this.vao),this.gl.deleteProgram(this.program))}async loadTile(t,n){try{const r=await fetch(t.url);if(!r.ok)throw new Error(`Tile fetch failed: ${r.status} ${r.statusText}`);const i=await r.blob(),o=await createImageBitmap(i);if(this.destroyed||n!==this.loadVersion)return o.close(),null;const s=this.gl.createTexture();if(!s)throw o.close(),new Error("Failed to create tile texture.");return this.gl.bindTexture(this.gl.TEXTURE_2D,s),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,1),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),this.gl.bindTexture(this.gl.TEXTURE_2D,null),o.close(),{id:t.id,bounds:t.bounds,texture:s}}catch(r){return console.error(`[M1TileRenderer] tile load failed: ${t.id}`,r),null}}resize(){if(this.destroyed)return;const t=this.canvas.getBoundingClientRect(),n=Math.max(1,t.width||this.canvas.clientWidth||1),r=Math.max(1,t.height||this.canvas.clientHeight||1),i=Math.max(1,window.devicePixelRatio||1),o=Math.max(1,Math.round(n*i)),s=Math.max(1,Math.round(r*i));(this.canvas.width!==o||this.canvas.height!==s)&&(this.canvas.width=o,this.canvas.height=s),this.camera.setViewport(n,r),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),!this.fitted&&!this.controlledViewState&&(this.fitToImage(),this.fitted=!0),this.requestRender()}fitToImage(){const t=this.camera.getViewportSize(),n=Math.min(t.width/this.imageWidth,t.height/this.imageHeight),r=Number.isFinite(n)&&n>0?n:1,i=t.width/r,o=t.height/r,s=(this.imageWidth-i)*.5,a=(this.imageHeight-o)*.5;this.camera.setViewState({zoom:r,offsetX:s,offsetY:a})}requestRender(){this.frameId!==null||this.destroyed||(this.frameId=requestAnimationFrame(()=>{this.frameId=null,this.render()}))}render(){if(!this.destroyed){this.gl.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.useProgram(this.program),this.gl.bindVertexArray(this.vao),this.gl.uniformMatrix3fv(this.uCameraLocation,!1,this.camera.getMatrix()),this.gl.uniform1i(this.uTextureLocation,0);for(const t of this.tiles)this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,t.texture),this.gl.uniform4f(this.uBoundsLocation,t.bounds[0],t.bounds[1],t.bounds[2],t.bounds[3]),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindVertexArray(null)}}disposeTiles(t){for(const n of t)this.gl.deleteTexture(n.texture)}}class Qe{constructor(t,n){this.next=null,this.key=t,this.data=n,this.left=null,this.right=null}}function Ai(e,t){return e>t?1:e<t?-1:0}function $e(e,t,n){const r=new Qe(null,null);let i=r,o=r;for(;;){const s=n(e,t.key);if(s<0){if(t.left===null)break;if(n(e,t.left.key)<0){const a=t.left;if(t.left=a.right,a.right=t,t=a,t.left===null)break}o.left=t,o=t,t=t.left}else if(s>0){if(t.right===null)break;if(n(e,t.right.key)>0){const a=t.right;if(t.right=a.left,a.left=t,t=a,t.right===null)break}i.right=t,i=t,t=t.right}else break}return i.right=t.left,o.left=t.right,t.left=r.right,t.right=r.left,t}function $t(e,t,n,r){const i=new Qe(e,t);if(n===null)return i.left=i.right=null,i;n=$e(e,n,r);const o=r(e,n.key);return o<0?(i.left=n.left,i.right=n,n.left=null):o>=0&&(i.right=n.right,i.left=n,n.right=null),i}function Ln(e,t,n){let r=null,i=null;if(t){t=$e(e,t,n);const o=n(t.key,e);o===0?(r=t.left,i=t.right):o<0?(i=t.right,t.right=null,r=t):(r=t.left,t.left=null,i=t)}return{left:r,right:i}}function vi(e,t,n){return t===null?e:(e===null||(t=$e(e.key,t,n),t.left=e),t)}function rn(e,t,n,r,i){if(e){r(`${t}${n?"└── ":"├── "}${i(e)}
33
- `);const o=t+(n?" ":"│ ");e.left&&rn(e.left,o,!1,r,i),e.right&&rn(e.right,o,!0,r,i)}}class wn{constructor(t=Ai){this._root=null,this._size=0,this._comparator=t}insert(t,n){return this._size++,this._root=$t(t,n,this._root,this._comparator)}add(t,n){const r=new Qe(t,n);this._root===null&&(r.left=r.right=null,this._size++,this._root=r);const i=this._comparator,o=$e(t,this._root,i),s=i(t,o.key);return s===0?this._root=o:(s<0?(r.left=o.left,r.right=o,o.left=null):s>0&&(r.right=o.right,r.left=o,o.right=null),this._size++,this._root=r),this._root}remove(t){this._root=this._remove(t,this._root,this._comparator)}_remove(t,n,r){let i;return n===null?null:(n=$e(t,n,r),r(t,n.key)===0?(n.left===null?i=n.right:(i=$e(t,n.left,r),i.right=n.right),this._size--,i):n)}pop(){let t=this._root;if(t){for(;t.left;)t=t.left;return this._root=$e(t.key,this._root,this._comparator),this._root=this._remove(t.key,this._root,this._comparator),{key:t.key,data:t.data}}return null}findStatic(t){let n=this._root;const r=this._comparator;for(;n;){const i=r(t,n.key);if(i===0)return n;i<0?n=n.left:n=n.right}return null}find(t){return this._root&&(this._root=$e(t,this._root,this._comparator),this._comparator(t,this._root.key)!==0)?null:this._root}contains(t){let n=this._root;const r=this._comparator;for(;n;){const i=r(t,n.key);if(i===0)return!0;i<0?n=n.left:n=n.right}return!1}forEach(t,n){let r=this._root;const i=[];let o=!1;for(;!o;)r!==null?(i.push(r),r=r.left):i.length!==0?(r=i.pop(),t.call(n,r),r=r.right):o=!0;return this}range(t,n,r,i){const o=[],s=this._comparator;let a=this._root,c;for(;o.length!==0||a;)if(a)o.push(a),a=a.left;else{if(a=o.pop(),c=s(a.key,n),c>0)break;if(s(a.key,t)>=0&&r.call(i,a))return this;a=a.right}return this}keys(){const t=[];return this.forEach(({key:n})=>{t.push(n)}),t}values(){const t=[];return this.forEach(({data:n})=>{t.push(n)}),t}min(){return this._root?this.minNode(this._root).key:null}max(){return this._root?this.maxNode(this._root).key:null}minNode(t=this._root){if(t)for(;t.left;)t=t.left;return t}maxNode(t=this._root){if(t)for(;t.right;)t=t.right;return t}at(t){let n=this._root,r=!1,i=0;const o=[];for(;!r;)if(n)o.push(n),n=n.left;else if(o.length>0){if(n=o.pop(),i===t)return n;i++,n=n.right}else r=!0;return null}next(t){let n=this._root,r=null;if(t.right){for(r=t.right;r.left;)r=r.left;return r}const i=this._comparator;for(;n;){const o=i(t.key,n.key);if(o===0)break;o<0?(r=n,n=n.left):n=n.right}return r}prev(t){let n=this._root,r=null;if(t.left!==null){for(r=t.left;r.right;)r=r.right;return r}const i=this._comparator;for(;n;){const o=i(t.key,n.key);if(o===0)break;o<0?n=n.left:(r=n,n=n.right)}return r}clear(){return this._root=null,this._size=0,this}toList(){return Pi(this._root)}load(t,n=[],r=!1){let i=t.length;const o=this._comparator;if(r&&an(t,n,0,i-1,o),this._root===null)this._root=on(t,n,0,i),this._size=i;else{const s=Ti(this.toList(),Ci(t,n),o);i=this._size+i,this._root=sn({head:s},0,i)}return this}isEmpty(){return this._root===null}get size(){return this._size}get root(){return this._root}toString(t=n=>String(n.key)){const n=[];return rn(this._root,"",!0,r=>n.push(r),t),n.join("")}update(t,n,r){const i=this._comparator;let{left:o,right:s}=Ln(t,this._root,i);i(t,n)<0?s=$t(n,r,s,i):o=$t(n,r,o,i),this._root=vi(o,s,i)}split(t){return Ln(t,this._root,this._comparator)}*[Symbol.iterator](){let t=this._root;const n=[];let r=!1;for(;!r;)t!==null?(n.push(t),t=t.left):n.length!==0?(t=n.pop(),yield t,t=t.right):r=!0}}function on(e,t,n,r){const i=r-n;if(i>0){const o=n+Math.floor(i/2),s=e[o],a=t[o],c=new Qe(s,a);return c.left=on(e,t,n,o),c.right=on(e,t,o+1,r),c}return null}function Ci(e,t){const n=new Qe(null,null);let r=n;for(let i=0;i<e.length;i++)r=r.next=new Qe(e[i],t[i]);return r.next=null,n.next}function Pi(e){let t=e;const n=[];let r=!1;const i=new Qe(null,null);let o=i;for(;!r;)t?(n.push(t),t=t.left):n.length>0?(t=o=o.next=n.pop(),t=t.right):r=!0;return o.next=null,i.next}function sn(e,t,n){const r=n-t;if(r>0){const i=t+Math.floor(r/2),o=sn(e,t,i),s=e.head;return s.left=o,e.head=e.head.next,s.right=sn(e,i+1,n),s}return null}function Ti(e,t,n){const r=new Qe(null,null);let i=r,o=e,s=t;for(;o!==null&&s!==null;)n(o.key,s.key)<0?(i.next=o,o=o.next):(i.next=s,s=s.next),i=i.next;return o!==null?i.next=o:s!==null&&(i.next=s),r.next}function an(e,t,n,r,i){if(n>=r)return;const o=e[n+r>>1];let s=n-1,a=r+1;for(;;){do s++;while(i(e[s],o)<0);do a--;while(i(e[a],o)>0);if(s>=a)break;let c=e[s];e[s]=e[a],e[a]=c,c=t[s],t[s]=t[a],t[a]=c}an(e,t,n,a,i),an(e,t,a+1,r,i)}const Ge=11102230246251565e-32,Pe=134217729,Ii=(3+8*Ge)*Ge;function Kt(e,t,n,r,i){let o,s,a,c,u=t[0],h=r[0],l=0,f=0;h>u==h>-u?(o=u,u=t[++l]):(o=h,h=r[++f]);let d=0;if(l<e&&f<n)for(h>u==h>-u?(s=u+o,a=o-(s-u),u=t[++l]):(s=h+o,a=o-(s-h),h=r[++f]),o=s,a!==0&&(i[d++]=a);l<e&&f<n;)h>u==h>-u?(s=o+u,c=s-o,a=o-(s-c)+(u-c),u=t[++l]):(s=o+h,c=s-o,a=o-(s-c)+(h-c),h=r[++f]),o=s,a!==0&&(i[d++]=a);for(;l<e;)s=o+u,c=s-o,a=o-(s-c)+(u-c),u=t[++l],o=s,a!==0&&(i[d++]=a);for(;f<n;)s=o+h,c=s-o,a=o-(s-c)+(h-c),h=r[++f],o=s,a!==0&&(i[d++]=a);return(o!==0||d===0)&&(i[d++]=o),d}function _i(e,t){let n=t[0];for(let r=1;r<e;r++)n+=t[r];return n}function gt(e){return new Float64Array(e)}const Fi=(3+16*Ge)*Ge,Li=(2+12*Ge)*Ge,ki=(9+64*Ge)*Ge*Ge,tt=gt(4),kn=gt(8),Nn=gt(12),Bn=gt(16),Ie=gt(4);function Ni(e,t,n,r,i,o,s){let a,c,u,h,l,f,d,m,p,y,b,x,C,S,A,I,O,z;const G=e-i,D=n-i,q=t-o,re=r-o;S=G*re,f=Pe*G,d=f-(f-G),m=G-d,f=Pe*re,p=f-(f-re),y=re-p,A=m*y-(S-d*p-m*p-d*y),I=q*D,f=Pe*q,d=f-(f-q),m=q-d,f=Pe*D,p=f-(f-D),y=D-p,O=m*y-(I-d*p-m*p-d*y),b=A-O,l=A-b,tt[0]=A-(b+l)+(l-O),x=S+b,l=x-S,C=S-(x-l)+(b-l),b=C-I,l=C-b,tt[1]=C-(b+l)+(l-I),z=x+b,l=z-x,tt[2]=x-(z-l)+(b-l),tt[3]=z;let P=_i(4,tt),H=Li*s;if(P>=H||-P>=H||(l=e-G,a=e-(G+l)+(l-i),l=n-D,u=n-(D+l)+(l-i),l=t-q,c=t-(q+l)+(l-o),l=r-re,h=r-(re+l)+(l-o),a===0&&c===0&&u===0&&h===0)||(H=ki*s+Ii*Math.abs(P),P+=G*h+re*a-(q*u+D*c),P>=H||-P>=H))return P;S=a*re,f=Pe*a,d=f-(f-a),m=a-d,f=Pe*re,p=f-(f-re),y=re-p,A=m*y-(S-d*p-m*p-d*y),I=c*D,f=Pe*c,d=f-(f-c),m=c-d,f=Pe*D,p=f-(f-D),y=D-p,O=m*y-(I-d*p-m*p-d*y),b=A-O,l=A-b,Ie[0]=A-(b+l)+(l-O),x=S+b,l=x-S,C=S-(x-l)+(b-l),b=C-I,l=C-b,Ie[1]=C-(b+l)+(l-I),z=x+b,l=z-x,Ie[2]=x-(z-l)+(b-l),Ie[3]=z;const N=Kt(4,tt,4,Ie,kn);S=G*h,f=Pe*G,d=f-(f-G),m=G-d,f=Pe*h,p=f-(f-h),y=h-p,A=m*y-(S-d*p-m*p-d*y),I=q*u,f=Pe*q,d=f-(f-q),m=q-d,f=Pe*u,p=f-(f-u),y=u-p,O=m*y-(I-d*p-m*p-d*y),b=A-O,l=A-b,Ie[0]=A-(b+l)+(l-O),x=S+b,l=x-S,C=S-(x-l)+(b-l),b=C-I,l=C-b,Ie[1]=C-(b+l)+(l-I),z=x+b,l=z-x,Ie[2]=x-(z-l)+(b-l),Ie[3]=z;const k=Kt(N,kn,4,Ie,Nn);S=a*h,f=Pe*a,d=f-(f-a),m=a-d,f=Pe*h,p=f-(f-h),y=h-p,A=m*y-(S-d*p-m*p-d*y),I=c*u,f=Pe*c,d=f-(f-c),m=c-d,f=Pe*u,p=f-(f-u),y=u-p,O=m*y-(I-d*p-m*p-d*y),b=A-O,l=A-b,Ie[0]=A-(b+l)+(l-O),x=S+b,l=x-S,C=S-(x-l)+(b-l),b=C-I,l=C-b,Ie[1]=C-(b+l)+(l-I),z=x+b,l=z-x,Ie[2]=x-(z-l)+(b-l),Ie[3]=z;const Z=Kt(k,Nn,4,Ie,Bn);return Bn[Z-1]}function Bi(e,t,n,r,i,o){const s=(t-o)*(n-i),a=(e-i)*(r-o),c=s-a,u=Math.abs(s+a);return Math.abs(c)>=Fi*u?c:-Ni(e,t,n,r,i,o,u)}const at=(e,t)=>e.ll.x<=t.x&&t.x<=e.ur.x&&e.ll.y<=t.y&&t.y<=e.ur.y,ln=(e,t)=>{if(t.ur.x<e.ll.x||e.ur.x<t.ll.x||t.ur.y<e.ll.y||e.ur.y<t.ll.y)return null;const n=e.ll.x<t.ll.x?t.ll.x:e.ll.x,r=e.ur.x<t.ur.x?e.ur.x:t.ur.x,i=e.ll.y<t.ll.y?t.ll.y:e.ll.y,o=e.ur.y<t.ur.y?e.ur.y:t.ur.y;return{ll:{x:n,y:i},ur:{x:r,y:o}}};let Ke=Number.EPSILON;Ke===void 0&&(Ke=Math.pow(2,-52));const zi=Ke*Ke,zn=(e,t)=>{if(-Ke<e&&e<Ke&&-Ke<t&&t<Ke)return 0;const n=e-t;return n*n<zi*e*t?0:e<t?-1:1};class Di{constructor(){this.reset()}reset(){this.xRounder=new Dn,this.yRounder=new Dn}round(t,n){return{x:this.xRounder.round(t),y:this.yRounder.round(n)}}}class Dn{constructor(){this.tree=new wn,this.round(0)}round(t){const n=this.tree.add(t),r=this.tree.prev(n);if(r!==null&&zn(n.key,r.key)===0)return this.tree.remove(t),r.key;const i=this.tree.next(n);return i!==null&&zn(n.key,i.key)===0?(this.tree.remove(t),i.key):t}}const ft=new Di,It=(e,t)=>e.x*t.y-e.y*t.x,Dr=(e,t)=>e.x*t.x+e.y*t.y,Un=(e,t,n)=>{const r=Bi(e.x,e.y,t.x,t.y,n.x,n.y);return r>0?-1:r<0?1:0},Nt=e=>Math.sqrt(Dr(e,e)),Ui=(e,t,n)=>{const r={x:t.x-e.x,y:t.y-e.y},i={x:n.x-e.x,y:n.y-e.y};return It(i,r)/Nt(i)/Nt(r)},Oi=(e,t,n)=>{const r={x:t.x-e.x,y:t.y-e.y},i={x:n.x-e.x,y:n.y-e.y};return Dr(i,r)/Nt(i)/Nt(r)},On=(e,t,n)=>t.y===0?null:{x:e.x+t.x/t.y*(n-e.y),y:n},Yn=(e,t,n)=>t.x===0?null:{x:n,y:e.y+t.y/t.x*(n-e.x)},Yi=(e,t,n,r)=>{if(t.x===0)return Yn(n,r,e.x);if(r.x===0)return Yn(e,t,n.x);if(t.y===0)return On(n,r,e.y);if(r.y===0)return On(e,t,n.y);const i=It(t,r);if(i==0)return null;const o={x:n.x-e.x,y:n.y-e.y},s=It(o,t)/i,a=It(o,r)/i,c=e.x+a*t.x,u=n.x+s*r.x,h=e.y+a*t.y,l=n.y+s*r.y,f=(c+u)/2,d=(h+l)/2;return{x:f,y:d}};class Be{static compare(t,n){const r=Be.comparePoints(t.point,n.point);return r!==0?r:(t.point!==n.point&&t.link(n),t.isLeft!==n.isLeft?t.isLeft?1:-1:je.compare(t.segment,n.segment))}static comparePoints(t,n){return t.x<n.x?-1:t.x>n.x?1:t.y<n.y?-1:t.y>n.y?1:0}constructor(t,n){t.events===void 0?t.events=[this]:t.events.push(this),this.point=t,this.isLeft=n}link(t){if(t.point===this.point)throw new Error("Tried to link already linked events");const n=t.point.events;for(let r=0,i=n.length;r<i;r++){const o=n[r];this.point.events.push(o),o.point=this.point}this.checkForConsuming()}checkForConsuming(){const t=this.point.events.length;for(let n=0;n<t;n++){const r=this.point.events[n];if(r.segment.consumedBy===void 0)for(let i=n+1;i<t;i++){const o=this.point.events[i];o.consumedBy===void 0&&r.otherSE.point.events===o.otherSE.point.events&&r.segment.consume(o.segment)}}}getAvailableLinkedEvents(){const t=[];for(let n=0,r=this.point.events.length;n<r;n++){const i=this.point.events[n];i!==this&&!i.segment.ringOut&&i.segment.isInResult()&&t.push(i)}return t}getLeftmostComparator(t){const n=new Map,r=i=>{const o=i.otherSE;n.set(i,{sine:Ui(this.point,t.point,o.point),cosine:Oi(this.point,t.point,o.point)})};return(i,o)=>{n.has(i)||r(i),n.has(o)||r(o);const{sine:s,cosine:a}=n.get(i),{sine:c,cosine:u}=n.get(o);return s>=0&&c>=0?a<u?1:a>u?-1:0:s<0&&c<0?a<u?-1:a>u?1:0:c<s?-1:c>s?1:0}}}let Wi=0;class je{static compare(t,n){const r=t.leftSE.point.x,i=n.leftSE.point.x,o=t.rightSE.point.x,s=n.rightSE.point.x;if(s<r)return 1;if(o<i)return-1;const a=t.leftSE.point.y,c=n.leftSE.point.y,u=t.rightSE.point.y,h=n.rightSE.point.y;if(r<i){if(c<a&&c<u)return 1;if(c>a&&c>u)return-1;const l=t.comparePoint(n.leftSE.point);if(l<0)return 1;if(l>0)return-1;const f=n.comparePoint(t.rightSE.point);return f!==0?f:-1}if(r>i){if(a<c&&a<h)return-1;if(a>c&&a>h)return 1;const l=n.comparePoint(t.leftSE.point);if(l!==0)return l;const f=t.comparePoint(n.rightSE.point);return f<0?1:f>0?-1:1}if(a<c)return-1;if(a>c)return 1;if(o<s){const l=n.comparePoint(t.rightSE.point);if(l!==0)return l}if(o>s){const l=t.comparePoint(n.rightSE.point);if(l<0)return 1;if(l>0)return-1}if(o!==s){const l=u-a,f=o-r,d=h-c,m=s-i;if(l>f&&d<m)return 1;if(l<f&&d>m)return-1}return o>s?1:o<s||u<h?-1:u>h?1:t.id<n.id?-1:t.id>n.id?1:0}constructor(t,n,r,i){this.id=++Wi,this.leftSE=t,t.segment=this,t.otherSE=n,this.rightSE=n,n.segment=this,n.otherSE=t,this.rings=r,this.windings=i}static fromRing(t,n,r){let i,o,s;const a=Be.comparePoints(t,n);if(a<0)i=t,o=n,s=1;else if(a>0)i=n,o=t,s=-1;else throw new Error(`Tried to create degenerate segment at [${t.x}, ${t.y}]`);const c=new Be(i,!0),u=new Be(o,!1);return new je(c,u,[r],[s])}replaceRightSE(t){this.rightSE=t,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const t=this.leftSE.point.y,n=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:t<n?t:n},ur:{x:this.rightSE.point.x,y:t>n?t:n}}}vector(){return{x:this.rightSE.point.x-this.leftSE.point.x,y:this.rightSE.point.y-this.leftSE.point.y}}isAnEndpoint(t){return t.x===this.leftSE.point.x&&t.y===this.leftSE.point.y||t.x===this.rightSE.point.x&&t.y===this.rightSE.point.y}comparePoint(t){if(this.isAnEndpoint(t))return 0;const n=this.leftSE.point,r=this.rightSE.point,i=this.vector();if(n.x===r.x)return t.x===n.x?0:t.x<n.x?1:-1;const o=(t.y-n.y)/i.y,s=n.x+o*i.x;if(t.x===s)return 0;const a=(t.x-n.x)/i.x,c=n.y+a*i.y;return t.y===c?0:t.y<c?-1:1}getIntersection(t){const n=this.bbox(),r=t.bbox(),i=ln(n,r);if(i===null)return null;const o=this.leftSE.point,s=this.rightSE.point,a=t.leftSE.point,c=t.rightSE.point,u=at(n,a)&&this.comparePoint(a)===0,h=at(r,o)&&t.comparePoint(o)===0,l=at(n,c)&&this.comparePoint(c)===0,f=at(r,s)&&t.comparePoint(s)===0;if(h&&u)return f&&!l?s:!f&&l?c:null;if(h)return l&&o.x===c.x&&o.y===c.y?null:o;if(u)return f&&s.x===a.x&&s.y===a.y?null:a;if(f&&l)return null;if(f)return s;if(l)return c;const d=Yi(o,this.vector(),a,t.vector());return d===null||!at(i,d)?null:ft.round(d.x,d.y)}split(t){const n=[],r=t.events!==void 0,i=new Be(t,!0),o=new Be(t,!1),s=this.rightSE;this.replaceRightSE(o),n.push(o),n.push(i);const a=new je(i,s,this.rings.slice(),this.windings.slice());return Be.comparePoints(a.leftSE.point,a.rightSE.point)>0&&a.swapEvents(),Be.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),r&&(i.checkForConsuming(),o.checkForConsuming()),n}swapEvents(){const t=this.rightSE;this.rightSE=this.leftSE,this.leftSE=t,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let n=0,r=this.windings.length;n<r;n++)this.windings[n]*=-1}consume(t){let n=this,r=t;for(;n.consumedBy;)n=n.consumedBy;for(;r.consumedBy;)r=r.consumedBy;const i=je.compare(n,r);if(i!==0){if(i>0){const o=n;n=r,r=o}if(n.prev===r){const o=n;n=r,r=o}for(let o=0,s=r.rings.length;o<s;o++){const a=r.rings[o],c=r.windings[o],u=n.rings.indexOf(a);u===-1?(n.rings.push(a),n.windings.push(c)):n.windings[u]+=c}r.rings=null,r.windings=null,r.consumedBy=n,r.leftSE.consumedBy=n.leftSE,r.rightSE.consumedBy=n.rightSE}}prevInResult(){return this._prevInResult!==void 0?this._prevInResult:(this.prev?this.prev.isInResult()?this._prevInResult=this.prev:this._prevInResult=this.prev.prevInResult():this._prevInResult=null,this._prevInResult)}beforeState(){if(this._beforeState!==void 0)return this._beforeState;if(!this.prev)this._beforeState={rings:[],windings:[],multiPolys:[]};else{const t=this.prev.consumedBy||this.prev;this._beforeState=t.afterState()}return this._beforeState}afterState(){if(this._afterState!==void 0)return this._afterState;const t=this.beforeState();this._afterState={rings:t.rings.slice(0),windings:t.windings.slice(0),multiPolys:[]};const n=this._afterState.rings,r=this._afterState.windings,i=this._afterState.multiPolys;for(let a=0,c=this.rings.length;a<c;a++){const u=this.rings[a],h=this.windings[a],l=n.indexOf(u);l===-1?(n.push(u),r.push(h)):r[l]+=h}const o=[],s=[];for(let a=0,c=n.length;a<c;a++){if(r[a]===0)continue;const u=n[a],h=u.poly;if(s.indexOf(h)===-1)if(u.isExterior)o.push(h);else{s.indexOf(h)===-1&&s.push(h);const l=o.indexOf(u.poly);l!==-1&&o.splice(l,1)}}for(let a=0,c=o.length;a<c;a++){const u=o[a].multiPoly;i.indexOf(u)===-1&&i.push(u)}return this._afterState}isInResult(){if(this.consumedBy)return!1;if(this._isInResult!==void 0)return this._isInResult;const t=this.beforeState().multiPolys,n=this.afterState().multiPolys;switch(We.type){case"union":{const r=t.length===0,i=n.length===0;this._isInResult=r!==i;break}case"intersection":{let r,i;t.length<n.length?(r=t.length,i=n.length):(r=n.length,i=t.length),this._isInResult=i===We.numMultiPolys&&r<i;break}case"xor":{const r=Math.abs(t.length-n.length);this._isInResult=r%2===1;break}case"difference":{const r=i=>i.length===1&&i[0].isSubject;this._isInResult=r(t)!==r(n);break}default:throw new Error(`Unrecognized operation type found ${We.type}`)}return this._isInResult}}class Wn{constructor(t,n,r){if(!Array.isArray(t)||t.length===0)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=n,this.isExterior=r,this.segments=[],typeof t[0][0]!="number"||typeof t[0][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const i=ft.round(t[0][0],t[0][1]);this.bbox={ll:{x:i.x,y:i.y},ur:{x:i.x,y:i.y}};let o=i;for(let s=1,a=t.length;s<a;s++){if(typeof t[s][0]!="number"||typeof t[s][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");let c=ft.round(t[s][0],t[s][1]);c.x===o.x&&c.y===o.y||(this.segments.push(je.fromRing(o,c,this)),c.x<this.bbox.ll.x&&(this.bbox.ll.x=c.x),c.y<this.bbox.ll.y&&(this.bbox.ll.y=c.y),c.x>this.bbox.ur.x&&(this.bbox.ur.x=c.x),c.y>this.bbox.ur.y&&(this.bbox.ur.y=c.y),o=c)}(i.x!==o.x||i.y!==o.y)&&this.segments.push(je.fromRing(o,i,this))}getSweepEvents(){const t=[];for(let n=0,r=this.segments.length;n<r;n++){const i=this.segments[n];t.push(i.leftSE),t.push(i.rightSE)}return t}}class Xi{constructor(t,n){if(!Array.isArray(t))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");this.exteriorRing=new Wn(t[0],this,!0),this.bbox={ll:{x:this.exteriorRing.bbox.ll.x,y:this.exteriorRing.bbox.ll.y},ur:{x:this.exteriorRing.bbox.ur.x,y:this.exteriorRing.bbox.ur.y}},this.interiorRings=[];for(let r=1,i=t.length;r<i;r++){const o=new Wn(t[r],this,!1);o.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=o.bbox.ll.x),o.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=o.bbox.ll.y),o.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=o.bbox.ur.x),o.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=o.bbox.ur.y),this.interiorRings.push(o)}this.multiPoly=n}getSweepEvents(){const t=this.exteriorRing.getSweepEvents();for(let n=0,r=this.interiorRings.length;n<r;n++){const i=this.interiorRings[n].getSweepEvents();for(let o=0,s=i.length;o<s;o++)t.push(i[o])}return t}}class Xn{constructor(t,n){if(!Array.isArray(t))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");try{typeof t[0][0][0]=="number"&&(t=[t])}catch{}this.polys=[],this.bbox={ll:{x:Number.POSITIVE_INFINITY,y:Number.POSITIVE_INFINITY},ur:{x:Number.NEGATIVE_INFINITY,y:Number.NEGATIVE_INFINITY}};for(let r=0,i=t.length;r<i;r++){const o=new Xi(t[r],this);o.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=o.bbox.ll.x),o.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=o.bbox.ll.y),o.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=o.bbox.ur.x),o.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=o.bbox.ur.y),this.polys.push(o)}this.isSubject=n}getSweepEvents(){const t=[];for(let n=0,r=this.polys.length;n<r;n++){const i=this.polys[n].getSweepEvents();for(let o=0,s=i.length;o<s;o++)t.push(i[o])}return t}}class Bt{static factory(t){const n=[];for(let r=0,i=t.length;r<i;r++){const o=t[r];if(!o.isInResult()||o.ringOut)continue;let s=null,a=o.leftSE,c=o.rightSE;const u=[a],h=a.point,l=[];for(;s=a,a=c,u.push(a),a.point!==h;)for(;;){const f=a.getAvailableLinkedEvents();if(f.length===0){const p=u[0].point,y=u[u.length-1].point;throw new Error(`Unable to complete output ring starting at [${p.x}, ${p.y}]. Last matching segment found ends at [${y.x}, ${y.y}].`)}if(f.length===1){c=f[0].otherSE;break}let d=null;for(let p=0,y=l.length;p<y;p++)if(l[p].point===a.point){d=p;break}if(d!==null){const p=l.splice(d)[0],y=u.splice(p.index);y.unshift(y[0].otherSE),n.push(new Bt(y.reverse()));continue}l.push({index:u.length,point:a.point});const m=a.getLeftmostComparator(s);c=f.sort(m)[0].otherSE;break}n.push(new Bt(u))}return n}constructor(t){this.events=t;for(let n=0,r=t.length;n<r;n++)t[n].segment.ringOut=this;this.poly=null}getGeom(){let t=this.events[0].point;const n=[t];for(let u=1,h=this.events.length-1;u<h;u++){const l=this.events[u].point,f=this.events[u+1].point;Un(l,t,f)!==0&&(n.push(l),t=l)}if(n.length===1)return null;const r=n[0],i=n[1];Un(r,t,i)===0&&n.shift(),n.push(n[0]);const o=this.isExteriorRing()?1:-1,s=this.isExteriorRing()?0:n.length-1,a=this.isExteriorRing()?n.length:-1,c=[];for(let u=s;u!=a;u+=o)c.push([n[u].x,n[u].y]);return c}isExteriorRing(){if(this._isExteriorRing===void 0){const t=this.enclosingRing();this._isExteriorRing=t?!t.isExteriorRing():!0}return this._isExteriorRing}enclosingRing(){return this._enclosingRing===void 0&&(this._enclosingRing=this._calcEnclosingRing()),this._enclosingRing}_calcEnclosingRing(){let t=this.events[0];for(let i=1,o=this.events.length;i<o;i++){const s=this.events[i];Be.compare(t,s)>0&&(t=s)}let n=t.segment.prevInResult(),r=n?n.prevInResult():null;for(;;){if(!n)return null;if(!r)return n.ringOut;if(r.ringOut!==n.ringOut)return r.ringOut.enclosingRing()!==n.ringOut?n.ringOut:n.ringOut.enclosingRing();n=r.prevInResult(),r=n?n.prevInResult():null}}}class Vn{constructor(t){this.exteriorRing=t,t.poly=this,this.interiorRings=[]}addInterior(t){this.interiorRings.push(t),t.poly=this}getGeom(){const t=[this.exteriorRing.getGeom()];if(t[0]===null)return null;for(let n=0,r=this.interiorRings.length;n<r;n++){const i=this.interiorRings[n].getGeom();i!==null&&t.push(i)}return t}}class Vi{constructor(t){this.rings=t,this.polys=this._composePolys(t)}getGeom(){const t=[];for(let n=0,r=this.polys.length;n<r;n++){const i=this.polys[n].getGeom();i!==null&&t.push(i)}return t}_composePolys(t){const n=[];for(let r=0,i=t.length;r<i;r++){const o=t[r];if(!o.poly)if(o.isExteriorRing())n.push(new Vn(o));else{const s=o.enclosingRing();s.poly||n.push(new Vn(s)),s.poly.addInterior(o)}}return n}}class Gi{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:je.compare;this.queue=t,this.tree=new wn(n),this.segments=[]}process(t){const n=t.segment,r=[];if(t.consumedBy)return t.isLeft?this.queue.remove(t.otherSE):this.tree.remove(n),r;const i=t.isLeft?this.tree.add(n):this.tree.find(n);if(!i)throw new Error(`Unable to find segment #${n.id} [${n.leftSE.point.x}, ${n.leftSE.point.y}] -> [${n.rightSE.point.x}, ${n.rightSE.point.y}] in SweepLine tree.`);let o=i,s=i,a,c;for(;a===void 0;)o=this.tree.prev(o),o===null?a=null:o.key.consumedBy===void 0&&(a=o.key);for(;c===void 0;)s=this.tree.next(s),s===null?c=null:s.key.consumedBy===void 0&&(c=s.key);if(t.isLeft){let u=null;if(a){const l=a.getIntersection(n);if(l!==null&&(n.isAnEndpoint(l)||(u=l),!a.isAnEndpoint(l))){const f=this._splitSafely(a,l);for(let d=0,m=f.length;d<m;d++)r.push(f[d])}}let h=null;if(c){const l=c.getIntersection(n);if(l!==null&&(n.isAnEndpoint(l)||(h=l),!c.isAnEndpoint(l))){const f=this._splitSafely(c,l);for(let d=0,m=f.length;d<m;d++)r.push(f[d])}}if(u!==null||h!==null){let l=null;u===null?l=h:h===null?l=u:l=Be.comparePoints(u,h)<=0?u:h,this.queue.remove(n.rightSE),r.push(n.rightSE);const f=n.split(l);for(let d=0,m=f.length;d<m;d++)r.push(f[d])}r.length>0?(this.tree.remove(n),r.push(t)):(this.segments.push(n),n.prev=a)}else{if(a&&c){const u=a.getIntersection(c);if(u!==null){if(!a.isAnEndpoint(u)){const h=this._splitSafely(a,u);for(let l=0,f=h.length;l<f;l++)r.push(h[l])}if(!c.isAnEndpoint(u)){const h=this._splitSafely(c,u);for(let l=0,f=h.length;l<f;l++)r.push(h[l])}}}this.tree.remove(n)}return r}_splitSafely(t,n){this.tree.remove(t);const r=t.rightSE;this.queue.remove(r);const i=t.split(n);return i.push(r),t.consumedBy===void 0&&this.tree.add(t),i}}const Gn=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_QUEUE_SIZE||1e6,qi=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS||1e6;class Hi{run(t,n,r){We.type=t,ft.reset();const i=[new Xn(n,!0)];for(let l=0,f=r.length;l<f;l++)i.push(new Xn(r[l],!1));if(We.numMultiPolys=i.length,We.type==="difference"){const l=i[0];let f=1;for(;f<i.length;)ln(i[f].bbox,l.bbox)!==null?f++:i.splice(f,1)}if(We.type==="intersection")for(let l=0,f=i.length;l<f;l++){const d=i[l];for(let m=l+1,p=i.length;m<p;m++)if(ln(d.bbox,i[m].bbox)===null)return[]}const o=new wn(Be.compare);for(let l=0,f=i.length;l<f;l++){const d=i[l].getSweepEvents();for(let m=0,p=d.length;m<p;m++)if(o.insert(d[m]),o.size>Gn)throw new Error("Infinite loop when putting segment endpoints in a priority queue (queue size too big).")}const s=new Gi(o);let a=o.size,c=o.pop();for(;c;){const l=c.key;if(o.size===a){const d=l.segment;throw new Error(`Unable to pop() ${l.isLeft?"left":"right"} SweepEvent [${l.point.x}, ${l.point.y}] from segment #${d.id} [${d.leftSE.point.x}, ${d.leftSE.point.y}] -> [${d.rightSE.point.x}, ${d.rightSE.point.y}] from queue.`)}if(o.size>Gn)throw new Error("Infinite loop when passing sweep line over endpoints (queue size too big).");if(s.segments.length>qi)throw new Error("Infinite loop when passing sweep line over endpoints (too many sweep line segments).");const f=s.process(l);for(let d=0,m=f.length;d<m;d++){const p=f[d];p.consumedBy===void 0&&o.insert(p)}a=o.size,c=o.pop()}ft.reset();const u=Bt.factory(s.segments);return new Vi(u).getGeom()}}const We=new Hi,Zi=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return We.run("union",e,n)},$i=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return We.run("intersection",e,n)},Ki=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return We.run("xor",e,n)},ji=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return We.run("difference",e,n)};var Qi={union:Zi,intersection:$i,xor:Ki,difference:ji};function pt(e){return e==null?null:Ur(e)||Or(e)||Ji(e)?e:null}function qn(e){return typeof e=="number"&&Number.isFinite(e)}function _t(e){return Array.isArray(e)&&e.length>=2&&qn(e[0])&&qn(e[1])}function Ur(e){return Array.isArray(e)&&e.length>0&&e.every(t=>_t(t))}function Or(e){return Array.isArray(e)&&e.length>0&&e.every(t=>Ur(t))}function Ji(e){return Array.isArray(e)&&e.length>0&&e.every(t=>Or(t))}function Ne(e){if(!Array.isArray(e)||e.length<3)return[];const t=[];for(const i of e){if(!Array.isArray(i)||i.length<2)continue;const o=Number(i[0]),s=Number(i[1]);if(!Number.isFinite(o)||!Number.isFinite(s))continue;const a=t[t.length-1];a&&a[0]===o&&a[1]===s||t.push([o,s])}if(t.length<3)return[];const n=t[0],r=t[t.length-1];return(n[0]!==r[0]||n[1]!==r[1])&&t.push([n[0],n[1]]),t.length>=4?t:[]}function ht(e){if(!Array.isArray(e)||e.length<4)return 0;let t=0;for(let n=0;n<e.length-1;n+=1){const r=e[n],i=e[n+1];t+=r[0]*i[1]-i[0]*r[1]}return t*.5}function jt(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const o of e){const s=Ne(o);s.length>=4&&t.push(s)}if(t.length===0)return[];if(t.length===1)return[t[0]];let n=0,r=0;for(let o=0;o<t.length;o+=1){const s=Math.abs(ht(t[o]));s<=r||(r=s,n=o)}const i=[t[n]];for(let o=0;o<t.length;o+=1)o!==n&&i.push(t[o]);return i}function Yr(e){if(!Array.isArray(e)||e.length===0)return[];const t=e[0];if(_t(t)){const i=jt([e]);return i.length>0?[i]:[]}if(!Array.isArray(t)||t.length===0)return[];const n=t[0];if(_t(n)){const i=jt(e);return i.length>0?[i]:[]}if(!Array.isArray(n)||n.length===0||!_t(n[0]))return[];const r=[];for(const i of e){const o=jt(i);o.length>0&&r.push(o)}return r}function Hn(e,t,n){let r=!1;for(let i=0,o=n.length-1;i<n.length;o=i,i+=1){const s=n[i][0],a=n[i][1],c=n[o][0],u=n[o][1];if(a===u||a>t==u>t)continue;e<(c-s)*(t-a)/(u-a)+s&&(r=!r)}return r}function yt(e){const t=[];for(const n of e??[]){const r=Yr(n);for(const i of r){const o=i[0];if(!o||o.length<4)continue;let s=1/0,a=1/0,c=-1/0,u=-1/0;for(const[l,f]of o)l<s&&(s=l),l>c&&(c=l),f<a&&(a=f),f>u&&(u=f);if(!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(c)||!Number.isFinite(u))continue;let h=Math.abs(ht(o));for(let l=1;l<i.length;l+=1)h-=Math.abs(ht(i[l]));t.push({outer:o,holes:i.slice(1),minX:s,minY:a,maxX:c,maxY:u,area:Math.max(1e-6,h)})}}return t}function Wr(e,t,n){if(e<n.minX||e>n.maxX||t<n.minY||t>n.maxY||!Hn(e,t,n.outer))return!1;for(const r of n.holes)if(Hn(e,t,r))return!1;return!0}function zt(e,t,n){for(const r of n)if(Wr(e,t,r))return!0;return!1}const xn=[160,160,160,255];function W(e,t,n){return Math.max(t,Math.min(n,e))}function Sn(e,t,n){const r=Number(e),i=Number(t),o=Number(n);return!Number.isFinite(r)||r<=0?1:!Number.isFinite(i)||!Number.isFinite(o)?r:Math.pow(2,i-o)*r}function eo(e,t,n){let i=100*Sn(e,t,n);if(Number(e)){let o="μm";return i>1e3&&(i/=1e3,o="mm"),`${i.toPrecision(3)} ${o}`}return`${Math.round(i*1e3)/1e3} pixels`}function be(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function et(e){const t=e.fillModes instanceof Uint8Array?e.fillModes.length:Number.MAX_SAFE_INTEGER;return Math.max(0,Math.min(Math.floor(e.count??0),Math.floor((e.positions?.length??0)/2),e.paletteIndices?.length??0,t))}function cn(e,t){return!e&&!t?!0:!e||!t?!1:Math.abs((e.zoom??0)-(t.zoom??0))<1e-6&&Math.abs((e.offsetX??0)-(t.offsetX??0))<1e-6&&Math.abs((e.offsetY??0)-(t.offsetY??0))<1e-6&&Math.abs((e.rotationDeg??0)-(t.rotationDeg??0))<1e-6}function to(e){const t=String(e??"").trim();if(!t)return"";if(/^bearer\s+/i.test(t)){const n=t.replace(/^bearer\s+/i,"").trim();return n?`Bearer ${n}`:""}return`Bearer ${t}`}function Xr(e){const n=String(e??"").trim().match(/^#?([0-9a-fA-F]{6})$/);if(!n)return[...xn];const r=Number.parseInt(n[1],16);return[r>>16&255,r>>8&255,r&255,255]}function no(e){const t=[[...xn]],n=new Map;for(const i of e??[]){const o=String(i?.termId??"");!o||n.has(o)||(n.set(o,t.length),t.push(Xr(i?.termColor)))}const r=new Uint8Array(t.length*4);for(let i=0;i<t.length;i+=1)r[i*4]=t[i][0],r[i*4+1]=t[i][1],r[i*4+2]=t[i][2],r[i*4+3]=t[i][3];return{colors:r,termToPaletteIndex:n}}const ro=[6,4,2],io=64,oo=.04,so=1,ao=4,Dt=1e-6,lo=.1;function co(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const n of e){if(!Array.isArray(n)||n.length<2)continue;const r=Number(n[0]),i=Number(n[1]);if(!Number.isFinite(r)||!Number.isFinite(i))continue;const o=t[t.length-1];o&&Math.abs(o[0]-r)<1e-9&&Math.abs(o[1]-i)<1e-9||t.push([r,i])}return t}function Zn(e,t,n){if(t<=Dt||n<8)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([e[0]+Math.cos(o)*t,e[1]+Math.sin(o)*t])}return Ne(r)}function uo(e,t,n,r){const i=t[0]-e[0],o=t[1]-e[1],s=Math.sqrt(i*i+o*o);if(!Number.isFinite(s)||s<=r)return[];const a=i/s,u=-(o/s),h=a,l=Math.max(Dt,n);return Ne([[e[0]+u*l,e[1]+h*l],[t[0]+u*l,t[1]+h*l],[t[0]-u*l,t[1]-h*l],[e[0]-u*l,e[1]-h*l]])}function $n(e,t){if(!e.length)return[];let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,c]of e)a<n&&(n=a),a>i&&(i=a),c<r&&(r=c),c>o&&(o=c);if(!Number.isFinite(n)||!Number.isFinite(r))return[];const s=Math.max(t,1);return Ne([[n-s,r-s],[i+s,r-s],[i+s,o+s],[n-s,o+s]])}function xt(e,t){return Ne(t?e.map(([n,r])=>[W(n,t[0],t[2]),W(r,t[1],t[3])]):e)}function Kn(e,t){return Number.isFinite(e)?Number(e.toFixed(t)):e}function fo(e,t){if(!Array.isArray(e)||e.length===0)return[];const n=[];for(const r of e){if(!Array.isArray(r)||r.length<2)continue;const i=Kn(Number(r[0]),t),o=Kn(Number(r[1]),t);if(!Number.isFinite(i)||!Number.isFinite(o))continue;const s=n[n.length-1];(!s||s[0]!==i||s[1]!==o)&&n.push([i,o])}if(n.length>=2){const r=n[0],i=n[n.length-1];if(!r||!i)return[];(r[0]!==i[0]||r[1]!==i[1])&&n.push([r[0],r[1]])}return n.length>=4?n:[]}function ho(e,t){if(!Array.isArray(e)||e.length===0)return[];const n=e.map(r=>fo(r,t)).filter(r=>r.length>=4);return n.length>0?n:[]}function mo(e,t){const n=e.map(i=>ho(i,t)).filter(i=>i.length>0);if(n.length===0)return null;let r=[n[0]];try{for(let i=1;i<n.length;i+=1)if(r=Qi.union(r,[n[i]]),!Array.isArray(r)||r.length===0)return null}catch(i){return console.error("buildBrushStrokePolygon union failed",t,i),null}return r.length>0?r:null}function go(e){if(e.length===0)return null;for(const t of ro){const n=mo(e,t);if(n)return n}return null}function po(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const n of e){if(!Array.isArray(n)||n.length<2)continue;const r=Number(n[0]),i=Number(n[1]);!Number.isFinite(r)||!Number.isFinite(i)||t.push([r,i])}return Ne(t)}function yo(e){let t=[],n=0;for(const r of e){if(!Array.isArray(r)||r.length===0)continue;const i=po(r[0]??[]);if(i.length<4)continue;const o=Math.abs(ht(i));o<=n||(n=o,t=i)}return t}function bo(e,t=1e-9){const n=Ne(e);if(n.length<5)return n;const r=[n[0]];for(let i=1;i<n.length-1;i+=1){const o=r[r.length-1],s=n[i],a=n[i+1],c=(s[0]-o[0])*(a[1]-s[1])-(s[1]-o[1])*(a[0]-s[0]);Math.abs(c)<=t||r.push(s)}return r.push(r[0]),Ne(r)}function wo(e,t,n){const r=n[0]-t[0],i=n[1]-t[1],o=r*r+i*i;if(o<=1e-12){const l=e[0]-t[0],f=e[1]-t[1];return l*l+f*f}const s=W(((e[0]-t[0])*r+(e[1]-t[1])*i)/o,0,1),a=t[0]+r*s,c=t[1]+i*s,u=e[0]-a,h=e[1]-c;return u*u+h*h}function xo(e,t){if(e.length<=2||t<=0)return e.slice();const n=new Uint8Array(e.length);n[0]=1,n[e.length-1]=1;const r=t*t,i=[[0,e.length-1]];for(;i.length>0;){const s=i.pop();if(!s)break;const[a,c]=s;if(c-a<=1)continue;let u=0,h=-1;for(let l=a+1;l<c;l+=1){const f=wo(e[l],e[a],e[c]);f>u&&(u=f,h=l)}h>=0&&u>r&&(n[h]=1,i.push([a,h],[h,c]))}const o=[];for(let s=0;s<e.length;s+=1)n[s]&&o.push(e[s]);return o}function So(e,t){const n=Ne(e);if(n.length<5||t<=0)return n;const r=n.slice(0,-1),i=xo(r,t);return i.length<3?n:Ne(i)}function Eo(e,t){let n=Ne(e);if(t<=0||n.length<5)return n;for(let r=0;r<t;r+=1){const i=n.slice(0,-1);if(i.length<3)break;const o=[];for(let s=0;s<i.length;s+=1){const a=i[s],c=i[(s+1)%i.length];o.push([a[0]*.75+c[0]*.25,a[1]*.75+c[1]*.25],[a[0]*.25+c[0]*.75,a[1]*.25+c[1]*.75])}n=Ne(o)}return n}function Ro(e,t){const n=co(e),r=Math.max(Dt,Number(t.radius)||0);if(n.length===0||!Number.isFinite(r))return[];const i=Math.max(12,Math.floor(t.circleSides||io));if(n.length===1)return xt(Zn(n[0],r,i),t.clipBounds);const o=[],s=Math.max(Dt,r*lo);for(let f=0;f<n.length;f+=1){const d=n[f],m=Zn(d,r,i);if(m.length>=4&&o.push([m]),f===0)continue;const p=uo(n[f-1],d,r,s);p.length>=4&&o.push([p])}const a=go(o),c=a?yo(a):[];if(!c.length)return xt($n(n,r),t.clipBounds);const u=typeof t.simplifyTolerance=="number"&&Number.isFinite(t.simplifyTolerance)?Math.max(0,t.simplifyTolerance):Math.max(.25,r*oo),h=typeof t.smoothingPasses=="number"&&Number.isFinite(t.smoothingPasses)?Math.round(W(t.smoothingPasses,0,ao)):so,l=So(Eo(bo(c,1e-9),h),u);return l.length<4?xt($n(n,r),t.clipBounds):xt(l,t.clipBounds)}const Je=[],jn=[],Xe={color:"#ff4d4f",width:2,lineDash:Je,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},Vr={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},Gr="rgba(23, 23, 25, 0.1)",qr=6,Ue={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},Ze={fontFamily:"Pretendard, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:13,fontWeight:500,textColor:"#FFFFFF",backgroundColor:"rgba(23, 23, 25, 0.5)",borderRadius:4,paddingX:6,paddingY:3},Qn={x:16,y:-24},Mo=20,Jn=1e-6,er="transparent",Ao=3,vo=2,Hr=96,Co=1,tr=1e3,Zr=2,$r=2,Po=4096,To=.2,Io=1.12,_o=.89,Fo=32,Lo="#000000",ko=.1,No="#FFCF00",Bo="#FF0000",zo=1.5,nr=[2,2],Do=1,Uo=.25,Oo=4,Yo=1,Wo=0,Xo=4,Vo=1.5;function Ut(e,t,n){return[W(e[0],0,t),W(e[1],0,n)]}function En(e){if(!Array.isArray(e)||e.length<2)return null;const t=Number(e[0]),n=Number(e[1]);return!Number.isFinite(t)||!Number.isFinite(n)?null:[t,n]}const Oe=En;function Fe(e){return Ne(e)}function Ft(e){return Math.abs(ht(Fe(e)))}function rr(e){if(!Array.isArray(e)||e.length===0)return[0,0,0,0];let t=1/0,n=1/0,r=-1/0,i=-1/0;for(const[o,s]of e)o<t&&(t=o),o>r&&(r=o),s<n&&(n=s),s>i&&(i=s);return[t,n,r,i]}function un(e,t,n=!1){if(t.length!==0){e.moveTo(t[0][0],t[0][1]);for(let r=1;r<t.length;r+=1)e.lineTo(t[r][0],t[r][1]);n&&e.closePath()}}function Te(e,t,n,r=!1,i=!1,o="rgba(255, 77, 79, 0.16)"){t.length!==0&&(e.beginPath(),un(e,t,r),i&&r&&(e.fillStyle=o,e.fill()),e.strokeStyle=n.color,e.lineWidth=n.width,e.lineJoin=n.lineJoin,e.lineCap=n.lineCap,e.shadowColor=n.shadowColor,e.shadowBlur=n.shadowBlur,e.shadowOffsetX=n.shadowOffsetX,e.shadowOffsetY=n.shadowOffsetY,e.setLineDash(n.lineDash),e.stroke(),e.setLineDash(Je),e.shadowColor="rgba(0, 0, 0, 0)",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0)}function Rn(e){const t=Array.isArray(e?.lineDash)?e.lineDash.filter(s=>Number.isFinite(s)&&s>=0):Je,n=typeof e?.width=="number"&&Number.isFinite(e.width)?Math.max(0,e.width):Xe.width,r=typeof e?.shadowBlur=="number"&&Number.isFinite(e.shadowBlur)?Math.max(0,e.shadowBlur):Xe.shadowBlur,i=typeof e?.shadowOffsetX=="number"&&Number.isFinite(e.shadowOffsetX)?e.shadowOffsetX:Xe.shadowOffsetX,o=typeof e?.shadowOffsetY=="number"&&Number.isFinite(e.shadowOffsetY)?e.shadowOffsetY:Xe.shadowOffsetY;return{color:e?.color||Xe.color,width:n,lineDash:t.length?t:Je,lineJoin:e?.lineJoin||Xe.lineJoin,lineCap:e?.lineCap||Xe.lineCap,shadowColor:e?.shadowColor||Xe.shadowColor,shadowBlur:r,shadowOffsetX:i,shadowOffsetY:o}}function Ve(e,t){return t?Rn({color:t.color??e.color,width:t.width??e.width,lineDash:t.lineDash??e.lineDash,lineJoin:t.lineJoin??e.lineJoin,lineCap:t.lineCap??e.lineCap,shadowColor:t.shadowColor??e.shadowColor,shadowBlur:t.shadowBlur??e.shadowBlur,shadowOffsetX:t.shadowOffsetX??e.shadowOffsetX,shadowOffsetY:t.shadowOffsetY??e.shadowOffsetY}):e}function Ot(e,t){return e==null||t===null||t===void 0?!1:String(e)===String(t)}function ir(e){return typeof e=="number"&&Number.isFinite(e)}function Go(e){return Array.isArray(e)&&e.length>=2&&ir(e[0])&&ir(e[1])}function qo(e){return Array.isArray(e)&&e.length>=2&&e.every(t=>Go(t))}function Kr(e,t){if(!(!Array.isArray(e)||e.length===0)){if(qo(e)){t.push(e.map(([n,r])=>[n,r]));return}for(const n of e)Kr(n,t)}}function or(e,t){const n=[];Kr(e,n);const r=[];for(const i of n){if(i.length<2)continue;const o=t?Fe(i):i;o.length>=(t?4:2)&&r.push(o)}return r}function ut(e,t){return typeof e!="number"||!Number.isFinite(e)||e<=0?t:e}function Ho(e,t){return typeof e!="number"||!Number.isFinite(e)?t:W(e,0,1)}function jr(e,t,n,r,i,o){const s=Math.max(0,Math.min(o,r*.5,i*.5));e.beginPath(),e.moveTo(t+s,n),e.lineTo(t+r-s,n),e.quadraticCurveTo(t+r,n,t+r,n+s),e.lineTo(t+r,n+i-s),e.quadraticCurveTo(t+r,n+i,t+r-s,n+i),e.lineTo(t+s,n+i),e.quadraticCurveTo(t,n+i,t,n+i-s),e.lineTo(t,n+s),e.quadraticCurveTo(t,n,t+s,n),e.closePath()}function Zo(e){const t=e[0];return Array.isArray(t)&&Array.isArray(t[0])}function Yt(e,t,n){if(!e||!t)return[];if(n){const r=n.worldToScreen(e[0],e[1]),i=n.worldToScreen(t[0],t[1]);if(r&&i){const o=[[r[0],r[1]],[i[0],r[1]],[i[0],i[1]],[r[0],i[1]]],s=[];for(const a of o){const c=n.screenToWorld(a);if(!c)return Yt(e,t);s.push(c)}return Fe(s)}}return Fe([[e[0],e[1]],[t[0],e[1]],[t[0],t[1]],[e[0],t[1]]])}function fn(e,t,n=Hr){if(!e||!t)return[];const r=(e[0]+t[0])*.5,i=(e[1]+t[1])*.5,o=Math.hypot(t[0]-e[0],t[1]-e[1])*.5;if(o<1)return[];const s=[];for(let a=0;a<=n;a+=1){const c=a/n*Math.PI*2;s.push([r+Math.cos(c)*o,i+Math.sin(c)*o])}return Fe(s)}function Wt(e){const t=Yr(pt(e));if(t.length===0)return[];const n=[];for(const r of t){const i=r[0];if(!i||i.length<4)continue;const o=i.map(([a,c])=>[a,c]),s=[];for(let a=1;a<r.length;a+=1){const c=r[a];!c||c.length<4||s.push(c.map(([u,h])=>[u,h]))}n.push({outer:o,holes:s})}return n}function $o(e){if(!Array.isArray(e))return nr;const t=e.filter(n=>Number.isFinite(n)&&n>=0);return t.length>0?t:nr}function Ko(e){return typeof e!="number"||!Number.isFinite(e)?Do:W(e,Uo,Oo)}function jo(e){return typeof e!="number"||!Number.isFinite(e)?Yo:Math.round(W(e,Wo,Xo))}function Qo(e){const t=ut(e?.radius,Fo),n=ut(e?.cursorLineWidth,zo),r=Ko(e?.edgeDetail),i=jo(e?.edgeSmoothing);return{radius:t,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:e?.clickSelectRoi===!0,fillColor:e?.fillColor||Lo,fillOpacity:Ho(e?.fillOpacity,ko),cursorColor:e?.cursorColor||No,cursorActiveColor:e?.cursorActiveColor||Bo,cursorLineWidth:n,cursorLineDash:$o(e?.cursorLineDash)}}function Jo(e,t,n){if(!t.isDrawing||t.screenPoints.length===0)return;const r=t.screenPoints;if(r.length===0)return;const i=n.radius;if(!(!Number.isFinite(i)||i<=0)){if(e.save(),e.globalAlpha=n.fillOpacity,e.fillStyle=n.fillColor,e.strokeStyle=n.fillColor,e.lineCap="round",e.lineJoin="round",e.lineWidth=i*2,r.length===1)e.beginPath(),e.arc(r[0][0],r[0][1],i,0,Math.PI*2),e.fill();else{e.beginPath(),e.moveTo(r[0][0],r[0][1]);for(let o=1;o<r.length;o+=1)e.lineTo(r[o][0],r[o][1]);e.stroke()}e.restore()}}function es(e,t,n,r){const i=t.cursor;if(!i)return;const o=t.cursorScreen??Oe(n?.worldToScreen(i[0],i[1])??[]);if(!o)return;const s=r.radius;!Number.isFinite(s)||s<=0||(e.save(),e.beginPath(),e.arc(o[0],o[1],s,0,Math.PI*2),e.strokeStyle=t.isDrawing?r.cursorActiveColor:r.cursorColor,e.lineWidth=r.cursorLineWidth,e.setLineDash(r.cursorLineDash),e.stroke(),e.setLineDash(Je),e.restore())}const ts=.58,ns=4096,rs=.5;let St=null;const Et=new Map;function is(){if(St)return St;if(typeof document>"u")return null;const t=document.createElement("canvas").getContext("2d");return t?(St=t,St):null}function Mn(e,t){const n=`${t.fontWeight}|${t.fontSize}|${t.fontFamily}|${e}`,r=Et.get(n);if(r!==void 0)return r;const i=e.length*t.fontSize*ts,o=is();let s=i;if(o){o.font=`${t.fontWeight} ${t.fontSize}px ${t.fontFamily}`;const a=o.measureText(e).width;Number.isFinite(a)&&a>=0&&(s=a)}return Et.size>ns&&Et.clear(),Et.set(n,s),s}function os(e,t="top-center"){if(!e.length)return null;let n=1/0;for(const o of e)o[1]<n&&(n=o[1]);if(!Number.isFinite(n))return null;let r=1/0,i=-1/0;for(const o of e)Math.abs(o[1]-n)>rs||(o[0]<r&&(r=o[0]),o[0]>i&&(i=o[0]));return!Number.isFinite(r)||!Number.isFinite(i)?null:t==="top-center"?[(r+i)*.5,n]:[r,n]}function An(e,t="top-center"){let n=null;for(const r of e){const i=os(r.outer,t);i&&(!n||i[1]<n[1]||i[1]===n[1]&&i[0]<n[0])&&(n=i)}return n}function vn(e){const t=typeof e?.paddingX=="number"&&Number.isFinite(e.paddingX)?Math.max(0,e.paddingX):Ue.paddingX,n=typeof e?.paddingY=="number"&&Number.isFinite(e.paddingY)?Math.max(0,e.paddingY):Ue.paddingY,r=typeof e?.fontSize=="number"&&Number.isFinite(e.fontSize)?Math.max(8,e.fontSize):Ue.fontSize,i=typeof e?.borderWidth=="number"&&Number.isFinite(e.borderWidth)?Math.max(0,e.borderWidth):Ue.borderWidth,o=typeof e?.offsetY=="number"&&Number.isFinite(e.offsetY)?e.offsetY:Ue.offsetY,s=typeof e?.borderRadius=="number"&&Number.isFinite(e.borderRadius)?Math.max(0,e.borderRadius):Ue.borderRadius;return{fontFamily:e?.fontFamily||Ue.fontFamily,fontSize:r,fontWeight:e?.fontWeight||Ue.fontWeight,textColor:e?.textColor||Ue.textColor,backgroundColor:e?.backgroundColor||Ue.backgroundColor,borderColor:e?.borderColor||Ue.borderColor,borderWidth:i,paddingX:t,paddingY:n,offsetY:o,borderRadius:s}}function Cn(e,t){return t?vn({fontFamily:t.fontFamily??e.fontFamily,fontSize:t.fontSize??e.fontSize,fontWeight:t.fontWeight??e.fontWeight,textColor:t.textColor??e.textColor,backgroundColor:t.backgroundColor??e.backgroundColor,borderColor:t.borderColor??e.borderColor,borderWidth:t.borderWidth??e.borderWidth,paddingX:t.paddingX??e.paddingX,paddingY:t.paddingY??e.paddingY,offsetY:t.offsetY??e.offsetY,borderRadius:t.borderRadius??e.borderRadius}):e}function Pn(e,t,n){if(!e||!n)return 0;const r=Number(n.minZoom),i=Number(n.maxZoom);return!Number.isFinite(r)||!Number.isFinite(i)||i-r<=Jn||!Number.isFinite(t)?0:t>=i-Jn?Mo:0}function ss(e){const t=typeof e?.fontSize=="number"&&Number.isFinite(e.fontSize)?Math.max(8,e.fontSize):Ze.fontSize,n=typeof e?.borderRadius=="number"&&Number.isFinite(e.borderRadius)?Math.max(0,e.borderRadius):Ze.borderRadius,r=typeof e?.paddingX=="number"&&Number.isFinite(e.paddingX)?Math.max(0,e.paddingX):Ze.paddingX,i=typeof e?.paddingY=="number"&&Number.isFinite(e.paddingY)?Math.max(0,e.paddingY):Ze.paddingY;return{fontFamily:e?.fontFamily||Ze.fontFamily,fontSize:t,fontWeight:e?.fontWeight||Ze.fontWeight,textColor:e?.textColor||Ze.textColor,backgroundColor:e?.backgroundColor||Ze.backgroundColor,borderRadius:n,paddingX:r,paddingY:i}}function as(e){const t=typeof e?.x=="number"&&Number.isFinite(e.x)?e.x:Qn.x,n=typeof e?.y=="number"&&Number.isFinite(e.y)?e.y:Qn.y;return{x:t,y:n}}function ls(e){return Number.isFinite(e)?`${Math.max(0,e).toFixed(3)} mm²`:"0.000 mm²"}function cs(e){const t=typeof e?.format=="function"?e.format:ls,n=as(e?.cursorOffset);return{enabled:e?.enabled===!0,format:t,style:ss(e?.style),cursorOffsetX:n.x,cursorOffsetY:n.y}}function Qr(e,t,n,r,i,o,s=!0){const a=t.trim();if(!a)return;e.save(),e.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,e.textAlign="center",e.textBaseline="middle";const u=Mn(a,o)+o.paddingX*2,h=o.fontSize+o.paddingY*2,l=n[0],f=n[1]-o.offsetY,d=s?W(l,u*.5+1,r-u*.5-1):l,m=s?W(f,h*.5+1,i-h*.5-1):f,p=d-u*.5,y=m-h*.5;e.fillStyle=o.backgroundColor,e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,jr(e,p,y,u,h,o.borderRadius),e.fill(),o.borderWidth>0&&e.stroke(),e.fillStyle=o.textColor,e.fillText(a,d,m+.5),e.restore()}function us(e,t,n,r,i,o,s,a){const c=t.trim();if(!c)return;e.save(),e.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,e.textAlign="center",e.textBaseline="middle";const h=Mn(c,o)+o.paddingX*2,l=o.fontSize+o.paddingY*2,f=W(n[0]+s,h*.5+1,r-h*.5-1),d=W(n[1]+a,l*.5+1,i-l*.5-1),m=f-h*.5,p=d-l*.5;e.fillStyle=o.backgroundColor,jr(e,m,p,h,l,o.borderRadius),e.fill(),e.fillStyle=o.textColor,e.fillText(c,f,d+.5),e.restore()}function fs(e,t,n,r){if(!(t.length<4||n.length===0)){e.save(),e.beginPath(),un(e,t,!0);for(const i of n)i.length<4||un(e,i,!0);e.fillStyle=r,e.fill("evenodd"),e.restore()}}function Jr(e){const{ctx:t,overlayShapes:n,imageOuterRing:r,worldToScreenPoints:i,baseStrokeStyle:o,onInvertedFillDebug:s}=e,a=!!globalThis.__OPEN_PLANT_DEBUG_OVERLAY__;for(let c=0;c<n.length;c+=1){const u=n[c];if(!u?.coordinates?.length||u.visible===!1)continue;const h=u.closed??Zo(u.coordinates),l=or(u.coordinates,h);if(u.invertedFill?.fillColor){const d=[],m=or(u.coordinates,!0);for(const p of m){const y=i(p);y.length>=4&&d.push(y)}a&&s&&s({id:u.id??c,outerRingPoints:r.length,sourceRingCount:m.length,holeRingCount:d.length,fillColor:u.invertedFill.fillColor}),fs(t,r,d,u.invertedFill.fillColor)}if(l.length===0)continue;const f=Ve(o,u.stroke??u.strokeStyle);for(const d of l){const m=i(d);m.length<2||Te(t,m,f,h,u.fill??!1)}}}function Rt(e){return typeof e=="string"&&(e==="stamp-rectangle"||e==="stamp-circle"||e==="stamp-rectangle-4096px"||e==="stamp-rectangle-2mm2"||e==="stamp-circle-2mm2"||e==="stamp-circle-hpf-0.2mm2")}function hs(e){return{rectangleAreaMm2:ut(e?.rectangleAreaMm2,Zr),circleAreaMm2:ut(e?.circleAreaMm2,$r),rectanglePixelSize:ut(e?.rectanglePixelSize,Po)}}const sr=1e3;function ds(e){return e*sr*sr}function ar(e,t,n){if(!e||!Number.isFinite(t)||t<=0)return[];if(n){const r=n.worldToScreen(e[0],e[1]),i=n.worldToScreen(e[0]+t,e[1]);if(r&&i){const o=Math.hypot(i[0]-r[0],i[1]-r[1]),s=[[r[0]-o,r[1]-o],[r[0]+o,r[1]-o],[r[0]+o,r[1]+o],[r[0]-o,r[1]+o]],a=[];for(const c of s){const u=n.screenToWorld(c);if(!u)throw new Error("Failed to create rectangle");a.push(u)}return Fe(a)}}return Fe([[e[0]-t,e[1]-t],[e[0]+t,e[1]-t],[e[0]+t,e[1]+t],[e[0]-t,e[1]+t]])}function ms(e,t,n=Hr){if(!e||!Number.isFinite(t)||t<=0)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([e[0]+Math.cos(o)*t,e[1]+Math.sin(o)*t])}return Fe(r)}function gs(e){const{stampTool:t,center:n,resolvedStampOptions:r,imageWidth:i,imageHeight:o,micronsToWorldPixels:s,getRectangleProjection:a}=e;if(!n)return[];if(t==="stamp-rectangle-4096px"){const l=r.rectanglePixelSize*.5;return ar(n,l,a()).map(f=>Ut(f,i,o))}let c=0;if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"?c=t==="stamp-rectangle-2mm2"?Zr:r.rectangleAreaMm2:(t==="stamp-circle"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2")&&(c=t==="stamp-circle-hpf-0.2mm2"?To:t==="stamp-circle-2mm2"?$r:r.circleAreaMm2),!Number.isFinite(c)||c<=0)return[];const u=ds(c);let h=[];if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"){const l=s(Math.sqrt(u)*.5);h=ar(n,l,a())}else if(t==="stamp-circle"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2"){const l=s(Math.sqrt(u/Math.PI));h=ms(n,l)}return h.length?h.map(l=>Ut(l,i,o)):[]}function ps(e){return{color:Gr,width:qr,lineDash:Je,lineJoin:e.lineJoin,lineCap:e.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function ys(e){if(typeof e!="string")return er;const t=e.trim();return t.length>0?t:er}function lr(e){return Array.isArray(e)&&e.length>=4&&Ft(e)>Co}function ei({tool:e,imageWidth:t,imageHeight:n,imageMpp:r,imageZoom:i,stampOptions:o,brushOptions:s,projectorRef:a,onBrushTap:c,onDrawComplete:u,onPatchComplete:h,enabled:l,viewStateSignal:f,persistedRegions:d,patchRegions:m,persistedPolygons:p,drawFillColor:y,regionStrokeStyle:b,regionStrokeHoverStyle:x,regionStrokeActiveStyle:C,patchStrokeStyle:S,resolveRegionStrokeStyle:A,resolveRegionLabelStyle:I,overlayShapes:O,hoveredRegionId:z=null,activeRegionId:G=null,regionLabelStyle:D,drawAreaTooltip:q,autoLiftRegionLabelAtMaxZoom:re=!1,regionLabelAnchor:P="top-center",clampRegionLabelToViewport:H=!0,regionLabelAutoLiftOffsetPx:N,invalidateRef:k,className:Z,style:we}){const se=g.useRef(null),Re=g.useRef(!1),Ce=g.useRef(new Map),xe=g.useRef(e),M=g.useRef({isDrawing:!1,pointerId:null,start:null,current:null,cursor:null,cursorScreen:null,points:[],screenPoints:[],stampCenter:null}),v=l??e!=="cursor",X=g.useMemo(()=>d&&d.length>0?d:!p||p.length===0?jn:p.map((w,E)=>({id:E,coordinates:w})),[d,p]),le=g.useMemo(()=>m??jn,[m]),Q=g.useMemo(()=>{const w=[];for(let E=0;E<X.length;E+=1){const T=X[E],F=Wt(T.coordinates);F.length!==0&&w.push({region:T,regionIndex:E,regionKey:T.id??E,polygons:F})}return w},[X]),ie=g.useMemo(()=>{const w=[];for(let E=0;E<le.length;E+=1){const T=le[E],F=Wt(T.coordinates);F.length!==0&&w.push({region:T,regionIndex:E,regionKey:T.id??E,polygons:F})}return w},[le]),he=g.useMemo(()=>Rn(b),[b]),me=g.useMemo(()=>Ve(he,x),[he,x]),$=g.useMemo(()=>Ve(he,C),[he,C]),pe=g.useMemo(()=>Ve(Vr,S),[S]),ye=g.useMemo(()=>ys(y),[y]),U=g.useMemo(()=>vn(D),[D]),V=g.useMemo(()=>cs(q),[q]),ee=g.useMemo(()=>hs(o),[o]),B=g.useMemo(()=>Qo(s),[s]),te=g.useMemo(()=>({position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",touchAction:"none",pointerEvents:v?"auto":"none",cursor:v?e==="brush"?"none":"crosshair":"default",...we}),[v,e,we]),de=g.useCallback(()=>{const w=se.current;if(!w)return;const E=w.getBoundingClientRect(),T=Math.max(1,window.devicePixelRatio||1),F=Math.max(1,Math.round(E.width*T)),j=Math.max(1,Math.round(E.height*T));(w.width!==F||w.height!==j)&&(w.width=F,w.height=j)},[]),ae=g.useCallback(w=>{const E=a.current;if(!E||w.length===0)return[];const T=new Array(w.length);for(let F=0;F<w.length;F+=1){const j=Oe(E.worldToScreen(w[F][0],w[F][1]));if(!j)return[];T[F]=j}return T},[a]),Me=g.useCallback(w=>{const E=a.current,T=se.current;if(!E||!T)return null;const F=T.getBoundingClientRect(),j=Oe(E.screenToWorld(F.left+w[0],F.top+w[1]));return j?Ut(j,t,n):null},[a,t,n]),Se=g.useCallback(()=>{const w=a.current,E=w?.getViewState?.().rotationDeg??0;if(!(Math.abs(E%360)<.01||!w))return{worldToScreen:(T,F)=>Oe(w.worldToScreen(T,F)),screenToWorld:Me}},[a,Me]),_=g.useCallback(w=>{if(!Number.isFinite(w)||w<=0)return 0;const E=typeof r=="number"&&Number.isFinite(r)&&r>0?r:1,T=typeof i=="number"&&Number.isFinite(i)?i:0,F=a.current?.getViewState?.().zoom,j=typeof F=="number"&&Number.isFinite(F)&&F>0?F:1,Ae=T+Math.log2(j),fe=Math.max(1e-9,Sn(E,T,Ae));return w/fe/j},[r,i,a]),Y=g.useCallback((w,E)=>gs({stampTool:w,center:E,resolvedStampOptions:ee,imageWidth:t,imageHeight:n,micronsToWorldPixels:_,getRectangleProjection:Se}),[_,t,n,ee,Se]),J=g.useCallback(()=>{const w=M.current;return Rt(e)?Y(e,w.stampCenter):e==="brush"?[]:w.isDrawing?e==="freehand"?w.points:e==="rectangle"?Yt(w.start,w.current,Se()):e==="circular"?fn(w.start,w.current):[]:[]},[e,Y,Se]),oe=g.useCallback(()=>{de();const w=se.current;if(!w)return;const E=w.getContext("2d");if(!E)return;const T=Math.max(1,window.devicePixelRatio||1),F=w.width/T,j=w.height/T;if(E.setTransform(1,0,0,1,0,0),E.clearRect(0,0,w.width,w.height),E.setTransform(T,0,0,T,0,0),Q.length>0)for(const fe of Q){const{region:ge,polygons:Ee,regionIndex:ve,regionKey:Le}=fe,De=Ot(G,Le)?"active":Ot(z,Le)?"hover":"default";let He=De==="active"?$:De==="hover"?me:he;if(A){const wt=A({region:ge,regionId:Le,regionIndex:ve,state:De});He=Ve(He,wt||void 0)}const bt=De==="default"?null:ps(He);for(const wt of Ee){const qt=ae(wt.outer);qt.length>=4&&(bt&&Te(E,qt,bt,!0,!1),Te(E,qt,He,!0,!1));for(const wi of wt.holes){const Ht=ae(wi);Ht.length>=4&&(bt&&Te(E,Ht,bt,!0,!1),Te(E,Ht,He,!0,!1))}}}if(ie.length>0)for(const fe of ie)for(const ge of fe.polygons){const Ee=ae(ge.outer);Ee.length>=4&&Te(E,Ee,pe,!0,!1);for(const ve of ge.holes){const Le=ae(ve);Le.length>=4&&Te(E,Le,pe,!0,!1)}}if(Array.isArray(O)&&O.length>0){const fe=ae(Fe([[0,0],[t,0],[t,n],[0,n]]));Jr({ctx:E,overlayShapes:O,imageOuterRing:fe,worldToScreenPoints:ae,baseStrokeStyle:he,onInvertedFillDebug:globalThis.__OPEN_PLANT_DEBUG_OVERLAY__?ge=>{const Ee=String(ge.id),ve=`${ge.outerRingPoints}|${ge.sourceRingCount}|${ge.holeRingCount}|${ge.fillColor}`;Ce.current.get(Ee)!==ve&&(Ce.current.set(Ee,ve),console.debug("[open-plant] invertedFill",ge))}:void 0})}const Ae=J();if(v){if(e==="brush")Jo(E,M.current,B),es(E,M.current,a.current,B);else if(Ae.length>0)if(e==="freehand"){const fe=ae(Ae);fe.length>=2&&Te(E,fe,he,!1,!1),fe.length>=3&&Te(E,ae(Fe(Ae)),he,!0,!0,ye)}else{const fe=ae(Ae);fe.length>=4&&Te(E,fe,he,!0,!0,ye)}}if(Q.length>0){const fe=Math.max(1e-6,a.current?.getViewState?.().zoom??1),ge=typeof N=="number"&&Number.isFinite(N)?Math.max(0,N):Pn(re,fe,a.current?.getZoomRange?.());for(const Ee of Q){if(!Ee.region.label)continue;const ve=An(Ee.polygons,P);if(!ve)continue;const Le=Oe(a.current?.worldToScreen(ve[0],ve[1])??[]);if(!Le)continue;let De=Cn(U,I?.({region:Ee.region,regionId:Ee.regionKey,regionIndex:Ee.regionIndex,zoom:fe}));ge>0&&(De={...De,offsetY:De.offsetY+ge}),Qr(E,Ee.region.label,Le,F,j,De,H)}}if(V.enabled&&v&&(e==="freehand"||e==="rectangle"||e==="circular")){const fe=M.current;if(fe.isDrawing){const ge=e==="freehand"?Fe(Ae):Ae;if(ge.length>=4){const Ee=Ft(ge),ve=typeof r=="number"&&Number.isFinite(r)&&r>0?r:0,Le=ve>0?Ee*ve*ve/(tr*tr):0,De=V.format(Le),He=fe.cursorScreen??(fe.current?Oe(a.current?.worldToScreen(fe.current[0],fe.current[1])??[]):null);He&&us(E,De,He,F,j,V.style,V.cursorOffsetX,V.cursorOffsetY)}}}},[v,e,J,de,ae,t,n,a,Q,O,z,G,he,me,$,ye,ie,pe,A,I,U,V,re,P,H,N,r,B]),L=g.useCallback(()=>{Re.current||(Re.current=!0,requestAnimationFrame(()=>{Re.current=!1,oe()}))},[oe]),K=g.useCallback((w=!1)=>{const E=M.current,T=se.current;T&&E.pointerId!==null&&T.hasPointerCapture(E.pointerId)&&T.releasePointerCapture(E.pointerId),E.isDrawing=!1,E.pointerId=null,E.start=null,E.current=null,E.points=[],E.screenPoints=[],E.stampCenter=null,w||(E.cursor=null,E.cursorScreen=null)},[]),ce=g.useCallback(w=>{const E=a.current;if(!E||t<=0||n<=0)return null;const T=Oe(E.screenToWorld(w.clientX,w.clientY));return T?Ut(T,t,n):null},[a,t,n]),ne=g.useCallback(w=>{const E=se.current;if(!E)return null;const T=E.getBoundingClientRect(),F=W(w.clientX-T.left,0,T.width),j=W(w.clientY-T.top,0,T.height);return!Number.isFinite(F)||!Number.isFinite(j)?null:[F,j]},[]),ue=g.useCallback(()=>{const w=M.current;if(!w.isDrawing){K(!0),L();return}let E=[];if(e==="freehand")w.points.length>=Ao&&(E=Fe(w.points));else if(e==="rectangle")E=Yt(w.start,w.current,Se());else if(e==="circular")E=fn(w.start,w.current);else if(e==="brush"){const T=w.points[w.points.length-1]??w.current??w.start;if(B.clickSelectRoi&&T&&w.points.length<=1&&c?.(T)){K(!0),L();return}const F=Math.max(.25,B.edgeDetail),j=w.screenPoints.length>0?w.screenPoints:ae(w.points),Ae=Math.max(.5,B.radius*.04/F),fe=Ro(j,{radius:B.radius,circleSides:Math.max(16,Math.round(32*F)),simplifyTolerance:Ae,smoothingPasses:B.edgeSmoothing}),ge=[];for(const Ee of fe){const ve=Me(Ee);ve&&ge.push(ve)}E=Fe(ge)}(e==="freehand"||e==="rectangle"||e==="circular"||e==="brush")&&lr(E)&&u&&u({tool:e,intent:e==="brush"?"brush":"roi",coordinates:E,bbox:rr(E),areaPx:Ft(E)}),K(!0),L()},[e,u,K,L,ae,Me,Se,B.radius,B.edgeDetail,B.edgeSmoothing,B.clickSelectRoi,c]),ze=g.useCallback((w,E)=>{const T=Y(w,E);if(!lr(T))return;const F=w==="stamp-rectangle-4096px"?"patch":"roi",j={tool:w,intent:F,coordinates:T,bbox:rr(T),areaPx:Ft(T)};u?.(j),F==="patch"&&h&&h(j)},[Y,u,h]),qe=g.useCallback((w,E,T)=>{const F=Math.max(Vo,B.radius*.1),j=F*F,Ae=w.screenPoints[w.screenPoints.length-1];if(!Ae){w.points.push(E),w.screenPoints.push(T),w.current=E;return}const fe=T[0]-Ae[0],ge=T[1]-Ae[1];fe*fe+ge*ge>=j?(w.points.push(E),w.screenPoints.push(T)):(w.points[w.points.length-1]=E,w.screenPoints[w.screenPoints.length-1]=T),w.current=E},[B.radius]),Gt=g.useCallback(w=>{if(!v||e==="cursor"||w.button!==0)return;const E=ce(w);if(!E)return;const T=ne(w);if(!T)return;if(w.preventDefault(),w.stopPropagation(),Rt(e)){const Ae=M.current;Ae.stampCenter=E,ze(e,E),L();return}const F=se.current;F&&F.setPointerCapture(w.pointerId);const j=M.current;j.isDrawing=!0,j.pointerId=w.pointerId,j.start=E,j.current=E,j.cursor=E,j.cursorScreen=T,j.points=e==="freehand"||e==="brush"?[E]:[],j.screenPoints=e==="brush"?[T]:[],L()},[v,e,ce,ne,ze,L]),st=g.useCallback(w=>{if(!v||e==="cursor")return;const E=ce(w);if(!E)return;const T=ne(w);if(!T)return;const F=M.current;if(F.cursor=E,F.cursorScreen=T,Rt(e)){F.stampCenter=E,w.preventDefault(),w.stopPropagation(),L();return}if(e==="brush"){if(!F.isDrawing||F.pointerId!==w.pointerId){L();return}w.preventDefault(),w.stopPropagation(),qe(F,E,T),L();return}if(!(!F.isDrawing||F.pointerId!==w.pointerId)){if(w.preventDefault(),w.stopPropagation(),e==="freehand"){const j=a.current,Ae=Math.max(1e-6,j?.getViewState?.().zoom??1),fe=vo/Ae,ge=fe*fe,Ee=F.points[F.points.length-1];if(!Ee)F.points.push(E);else{const ve=E[0]-Ee[0],Le=E[1]-Ee[1];ve*ve+Le*Le>=ge&&F.points.push(E)}}else F.current=E;L()}},[v,e,ce,ne,L,a,qe]),_n=g.useCallback(w=>{const E=M.current;if(!E.isDrawing||E.pointerId!==w.pointerId)return;w.preventDefault(),w.stopPropagation();const T=ce(w),F=ne(w);T&&(E.cursor=T,F&&(E.cursorScreen=F),e==="brush"?F&&qe(E,T,F):E.current=T);const j=se.current;j&&j.hasPointerCapture(w.pointerId)&&j.releasePointerCapture(w.pointerId),ue()},[ue,ce,ne,e,qe]),bi=g.useCallback(()=>{const w=M.current;let E=!1;e==="brush"&&!w.isDrawing&&w.cursor&&(w.cursor=null,w.cursorScreen=null,E=!0),Rt(e)&&w.stampCenter&&(w.stampCenter=null,E=!0),E&&L()},[e,L]);return g.useEffect(()=>{de(),L();const w=se.current;if(!w)return;const E=new ResizeObserver(()=>{de(),L()});return E.observe(w),()=>{E.disconnect()}},[de,L]),g.useEffect(()=>{v||K(),L()},[v,L,K]),g.useEffect(()=>{xe.current!==e&&(xe.current=e,K(),L())},[e,K,L]),g.useEffect(()=>{L()},[f,X,O,L]),g.useEffect(()=>{if(k)return k.current=L,()=>{k.current===L&&(k.current=null)}},[k,L]),g.useEffect(()=>{if(!v)return;const w=E=>{E.key==="Escape"&&(K(),L())};return window.addEventListener("keydown",w),()=>{window.removeEventListener("keydown",w)}},[v,K,L]),Ye.jsx("canvas",{ref:se,className:Z,style:te,onPointerDown:Gt,onPointerMove:st,onPointerUp:_n,onPointerCancel:_n,onPointerLeave:bi,onContextMenu:w=>{v&&w.preventDefault()},onWheel:w=>{if(!v)return;const E=se.current,T=a.current;if(!E||typeof T?.zoomBy!="function")return;w.preventDefault(),w.stopPropagation();const F=E.getBoundingClientRect(),j=w.clientX-F.left,Ae=w.clientY-F.top;T.zoomBy(w.deltaY<0?Io:_o,j,Ae),L()}})}const ti=g.createContext(null),bs=ti.Provider;function ot(){const e=g.useContext(ti);if(!e)throw new Error("useViewerContext must be used within a <WsiViewer>");return e}function ws({tool:e="cursor",stampOptions:t,brushOptions:n,fillColor:r,areaTooltip:i,onComplete:o,onPatchComplete:s,onBrushTap:a}){const{source:c,rendererRef:u,rendererSerial:h,setInteractionLock:l}=ot(),f=e!=="cursor";g.useEffect(()=>(l("drawing-layer",f),()=>l("drawing-layer",!1)),[f,l]);const d=g.useMemo(()=>u.current?.getViewState(),[h]);return c?Ye.jsx(ei,{tool:e,enabled:f,imageWidth:c.width,imageHeight:c.height,imageMpp:c.mpp,imageZoom:c.maxTierZoom,stampOptions:t,brushOptions:n,drawFillColor:r,projectorRef:u,onBrushTap:a,viewStateSignal:d,drawAreaTooltip:i,onDrawComplete:o,onPatchComplete:s}):null}const cr="__overlay_layer__";function xs({shapes:e}){const{rendererRef:t,source:n,registerDrawCallback:r,unregisterDrawCallback:i,requestOverlayRedraw:o}=ot(),s=g.useCallback(c=>{const u=t.current;if(!u||c.length===0)return[];const h=new Array(c.length);for(let l=0;l<c.length;l+=1){const f=Oe(u.worldToScreen(c[l][0],c[l][1]));if(!f)return[];h[l]=f}return h},[]),a=g.useRef({shapes:e,worldToScreenPoints:s,source:n});return a.current={shapes:e,worldToScreenPoints:s,source:n},g.useEffect(()=>(r(cr,30,u=>{const{shapes:h,worldToScreenPoints:l,source:f}=a.current;if(!Array.isArray(h)||h.length===0||!f)return;const d=l(Fe([[0,0],[f.width,0],[f.width,f.height],[0,f.height]]));Jr({ctx:u,overlayShapes:h,imageOuterRing:d,worldToScreenPoints:l,baseStrokeStyle:Xe})}),()=>i(cr)),[r,i]),g.useEffect(()=>{o()},[e,o]),null}function ur(e){return String(e??"").replace(/\/+$/,"")}function ni(e){const t=String(e??"");return t.startsWith("/")?t:`/${t}`}function Ss(e){const t=ur(e);if(!t)return"";if(/\/TileGroup\d+$/i.test(t))return t;let n=null;try{n=new URL(t)}catch{n=null}if(n){const r=`${n.protocol}//${n.host}`,i=ur(n.pathname||"");return/\/ims$/i.test(i)?`${r}${i}`:/\/tiles$/i.test(i)?`${r}${i}`:`${r}${i}/tiles`}return/\/ims$/i.test(t)?"/ims":/\/tiles$/i.test(t)?`${t}`:`${t}/tiles`}function Es(e,t){const n=e?.imsInfo??{},r=!!e?.imsInfo,i=Number(n.width??e?.width??0),o=Number(n.height??e?.height??0),s=Number(n.tileSize??e?.tileSize??0),a=Number(n.zoom??e?.zoom??0),c=String(n.path??e?.path??""),u=Number(n.mpp??e?.mpp??0);if(!i||!o||!s||!c)throw new Error("Incomplete image metadata: width/height/tileSize/path required");const h=Array.isArray(e?.terms)?e.terms.map(m=>({termId:String(m?.termId??""),termName:String(m?.termName??""),termColor:String(m?.termColor??"")})):[],l=ni(c),f=Ss(t),d=r?(m,p,y)=>`${f}${l}/${m}/${y}_${p}.webp`:void 0;return{id:e?._id||"unknown",name:e?.name||"unknown",width:i,height:o,mpp:Number.isFinite(u)&&u>0?u:void 0,tileSize:s,maxTierZoom:Number.isFinite(a)?Math.max(0,Math.floor(a)):0,tilePath:c,tileBaseUrl:t,terms:h,tileUrlBuilder:d}}function Tn(e,t,n,r){if(e.tileUrlBuilder)return e.tileUrlBuilder(t,n,r);const i=ni(e.tilePath);return`${e.tileBaseUrl}${i}/${t}/${r}_${n}.webp`}function Rs(e,t){if(!t)return!1;const n=new URL(e,typeof window<"u"?window.location.href:void 0).hostname.toLowerCase();return!(n.includes("amazonaws.com")||n.startsWith("s3.")||n.includes(".s3."))}const ke={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:"rgba(255, 106, 61, 0.95)",viewportBorderStyle:"dash",viewportFillColor:"transparent",interactive:!0,showThumbnail:!0,maxThumbnailTiles:16};function fr(e,t,n,r){const i=t.length;if(!(i<3)){for(let o=0;o<i;o+=1){const s=t[o],a=t[(o+1)%i],c=Math.hypot(a[0]-s[0],a[1]-s[1]);if(c<1e-6)continue;const u=Math.max(1,Math.round((c+r)/(n+r))),h=u*n+(u-1)*r,l=c/Math.max(1e-6,h),f=n*l,d=r*l;e.beginPath(),e.moveTo(s[0],s[1]),e.lineTo(a[0],a[1]),e.setLineDash([f,d]),e.lineDashOffset=0,e.stroke()}e.setLineDash([]),e.lineDashOffset=0}}function hr(e,t,n=1e-4){return Math.abs(e[0]-t[0])<=n&&Math.abs(e[1]-t[1])<=n}function dr(e){const t=[];for(const n of e){const r=t[t.length-1];(!r||!hr(r,n))&&t.push(n)}return t.length>1&&hr(t[0],t[t.length-1])&&t.pop(),t}function mr(e,t,n){const r=t[0]-e[0];if(Math.abs(r)<1e-6)return[n,e[1]];const i=(n-e[0])/r;return[n,e[1]+(t[1]-e[1])*i]}function gr(e,t,n){const r=t[1]-e[1];if(Math.abs(r)<1e-6)return[e[0],n];const i=(n-e[1])/r;return[e[0]+(t[0]-e[0])*i,n]}function Ms(e,t,n,r,i){let o=dr(e);if(o.length<3)return[];const s=[{inside:a=>a[0]>=t,intersect:(a,c)=>mr(a,c,t)},{inside:a=>a[0]<=r,intersect:(a,c)=>mr(a,c,r)},{inside:a=>a[1]>=n,intersect:(a,c)=>gr(a,c,n)},{inside:a=>a[1]<=i,intersect:(a,c)=>gr(a,c,i)}];for(const a of s){if(o.length===0)return[];const c=o;o=[];let u=c[c.length-1],h=a.inside(u);for(const l of c){const f=a.inside(l);f?(h||o.push(a.intersect(u,l)),o.push(l)):h&&o.push(a.intersect(u,l)),u=l,h=f}o=dr(o)}return o.length>=3?o:[]}function nt(e,t,n=1){return typeof e!="number"||!Number.isFinite(e)?t:Math.max(n,e)}function lt(e){return Array.isArray(e)&&e.length===4&&Number.isFinite(e[0])&&Number.isFinite(e[1])&&Number.isFinite(e[2])&&Number.isFinite(e[3])}const As={position:"absolute",top:4,right:4,zIndex:1,width:18,height:18,borderRadius:999,border:"1px solid rgba(255,255,255,0.4)",background:"rgba(16, 17, 19, 0.85)",color:"#fff",fontSize:12,lineHeight:1,cursor:"pointer",padding:0,display:"flex",alignItems:"center",justifyContent:"center"};function vs({source:e,projectorRef:t,authToken:n="",options:r,invalidateRef:i,className:o,style:s}){const a=g.useRef(null),c=g.useRef(null),u=g.useRef(null),h=g.useRef({active:!1,pointerId:null}),l=g.useRef(null),f=g.useRef(!1),d=nt(r?.width,ke.width,64),m=nt(r?.height,ke.height,48),p=g.useMemo(()=>{const M=Math.max(1,e.width),v=Math.max(1,e.height),X=M/v,le=d/m;let Q,ie;return X>le?(Q=d,ie=d/X):(ie=m,Q=m*X),{x:(d-Q)/2,y:(m-ie)/2,w:Q,h:ie}},[e.width,e.height,d,m]),y=nt(r?.margin,ke.margin,0),b=nt(r?.borderRadius,ke.borderRadius,0),x=nt(r?.borderWidth,ke.borderWidth,0),C=Math.max(1,Math.round(nt(r?.maxThumbnailTiles,ke.maxThumbnailTiles,1))),S=r?.backgroundColor||ke.backgroundColor,A=r?.borderColor||ke.borderColor,I=r?.viewportBorderColor||ke.viewportBorderColor,O=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:ke.viewportBorderStyle,z=r?.viewportFillColor??ke.viewportFillColor,G=r?.interactive??ke.interactive,D=r?.showThumbnail??ke.showThumbnail,q=r?.position||ke.position,re=r?.onClose,P=r?.closeIcon,H=r?.closeButtonStyle,N=g.useMemo(()=>{const M={};return q==="top-left"||q==="bottom-left"?M.left=y:M.right=y,q==="top-left"||q==="top-right"?M.top=y:M.bottom=y,{position:"absolute",...M,width:d,height:m,borderRadius:b,overflow:"hidden",zIndex:4,pointerEvents:G?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[y,q,d,m,b,G,s]),k=g.useCallback(()=>{const M=a.current;if(!M)return;const v=M.getContext("2d");if(!v)return;const X=d,le=m,Q=Math.max(1,window.devicePixelRatio||1),ie=Math.max(1,Math.round(X*Q)),he=Math.max(1,Math.round(le*Q));(M.width!==ie||M.height!==he)&&(M.width=ie,M.height=he),v.setTransform(1,0,0,1,0,0),v.clearRect(0,0,M.width,M.height),v.setTransform(Q,0,0,Q,0,0),v.fillStyle=S,v.fillRect(0,0,X,le);const{x:me,y:$,w:pe,h:ye}=p,U=c.current;U&&v.drawImage(U,me,$,pe,ye),v.strokeStyle=A,v.lineWidth=x,v.strokeRect(x*.5,x*.5,X-x,le-x);const V=t.current,ee=V?.getViewBounds?.(),B=V?.getViewCorners?.(),te=Array.isArray(B)&&B.length>=4&&B.every(ce=>Array.isArray(ce)&&ce.length>=2&&Number.isFinite(ce[0])&&Number.isFinite(ce[1]))?B:null,de=lt(ee)?ee:lt(u.current)?u.current:null;lt(ee)&&(u.current=ee);const ae=pe/Math.max(1,e.width),Me=ye/Math.max(1,e.height),Se=O==="dash";if(te){const ce=te.map(ue=>[me+ue[0]*ae,$+ue[1]*Me]),ne=Ms(ce,me,$,me+pe,$+ye);if(ne.length>=3){v.beginPath();for(let ue=0;ue<ne.length;ue+=1)ue===0?v.moveTo(ne[ue][0],ne[ue][1]):v.lineTo(ne[ue][0],ne[ue][1]);v.closePath(),v.fillStyle=z,v.fill(),v.strokeStyle=I,v.lineWidth=2.25,Se?fr(v,ne,4,3):v.stroke();return}}if(!de)return;const _=W(me+de[0]*ae,me,me+pe),Y=W($+de[1]*Me,$,$+ye),J=W(me+de[2]*ae,me,me+pe),oe=W($+de[3]*Me,$,$+ye),L=Math.max(1,J-_),K=Math.max(1,oe-Y);if(v.fillStyle=z,v.fillRect(_,Y,L,K),v.strokeStyle=I,v.lineWidth=2.25,Se){const ce=[[_+.5,Y+.5],[_+.5+Math.max(1,L-1),Y+.5],[_+.5+Math.max(1,L-1),Y+.5+Math.max(1,K-1)],[_+.5,Y+.5+Math.max(1,K-1)]];fr(v,ce,4,3)}else v.strokeRect(_+.5,Y+.5,Math.max(1,L-1),Math.max(1,K-1))},[d,m,p,S,A,x,t,e.width,e.height,z,I,O]),Z=g.useCallback(()=>{f.current||(f.current=!0,l.current=requestAnimationFrame(()=>{f.current=!1,l.current=null,k()}))},[k]),we=g.useCallback((M,v)=>{const X=a.current;if(!X)return null;const le=X.getBoundingClientRect();if(!le.width||!le.height)return null;const Q=le.width/d,ie=le.height/m,he=p.x*Q,me=p.y*ie,$=p.w*Q,pe=p.h*ie,ye=W((M-le.left-he)/$,0,1),U=W((v-le.top-me)/pe,0,1);return[ye*e.width,U*e.height]},[e.width,e.height,d,m,p]),se=g.useCallback((M,v)=>{const X=t.current;if(!X)return;if(X.setViewCenter){X.setViewCenter(M,v),Z();return}const le=X.getViewBounds?.(),Q=lt(le)?le:lt(u.current)?u.current:null;if(!Q)return;const ie=Math.max(1e-6,Q[2]-Q[0]),he=Math.max(1e-6,Q[3]-Q[1]);X.setViewState({offsetX:M-ie*.5,offsetY:v-he*.5}),Z()},[t,Z]),Re=g.useCallback(M=>{if(!G||M.button!==0)return;const v=a.current;if(!v)return;const X=we(M.clientX,M.clientY);X&&(M.preventDefault(),M.stopPropagation(),v.setPointerCapture(M.pointerId),h.current={active:!0,pointerId:M.pointerId},se(X[0],X[1]))},[G,we,se]),Ce=g.useCallback(M=>{const v=h.current;if(!v.active||v.pointerId!==M.pointerId)return;const X=we(M.clientX,M.clientY);X&&(M.preventDefault(),M.stopPropagation(),se(X[0],X[1]))},[we,se]),xe=g.useCallback(M=>{const v=h.current;if(!v.active||v.pointerId!==M.pointerId)return;const X=a.current;if(X&&X.hasPointerCapture(M.pointerId))try{X.releasePointerCapture(M.pointerId)}catch{}h.current={active:!1,pointerId:null},Z()},[Z]);return g.useEffect(()=>{let M=!1;c.current=null,Z();const v=0,X=2**(e.maxTierZoom-v),le=Math.ceil(e.width/X),Q=Math.ceil(e.height/X),ie=Math.max(1,Math.ceil(le/e.tileSize)),he=Math.max(1,Math.ceil(Q/e.tileSize)),me=ie*he;if(!D||me>C)return;const $=document.createElement("canvas");$.width=Math.max(1,Math.round(p.w)),$.height=Math.max(1,Math.round(p.h));const pe=$.getContext("2d");if(!pe)return;pe.fillStyle=S,pe.fillRect(0,0,$.width,$.height);const ye=[];for(let U=0;U<he;U+=1)for(let V=0;V<ie;V+=1){const ee=V*e.tileSize*X,B=U*e.tileSize*X,te=Math.min((V+1)*e.tileSize,le)*X,de=Math.min((U+1)*e.tileSize,Q)*X;ye.push({url:Tn(e,v,V,U),bounds:[ee,B,te,de]})}return Promise.allSettled(ye.map(async U=>{const V=Rs(U.url,n),ee=await fetch(U.url,{headers:V?{Authorization:n}:void 0});if(!ee.ok)throw new Error(`HTTP ${ee.status}`);const B=await createImageBitmap(await ee.blob());return{tile:U,bitmap:B}})).then(U=>{if(M){for(const B of U)B.status==="fulfilled"&&B.value.bitmap.close();return}const V=$.width/Math.max(1,e.width),ee=$.height/Math.max(1,e.height);for(const B of U){if(B.status!=="fulfilled")continue;const{tile:{bounds:te},bitmap:de}=B.value,ae=te[0]*V,Me=te[1]*ee,Se=Math.max(1,(te[2]-te[0])*V),_=Math.max(1,(te[3]-te[1])*ee);pe.drawImage(de,ae,Me,Se,_),de.close()}c.current=$,Z()}),()=>{M=!0}},[e,n,p,S,D,C,Z]),g.useEffect(()=>{Z()},[Z]),g.useEffect(()=>{if(i)return i.current=Z,()=>{i.current===Z&&(i.current=null)}},[i,Z]),g.useEffect(()=>()=>{h.current={active:!1,pointerId:null},l.current!==null&&(cancelAnimationFrame(l.current),l.current=null),f.current=!1},[]),Ye.jsxs("div",{className:o,style:N,children:[Ye.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:Re,onPointerMove:Ce,onPointerUp:xe,onPointerCancel:xe,onContextMenu:M=>{M.preventDefault()},onWheel:M=>{M.preventDefault(),M.stopPropagation()}}),re&&Ye.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:M=>{M.stopPropagation(),re()},style:H?{...H}:{...As},children:P??"×"})]})}const pr="__patch_layer__",Cs=[];function Ps({regions:e,strokeStyle:t}){const{rendererRef:n,registerDrawCallback:r,unregisterDrawCallback:i,requestOverlayRedraw:o}=ot(),s=e??Cs,a=g.useMemo(()=>Ve(Vr,t),[t]),c=g.useMemo(()=>{const l=[];for(let f=0;f<s.length;f+=1){const d=s[f],m=Wt(d.coordinates);m.length!==0&&l.push({region:d,regionIndex:f,regionKey:d.id??f,polygons:m})}return l},[s]),u=g.useCallback(l=>{const f=n.current;if(!f||l.length===0)return[];const d=new Array(l.length);for(let m=0;m<l.length;m+=1){const p=Oe(f.worldToScreen(l[m][0],l[m][1]));if(!p)return[];d[m]=p}return d},[]),h=g.useRef({prepared:c,resolvedStrokeStyle:a,worldToScreenPoints:u});return h.current={prepared:c,resolvedStrokeStyle:a,worldToScreenPoints:u},g.useEffect(()=>(r(pr,20,f=>{const{prepared:d,resolvedStrokeStyle:m,worldToScreenPoints:p}=h.current;for(const y of d)for(const b of y.polygons){const x=p(b.outer);x.length>=4&&Te(f,x,m,!0,!1);for(const C of b.holes){const S=p(C);S.length>=4&&Te(f,S,m,!0,!1)}}}),()=>i(pr)),[r,i]),g.useEffect(()=>{o()},[c,a,o]),null}function dt(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return null;const n=yt(t??[]);if(n.length===0){const m={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return e.fillModes instanceof Uint8Array&&(m.fillModes=new Uint8Array(0)),e.ids instanceof Uint32Array&&(m.ids=new Uint32Array(0)),m}const r=et(e),i=e.positions,o=e.paletteIndices,s=e.fillModes instanceof Uint8Array&&e.fillModes.length>=r?e.fillModes:null,a=e.ids instanceof Uint32Array&&e.ids.length>=r?e.ids:null,c=new Float32Array(r*2),u=new Uint16Array(r),h=s?new Uint8Array(r):null,l=a?new Uint32Array(r):null;let f=0;for(let m=0;m<r;m+=1){const p=i[m*2],y=i[m*2+1];zt(p,y,n)&&(c[f*2]=p,c[f*2+1]=y,u[f]=o[m],h&&(h[f]=s[m]),l&&(l[f]=a[m]),f+=1)}const d={count:f,positions:c.subarray(0,f*2),paletteIndices:u.subarray(0,f)};return h&&(d.fillModes=h.subarray(0,f)),l&&(d.ids=l.subarray(0,f)),d}function ri(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return new Uint32Array(0);const n=yt(t??[]);if(n.length===0)return new Uint32Array(0);const r=et(e);if(r===0)return new Uint32Array(0);const i=e.positions,o=new Uint32Array(r);let s=0;for(let a=0;a<r;a+=1){const c=i[a*2],u=i[a*2+1];zt(c,u,n)&&(o[s]=a,s+=1)}return o.subarray(0,s)}let Mt=null;const Ts=`
33
+ `);const o=t+(n?" ":"│ ");e.left&&rn(e.left,o,!1,r,i),e.right&&rn(e.right,o,!0,r,i)}}class wn{constructor(t=Ai){this._root=null,this._size=0,this._comparator=t}insert(t,n){return this._size++,this._root=$t(t,n,this._root,this._comparator)}add(t,n){const r=new Qe(t,n);this._root===null&&(r.left=r.right=null,this._size++,this._root=r);const i=this._comparator,o=$e(t,this._root,i),s=i(t,o.key);return s===0?this._root=o:(s<0?(r.left=o.left,r.right=o,o.left=null):s>0&&(r.right=o.right,r.left=o,o.right=null),this._size++,this._root=r),this._root}remove(t){this._root=this._remove(t,this._root,this._comparator)}_remove(t,n,r){let i;return n===null?null:(n=$e(t,n,r),r(t,n.key)===0?(n.left===null?i=n.right:(i=$e(t,n.left,r),i.right=n.right),this._size--,i):n)}pop(){let t=this._root;if(t){for(;t.left;)t=t.left;return this._root=$e(t.key,this._root,this._comparator),this._root=this._remove(t.key,this._root,this._comparator),{key:t.key,data:t.data}}return null}findStatic(t){let n=this._root;const r=this._comparator;for(;n;){const i=r(t,n.key);if(i===0)return n;i<0?n=n.left:n=n.right}return null}find(t){return this._root&&(this._root=$e(t,this._root,this._comparator),this._comparator(t,this._root.key)!==0)?null:this._root}contains(t){let n=this._root;const r=this._comparator;for(;n;){const i=r(t,n.key);if(i===0)return!0;i<0?n=n.left:n=n.right}return!1}forEach(t,n){let r=this._root;const i=[];let o=!1;for(;!o;)r!==null?(i.push(r),r=r.left):i.length!==0?(r=i.pop(),t.call(n,r),r=r.right):o=!0;return this}range(t,n,r,i){const o=[],s=this._comparator;let a=this._root,c;for(;o.length!==0||a;)if(a)o.push(a),a=a.left;else{if(a=o.pop(),c=s(a.key,n),c>0)break;if(s(a.key,t)>=0&&r.call(i,a))return this;a=a.right}return this}keys(){const t=[];return this.forEach(({key:n})=>{t.push(n)}),t}values(){const t=[];return this.forEach(({data:n})=>{t.push(n)}),t}min(){return this._root?this.minNode(this._root).key:null}max(){return this._root?this.maxNode(this._root).key:null}minNode(t=this._root){if(t)for(;t.left;)t=t.left;return t}maxNode(t=this._root){if(t)for(;t.right;)t=t.right;return t}at(t){let n=this._root,r=!1,i=0;const o=[];for(;!r;)if(n)o.push(n),n=n.left;else if(o.length>0){if(n=o.pop(),i===t)return n;i++,n=n.right}else r=!0;return null}next(t){let n=this._root,r=null;if(t.right){for(r=t.right;r.left;)r=r.left;return r}const i=this._comparator;for(;n;){const o=i(t.key,n.key);if(o===0)break;o<0?(r=n,n=n.left):n=n.right}return r}prev(t){let n=this._root,r=null;if(t.left!==null){for(r=t.left;r.right;)r=r.right;return r}const i=this._comparator;for(;n;){const o=i(t.key,n.key);if(o===0)break;o<0?n=n.left:(r=n,n=n.right)}return r}clear(){return this._root=null,this._size=0,this}toList(){return Ii(this._root)}load(t,n=[],r=!1){let i=t.length;const o=this._comparator;if(r&&an(t,n,0,i-1,o),this._root===null)this._root=on(t,n,0,i),this._size=i;else{const s=Pi(this.toList(),Ci(t,n),o);i=this._size+i,this._root=sn({head:s},0,i)}return this}isEmpty(){return this._root===null}get size(){return this._size}get root(){return this._root}toString(t=n=>String(n.key)){const n=[];return rn(this._root,"",!0,r=>n.push(r),t),n.join("")}update(t,n,r){const i=this._comparator;let{left:o,right:s}=Ln(t,this._root,i);i(t,n)<0?s=$t(n,r,s,i):o=$t(n,r,o,i),this._root=vi(o,s,i)}split(t){return Ln(t,this._root,this._comparator)}*[Symbol.iterator](){let t=this._root;const n=[];let r=!1;for(;!r;)t!==null?(n.push(t),t=t.left):n.length!==0?(t=n.pop(),yield t,t=t.right):r=!0}}function on(e,t,n,r){const i=r-n;if(i>0){const o=n+Math.floor(i/2),s=e[o],a=t[o],c=new Qe(s,a);return c.left=on(e,t,n,o),c.right=on(e,t,o+1,r),c}return null}function Ci(e,t){const n=new Qe(null,null);let r=n;for(let i=0;i<e.length;i++)r=r.next=new Qe(e[i],t[i]);return r.next=null,n.next}function Ii(e){let t=e;const n=[];let r=!1;const i=new Qe(null,null);let o=i;for(;!r;)t?(n.push(t),t=t.left):n.length>0?(t=o=o.next=n.pop(),t=t.right):r=!0;return o.next=null,i.next}function sn(e,t,n){const r=n-t;if(r>0){const i=t+Math.floor(r/2),o=sn(e,t,i),s=e.head;return s.left=o,e.head=e.head.next,s.right=sn(e,i+1,n),s}return null}function Pi(e,t,n){const r=new Qe(null,null);let i=r,o=e,s=t;for(;o!==null&&s!==null;)n(o.key,s.key)<0?(i.next=o,o=o.next):(i.next=s,s=s.next),i=i.next;return o!==null?i.next=o:s!==null&&(i.next=s),r.next}function an(e,t,n,r,i){if(n>=r)return;const o=e[n+r>>1];let s=n-1,a=r+1;for(;;){do s++;while(i(e[s],o)<0);do a--;while(i(e[a],o)>0);if(s>=a)break;let c=e[s];e[s]=e[a],e[a]=c,c=t[s],t[s]=t[a],t[a]=c}an(e,t,n,a,i),an(e,t,a+1,r,i)}const Ge=11102230246251565e-32,Ie=134217729,Ti=(3+8*Ge)*Ge;function Kt(e,t,n,r,i){let o,s,a,c,u=t[0],h=r[0],l=0,f=0;h>u==h>-u?(o=u,u=t[++l]):(o=h,h=r[++f]);let d=0;if(l<e&&f<n)for(h>u==h>-u?(s=u+o,a=o-(s-u),u=t[++l]):(s=h+o,a=o-(s-h),h=r[++f]),o=s,a!==0&&(i[d++]=a);l<e&&f<n;)h>u==h>-u?(s=o+u,c=s-o,a=o-(s-c)+(u-c),u=t[++l]):(s=o+h,c=s-o,a=o-(s-c)+(h-c),h=r[++f]),o=s,a!==0&&(i[d++]=a);for(;l<e;)s=o+u,c=s-o,a=o-(s-c)+(u-c),u=t[++l],o=s,a!==0&&(i[d++]=a);for(;f<n;)s=o+h,c=s-o,a=o-(s-c)+(h-c),h=r[++f],o=s,a!==0&&(i[d++]=a);return(o!==0||d===0)&&(i[d++]=o),d}function _i(e,t){let n=t[0];for(let r=1;r<e;r++)n+=t[r];return n}function gt(e){return new Float64Array(e)}const Fi=(3+16*Ge)*Ge,Li=(2+12*Ge)*Ge,ki=(9+64*Ge)*Ge*Ge,tt=gt(4),kn=gt(8),Nn=gt(12),Bn=gt(16),Te=gt(4);function Ni(e,t,n,r,i,o,s){let a,c,u,h,l,f,d,m,p,y,b,x,C,S,A,T,O,z;const G=e-i,D=n-i,q=t-o,re=r-o;S=G*re,f=Ie*G,d=f-(f-G),m=G-d,f=Ie*re,p=f-(f-re),y=re-p,A=m*y-(S-d*p-m*p-d*y),T=q*D,f=Ie*q,d=f-(f-q),m=q-d,f=Ie*D,p=f-(f-D),y=D-p,O=m*y-(T-d*p-m*p-d*y),b=A-O,l=A-b,tt[0]=A-(b+l)+(l-O),x=S+b,l=x-S,C=S-(x-l)+(b-l),b=C-T,l=C-b,tt[1]=C-(b+l)+(l-T),z=x+b,l=z-x,tt[2]=x-(z-l)+(b-l),tt[3]=z;let I=_i(4,tt),H=Li*s;if(I>=H||-I>=H||(l=e-G,a=e-(G+l)+(l-i),l=n-D,u=n-(D+l)+(l-i),l=t-q,c=t-(q+l)+(l-o),l=r-re,h=r-(re+l)+(l-o),a===0&&c===0&&u===0&&h===0)||(H=ki*s+Ti*Math.abs(I),I+=G*h+re*a-(q*u+D*c),I>=H||-I>=H))return I;S=a*re,f=Ie*a,d=f-(f-a),m=a-d,f=Ie*re,p=f-(f-re),y=re-p,A=m*y-(S-d*p-m*p-d*y),T=c*D,f=Ie*c,d=f-(f-c),m=c-d,f=Ie*D,p=f-(f-D),y=D-p,O=m*y-(T-d*p-m*p-d*y),b=A-O,l=A-b,Te[0]=A-(b+l)+(l-O),x=S+b,l=x-S,C=S-(x-l)+(b-l),b=C-T,l=C-b,Te[1]=C-(b+l)+(l-T),z=x+b,l=z-x,Te[2]=x-(z-l)+(b-l),Te[3]=z;const N=Kt(4,tt,4,Te,kn);S=G*h,f=Ie*G,d=f-(f-G),m=G-d,f=Ie*h,p=f-(f-h),y=h-p,A=m*y-(S-d*p-m*p-d*y),T=q*u,f=Ie*q,d=f-(f-q),m=q-d,f=Ie*u,p=f-(f-u),y=u-p,O=m*y-(T-d*p-m*p-d*y),b=A-O,l=A-b,Te[0]=A-(b+l)+(l-O),x=S+b,l=x-S,C=S-(x-l)+(b-l),b=C-T,l=C-b,Te[1]=C-(b+l)+(l-T),z=x+b,l=z-x,Te[2]=x-(z-l)+(b-l),Te[3]=z;const k=Kt(N,kn,4,Te,Nn);S=a*h,f=Ie*a,d=f-(f-a),m=a-d,f=Ie*h,p=f-(f-h),y=h-p,A=m*y-(S-d*p-m*p-d*y),T=c*u,f=Ie*c,d=f-(f-c),m=c-d,f=Ie*u,p=f-(f-u),y=u-p,O=m*y-(T-d*p-m*p-d*y),b=A-O,l=A-b,Te[0]=A-(b+l)+(l-O),x=S+b,l=x-S,C=S-(x-l)+(b-l),b=C-T,l=C-b,Te[1]=C-(b+l)+(l-T),z=x+b,l=z-x,Te[2]=x-(z-l)+(b-l),Te[3]=z;const Z=Kt(k,Nn,4,Te,Bn);return Bn[Z-1]}function Bi(e,t,n,r,i,o){const s=(t-o)*(n-i),a=(e-i)*(r-o),c=s-a,u=Math.abs(s+a);return Math.abs(c)>=Fi*u?c:-Ni(e,t,n,r,i,o,u)}const at=(e,t)=>e.ll.x<=t.x&&t.x<=e.ur.x&&e.ll.y<=t.y&&t.y<=e.ur.y,ln=(e,t)=>{if(t.ur.x<e.ll.x||e.ur.x<t.ll.x||t.ur.y<e.ll.y||e.ur.y<t.ll.y)return null;const n=e.ll.x<t.ll.x?t.ll.x:e.ll.x,r=e.ur.x<t.ur.x?e.ur.x:t.ur.x,i=e.ll.y<t.ll.y?t.ll.y:e.ll.y,o=e.ur.y<t.ur.y?e.ur.y:t.ur.y;return{ll:{x:n,y:i},ur:{x:r,y:o}}};let Ke=Number.EPSILON;Ke===void 0&&(Ke=Math.pow(2,-52));const zi=Ke*Ke,zn=(e,t)=>{if(-Ke<e&&e<Ke&&-Ke<t&&t<Ke)return 0;const n=e-t;return n*n<zi*e*t?0:e<t?-1:1};class Di{constructor(){this.reset()}reset(){this.xRounder=new Dn,this.yRounder=new Dn}round(t,n){return{x:this.xRounder.round(t),y:this.yRounder.round(n)}}}class Dn{constructor(){this.tree=new wn,this.round(0)}round(t){const n=this.tree.add(t),r=this.tree.prev(n);if(r!==null&&zn(n.key,r.key)===0)return this.tree.remove(t),r.key;const i=this.tree.next(n);return i!==null&&zn(n.key,i.key)===0?(this.tree.remove(t),i.key):t}}const ft=new Di,Tt=(e,t)=>e.x*t.y-e.y*t.x,Dr=(e,t)=>e.x*t.x+e.y*t.y,Un=(e,t,n)=>{const r=Bi(e.x,e.y,t.x,t.y,n.x,n.y);return r>0?-1:r<0?1:0},Nt=e=>Math.sqrt(Dr(e,e)),Ui=(e,t,n)=>{const r={x:t.x-e.x,y:t.y-e.y},i={x:n.x-e.x,y:n.y-e.y};return Tt(i,r)/Nt(i)/Nt(r)},Oi=(e,t,n)=>{const r={x:t.x-e.x,y:t.y-e.y},i={x:n.x-e.x,y:n.y-e.y};return Dr(i,r)/Nt(i)/Nt(r)},On=(e,t,n)=>t.y===0?null:{x:e.x+t.x/t.y*(n-e.y),y:n},Yn=(e,t,n)=>t.x===0?null:{x:n,y:e.y+t.y/t.x*(n-e.x)},Yi=(e,t,n,r)=>{if(t.x===0)return Yn(n,r,e.x);if(r.x===0)return Yn(e,t,n.x);if(t.y===0)return On(n,r,e.y);if(r.y===0)return On(e,t,n.y);const i=Tt(t,r);if(i==0)return null;const o={x:n.x-e.x,y:n.y-e.y},s=Tt(o,t)/i,a=Tt(o,r)/i,c=e.x+a*t.x,u=n.x+s*r.x,h=e.y+a*t.y,l=n.y+s*r.y,f=(c+u)/2,d=(h+l)/2;return{x:f,y:d}};class Be{static compare(t,n){const r=Be.comparePoints(t.point,n.point);return r!==0?r:(t.point!==n.point&&t.link(n),t.isLeft!==n.isLeft?t.isLeft?1:-1:je.compare(t.segment,n.segment))}static comparePoints(t,n){return t.x<n.x?-1:t.x>n.x?1:t.y<n.y?-1:t.y>n.y?1:0}constructor(t,n){t.events===void 0?t.events=[this]:t.events.push(this),this.point=t,this.isLeft=n}link(t){if(t.point===this.point)throw new Error("Tried to link already linked events");const n=t.point.events;for(let r=0,i=n.length;r<i;r++){const o=n[r];this.point.events.push(o),o.point=this.point}this.checkForConsuming()}checkForConsuming(){const t=this.point.events.length;for(let n=0;n<t;n++){const r=this.point.events[n];if(r.segment.consumedBy===void 0)for(let i=n+1;i<t;i++){const o=this.point.events[i];o.consumedBy===void 0&&r.otherSE.point.events===o.otherSE.point.events&&r.segment.consume(o.segment)}}}getAvailableLinkedEvents(){const t=[];for(let n=0,r=this.point.events.length;n<r;n++){const i=this.point.events[n];i!==this&&!i.segment.ringOut&&i.segment.isInResult()&&t.push(i)}return t}getLeftmostComparator(t){const n=new Map,r=i=>{const o=i.otherSE;n.set(i,{sine:Ui(this.point,t.point,o.point),cosine:Oi(this.point,t.point,o.point)})};return(i,o)=>{n.has(i)||r(i),n.has(o)||r(o);const{sine:s,cosine:a}=n.get(i),{sine:c,cosine:u}=n.get(o);return s>=0&&c>=0?a<u?1:a>u?-1:0:s<0&&c<0?a<u?-1:a>u?1:0:c<s?-1:c>s?1:0}}}let Wi=0;class je{static compare(t,n){const r=t.leftSE.point.x,i=n.leftSE.point.x,o=t.rightSE.point.x,s=n.rightSE.point.x;if(s<r)return 1;if(o<i)return-1;const a=t.leftSE.point.y,c=n.leftSE.point.y,u=t.rightSE.point.y,h=n.rightSE.point.y;if(r<i){if(c<a&&c<u)return 1;if(c>a&&c>u)return-1;const l=t.comparePoint(n.leftSE.point);if(l<0)return 1;if(l>0)return-1;const f=n.comparePoint(t.rightSE.point);return f!==0?f:-1}if(r>i){if(a<c&&a<h)return-1;if(a>c&&a>h)return 1;const l=n.comparePoint(t.leftSE.point);if(l!==0)return l;const f=t.comparePoint(n.rightSE.point);return f<0?1:f>0?-1:1}if(a<c)return-1;if(a>c)return 1;if(o<s){const l=n.comparePoint(t.rightSE.point);if(l!==0)return l}if(o>s){const l=t.comparePoint(n.rightSE.point);if(l<0)return 1;if(l>0)return-1}if(o!==s){const l=u-a,f=o-r,d=h-c,m=s-i;if(l>f&&d<m)return 1;if(l<f&&d>m)return-1}return o>s?1:o<s||u<h?-1:u>h?1:t.id<n.id?-1:t.id>n.id?1:0}constructor(t,n,r,i){this.id=++Wi,this.leftSE=t,t.segment=this,t.otherSE=n,this.rightSE=n,n.segment=this,n.otherSE=t,this.rings=r,this.windings=i}static fromRing(t,n,r){let i,o,s;const a=Be.comparePoints(t,n);if(a<0)i=t,o=n,s=1;else if(a>0)i=n,o=t,s=-1;else throw new Error(`Tried to create degenerate segment at [${t.x}, ${t.y}]`);const c=new Be(i,!0),u=new Be(o,!1);return new je(c,u,[r],[s])}replaceRightSE(t){this.rightSE=t,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const t=this.leftSE.point.y,n=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:t<n?t:n},ur:{x:this.rightSE.point.x,y:t>n?t:n}}}vector(){return{x:this.rightSE.point.x-this.leftSE.point.x,y:this.rightSE.point.y-this.leftSE.point.y}}isAnEndpoint(t){return t.x===this.leftSE.point.x&&t.y===this.leftSE.point.y||t.x===this.rightSE.point.x&&t.y===this.rightSE.point.y}comparePoint(t){if(this.isAnEndpoint(t))return 0;const n=this.leftSE.point,r=this.rightSE.point,i=this.vector();if(n.x===r.x)return t.x===n.x?0:t.x<n.x?1:-1;const o=(t.y-n.y)/i.y,s=n.x+o*i.x;if(t.x===s)return 0;const a=(t.x-n.x)/i.x,c=n.y+a*i.y;return t.y===c?0:t.y<c?-1:1}getIntersection(t){const n=this.bbox(),r=t.bbox(),i=ln(n,r);if(i===null)return null;const o=this.leftSE.point,s=this.rightSE.point,a=t.leftSE.point,c=t.rightSE.point,u=at(n,a)&&this.comparePoint(a)===0,h=at(r,o)&&t.comparePoint(o)===0,l=at(n,c)&&this.comparePoint(c)===0,f=at(r,s)&&t.comparePoint(s)===0;if(h&&u)return f&&!l?s:!f&&l?c:null;if(h)return l&&o.x===c.x&&o.y===c.y?null:o;if(u)return f&&s.x===a.x&&s.y===a.y?null:a;if(f&&l)return null;if(f)return s;if(l)return c;const d=Yi(o,this.vector(),a,t.vector());return d===null||!at(i,d)?null:ft.round(d.x,d.y)}split(t){const n=[],r=t.events!==void 0,i=new Be(t,!0),o=new Be(t,!1),s=this.rightSE;this.replaceRightSE(o),n.push(o),n.push(i);const a=new je(i,s,this.rings.slice(),this.windings.slice());return Be.comparePoints(a.leftSE.point,a.rightSE.point)>0&&a.swapEvents(),Be.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),r&&(i.checkForConsuming(),o.checkForConsuming()),n}swapEvents(){const t=this.rightSE;this.rightSE=this.leftSE,this.leftSE=t,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let n=0,r=this.windings.length;n<r;n++)this.windings[n]*=-1}consume(t){let n=this,r=t;for(;n.consumedBy;)n=n.consumedBy;for(;r.consumedBy;)r=r.consumedBy;const i=je.compare(n,r);if(i!==0){if(i>0){const o=n;n=r,r=o}if(n.prev===r){const o=n;n=r,r=o}for(let o=0,s=r.rings.length;o<s;o++){const a=r.rings[o],c=r.windings[o],u=n.rings.indexOf(a);u===-1?(n.rings.push(a),n.windings.push(c)):n.windings[u]+=c}r.rings=null,r.windings=null,r.consumedBy=n,r.leftSE.consumedBy=n.leftSE,r.rightSE.consumedBy=n.rightSE}}prevInResult(){return this._prevInResult!==void 0?this._prevInResult:(this.prev?this.prev.isInResult()?this._prevInResult=this.prev:this._prevInResult=this.prev.prevInResult():this._prevInResult=null,this._prevInResult)}beforeState(){if(this._beforeState!==void 0)return this._beforeState;if(!this.prev)this._beforeState={rings:[],windings:[],multiPolys:[]};else{const t=this.prev.consumedBy||this.prev;this._beforeState=t.afterState()}return this._beforeState}afterState(){if(this._afterState!==void 0)return this._afterState;const t=this.beforeState();this._afterState={rings:t.rings.slice(0),windings:t.windings.slice(0),multiPolys:[]};const n=this._afterState.rings,r=this._afterState.windings,i=this._afterState.multiPolys;for(let a=0,c=this.rings.length;a<c;a++){const u=this.rings[a],h=this.windings[a],l=n.indexOf(u);l===-1?(n.push(u),r.push(h)):r[l]+=h}const o=[],s=[];for(let a=0,c=n.length;a<c;a++){if(r[a]===0)continue;const u=n[a],h=u.poly;if(s.indexOf(h)===-1)if(u.isExterior)o.push(h);else{s.indexOf(h)===-1&&s.push(h);const l=o.indexOf(u.poly);l!==-1&&o.splice(l,1)}}for(let a=0,c=o.length;a<c;a++){const u=o[a].multiPoly;i.indexOf(u)===-1&&i.push(u)}return this._afterState}isInResult(){if(this.consumedBy)return!1;if(this._isInResult!==void 0)return this._isInResult;const t=this.beforeState().multiPolys,n=this.afterState().multiPolys;switch(We.type){case"union":{const r=t.length===0,i=n.length===0;this._isInResult=r!==i;break}case"intersection":{let r,i;t.length<n.length?(r=t.length,i=n.length):(r=n.length,i=t.length),this._isInResult=i===We.numMultiPolys&&r<i;break}case"xor":{const r=Math.abs(t.length-n.length);this._isInResult=r%2===1;break}case"difference":{const r=i=>i.length===1&&i[0].isSubject;this._isInResult=r(t)!==r(n);break}default:throw new Error(`Unrecognized operation type found ${We.type}`)}return this._isInResult}}class Wn{constructor(t,n,r){if(!Array.isArray(t)||t.length===0)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=n,this.isExterior=r,this.segments=[],typeof t[0][0]!="number"||typeof t[0][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const i=ft.round(t[0][0],t[0][1]);this.bbox={ll:{x:i.x,y:i.y},ur:{x:i.x,y:i.y}};let o=i;for(let s=1,a=t.length;s<a;s++){if(typeof t[s][0]!="number"||typeof t[s][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");let c=ft.round(t[s][0],t[s][1]);c.x===o.x&&c.y===o.y||(this.segments.push(je.fromRing(o,c,this)),c.x<this.bbox.ll.x&&(this.bbox.ll.x=c.x),c.y<this.bbox.ll.y&&(this.bbox.ll.y=c.y),c.x>this.bbox.ur.x&&(this.bbox.ur.x=c.x),c.y>this.bbox.ur.y&&(this.bbox.ur.y=c.y),o=c)}(i.x!==o.x||i.y!==o.y)&&this.segments.push(je.fromRing(o,i,this))}getSweepEvents(){const t=[];for(let n=0,r=this.segments.length;n<r;n++){const i=this.segments[n];t.push(i.leftSE),t.push(i.rightSE)}return t}}class Xi{constructor(t,n){if(!Array.isArray(t))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");this.exteriorRing=new Wn(t[0],this,!0),this.bbox={ll:{x:this.exteriorRing.bbox.ll.x,y:this.exteriorRing.bbox.ll.y},ur:{x:this.exteriorRing.bbox.ur.x,y:this.exteriorRing.bbox.ur.y}},this.interiorRings=[];for(let r=1,i=t.length;r<i;r++){const o=new Wn(t[r],this,!1);o.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=o.bbox.ll.x),o.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=o.bbox.ll.y),o.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=o.bbox.ur.x),o.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=o.bbox.ur.y),this.interiorRings.push(o)}this.multiPoly=n}getSweepEvents(){const t=this.exteriorRing.getSweepEvents();for(let n=0,r=this.interiorRings.length;n<r;n++){const i=this.interiorRings[n].getSweepEvents();for(let o=0,s=i.length;o<s;o++)t.push(i[o])}return t}}class Xn{constructor(t,n){if(!Array.isArray(t))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");try{typeof t[0][0][0]=="number"&&(t=[t])}catch{}this.polys=[],this.bbox={ll:{x:Number.POSITIVE_INFINITY,y:Number.POSITIVE_INFINITY},ur:{x:Number.NEGATIVE_INFINITY,y:Number.NEGATIVE_INFINITY}};for(let r=0,i=t.length;r<i;r++){const o=new Xi(t[r],this);o.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=o.bbox.ll.x),o.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=o.bbox.ll.y),o.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=o.bbox.ur.x),o.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=o.bbox.ur.y),this.polys.push(o)}this.isSubject=n}getSweepEvents(){const t=[];for(let n=0,r=this.polys.length;n<r;n++){const i=this.polys[n].getSweepEvents();for(let o=0,s=i.length;o<s;o++)t.push(i[o])}return t}}class Bt{static factory(t){const n=[];for(let r=0,i=t.length;r<i;r++){const o=t[r];if(!o.isInResult()||o.ringOut)continue;let s=null,a=o.leftSE,c=o.rightSE;const u=[a],h=a.point,l=[];for(;s=a,a=c,u.push(a),a.point!==h;)for(;;){const f=a.getAvailableLinkedEvents();if(f.length===0){const p=u[0].point,y=u[u.length-1].point;throw new Error(`Unable to complete output ring starting at [${p.x}, ${p.y}]. Last matching segment found ends at [${y.x}, ${y.y}].`)}if(f.length===1){c=f[0].otherSE;break}let d=null;for(let p=0,y=l.length;p<y;p++)if(l[p].point===a.point){d=p;break}if(d!==null){const p=l.splice(d)[0],y=u.splice(p.index);y.unshift(y[0].otherSE),n.push(new Bt(y.reverse()));continue}l.push({index:u.length,point:a.point});const m=a.getLeftmostComparator(s);c=f.sort(m)[0].otherSE;break}n.push(new Bt(u))}return n}constructor(t){this.events=t;for(let n=0,r=t.length;n<r;n++)t[n].segment.ringOut=this;this.poly=null}getGeom(){let t=this.events[0].point;const n=[t];for(let u=1,h=this.events.length-1;u<h;u++){const l=this.events[u].point,f=this.events[u+1].point;Un(l,t,f)!==0&&(n.push(l),t=l)}if(n.length===1)return null;const r=n[0],i=n[1];Un(r,t,i)===0&&n.shift(),n.push(n[0]);const o=this.isExteriorRing()?1:-1,s=this.isExteriorRing()?0:n.length-1,a=this.isExteriorRing()?n.length:-1,c=[];for(let u=s;u!=a;u+=o)c.push([n[u].x,n[u].y]);return c}isExteriorRing(){if(this._isExteriorRing===void 0){const t=this.enclosingRing();this._isExteriorRing=t?!t.isExteriorRing():!0}return this._isExteriorRing}enclosingRing(){return this._enclosingRing===void 0&&(this._enclosingRing=this._calcEnclosingRing()),this._enclosingRing}_calcEnclosingRing(){let t=this.events[0];for(let i=1,o=this.events.length;i<o;i++){const s=this.events[i];Be.compare(t,s)>0&&(t=s)}let n=t.segment.prevInResult(),r=n?n.prevInResult():null;for(;;){if(!n)return null;if(!r)return n.ringOut;if(r.ringOut!==n.ringOut)return r.ringOut.enclosingRing()!==n.ringOut?n.ringOut:n.ringOut.enclosingRing();n=r.prevInResult(),r=n?n.prevInResult():null}}}class Vn{constructor(t){this.exteriorRing=t,t.poly=this,this.interiorRings=[]}addInterior(t){this.interiorRings.push(t),t.poly=this}getGeom(){const t=[this.exteriorRing.getGeom()];if(t[0]===null)return null;for(let n=0,r=this.interiorRings.length;n<r;n++){const i=this.interiorRings[n].getGeom();i!==null&&t.push(i)}return t}}class Vi{constructor(t){this.rings=t,this.polys=this._composePolys(t)}getGeom(){const t=[];for(let n=0,r=this.polys.length;n<r;n++){const i=this.polys[n].getGeom();i!==null&&t.push(i)}return t}_composePolys(t){const n=[];for(let r=0,i=t.length;r<i;r++){const o=t[r];if(!o.poly)if(o.isExteriorRing())n.push(new Vn(o));else{const s=o.enclosingRing();s.poly||n.push(new Vn(s)),s.poly.addInterior(o)}}return n}}class Gi{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:je.compare;this.queue=t,this.tree=new wn(n),this.segments=[]}process(t){const n=t.segment,r=[];if(t.consumedBy)return t.isLeft?this.queue.remove(t.otherSE):this.tree.remove(n),r;const i=t.isLeft?this.tree.add(n):this.tree.find(n);if(!i)throw new Error(`Unable to find segment #${n.id} [${n.leftSE.point.x}, ${n.leftSE.point.y}] -> [${n.rightSE.point.x}, ${n.rightSE.point.y}] in SweepLine tree.`);let o=i,s=i,a,c;for(;a===void 0;)o=this.tree.prev(o),o===null?a=null:o.key.consumedBy===void 0&&(a=o.key);for(;c===void 0;)s=this.tree.next(s),s===null?c=null:s.key.consumedBy===void 0&&(c=s.key);if(t.isLeft){let u=null;if(a){const l=a.getIntersection(n);if(l!==null&&(n.isAnEndpoint(l)||(u=l),!a.isAnEndpoint(l))){const f=this._splitSafely(a,l);for(let d=0,m=f.length;d<m;d++)r.push(f[d])}}let h=null;if(c){const l=c.getIntersection(n);if(l!==null&&(n.isAnEndpoint(l)||(h=l),!c.isAnEndpoint(l))){const f=this._splitSafely(c,l);for(let d=0,m=f.length;d<m;d++)r.push(f[d])}}if(u!==null||h!==null){let l=null;u===null?l=h:h===null?l=u:l=Be.comparePoints(u,h)<=0?u:h,this.queue.remove(n.rightSE),r.push(n.rightSE);const f=n.split(l);for(let d=0,m=f.length;d<m;d++)r.push(f[d])}r.length>0?(this.tree.remove(n),r.push(t)):(this.segments.push(n),n.prev=a)}else{if(a&&c){const u=a.getIntersection(c);if(u!==null){if(!a.isAnEndpoint(u)){const h=this._splitSafely(a,u);for(let l=0,f=h.length;l<f;l++)r.push(h[l])}if(!c.isAnEndpoint(u)){const h=this._splitSafely(c,u);for(let l=0,f=h.length;l<f;l++)r.push(h[l])}}}this.tree.remove(n)}return r}_splitSafely(t,n){this.tree.remove(t);const r=t.rightSE;this.queue.remove(r);const i=t.split(n);return i.push(r),t.consumedBy===void 0&&this.tree.add(t),i}}const Gn=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_QUEUE_SIZE||1e6,qi=typeof process<"u"&&process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS||1e6;class Hi{run(t,n,r){We.type=t,ft.reset();const i=[new Xn(n,!0)];for(let l=0,f=r.length;l<f;l++)i.push(new Xn(r[l],!1));if(We.numMultiPolys=i.length,We.type==="difference"){const l=i[0];let f=1;for(;f<i.length;)ln(i[f].bbox,l.bbox)!==null?f++:i.splice(f,1)}if(We.type==="intersection")for(let l=0,f=i.length;l<f;l++){const d=i[l];for(let m=l+1,p=i.length;m<p;m++)if(ln(d.bbox,i[m].bbox)===null)return[]}const o=new wn(Be.compare);for(let l=0,f=i.length;l<f;l++){const d=i[l].getSweepEvents();for(let m=0,p=d.length;m<p;m++)if(o.insert(d[m]),o.size>Gn)throw new Error("Infinite loop when putting segment endpoints in a priority queue (queue size too big).")}const s=new Gi(o);let a=o.size,c=o.pop();for(;c;){const l=c.key;if(o.size===a){const d=l.segment;throw new Error(`Unable to pop() ${l.isLeft?"left":"right"} SweepEvent [${l.point.x}, ${l.point.y}] from segment #${d.id} [${d.leftSE.point.x}, ${d.leftSE.point.y}] -> [${d.rightSE.point.x}, ${d.rightSE.point.y}] from queue.`)}if(o.size>Gn)throw new Error("Infinite loop when passing sweep line over endpoints (queue size too big).");if(s.segments.length>qi)throw new Error("Infinite loop when passing sweep line over endpoints (too many sweep line segments).");const f=s.process(l);for(let d=0,m=f.length;d<m;d++){const p=f[d];p.consumedBy===void 0&&o.insert(p)}a=o.size,c=o.pop()}ft.reset();const u=Bt.factory(s.segments);return new Vi(u).getGeom()}}const We=new Hi,Zi=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return We.run("union",e,n)},$i=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return We.run("intersection",e,n)},Ki=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return We.run("xor",e,n)},ji=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return We.run("difference",e,n)};var Qi={union:Zi,intersection:$i,xor:Ki,difference:ji};function pt(e){return e==null?null:Ur(e)||Or(e)||Ji(e)?e:null}function qn(e){return typeof e=="number"&&Number.isFinite(e)}function _t(e){return Array.isArray(e)&&e.length>=2&&qn(e[0])&&qn(e[1])}function Ur(e){return Array.isArray(e)&&e.length>0&&e.every(t=>_t(t))}function Or(e){return Array.isArray(e)&&e.length>0&&e.every(t=>Ur(t))}function Ji(e){return Array.isArray(e)&&e.length>0&&e.every(t=>Or(t))}function Ne(e){if(!Array.isArray(e)||e.length<3)return[];const t=[];for(const i of e){if(!Array.isArray(i)||i.length<2)continue;const o=Number(i[0]),s=Number(i[1]);if(!Number.isFinite(o)||!Number.isFinite(s))continue;const a=t[t.length-1];a&&a[0]===o&&a[1]===s||t.push([o,s])}if(t.length<3)return[];const n=t[0],r=t[t.length-1];return(n[0]!==r[0]||n[1]!==r[1])&&t.push([n[0],n[1]]),t.length>=4?t:[]}function ht(e){if(!Array.isArray(e)||e.length<4)return 0;let t=0;for(let n=0;n<e.length-1;n+=1){const r=e[n],i=e[n+1];t+=r[0]*i[1]-i[0]*r[1]}return t*.5}function jt(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const o of e){const s=Ne(o);s.length>=4&&t.push(s)}if(t.length===0)return[];if(t.length===1)return[t[0]];let n=0,r=0;for(let o=0;o<t.length;o+=1){const s=Math.abs(ht(t[o]));s<=r||(r=s,n=o)}const i=[t[n]];for(let o=0;o<t.length;o+=1)o!==n&&i.push(t[o]);return i}function Yr(e){if(!Array.isArray(e)||e.length===0)return[];const t=e[0];if(_t(t)){const i=jt([e]);return i.length>0?[i]:[]}if(!Array.isArray(t)||t.length===0)return[];const n=t[0];if(_t(n)){const i=jt(e);return i.length>0?[i]:[]}if(!Array.isArray(n)||n.length===0||!_t(n[0]))return[];const r=[];for(const i of e){const o=jt(i);o.length>0&&r.push(o)}return r}function Hn(e,t,n){let r=!1;for(let i=0,o=n.length-1;i<n.length;o=i,i+=1){const s=n[i][0],a=n[i][1],c=n[o][0],u=n[o][1];if(a===u||a>t==u>t)continue;e<(c-s)*(t-a)/(u-a)+s&&(r=!r)}return r}function yt(e){const t=[];for(const n of e??[]){const r=Yr(n);for(const i of r){const o=i[0];if(!o||o.length<4)continue;let s=1/0,a=1/0,c=-1/0,u=-1/0;for(const[l,f]of o)l<s&&(s=l),l>c&&(c=l),f<a&&(a=f),f>u&&(u=f);if(!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(c)||!Number.isFinite(u))continue;let h=Math.abs(ht(o));for(let l=1;l<i.length;l+=1)h-=Math.abs(ht(i[l]));t.push({outer:o,holes:i.slice(1),minX:s,minY:a,maxX:c,maxY:u,area:Math.max(1e-6,h)})}}return t}function Wr(e,t,n){if(e<n.minX||e>n.maxX||t<n.minY||t>n.maxY||!Hn(e,t,n.outer))return!1;for(const r of n.holes)if(Hn(e,t,r))return!1;return!0}function zt(e,t,n){for(const r of n)if(Wr(e,t,r))return!0;return!1}const xn=[160,160,160,255];function W(e,t,n){return Math.max(t,Math.min(n,e))}function Sn(e,t,n){const r=Number(e),i=Number(t),o=Number(n);return!Number.isFinite(r)||r<=0?1:!Number.isFinite(i)||!Number.isFinite(o)?r:Math.pow(2,i-o)*r}function eo(e,t,n){let i=100*Sn(e,t,n);if(Number(e)){let o="μm";return i>1e3&&(i/=1e3,o="mm"),`${i.toPrecision(3)} ${o}`}return`${Math.round(i*1e3)/1e3} pixels`}function be(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function et(e){const t=e.fillModes instanceof Uint8Array?e.fillModes.length:Number.MAX_SAFE_INTEGER;return Math.max(0,Math.min(Math.floor(e.count??0),Math.floor((e.positions?.length??0)/2),e.paletteIndices?.length??0,t))}function cn(e,t){return!e&&!t?!0:!e||!t?!1:Math.abs((e.zoom??0)-(t.zoom??0))<1e-6&&Math.abs((e.offsetX??0)-(t.offsetX??0))<1e-6&&Math.abs((e.offsetY??0)-(t.offsetY??0))<1e-6&&Math.abs((e.rotationDeg??0)-(t.rotationDeg??0))<1e-6}function to(e){const t=String(e??"").trim();if(!t)return"";if(/^bearer\s+/i.test(t)){const n=t.replace(/^bearer\s+/i,"").trim();return n?`Bearer ${n}`:""}return`Bearer ${t}`}function Xr(e){const n=String(e??"").trim().match(/^#?([0-9a-fA-F]{6})$/);if(!n)return[...xn];const r=Number.parseInt(n[1],16);return[r>>16&255,r>>8&255,r&255,255]}function no(e){const t=[[...xn]],n=new Map;for(const i of e??[]){const o=String(i?.termId??"");!o||n.has(o)||(n.set(o,t.length),t.push(Xr(i?.termColor)))}const r=new Uint8Array(t.length*4);for(let i=0;i<t.length;i+=1)r[i*4]=t[i][0],r[i*4+1]=t[i][1],r[i*4+2]=t[i][2],r[i*4+3]=t[i][3];return{colors:r,termToPaletteIndex:n}}const ro=[6,4,2],io=64,oo=.04,so=1,ao=4,Dt=1e-6,lo=.1;function co(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const n of e){if(!Array.isArray(n)||n.length<2)continue;const r=Number(n[0]),i=Number(n[1]);if(!Number.isFinite(r)||!Number.isFinite(i))continue;const o=t[t.length-1];o&&Math.abs(o[0]-r)<1e-9&&Math.abs(o[1]-i)<1e-9||t.push([r,i])}return t}function Zn(e,t,n){if(t<=Dt||n<8)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([e[0]+Math.cos(o)*t,e[1]+Math.sin(o)*t])}return Ne(r)}function uo(e,t,n,r){const i=t[0]-e[0],o=t[1]-e[1],s=Math.sqrt(i*i+o*o);if(!Number.isFinite(s)||s<=r)return[];const a=i/s,u=-(o/s),h=a,l=Math.max(Dt,n);return Ne([[e[0]+u*l,e[1]+h*l],[t[0]+u*l,t[1]+h*l],[t[0]-u*l,t[1]-h*l],[e[0]-u*l,e[1]-h*l]])}function $n(e,t){if(!e.length)return[];let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[a,c]of e)a<n&&(n=a),a>i&&(i=a),c<r&&(r=c),c>o&&(o=c);if(!Number.isFinite(n)||!Number.isFinite(r))return[];const s=Math.max(t,1);return Ne([[n-s,r-s],[i+s,r-s],[i+s,o+s],[n-s,o+s]])}function xt(e,t){return Ne(t?e.map(([n,r])=>[W(n,t[0],t[2]),W(r,t[1],t[3])]):e)}function Kn(e,t){return Number.isFinite(e)?Number(e.toFixed(t)):e}function fo(e,t){if(!Array.isArray(e)||e.length===0)return[];const n=[];for(const r of e){if(!Array.isArray(r)||r.length<2)continue;const i=Kn(Number(r[0]),t),o=Kn(Number(r[1]),t);if(!Number.isFinite(i)||!Number.isFinite(o))continue;const s=n[n.length-1];(!s||s[0]!==i||s[1]!==o)&&n.push([i,o])}if(n.length>=2){const r=n[0],i=n[n.length-1];if(!r||!i)return[];(r[0]!==i[0]||r[1]!==i[1])&&n.push([r[0],r[1]])}return n.length>=4?n:[]}function ho(e,t){if(!Array.isArray(e)||e.length===0)return[];const n=e.map(r=>fo(r,t)).filter(r=>r.length>=4);return n.length>0?n:[]}function mo(e,t){const n=e.map(i=>ho(i,t)).filter(i=>i.length>0);if(n.length===0)return null;let r=[n[0]];try{for(let i=1;i<n.length;i+=1)if(r=Qi.union(r,[n[i]]),!Array.isArray(r)||r.length===0)return null}catch(i){return console.error("buildBrushStrokePolygon union failed",t,i),null}return r.length>0?r:null}function go(e){if(e.length===0)return null;for(const t of ro){const n=mo(e,t);if(n)return n}return null}function po(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const n of e){if(!Array.isArray(n)||n.length<2)continue;const r=Number(n[0]),i=Number(n[1]);!Number.isFinite(r)||!Number.isFinite(i)||t.push([r,i])}return Ne(t)}function yo(e){let t=[],n=0;for(const r of e){if(!Array.isArray(r)||r.length===0)continue;const i=po(r[0]??[]);if(i.length<4)continue;const o=Math.abs(ht(i));o<=n||(n=o,t=i)}return t}function bo(e,t=1e-9){const n=Ne(e);if(n.length<5)return n;const r=[n[0]];for(let i=1;i<n.length-1;i+=1){const o=r[r.length-1],s=n[i],a=n[i+1],c=(s[0]-o[0])*(a[1]-s[1])-(s[1]-o[1])*(a[0]-s[0]);Math.abs(c)<=t||r.push(s)}return r.push(r[0]),Ne(r)}function wo(e,t,n){const r=n[0]-t[0],i=n[1]-t[1],o=r*r+i*i;if(o<=1e-12){const l=e[0]-t[0],f=e[1]-t[1];return l*l+f*f}const s=W(((e[0]-t[0])*r+(e[1]-t[1])*i)/o,0,1),a=t[0]+r*s,c=t[1]+i*s,u=e[0]-a,h=e[1]-c;return u*u+h*h}function xo(e,t){if(e.length<=2||t<=0)return e.slice();const n=new Uint8Array(e.length);n[0]=1,n[e.length-1]=1;const r=t*t,i=[[0,e.length-1]];for(;i.length>0;){const s=i.pop();if(!s)break;const[a,c]=s;if(c-a<=1)continue;let u=0,h=-1;for(let l=a+1;l<c;l+=1){const f=wo(e[l],e[a],e[c]);f>u&&(u=f,h=l)}h>=0&&u>r&&(n[h]=1,i.push([a,h],[h,c]))}const o=[];for(let s=0;s<e.length;s+=1)n[s]&&o.push(e[s]);return o}function So(e,t){const n=Ne(e);if(n.length<5||t<=0)return n;const r=n.slice(0,-1),i=xo(r,t);return i.length<3?n:Ne(i)}function Eo(e,t){let n=Ne(e);if(t<=0||n.length<5)return n;for(let r=0;r<t;r+=1){const i=n.slice(0,-1);if(i.length<3)break;const o=[];for(let s=0;s<i.length;s+=1){const a=i[s],c=i[(s+1)%i.length];o.push([a[0]*.75+c[0]*.25,a[1]*.75+c[1]*.25],[a[0]*.25+c[0]*.75,a[1]*.25+c[1]*.75])}n=Ne(o)}return n}function Ro(e,t){const n=co(e),r=Math.max(Dt,Number(t.radius)||0);if(n.length===0||!Number.isFinite(r))return[];const i=Math.max(12,Math.floor(t.circleSides||io));if(n.length===1)return xt(Zn(n[0],r,i),t.clipBounds);const o=[],s=Math.max(Dt,r*lo);for(let f=0;f<n.length;f+=1){const d=n[f],m=Zn(d,r,i);if(m.length>=4&&o.push([m]),f===0)continue;const p=uo(n[f-1],d,r,s);p.length>=4&&o.push([p])}const a=go(o),c=a?yo(a):[];if(!c.length)return xt($n(n,r),t.clipBounds);const u=typeof t.simplifyTolerance=="number"&&Number.isFinite(t.simplifyTolerance)?Math.max(0,t.simplifyTolerance):Math.max(.25,r*oo),h=typeof t.smoothingPasses=="number"&&Number.isFinite(t.smoothingPasses)?Math.round(W(t.smoothingPasses,0,ao)):so,l=So(Eo(bo(c,1e-9),h),u);return l.length<4?xt($n(n,r),t.clipBounds):xt(l,t.clipBounds)}const Je=[],jn=[],Xe={color:"#ff4d4f",width:2,lineDash:Je,lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},Vr={color:"#4cc9f0",width:2,lineDash:[10,8],lineJoin:"round",lineCap:"round",shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0},Gr="rgba(23, 23, 25, 0.1)",qr=6,Ue={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},Ze={fontFamily:"Pretendard, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:13,fontWeight:500,textColor:"#FFFFFF",backgroundColor:"rgba(23, 23, 25, 0.5)",borderRadius:4,paddingX:6,paddingY:3},Qn={x:16,y:-24},Mo=20,Jn=1e-6,er="transparent",Ao=3,vo=2,Hr=96,Co=1,tr=1e3,Zr=2,$r=2,Io=4096,Po=.2,To=1.12,_o=.89,Fo=32,Lo="#000000",ko=.1,No="#FFCF00",Bo="#FF0000",zo=1.5,nr=[2,2],Do=1,Uo=.25,Oo=4,Yo=1,Wo=0,Xo=4,Vo=1.5;function Ut(e,t,n){return[W(e[0],0,t),W(e[1],0,n)]}function En(e){if(!Array.isArray(e)||e.length<2)return null;const t=Number(e[0]),n=Number(e[1]);return!Number.isFinite(t)||!Number.isFinite(n)?null:[t,n]}const Oe=En;function Fe(e){return Ne(e)}function Ft(e){return Math.abs(ht(Fe(e)))}function rr(e){if(!Array.isArray(e)||e.length===0)return[0,0,0,0];let t=1/0,n=1/0,r=-1/0,i=-1/0;for(const[o,s]of e)o<t&&(t=o),o>r&&(r=o),s<n&&(n=s),s>i&&(i=s);return[t,n,r,i]}function un(e,t,n=!1){if(t.length!==0){e.moveTo(t[0][0],t[0][1]);for(let r=1;r<t.length;r+=1)e.lineTo(t[r][0],t[r][1]);n&&e.closePath()}}function Pe(e,t,n,r=!1,i=!1,o="rgba(255, 77, 79, 0.16)"){t.length!==0&&(e.beginPath(),un(e,t,r),i&&r&&(e.fillStyle=o,e.fill()),e.strokeStyle=n.color,e.lineWidth=n.width,e.lineJoin=n.lineJoin,e.lineCap=n.lineCap,e.shadowColor=n.shadowColor,e.shadowBlur=n.shadowBlur,e.shadowOffsetX=n.shadowOffsetX,e.shadowOffsetY=n.shadowOffsetY,e.setLineDash(n.lineDash),e.stroke(),e.setLineDash(Je),e.shadowColor="rgba(0, 0, 0, 0)",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0)}function Rn(e){const t=Array.isArray(e?.lineDash)?e.lineDash.filter(s=>Number.isFinite(s)&&s>=0):Je,n=typeof e?.width=="number"&&Number.isFinite(e.width)?Math.max(0,e.width):Xe.width,r=typeof e?.shadowBlur=="number"&&Number.isFinite(e.shadowBlur)?Math.max(0,e.shadowBlur):Xe.shadowBlur,i=typeof e?.shadowOffsetX=="number"&&Number.isFinite(e.shadowOffsetX)?e.shadowOffsetX:Xe.shadowOffsetX,o=typeof e?.shadowOffsetY=="number"&&Number.isFinite(e.shadowOffsetY)?e.shadowOffsetY:Xe.shadowOffsetY;return{color:e?.color||Xe.color,width:n,lineDash:t.length?t:Je,lineJoin:e?.lineJoin||Xe.lineJoin,lineCap:e?.lineCap||Xe.lineCap,shadowColor:e?.shadowColor||Xe.shadowColor,shadowBlur:r,shadowOffsetX:i,shadowOffsetY:o}}function Ve(e,t){return t?Rn({color:t.color??e.color,width:t.width??e.width,lineDash:t.lineDash??e.lineDash,lineJoin:t.lineJoin??e.lineJoin,lineCap:t.lineCap??e.lineCap,shadowColor:t.shadowColor??e.shadowColor,shadowBlur:t.shadowBlur??e.shadowBlur,shadowOffsetX:t.shadowOffsetX??e.shadowOffsetX,shadowOffsetY:t.shadowOffsetY??e.shadowOffsetY}):e}function Ot(e,t){return e==null||t===null||t===void 0?!1:String(e)===String(t)}function ir(e){return typeof e=="number"&&Number.isFinite(e)}function Go(e){return Array.isArray(e)&&e.length>=2&&ir(e[0])&&ir(e[1])}function qo(e){return Array.isArray(e)&&e.length>=2&&e.every(t=>Go(t))}function Kr(e,t){if(!(!Array.isArray(e)||e.length===0)){if(qo(e)){t.push(e.map(([n,r])=>[n,r]));return}for(const n of e)Kr(n,t)}}function or(e,t){const n=[];Kr(e,n);const r=[];for(const i of n){if(i.length<2)continue;const o=t?Fe(i):i;o.length>=(t?4:2)&&r.push(o)}return r}function ut(e,t){return typeof e!="number"||!Number.isFinite(e)||e<=0?t:e}function Ho(e,t){return typeof e!="number"||!Number.isFinite(e)?t:W(e,0,1)}function jr(e,t,n,r,i,o){const s=Math.max(0,Math.min(o,r*.5,i*.5));e.beginPath(),e.moveTo(t+s,n),e.lineTo(t+r-s,n),e.quadraticCurveTo(t+r,n,t+r,n+s),e.lineTo(t+r,n+i-s),e.quadraticCurveTo(t+r,n+i,t+r-s,n+i),e.lineTo(t+s,n+i),e.quadraticCurveTo(t,n+i,t,n+i-s),e.lineTo(t,n+s),e.quadraticCurveTo(t,n,t+s,n),e.closePath()}function Zo(e){const t=e[0];return Array.isArray(t)&&Array.isArray(t[0])}function Yt(e,t,n){if(!e||!t)return[];if(n){const r=n.worldToScreen(e[0],e[1]),i=n.worldToScreen(t[0],t[1]);if(r&&i){const o=[[r[0],r[1]],[i[0],r[1]],[i[0],i[1]],[r[0],i[1]]],s=[];for(const a of o){const c=n.screenToWorld(a);if(!c)return Yt(e,t);s.push(c)}return Fe(s)}}return Fe([[e[0],e[1]],[t[0],e[1]],[t[0],t[1]],[e[0],t[1]]])}function fn(e,t,n=Hr){if(!e||!t)return[];const r=(e[0]+t[0])*.5,i=(e[1]+t[1])*.5,o=Math.hypot(t[0]-e[0],t[1]-e[1])*.5;if(o<1)return[];const s=[];for(let a=0;a<=n;a+=1){const c=a/n*Math.PI*2;s.push([r+Math.cos(c)*o,i+Math.sin(c)*o])}return Fe(s)}function Wt(e){const t=Yr(pt(e));if(t.length===0)return[];const n=[];for(const r of t){const i=r[0];if(!i||i.length<4)continue;const o=i.map(([a,c])=>[a,c]),s=[];for(let a=1;a<r.length;a+=1){const c=r[a];!c||c.length<4||s.push(c.map(([u,h])=>[u,h]))}n.push({outer:o,holes:s})}return n}function $o(e){if(!Array.isArray(e))return nr;const t=e.filter(n=>Number.isFinite(n)&&n>=0);return t.length>0?t:nr}function Ko(e){return typeof e!="number"||!Number.isFinite(e)?Do:W(e,Uo,Oo)}function jo(e){return typeof e!="number"||!Number.isFinite(e)?Yo:Math.round(W(e,Wo,Xo))}function Qo(e){const t=ut(e?.radius,Fo),n=ut(e?.cursorLineWidth,zo),r=Ko(e?.edgeDetail),i=jo(e?.edgeSmoothing);return{radius:t,edgeDetail:r,edgeSmoothing:i,clickSelectRoi:e?.clickSelectRoi===!0,fillColor:e?.fillColor||Lo,fillOpacity:Ho(e?.fillOpacity,ko),cursorColor:e?.cursorColor||No,cursorActiveColor:e?.cursorActiveColor||Bo,cursorLineWidth:n,cursorLineDash:$o(e?.cursorLineDash)}}function Jo(e,t,n){if(!t.isDrawing||t.screenPoints.length===0)return;const r=t.screenPoints;if(r.length===0)return;const i=n.radius;if(!(!Number.isFinite(i)||i<=0)){if(e.save(),e.globalAlpha=n.fillOpacity,e.fillStyle=n.fillColor,e.strokeStyle=n.fillColor,e.lineCap="round",e.lineJoin="round",e.lineWidth=i*2,r.length===1)e.beginPath(),e.arc(r[0][0],r[0][1],i,0,Math.PI*2),e.fill();else{e.beginPath(),e.moveTo(r[0][0],r[0][1]);for(let o=1;o<r.length;o+=1)e.lineTo(r[o][0],r[o][1]);e.stroke()}e.restore()}}function es(e,t,n,r){const i=t.cursor;if(!i)return;const o=t.cursorScreen??Oe(n?.worldToScreen(i[0],i[1])??[]);if(!o)return;const s=r.radius;!Number.isFinite(s)||s<=0||(e.save(),e.beginPath(),e.arc(o[0],o[1],s,0,Math.PI*2),e.strokeStyle=t.isDrawing?r.cursorActiveColor:r.cursorColor,e.lineWidth=r.cursorLineWidth,e.setLineDash(r.cursorLineDash),e.stroke(),e.setLineDash(Je),e.restore())}const ts=.58,ns=4096,rs=.5;let St=null;const Et=new Map;function is(){if(St)return St;if(typeof document>"u")return null;const t=document.createElement("canvas").getContext("2d");return t?(St=t,St):null}function Mn(e,t){const n=`${t.fontWeight}|${t.fontSize}|${t.fontFamily}|${e}`,r=Et.get(n);if(r!==void 0)return r;const i=e.length*t.fontSize*ts,o=is();let s=i;if(o){o.font=`${t.fontWeight} ${t.fontSize}px ${t.fontFamily}`;const a=o.measureText(e).width;Number.isFinite(a)&&a>=0&&(s=a)}return Et.size>ns&&Et.clear(),Et.set(n,s),s}function os(e,t="top-center"){if(!e.length)return null;let n=1/0;for(const o of e)o[1]<n&&(n=o[1]);if(!Number.isFinite(n))return null;let r=1/0,i=-1/0;for(const o of e)Math.abs(o[1]-n)>rs||(o[0]<r&&(r=o[0]),o[0]>i&&(i=o[0]));return!Number.isFinite(r)||!Number.isFinite(i)?null:t==="top-center"?[(r+i)*.5,n]:[r,n]}function An(e,t="top-center"){let n=null;for(const r of e){const i=os(r.outer,t);i&&(!n||i[1]<n[1]||i[1]===n[1]&&i[0]<n[0])&&(n=i)}return n}function vn(e){const t=typeof e?.paddingX=="number"&&Number.isFinite(e.paddingX)?Math.max(0,e.paddingX):Ue.paddingX,n=typeof e?.paddingY=="number"&&Number.isFinite(e.paddingY)?Math.max(0,e.paddingY):Ue.paddingY,r=typeof e?.fontSize=="number"&&Number.isFinite(e.fontSize)?Math.max(8,e.fontSize):Ue.fontSize,i=typeof e?.borderWidth=="number"&&Number.isFinite(e.borderWidth)?Math.max(0,e.borderWidth):Ue.borderWidth,o=typeof e?.offsetY=="number"&&Number.isFinite(e.offsetY)?e.offsetY:Ue.offsetY,s=typeof e?.borderRadius=="number"&&Number.isFinite(e.borderRadius)?Math.max(0,e.borderRadius):Ue.borderRadius;return{fontFamily:e?.fontFamily||Ue.fontFamily,fontSize:r,fontWeight:e?.fontWeight||Ue.fontWeight,textColor:e?.textColor||Ue.textColor,backgroundColor:e?.backgroundColor||Ue.backgroundColor,borderColor:e?.borderColor||Ue.borderColor,borderWidth:i,paddingX:t,paddingY:n,offsetY:o,borderRadius:s}}function Cn(e,t){return t?vn({fontFamily:t.fontFamily??e.fontFamily,fontSize:t.fontSize??e.fontSize,fontWeight:t.fontWeight??e.fontWeight,textColor:t.textColor??e.textColor,backgroundColor:t.backgroundColor??e.backgroundColor,borderColor:t.borderColor??e.borderColor,borderWidth:t.borderWidth??e.borderWidth,paddingX:t.paddingX??e.paddingX,paddingY:t.paddingY??e.paddingY,offsetY:t.offsetY??e.offsetY,borderRadius:t.borderRadius??e.borderRadius}):e}function In(e,t,n){if(!e||!n)return 0;const r=Number(n.minZoom),i=Number(n.maxZoom);return!Number.isFinite(r)||!Number.isFinite(i)||i-r<=Jn||!Number.isFinite(t)?0:t>=i-Jn?Mo:0}function ss(e){const t=typeof e?.fontSize=="number"&&Number.isFinite(e.fontSize)?Math.max(8,e.fontSize):Ze.fontSize,n=typeof e?.borderRadius=="number"&&Number.isFinite(e.borderRadius)?Math.max(0,e.borderRadius):Ze.borderRadius,r=typeof e?.paddingX=="number"&&Number.isFinite(e.paddingX)?Math.max(0,e.paddingX):Ze.paddingX,i=typeof e?.paddingY=="number"&&Number.isFinite(e.paddingY)?Math.max(0,e.paddingY):Ze.paddingY;return{fontFamily:e?.fontFamily||Ze.fontFamily,fontSize:t,fontWeight:e?.fontWeight||Ze.fontWeight,textColor:e?.textColor||Ze.textColor,backgroundColor:e?.backgroundColor||Ze.backgroundColor,borderRadius:n,paddingX:r,paddingY:i}}function as(e){const t=typeof e?.x=="number"&&Number.isFinite(e.x)?e.x:Qn.x,n=typeof e?.y=="number"&&Number.isFinite(e.y)?e.y:Qn.y;return{x:t,y:n}}function ls(e){return Number.isFinite(e)?`${Math.max(0,e).toFixed(3)} mm²`:"0.000 mm²"}function cs(e){const t=typeof e?.format=="function"?e.format:ls,n=as(e?.cursorOffset);return{enabled:e?.enabled===!0,format:t,style:ss(e?.style),cursorOffsetX:n.x,cursorOffsetY:n.y}}function Qr(e,t,n,r,i,o,s=!0){const a=t.trim();if(!a)return;e.save(),e.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,e.textAlign="center",e.textBaseline="middle";const u=Mn(a,o)+o.paddingX*2,h=o.fontSize+o.paddingY*2,l=n[0],f=n[1]-o.offsetY,d=s?W(l,u*.5+1,r-u*.5-1):l,m=s?W(f,h*.5+1,i-h*.5-1):f,p=d-u*.5,y=m-h*.5;e.fillStyle=o.backgroundColor,e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,jr(e,p,y,u,h,o.borderRadius),e.fill(),o.borderWidth>0&&e.stroke(),e.fillStyle=o.textColor,e.fillText(a,d,m+.5),e.restore()}function us(e,t,n,r,i,o,s,a){const c=t.trim();if(!c)return;e.save(),e.font=`${o.fontWeight} ${o.fontSize}px ${o.fontFamily}`,e.textAlign="center",e.textBaseline="middle";const h=Mn(c,o)+o.paddingX*2,l=o.fontSize+o.paddingY*2,f=W(n[0]+s,h*.5+1,r-h*.5-1),d=W(n[1]+a,l*.5+1,i-l*.5-1),m=f-h*.5,p=d-l*.5;e.fillStyle=o.backgroundColor,jr(e,m,p,h,l,o.borderRadius),e.fill(),e.fillStyle=o.textColor,e.fillText(c,f,d+.5),e.restore()}function fs(e,t,n,r){if(!(t.length<4||n.length===0)){e.save(),e.beginPath(),un(e,t,!0);for(const i of n)i.length<4||un(e,i,!0);e.fillStyle=r,e.fill("evenodd"),e.restore()}}function Jr(e){const{ctx:t,overlayShapes:n,imageOuterRing:r,worldToScreenPoints:i,baseStrokeStyle:o,onInvertedFillDebug:s}=e,a=!!globalThis.__OPEN_PLANT_DEBUG_OVERLAY__;for(let c=0;c<n.length;c+=1){const u=n[c];if(!u?.coordinates?.length||u.visible===!1)continue;const h=u.closed??Zo(u.coordinates),l=or(u.coordinates,h);if(u.invertedFill?.fillColor){const d=[],m=or(u.coordinates,!0);for(const p of m){const y=i(p);y.length>=4&&d.push(y)}a&&s&&s({id:u.id??c,outerRingPoints:r.length,sourceRingCount:m.length,holeRingCount:d.length,fillColor:u.invertedFill.fillColor}),fs(t,r,d,u.invertedFill.fillColor)}if(l.length===0)continue;const f=Ve(o,u.stroke??u.strokeStyle);for(const d of l){const m=i(d);m.length<2||Pe(t,m,f,h,u.fill??!1)}}}function Rt(e){return typeof e=="string"&&(e==="stamp-rectangle"||e==="stamp-circle"||e==="stamp-rectangle-4096px"||e==="stamp-rectangle-2mm2"||e==="stamp-circle-2mm2"||e==="stamp-circle-hpf-0.2mm2")}function hs(e){return{rectangleAreaMm2:ut(e?.rectangleAreaMm2,Zr),circleAreaMm2:ut(e?.circleAreaMm2,$r),rectanglePixelSize:ut(e?.rectanglePixelSize,Io)}}const sr=1e3;function ds(e){return e*sr*sr}function ar(e,t,n){if(!e||!Number.isFinite(t)||t<=0)return[];if(n){const r=n.worldToScreen(e[0],e[1]),i=n.worldToScreen(e[0]+t,e[1]);if(r&&i){const o=Math.hypot(i[0]-r[0],i[1]-r[1]),s=[[r[0]-o,r[1]-o],[r[0]+o,r[1]-o],[r[0]+o,r[1]+o],[r[0]-o,r[1]+o]],a=[];for(const c of s){const u=n.screenToWorld(c);if(!u)throw new Error("Failed to create rectangle");a.push(u)}return Fe(a)}}return Fe([[e[0]-t,e[1]-t],[e[0]+t,e[1]-t],[e[0]+t,e[1]+t],[e[0]-t,e[1]+t]])}function ms(e,t,n=Hr){if(!e||!Number.isFinite(t)||t<=0)return[];const r=[];for(let i=0;i<=n;i+=1){const o=i/n*Math.PI*2;r.push([e[0]+Math.cos(o)*t,e[1]+Math.sin(o)*t])}return Fe(r)}function gs(e){const{stampTool:t,center:n,resolvedStampOptions:r,imageWidth:i,imageHeight:o,micronsToWorldPixels:s,getRectangleProjection:a}=e;if(!n)return[];if(t==="stamp-rectangle-4096px"){const l=r.rectanglePixelSize*.5;return ar(n,l,a()).map(f=>Ut(f,i,o))}let c=0;if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"?c=t==="stamp-rectangle-2mm2"?Zr:r.rectangleAreaMm2:(t==="stamp-circle"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2")&&(c=t==="stamp-circle-hpf-0.2mm2"?Po:t==="stamp-circle-2mm2"?$r:r.circleAreaMm2),!Number.isFinite(c)||c<=0)return[];const u=ds(c);let h=[];if(t==="stamp-rectangle"||t==="stamp-rectangle-2mm2"){const l=s(Math.sqrt(u)*.5);h=ar(n,l,a())}else if(t==="stamp-circle"||t==="stamp-circle-2mm2"||t==="stamp-circle-hpf-0.2mm2"){const l=s(Math.sqrt(u/Math.PI));h=ms(n,l)}return h.length?h.map(l=>Ut(l,i,o)):[]}function ps(e){return{color:Gr,width:qr,lineDash:Je,lineJoin:e.lineJoin,lineCap:e.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function ys(e){if(typeof e!="string")return er;const t=e.trim();return t.length>0?t:er}function lr(e){return Array.isArray(e)&&e.length>=4&&Ft(e)>Co}function ei({tool:e,imageWidth:t,imageHeight:n,imageMpp:r,imageZoom:i,stampOptions:o,brushOptions:s,projectorRef:a,onBrushTap:c,onDrawComplete:u,onPatchComplete:h,enabled:l,viewStateSignal:f,persistedRegions:d,patchRegions:m,persistedPolygons:p,drawFillColor:y,regionStrokeStyle:b,regionStrokeHoverStyle:x,regionStrokeActiveStyle:C,patchStrokeStyle:S,resolveRegionStrokeStyle:A,resolveRegionLabelStyle:T,overlayShapes:O,hoveredRegionId:z=null,activeRegionId:G=null,regionLabelStyle:D,drawAreaTooltip:q,autoLiftRegionLabelAtMaxZoom:re=!1,regionLabelAnchor:I="top-center",clampRegionLabelToViewport:H=!0,regionLabelAutoLiftOffsetPx:N,invalidateRef:k,className:Z,style:we}){const se=g.useRef(null),Re=g.useRef(!1),Ce=g.useRef(new Map),xe=g.useRef(e),M=g.useRef({isDrawing:!1,pointerId:null,start:null,current:null,cursor:null,cursorScreen:null,points:[],screenPoints:[],stampCenter:null}),v=l??e!=="cursor",X=g.useMemo(()=>d&&d.length>0?d:!p||p.length===0?jn:p.map((w,E)=>({id:E,coordinates:w})),[d,p]),le=g.useMemo(()=>m??jn,[m]),Q=g.useMemo(()=>{const w=[];for(let E=0;E<X.length;E+=1){const P=X[E],F=Wt(P.coordinates);F.length!==0&&w.push({region:P,regionIndex:E,regionKey:P.id??E,polygons:F})}return w},[X]),ie=g.useMemo(()=>{const w=[];for(let E=0;E<le.length;E+=1){const P=le[E],F=Wt(P.coordinates);F.length!==0&&w.push({region:P,regionIndex:E,regionKey:P.id??E,polygons:F})}return w},[le]),he=g.useMemo(()=>Rn(b),[b]),me=g.useMemo(()=>Ve(he,x),[he,x]),$=g.useMemo(()=>Ve(he,C),[he,C]),pe=g.useMemo(()=>Ve(Vr,S),[S]),ye=g.useMemo(()=>ys(y),[y]),U=g.useMemo(()=>vn(D),[D]),V=g.useMemo(()=>cs(q),[q]),ee=g.useMemo(()=>hs(o),[o]),B=g.useMemo(()=>Qo(s),[s]),te=g.useMemo(()=>({position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",touchAction:"none",pointerEvents:v?"auto":"none",cursor:v?e==="brush"?"none":"crosshair":"default",...we}),[v,e,we]),de=g.useCallback(()=>{const w=se.current;if(!w)return;const E=w.getBoundingClientRect(),P=Math.max(1,window.devicePixelRatio||1),F=Math.max(1,Math.round(E.width*P)),j=Math.max(1,Math.round(E.height*P));(w.width!==F||w.height!==j)&&(w.width=F,w.height=j)},[]),ae=g.useCallback(w=>{const E=a.current;if(!E||w.length===0)return[];const P=new Array(w.length);for(let F=0;F<w.length;F+=1){const j=Oe(E.worldToScreen(w[F][0],w[F][1]));if(!j)return[];P[F]=j}return P},[a]),Me=g.useCallback(w=>{const E=a.current,P=se.current;if(!E||!P)return null;const F=P.getBoundingClientRect(),j=Oe(E.screenToWorld(F.left+w[0],F.top+w[1]));return j?Ut(j,t,n):null},[a,t,n]),Se=g.useCallback(()=>{const w=a.current,E=w?.getViewState?.().rotationDeg??0;if(!(Math.abs(E%360)<.01||!w))return{worldToScreen:(P,F)=>Oe(w.worldToScreen(P,F)),screenToWorld:Me}},[a,Me]),_=g.useCallback(w=>{if(!Number.isFinite(w)||w<=0)return 0;const E=typeof r=="number"&&Number.isFinite(r)&&r>0?r:1,P=typeof i=="number"&&Number.isFinite(i)?i:0,F=a.current?.getViewState?.().zoom,j=typeof F=="number"&&Number.isFinite(F)&&F>0?F:1,Ae=P+Math.log2(j),fe=Math.max(1e-9,Sn(E,P,Ae));return w/fe/j},[r,i,a]),Y=g.useCallback((w,E)=>gs({stampTool:w,center:E,resolvedStampOptions:ee,imageWidth:t,imageHeight:n,micronsToWorldPixels:_,getRectangleProjection:Se}),[_,t,n,ee,Se]),J=g.useCallback(()=>{const w=M.current;return Rt(e)?Y(e,w.stampCenter):e==="brush"?[]:w.isDrawing?e==="freehand"?w.points:e==="rectangle"?Yt(w.start,w.current,Se()):e==="circular"?fn(w.start,w.current):[]:[]},[e,Y,Se]),oe=g.useCallback(()=>{de();const w=se.current;if(!w)return;const E=w.getContext("2d");if(!E)return;const P=Math.max(1,window.devicePixelRatio||1),F=w.width/P,j=w.height/P;if(E.setTransform(1,0,0,1,0,0),E.clearRect(0,0,w.width,w.height),E.setTransform(P,0,0,P,0,0),Q.length>0)for(const fe of Q){const{region:ge,polygons:Ee,regionIndex:ve,regionKey:Le}=fe,De=Ot(G,Le)?"active":Ot(z,Le)?"hover":"default";let He=De==="active"?$:De==="hover"?me:he;if(A){const wt=A({region:ge,regionId:Le,regionIndex:ve,state:De});He=Ve(He,wt||void 0)}const bt=De==="default"?null:ps(He);for(const wt of Ee){const qt=ae(wt.outer);qt.length>=4&&(bt&&Pe(E,qt,bt,!0,!1),Pe(E,qt,He,!0,!1));for(const wi of wt.holes){const Ht=ae(wi);Ht.length>=4&&(bt&&Pe(E,Ht,bt,!0,!1),Pe(E,Ht,He,!0,!1))}}}if(ie.length>0)for(const fe of ie)for(const ge of fe.polygons){const Ee=ae(ge.outer);Ee.length>=4&&Pe(E,Ee,pe,!0,!1);for(const ve of ge.holes){const Le=ae(ve);Le.length>=4&&Pe(E,Le,pe,!0,!1)}}if(Array.isArray(O)&&O.length>0){const fe=ae(Fe([[0,0],[t,0],[t,n],[0,n]]));Jr({ctx:E,overlayShapes:O,imageOuterRing:fe,worldToScreenPoints:ae,baseStrokeStyle:he,onInvertedFillDebug:globalThis.__OPEN_PLANT_DEBUG_OVERLAY__?ge=>{const Ee=String(ge.id),ve=`${ge.outerRingPoints}|${ge.sourceRingCount}|${ge.holeRingCount}|${ge.fillColor}`;Ce.current.get(Ee)!==ve&&(Ce.current.set(Ee,ve),console.debug("[open-plant] invertedFill",ge))}:void 0})}const Ae=J();if(v){if(e==="brush")Jo(E,M.current,B),es(E,M.current,a.current,B);else if(Ae.length>0)if(e==="freehand"){const fe=ae(Ae);fe.length>=2&&Pe(E,fe,he,!1,!1),fe.length>=3&&Pe(E,ae(Fe(Ae)),he,!0,!0,ye)}else{const fe=ae(Ae);fe.length>=4&&Pe(E,fe,he,!0,!0,ye)}}if(Q.length>0){const fe=Math.max(1e-6,a.current?.getViewState?.().zoom??1),ge=typeof N=="number"&&Number.isFinite(N)?Math.max(0,N):In(re,fe,a.current?.getZoomRange?.());for(const Ee of Q){if(!Ee.region.label)continue;const ve=An(Ee.polygons,I);if(!ve)continue;const Le=Oe(a.current?.worldToScreen(ve[0],ve[1])??[]);if(!Le)continue;let De=Cn(U,T?.({region:Ee.region,regionId:Ee.regionKey,regionIndex:Ee.regionIndex,zoom:fe}));ge>0&&(De={...De,offsetY:De.offsetY+ge}),Qr(E,Ee.region.label,Le,F,j,De,H)}}if(V.enabled&&v&&(e==="freehand"||e==="rectangle"||e==="circular")){const fe=M.current;if(fe.isDrawing){const ge=e==="freehand"?Fe(Ae):Ae;if(ge.length>=4){const Ee=Ft(ge),ve=typeof r=="number"&&Number.isFinite(r)&&r>0?r:0,Le=ve>0?Ee*ve*ve/(tr*tr):0,De=V.format(Le),He=fe.cursorScreen??(fe.current?Oe(a.current?.worldToScreen(fe.current[0],fe.current[1])??[]):null);He&&us(E,De,He,F,j,V.style,V.cursorOffsetX,V.cursorOffsetY)}}}},[v,e,J,de,ae,t,n,a,Q,O,z,G,he,me,$,ye,ie,pe,A,T,U,V,re,I,H,N,r,B]),L=g.useCallback(()=>{Re.current||(Re.current=!0,requestAnimationFrame(()=>{Re.current=!1,oe()}))},[oe]),K=g.useCallback((w=!1)=>{const E=M.current,P=se.current;P&&E.pointerId!==null&&P.hasPointerCapture(E.pointerId)&&P.releasePointerCapture(E.pointerId),E.isDrawing=!1,E.pointerId=null,E.start=null,E.current=null,E.points=[],E.screenPoints=[],E.stampCenter=null,w||(E.cursor=null,E.cursorScreen=null)},[]),ce=g.useCallback(w=>{const E=a.current;if(!E||t<=0||n<=0)return null;const P=Oe(E.screenToWorld(w.clientX,w.clientY));return P?Ut(P,t,n):null},[a,t,n]),ne=g.useCallback(w=>{const E=se.current;if(!E)return null;const P=E.getBoundingClientRect(),F=W(w.clientX-P.left,0,P.width),j=W(w.clientY-P.top,0,P.height);return!Number.isFinite(F)||!Number.isFinite(j)?null:[F,j]},[]),ue=g.useCallback(()=>{const w=M.current;if(!w.isDrawing){K(!0),L();return}let E=[];if(e==="freehand")w.points.length>=Ao&&(E=Fe(w.points));else if(e==="rectangle")E=Yt(w.start,w.current,Se());else if(e==="circular")E=fn(w.start,w.current);else if(e==="brush"){const P=w.points[w.points.length-1]??w.current??w.start;if(B.clickSelectRoi&&P&&w.points.length<=1&&c?.(P)){K(!0),L();return}const F=Math.max(.25,B.edgeDetail),j=w.screenPoints.length>0?w.screenPoints:ae(w.points),Ae=Math.max(.5,B.radius*.04/F),fe=Ro(j,{radius:B.radius,circleSides:Math.max(16,Math.round(32*F)),simplifyTolerance:Ae,smoothingPasses:B.edgeSmoothing}),ge=[];for(const Ee of fe){const ve=Me(Ee);ve&&ge.push(ve)}E=Fe(ge)}(e==="freehand"||e==="rectangle"||e==="circular"||e==="brush")&&lr(E)&&u&&u({tool:e,intent:e==="brush"?"brush":"roi",coordinates:E,bbox:rr(E),areaPx:Ft(E)}),K(!0),L()},[e,u,K,L,ae,Me,Se,B.radius,B.edgeDetail,B.edgeSmoothing,B.clickSelectRoi,c]),ze=g.useCallback((w,E)=>{const P=Y(w,E);if(!lr(P))return;const F=w==="stamp-rectangle-4096px"?"patch":"roi",j={tool:w,intent:F,coordinates:P,bbox:rr(P),areaPx:Ft(P)};u?.(j),F==="patch"&&h&&h(j)},[Y,u,h]),qe=g.useCallback((w,E,P)=>{const F=Math.max(Vo,B.radius*.1),j=F*F,Ae=w.screenPoints[w.screenPoints.length-1];if(!Ae){w.points.push(E),w.screenPoints.push(P),w.current=E;return}const fe=P[0]-Ae[0],ge=P[1]-Ae[1];fe*fe+ge*ge>=j?(w.points.push(E),w.screenPoints.push(P)):(w.points[w.points.length-1]=E,w.screenPoints[w.screenPoints.length-1]=P),w.current=E},[B.radius]),Gt=g.useCallback(w=>{if(!v||e==="cursor"||w.button!==0)return;const E=ce(w);if(!E)return;const P=ne(w);if(!P)return;if(w.preventDefault(),w.stopPropagation(),Rt(e)){const Ae=M.current;Ae.stampCenter=E,ze(e,E),L();return}const F=se.current;F&&F.setPointerCapture(w.pointerId);const j=M.current;j.isDrawing=!0,j.pointerId=w.pointerId,j.start=E,j.current=E,j.cursor=E,j.cursorScreen=P,j.points=e==="freehand"||e==="brush"?[E]:[],j.screenPoints=e==="brush"?[P]:[],L()},[v,e,ce,ne,ze,L]),st=g.useCallback(w=>{if(!v||e==="cursor")return;const E=ce(w);if(!E)return;const P=ne(w);if(!P)return;const F=M.current;if(F.cursor=E,F.cursorScreen=P,Rt(e)){F.stampCenter=E,w.preventDefault(),w.stopPropagation(),L();return}if(e==="brush"){if(!F.isDrawing||F.pointerId!==w.pointerId){L();return}w.preventDefault(),w.stopPropagation(),qe(F,E,P),L();return}if(!(!F.isDrawing||F.pointerId!==w.pointerId)){if(w.preventDefault(),w.stopPropagation(),e==="freehand"){const j=a.current,Ae=Math.max(1e-6,j?.getViewState?.().zoom??1),fe=vo/Ae,ge=fe*fe,Ee=F.points[F.points.length-1];if(!Ee)F.points.push(E);else{const ve=E[0]-Ee[0],Le=E[1]-Ee[1];ve*ve+Le*Le>=ge&&F.points.push(E)}}else F.current=E;L()}},[v,e,ce,ne,L,a,qe]),_n=g.useCallback(w=>{const E=M.current;if(!E.isDrawing||E.pointerId!==w.pointerId)return;w.preventDefault(),w.stopPropagation();const P=ce(w),F=ne(w);P&&(E.cursor=P,F&&(E.cursorScreen=F),e==="brush"?F&&qe(E,P,F):E.current=P);const j=se.current;j&&j.hasPointerCapture(w.pointerId)&&j.releasePointerCapture(w.pointerId),ue()},[ue,ce,ne,e,qe]),bi=g.useCallback(()=>{const w=M.current;let E=!1;e==="brush"&&!w.isDrawing&&w.cursor&&(w.cursor=null,w.cursorScreen=null,E=!0),Rt(e)&&w.stampCenter&&(w.stampCenter=null,E=!0),E&&L()},[e,L]);return g.useEffect(()=>{de(),L();const w=se.current;if(!w)return;const E=new ResizeObserver(()=>{de(),L()});return E.observe(w),()=>{E.disconnect()}},[de,L]),g.useEffect(()=>{v||K(),L()},[v,L,K]),g.useEffect(()=>{xe.current!==e&&(xe.current=e,K(),L())},[e,K,L]),g.useEffect(()=>{L()},[f,X,O,L]),g.useEffect(()=>{if(k)return k.current=L,()=>{k.current===L&&(k.current=null)}},[k,L]),g.useEffect(()=>{if(!v)return;const w=E=>{E.key==="Escape"&&(K(),L())};return window.addEventListener("keydown",w),()=>{window.removeEventListener("keydown",w)}},[v,K,L]),Ye.jsx("canvas",{ref:se,className:Z,style:te,onPointerDown:Gt,onPointerMove:st,onPointerUp:_n,onPointerCancel:_n,onPointerLeave:bi,onContextMenu:w=>{v&&w.preventDefault()},onWheel:w=>{if(!v)return;const E=se.current,P=a.current;if(!E||typeof P?.zoomBy!="function")return;w.preventDefault(),w.stopPropagation();const F=E.getBoundingClientRect(),j=w.clientX-F.left,Ae=w.clientY-F.top;P.zoomBy(w.deltaY<0?To:_o,j,Ae),L()}})}const ti=g.createContext(null),bs=ti.Provider;function ot(){const e=g.useContext(ti);if(!e)throw new Error("useViewerContext must be used within a <WsiViewer>");return e}function ws({tool:e="cursor",stampOptions:t,brushOptions:n,fillColor:r,areaTooltip:i,onComplete:o,onPatchComplete:s,onBrushTap:a}){const{source:c,rendererRef:u,rendererSerial:h,setInteractionLock:l}=ot(),f=e!=="cursor";g.useEffect(()=>(l("drawing-layer",f),()=>l("drawing-layer",!1)),[f,l]);const d=g.useMemo(()=>u.current?.getViewState(),[h]);return c?Ye.jsx(ei,{tool:e,enabled:f,imageWidth:c.width,imageHeight:c.height,imageMpp:c.mpp,imageZoom:c.maxTierZoom,stampOptions:t,brushOptions:n,drawFillColor:r,projectorRef:u,onBrushTap:a,viewStateSignal:d,drawAreaTooltip:i,onDrawComplete:o,onPatchComplete:s}):null}const cr="__overlay_layer__";function xs({shapes:e}){const{rendererRef:t,source:n,registerDrawCallback:r,unregisterDrawCallback:i,requestOverlayRedraw:o}=ot(),s=g.useCallback(c=>{const u=t.current;if(!u||c.length===0)return[];const h=new Array(c.length);for(let l=0;l<c.length;l+=1){const f=Oe(u.worldToScreen(c[l][0],c[l][1]));if(!f)return[];h[l]=f}return h},[]),a=g.useRef({shapes:e,worldToScreenPoints:s,source:n});return a.current={shapes:e,worldToScreenPoints:s,source:n},g.useEffect(()=>(r(cr,30,u=>{const{shapes:h,worldToScreenPoints:l,source:f}=a.current;if(!Array.isArray(h)||h.length===0||!f)return;const d=l(Fe([[0,0],[f.width,0],[f.width,f.height],[0,f.height]]));Jr({ctx:u,overlayShapes:h,imageOuterRing:d,worldToScreenPoints:l,baseStrokeStyle:Xe})}),()=>i(cr)),[r,i]),g.useEffect(()=>{o()},[e,o]),null}function ur(e){return String(e??"").replace(/\/+$/,"")}function ni(e){const t=String(e??"");return t.startsWith("/")?t:`/${t}`}function Ss(e){const t=ur(e);if(!t)return"";if(/\/TileGroup\d+$/i.test(t))return t;let n=null;try{n=new URL(t)}catch{n=null}if(n){const r=`${n.protocol}//${n.host}`,i=ur(n.pathname||"");return/\/ims$/i.test(i)?`${r}${i}`:/\/tiles$/i.test(i)?`${r}${i}`:`${r}${i}/tiles`}return/\/ims$/i.test(t)?"/ims":/\/tiles$/i.test(t)?`${t}`:`${t}/tiles`}function Es(e,t){const n=e?.imsInfo??{},r=!!e?.imsInfo,i=Number(n.width??e?.width??0),o=Number(n.height??e?.height??0),s=Number(n.tileSize??e?.tileSize??0),a=Number(n.zoom??e?.zoom??0),c=String(n.path??e?.path??""),u=Number(n.mpp??e?.mpp??0);if(!i||!o||!s||!c)throw new Error("Incomplete image metadata: width/height/tileSize/path required");const h=Array.isArray(e?.terms)?e.terms.map(m=>({termId:String(m?.termId??""),termName:String(m?.termName??""),termColor:String(m?.termColor??"")})):[],l=ni(c),f=Ss(t),d=r?(m,p,y)=>`${f}${l}/${m}/${y}_${p}.webp`:void 0;return{id:e?._id||"unknown",name:e?.name||"unknown",width:i,height:o,mpp:Number.isFinite(u)&&u>0?u:void 0,tileSize:s,maxTierZoom:Number.isFinite(a)?Math.max(0,Math.floor(a)):0,tilePath:c,tileBaseUrl:t,terms:h,tileUrlBuilder:d}}function Pn(e,t,n,r){if(e.tileUrlBuilder)return e.tileUrlBuilder(t,n,r);const i=ni(e.tilePath);return`${e.tileBaseUrl}${i}/${t}/${r}_${n}.webp`}function Rs(e,t){if(!t)return!1;const n=new URL(e,typeof window<"u"?window.location.href:void 0).hostname.toLowerCase();return!(n.includes("amazonaws.com")||n.startsWith("s3.")||n.includes(".s3."))}const ke={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:"rgba(255, 106, 61, 0.95)",viewportBorderStyle:"dash",viewportFillColor:"transparent",interactive:!0,showThumbnail:!0,maxThumbnailTiles:16};function fr(e,t,n,r){const i=t.length;if(!(i<3)){for(let o=0;o<i;o+=1){const s=t[o],a=t[(o+1)%i],c=Math.hypot(a[0]-s[0],a[1]-s[1]);if(c<1e-6)continue;const u=Math.max(1,Math.round((c+r)/(n+r))),h=u*n+(u-1)*r,l=c/Math.max(1e-6,h),f=n*l,d=r*l;e.beginPath(),e.moveTo(s[0],s[1]),e.lineTo(a[0],a[1]),e.setLineDash([f,d]),e.lineDashOffset=0,e.stroke()}e.setLineDash([]),e.lineDashOffset=0}}function hr(e,t,n=1e-4){return Math.abs(e[0]-t[0])<=n&&Math.abs(e[1]-t[1])<=n}function dr(e){const t=[];for(const n of e){const r=t[t.length-1];(!r||!hr(r,n))&&t.push(n)}return t.length>1&&hr(t[0],t[t.length-1])&&t.pop(),t}function mr(e,t,n){const r=t[0]-e[0];if(Math.abs(r)<1e-6)return[n,e[1]];const i=(n-e[0])/r;return[n,e[1]+(t[1]-e[1])*i]}function gr(e,t,n){const r=t[1]-e[1];if(Math.abs(r)<1e-6)return[e[0],n];const i=(n-e[1])/r;return[e[0]+(t[0]-e[0])*i,n]}function Ms(e,t,n,r,i){let o=dr(e);if(o.length<3)return[];const s=[{inside:a=>a[0]>=t,intersect:(a,c)=>mr(a,c,t)},{inside:a=>a[0]<=r,intersect:(a,c)=>mr(a,c,r)},{inside:a=>a[1]>=n,intersect:(a,c)=>gr(a,c,n)},{inside:a=>a[1]<=i,intersect:(a,c)=>gr(a,c,i)}];for(const a of s){if(o.length===0)return[];const c=o;o=[];let u=c[c.length-1],h=a.inside(u);for(const l of c){const f=a.inside(l);f?(h||o.push(a.intersect(u,l)),o.push(l)):h&&o.push(a.intersect(u,l)),u=l,h=f}o=dr(o)}return o.length>=3?o:[]}function nt(e,t,n=1){return typeof e!="number"||!Number.isFinite(e)?t:Math.max(n,e)}function lt(e){return Array.isArray(e)&&e.length===4&&Number.isFinite(e[0])&&Number.isFinite(e[1])&&Number.isFinite(e[2])&&Number.isFinite(e[3])}const As={position:"absolute",top:4,right:4,zIndex:1,width:18,height:18,borderRadius:999,border:"1px solid rgba(255,255,255,0.4)",background:"rgba(16, 17, 19, 0.85)",color:"#fff",fontSize:12,lineHeight:1,cursor:"pointer",padding:0,display:"flex",alignItems:"center",justifyContent:"center"};function vs({source:e,projectorRef:t,authToken:n="",options:r,invalidateRef:i,className:o,style:s}){const a=g.useRef(null),c=g.useRef(null),u=g.useRef(null),h=g.useRef({active:!1,pointerId:null}),l=g.useRef(null),f=g.useRef(!1),d=nt(r?.width,ke.width,64),m=nt(r?.height,ke.height,48),p=g.useMemo(()=>{const M=Math.max(1,e.width),v=Math.max(1,e.height),X=M/v,le=d/m;let Q,ie;return X>le?(Q=d,ie=d/X):(ie=m,Q=m*X),{x:(d-Q)/2,y:(m-ie)/2,w:Q,h:ie}},[e.width,e.height,d,m]),y=nt(r?.margin,ke.margin,0),b=nt(r?.borderRadius,ke.borderRadius,0),x=nt(r?.borderWidth,ke.borderWidth,0),C=Math.max(1,Math.round(nt(r?.maxThumbnailTiles,ke.maxThumbnailTiles,1))),S=r?.backgroundColor||ke.backgroundColor,A=r?.borderColor||ke.borderColor,T=r?.viewportBorderColor||ke.viewportBorderColor,O=r?.viewportBorderStyle==="stroke"||r?.viewportBorderStyle==="dash"?r.viewportBorderStyle:ke.viewportBorderStyle,z=r?.viewportFillColor??ke.viewportFillColor,G=r?.interactive??ke.interactive,D=r?.showThumbnail??ke.showThumbnail,q=r?.position||ke.position,re=r?.onClose,I=r?.closeIcon,H=r?.closeButtonStyle,N=g.useMemo(()=>{const M={};return q==="top-left"||q==="bottom-left"?M.left=y:M.right=y,q==="top-left"||q==="top-right"?M.top=y:M.bottom=y,{position:"absolute",...M,width:d,height:m,borderRadius:b,overflow:"hidden",zIndex:4,pointerEvents:G?"auto":"none",touchAction:"none",boxShadow:"0 10px 22px rgba(0, 0, 0, 0.3)",...s}},[y,q,d,m,b,G,s]),k=g.useCallback(()=>{const M=a.current;if(!M)return;const v=M.getContext("2d");if(!v)return;const X=d,le=m,Q=Math.max(1,window.devicePixelRatio||1),ie=Math.max(1,Math.round(X*Q)),he=Math.max(1,Math.round(le*Q));(M.width!==ie||M.height!==he)&&(M.width=ie,M.height=he),v.setTransform(1,0,0,1,0,0),v.clearRect(0,0,M.width,M.height),v.setTransform(Q,0,0,Q,0,0),v.fillStyle=S,v.fillRect(0,0,X,le);const{x:me,y:$,w:pe,h:ye}=p,U=c.current;U&&v.drawImage(U,me,$,pe,ye),v.strokeStyle=A,v.lineWidth=x,v.strokeRect(x*.5,x*.5,X-x,le-x);const V=t.current,ee=V?.getViewBounds?.(),B=V?.getViewCorners?.(),te=Array.isArray(B)&&B.length>=4&&B.every(ce=>Array.isArray(ce)&&ce.length>=2&&Number.isFinite(ce[0])&&Number.isFinite(ce[1]))?B:null,de=lt(ee)?ee:lt(u.current)?u.current:null;lt(ee)&&(u.current=ee);const ae=pe/Math.max(1,e.width),Me=ye/Math.max(1,e.height),Se=O==="dash";if(te){const ce=te.map(ue=>[me+ue[0]*ae,$+ue[1]*Me]),ne=Ms(ce,me,$,me+pe,$+ye);if(ne.length>=3){v.beginPath();for(let ue=0;ue<ne.length;ue+=1)ue===0?v.moveTo(ne[ue][0],ne[ue][1]):v.lineTo(ne[ue][0],ne[ue][1]);v.closePath(),v.fillStyle=z,v.fill(),v.strokeStyle=T,v.lineWidth=2.25,Se?fr(v,ne,4,3):v.stroke();return}}if(!de)return;const _=W(me+de[0]*ae,me,me+pe),Y=W($+de[1]*Me,$,$+ye),J=W(me+de[2]*ae,me,me+pe),oe=W($+de[3]*Me,$,$+ye),L=Math.max(1,J-_),K=Math.max(1,oe-Y);if(v.fillStyle=z,v.fillRect(_,Y,L,K),v.strokeStyle=T,v.lineWidth=2.25,Se){const ce=[[_+.5,Y+.5],[_+.5+Math.max(1,L-1),Y+.5],[_+.5+Math.max(1,L-1),Y+.5+Math.max(1,K-1)],[_+.5,Y+.5+Math.max(1,K-1)]];fr(v,ce,4,3)}else v.strokeRect(_+.5,Y+.5,Math.max(1,L-1),Math.max(1,K-1))},[d,m,p,S,A,x,t,e.width,e.height,z,T,O]),Z=g.useCallback(()=>{f.current||(f.current=!0,l.current=requestAnimationFrame(()=>{f.current=!1,l.current=null,k()}))},[k]),we=g.useCallback((M,v)=>{const X=a.current;if(!X)return null;const le=X.getBoundingClientRect();if(!le.width||!le.height)return null;const Q=le.width/d,ie=le.height/m,he=p.x*Q,me=p.y*ie,$=p.w*Q,pe=p.h*ie,ye=W((M-le.left-he)/$,0,1),U=W((v-le.top-me)/pe,0,1);return[ye*e.width,U*e.height]},[e.width,e.height,d,m,p]),se=g.useCallback((M,v)=>{const X=t.current;if(!X)return;if(X.setViewCenter){X.setViewCenter(M,v),Z();return}const le=X.getViewBounds?.(),Q=lt(le)?le:lt(u.current)?u.current:null;if(!Q)return;const ie=Math.max(1e-6,Q[2]-Q[0]),he=Math.max(1e-6,Q[3]-Q[1]);X.setViewState({offsetX:M-ie*.5,offsetY:v-he*.5}),Z()},[t,Z]),Re=g.useCallback(M=>{if(!G||M.button!==0)return;const v=a.current;if(!v)return;const X=we(M.clientX,M.clientY);X&&(M.preventDefault(),M.stopPropagation(),v.setPointerCapture(M.pointerId),h.current={active:!0,pointerId:M.pointerId},se(X[0],X[1]))},[G,we,se]),Ce=g.useCallback(M=>{const v=h.current;if(!v.active||v.pointerId!==M.pointerId)return;const X=we(M.clientX,M.clientY);X&&(M.preventDefault(),M.stopPropagation(),se(X[0],X[1]))},[we,se]),xe=g.useCallback(M=>{const v=h.current;if(!v.active||v.pointerId!==M.pointerId)return;const X=a.current;if(X&&X.hasPointerCapture(M.pointerId))try{X.releasePointerCapture(M.pointerId)}catch{}h.current={active:!1,pointerId:null},Z()},[Z]);return g.useEffect(()=>{let M=!1;c.current=null,Z();const v=0,X=2**(e.maxTierZoom-v),le=Math.ceil(e.width/X),Q=Math.ceil(e.height/X),ie=Math.max(1,Math.ceil(le/e.tileSize)),he=Math.max(1,Math.ceil(Q/e.tileSize)),me=ie*he;if(!D||me>C)return;const $=document.createElement("canvas");$.width=Math.max(1,Math.round(p.w)),$.height=Math.max(1,Math.round(p.h));const pe=$.getContext("2d");if(!pe)return;pe.fillStyle=S,pe.fillRect(0,0,$.width,$.height);const ye=[];for(let U=0;U<he;U+=1)for(let V=0;V<ie;V+=1){const ee=V*e.tileSize*X,B=U*e.tileSize*X,te=Math.min((V+1)*e.tileSize,le)*X,de=Math.min((U+1)*e.tileSize,Q)*X;ye.push({url:Pn(e,v,V,U),bounds:[ee,B,te,de]})}return Promise.allSettled(ye.map(async U=>{const V=Rs(U.url,n),ee=await fetch(U.url,{headers:V?{Authorization:n}:void 0});if(!ee.ok)throw new Error(`HTTP ${ee.status}`);const B=await createImageBitmap(await ee.blob());return{tile:U,bitmap:B}})).then(U=>{if(M){for(const B of U)B.status==="fulfilled"&&B.value.bitmap.close();return}const V=$.width/Math.max(1,e.width),ee=$.height/Math.max(1,e.height);for(const B of U){if(B.status!=="fulfilled")continue;const{tile:{bounds:te},bitmap:de}=B.value,ae=te[0]*V,Me=te[1]*ee,Se=Math.max(1,(te[2]-te[0])*V),_=Math.max(1,(te[3]-te[1])*ee);pe.drawImage(de,ae,Me,Se,_),de.close()}c.current=$,Z()}),()=>{M=!0}},[e,n,p,S,D,C,Z]),g.useEffect(()=>{Z()},[Z]),g.useEffect(()=>{if(i)return i.current=Z,()=>{i.current===Z&&(i.current=null)}},[i,Z]),g.useEffect(()=>()=>{h.current={active:!1,pointerId:null},l.current!==null&&(cancelAnimationFrame(l.current),l.current=null),f.current=!1},[]),Ye.jsxs("div",{className:o,style:N,children:[Ye.jsx("canvas",{ref:a,style:{width:"100%",height:"100%",display:"block",borderRadius:"inherit"},onPointerDown:Re,onPointerMove:Ce,onPointerUp:xe,onPointerCancel:xe,onContextMenu:M=>{M.preventDefault()},onWheel:M=>{M.preventDefault(),M.stopPropagation()}}),re&&Ye.jsx("button",{type:"button","aria-label":"Hide overview map",onClick:M=>{M.stopPropagation(),re()},style:H?{...H}:{...As},children:I??"×"})]})}const pr="__patch_layer__",Cs=[];function Is({regions:e,strokeStyle:t}){const{rendererRef:n,registerDrawCallback:r,unregisterDrawCallback:i,requestOverlayRedraw:o}=ot(),s=e??Cs,a=g.useMemo(()=>Ve(Vr,t),[t]),c=g.useMemo(()=>{const l=[];for(let f=0;f<s.length;f+=1){const d=s[f],m=Wt(d.coordinates);m.length!==0&&l.push({region:d,regionIndex:f,regionKey:d.id??f,polygons:m})}return l},[s]),u=g.useCallback(l=>{const f=n.current;if(!f||l.length===0)return[];const d=new Array(l.length);for(let m=0;m<l.length;m+=1){const p=Oe(f.worldToScreen(l[m][0],l[m][1]));if(!p)return[];d[m]=p}return d},[]),h=g.useRef({prepared:c,resolvedStrokeStyle:a,worldToScreenPoints:u});return h.current={prepared:c,resolvedStrokeStyle:a,worldToScreenPoints:u},g.useEffect(()=>(r(pr,20,f=>{const{prepared:d,resolvedStrokeStyle:m,worldToScreenPoints:p}=h.current;for(const y of d)for(const b of y.polygons){const x=p(b.outer);x.length>=4&&Pe(f,x,m,!0,!1);for(const C of b.holes){const S=p(C);S.length>=4&&Pe(f,S,m,!0,!1)}}}),()=>i(pr)),[r,i]),g.useEffect(()=>{o()},[c,a,o]),null}function dt(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return null;const n=yt(t??[]);if(n.length===0){const m={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return e.fillModes instanceof Uint8Array&&(m.fillModes=new Uint8Array(0)),e.ids instanceof Uint32Array&&(m.ids=new Uint32Array(0)),m}const r=et(e),i=e.positions,o=e.paletteIndices,s=e.fillModes instanceof Uint8Array&&e.fillModes.length>=r?e.fillModes:null,a=e.ids instanceof Uint32Array&&e.ids.length>=r?e.ids:null,c=new Float32Array(r*2),u=new Uint16Array(r),h=s?new Uint8Array(r):null,l=a?new Uint32Array(r):null;let f=0;for(let m=0;m<r;m+=1){const p=i[m*2],y=i[m*2+1];zt(p,y,n)&&(c[f*2]=p,c[f*2+1]=y,u[f]=o[m],h&&(h[f]=s[m]),l&&(l[f]=a[m]),f+=1)}const d={count:f,positions:c.subarray(0,f*2),paletteIndices:u.subarray(0,f)};return h&&(d.fillModes=h.subarray(0,f)),l&&(d.ids=l.subarray(0,f)),d}function ri(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return new Uint32Array(0);const n=yt(t??[]);if(n.length===0)return new Uint32Array(0);const r=et(e);if(r===0)return new Uint32Array(0);const i=e.positions,o=new Uint32Array(r);let s=0;for(let a=0;a<r;a+=1){const c=i[a*2],u=i[a*2+1];zt(c,u,n)&&(o[s]=a,s+=1)}return o.subarray(0,s)}let Mt=null;const Ps=`
34
34
  struct Params {
35
35
  pointCount: u32,
36
36
  boundsCount: u32,
@@ -61,7 +61,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
61
61
  }
62
62
  outputMask[i] = inside;
63
63
  }
64
- `;function Is(){if(typeof navigator>"u")return!1;const e=navigator;return typeof e.gpu=="object"&&e.gpu!==null}function ii(){if(!Is())return null;const t=navigator.gpu;if(!t||typeof t!="object")return null;const n=t;return typeof n.requestAdapter!="function"?null:n}const At=globalThis.GPUShaderStage?.COMPUTE??4,Qt=globalThis.GPUBufferUsage?.STORAGE??128,vt=globalThis.GPUBufferUsage?.COPY_DST??8,_s=globalThis.GPUBufferUsage?.COPY_SRC??4,Fs=globalThis.GPUBufferUsage?.UNIFORM??64,Ls=globalThis.GPUBufferUsage?.MAP_READ??1,ks=globalThis.GPUMapMode?.READ??1;async function Ns(){const e=ii();if(!e)return{supported:!1,features:[]};const t=await e.requestAdapter();return t?{supported:!0,adapterName:t.info?.description??t.info?.vendor??"unknown",features:Array.from(t.features),limits:{maxStorageBufferBindingSize:Number(t.limits.maxStorageBufferBindingSize),maxComputeInvocationsPerWorkgroup:Number(t.limits.maxComputeInvocationsPerWorkgroup),maxComputeWorkgroupSizeX:Number(t.limits.maxComputeWorkgroupSizeX)}}:{supported:!1,features:[]}}async function Bs(){return Mt||(Mt=(async()=>{const e=ii();if(!e)return null;const t=await e.requestAdapter();if(!t)return null;const n=await t.requestDevice(),r=n.createBindGroupLayout({entries:[{binding:0,visibility:At,buffer:{type:"read-only-storage"}},{binding:1,visibility:At,buffer:{type:"read-only-storage"}},{binding:2,visibility:At,buffer:{type:"storage"}},{binding:3,visibility:At,buffer:{type:"uniform"}}]}),i=n.createComputePipeline({layout:n.createPipelineLayout({bindGroupLayouts:[r]}),compute:{module:n.createShaderModule({code:Ts}),entryPoint:"main"}});return{device:n,pipeline:i,bindGroupLayout:r}})(),Mt)}function Ct(e,t){return Math.ceil(e/t)*t}async function oi(e,t,n){const r=await Bs();if(!r)return null;const i=Math.max(0,Math.floor(t)),o=Math.max(0,Math.floor(n.length/4));if(i===0||o===0)return new Uint32Array(0);const s=Math.min(i,Math.floor(e.length/2));if(s===0)return new Uint32Array(0);const a=s*2*Float32Array.BYTES_PER_ELEMENT,c=o*4*Float32Array.BYTES_PER_ELEMENT,u=s*Uint32Array.BYTES_PER_ELEMENT,h=Number(r.device.limits.maxStorageBufferBindingSize);if(a>h||c>h||u>h)return null;const l=r.device.createBuffer({size:Ct(a,4),usage:Qt|vt}),f=r.device.createBuffer({size:Ct(c,4),usage:Qt|vt}),d=r.device.createBuffer({size:Ct(u,4),usage:Qt|_s}),m=r.device.createBuffer({size:16,usage:Fs|vt}),p=r.device.createBuffer({size:Ct(u,4),usage:vt|Ls});let y=!1;try{r.device.queue.writeBuffer(l,0,e.buffer,e.byteOffset,a),r.device.queue.writeBuffer(f,0,n.buffer,n.byteOffset,c),r.device.queue.writeBuffer(m,0,new Uint32Array([s,o,0,0]));const b=r.device.createBindGroup({layout:r.bindGroupLayout,entries:[{binding:0,resource:{buffer:l}},{binding:1,resource:{buffer:f}},{binding:2,resource:{buffer:d}},{binding:3,resource:{buffer:m}}]}),x=r.device.createCommandEncoder(),C=x.beginComputePass();C.setPipeline(r.pipeline),C.setBindGroup(0,b),C.dispatchWorkgroups(Math.ceil(s/256)),C.end(),x.copyBufferToBuffer(d,0,p,0,u),r.device.queue.submit([x.finish()]),await p.mapAsync(ks),y=!0;const S=p.getMappedRange();return new Uint32Array(S.slice(0))}finally{if(y)try{p.unmap()}catch{}l.destroy(),f.destroy(),d.destroy(),m.destroy(),p.destroy()}}async function si(e,t,n={}){const r=be(),i=n.bridgeToDraw===!0;if(!e||!e.count||!e.positions||!e.paletteIndices)return{data:null,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}};const o=yt(t??[]);if(o.length===0){const S={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return e.fillModes instanceof Uint8Array&&(S.fillModes=new Uint8Array(0)),e.ids instanceof Uint32Array&&(S.ids=new Uint32Array(0)),{data:S,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const s=et(e),a=e.fillModes instanceof Uint8Array&&e.fillModes.length>=s?e.fillModes:null,c=e.ids instanceof Uint32Array&&e.ids.length>=s?e.ids:null;if(s===0){const S={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(S.fillModes=new Uint8Array(0)),c&&(S.ids=new Uint32Array(0)),{data:S,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const u=new Float32Array(o.length*4);for(let S=0;S<o.length;S+=1){const A=S*4,I=o[S];u[A]=I.minX,u[A+1]=I.minY,u[A+2]=I.maxX,u[A+3]=I.maxY}let h=null,l=!1;try{h=await oi(e.positions,s,u),l=!!h}catch{h=null,l=!1}if(!h)return{data:dt(e,t),meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!1,candidateCount:s,bridgedToDraw:!1}};let f=0;for(let S=0;S<s;S+=1)h[S]===1&&(f+=1);const d=new Uint32Array(f);if(f>0){let S=0;for(let A=0;A<s;A+=1)h[A]===1&&(d[S]=A,S+=1)}if(f===0){if(i){const A={count:s,positions:e.positions.subarray(0,s*2),paletteIndices:e.paletteIndices.subarray(0,s),drawIndices:new Uint32Array(0)};return a&&(A.fillModes=a.subarray(0,s)),c&&(A.ids=c.subarray(0,s)),{data:A,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!0}}}const S={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(S.fillModes=new Uint8Array(0)),c&&(S.ids=new Uint32Array(0)),{data:S,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const S=new Uint32Array(f);let A=0;for(let O=0;O<f;O+=1){const z=d[O]??0,G=e.positions[z*2],D=e.positions[z*2+1];zt(G,D,o)&&(S[A]=z,A+=1)}const I={count:s,positions:e.positions.subarray(0,s*2),paletteIndices:e.paletteIndices.subarray(0,s),drawIndices:S.subarray(0,A)};return a&&(I.fillModes=a.subarray(0,s)),c&&(I.ids=c.subarray(0,s)),{data:I,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!0,candidateCount:f,bridgedToDraw:!0}}}const m=new Float32Array(f*2),p=new Uint16Array(f),y=a?new Uint8Array(f):null,b=c?new Uint32Array(f):null;let x=0;for(let S=0;S<f;S+=1){const A=d[S]??0,I=e.positions[A*2],O=e.positions[A*2+1];zt(I,O,o)&&(m[x*2]=I,m[x*2+1]=O,p[x]=e.paletteIndices[A],y&&(y[x]=a[A]),b&&(b[x]=c[A]),x+=1)}const C={count:x,positions:m.subarray(0,x*2),paletteIndices:p.subarray(0,x)};return y&&(C.fillModes=y.subarray(0,x)),b&&(C.ids=b.subarray(0,x)),{data:C,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!0,candidateCount:f,bridgedToDraw:!1}}}class ai{constructor(t,n){R(this,"worker",null);R(this,"supported",!0);R(this,"requestId",1);R(this,"pendingById",new Map);R(this,"handleMessage",t=>{const n=t.data;if(!n)return;const r=this.pendingById.get(n.id);r&&(this.pendingById.delete(n.id),this.handlers.onResponse(n,r))});R(this,"handleError",()=>{this.supported=!1,this.teardownWorker("worker crashed")});this.createWorker=t,this.handlers=n}beginRequest(t){const n=this.getOrCreateWorker();if(!n)return null;const r=this.requestId++;return this.pendingById.set(r,t),{id:r,worker:n}}cancelRequest(t){const n=this.pendingById.get(t);if(n)return this.pendingById.delete(t),n}terminate(t="worker terminated"){this.teardownWorker(t)}getOrCreateWorker(){if(!this.supported)return null;if(this.worker)return this.worker;try{const t=this.createWorker();return t.addEventListener("message",this.handleMessage),t.addEventListener("error",this.handleError),this.worker=t,t}catch{return this.supported=!1,null}}teardownWorker(t){this.worker&&(this.worker.removeEventListener("message",this.handleMessage),this.worker.removeEventListener("error",this.handleError),this.worker.terminate(),this.worker=null);const n=new Error(t);for(const[,r]of this.pendingById)this.handlers.rejectPending(r,n);this.pendingById.clear()}}const mt=new ai(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/roi-clip-worker-BuNuUQQg.js").href:new URL("assets/roi-clip-worker-BuNuUQQg.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:it&&it.tagName.toUpperCase()==="SCRIPT"&&it.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(e,t)=>{if(e.type==="roi-clip-failure"){t.reject(new Error(e.error||"worker clip failed"));return}if(e.type==="roi-clip-index-success"){if(t.kind!=="index"){t.reject(new Error("worker response mismatch: expected point data result"));return}const c=Math.max(0,Math.floor(e.count)),u=new Uint32Array(e.indices).subarray(0,c);t.resolve({indices:u,meta:{mode:"worker",durationMs:Number.isFinite(e.durationMs)?e.durationMs:be()-t.startMs}});return}if(t.kind!=="data"){t.reject(new Error("worker response mismatch: expected index result"));return}const n=Math.max(0,Math.floor(e.count)),r=new Float32Array(e.positions),i=new Uint16Array(e.paletteIndices),o=e.fillModes?new Uint8Array(e.fillModes):null,s=e.ids?new Uint32Array(e.ids):null,a={count:n,positions:r.subarray(0,n*2),paletteIndices:i.subarray(0,n)};o&&(a.fillModes=o.subarray(0,n)),s&&(a.ids=s.subarray(0,n)),t.resolve({data:a,meta:{mode:"worker",durationMs:Number.isFinite(e.durationMs)?e.durationMs:be()-t.startMs}})},rejectPending:(e,t)=>{e.reject(t)}});function zs(){mt.terminate("worker terminated")}async function li(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return{data:null,meta:{mode:"worker",durationMs:0}};const n=et(e),r=e.positions.slice(0,n*2),i=e.paletteIndices.slice(0,n),o=e.fillModes instanceof Uint8Array&&e.fillModes.length>=n?e.fillModes.slice(0,n):null,s=e.ids instanceof Uint32Array&&e.ids.length>=n?e.ids.slice(0,n):null;return new Promise((a,c)=>{const u=be(),h=mt.beginRequest({kind:"data",resolve:a,reject:c,startMs:u});if(!h){a({data:dt(e,t),meta:{mode:"sync",durationMs:be()-u}});return}const l={type:"roi-clip-request",id:h.id,count:n,positions:r.buffer,paletteIndices:i.buffer,fillModes:o?.buffer,ids:s?.buffer,polygons:t??[]},f=[r.buffer,i.buffer];o&&f.push(o.buffer),s&&f.push(s.buffer);try{h.worker.postMessage(l,f)}catch(d){const m=mt.cancelRequest(h.id);m?m.reject(d):c(d)}})}async function Ds(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return{indices:new Uint32Array(0),meta:{mode:"worker",durationMs:0}};const n=et(e),r=e.positions.slice(0,n*2);return new Promise((i,o)=>{const s=be(),a=mt.beginRequest({kind:"index",resolve:i,reject:o,startMs:s});if(!a){i({indices:ri(e,t),meta:{mode:"sync",durationMs:be()-s}});return}const c={type:"roi-clip-index-request",id:a.id,count:n,positions:r.buffer,polygons:t??[]};try{a.worker.postMessage(c,[r.buffer])}catch(u){const h=mt.cancelRequest(a.id);h?h.reject(u):o(u)}})}const Us={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};function Os(e,t,n,r,i){const o=g.useRef(0),[s,a]=g.useState(n),c=g.useMemo(()=>r.map(u=>pt(u.coordinates)).filter(u=>u!=null),[r]);return g.useEffect(()=>{const u=++o.current;let h=!1;if(!e)return a(n),()=>{h=!0};if(!n||!n.count||!n.positions||!n.paletteIndices)return a(null),()=>{h=!0};if(c.length===0)return a(Us),i?.({mode:t,durationMs:0,inputCount:n.count,outputCount:0,polygonCount:0}),()=>{h=!0};const l=(d,m)=>{if(h||u!==o.current)return;const p=n.count,y=d?.drawIndices?d.drawIndices.length:d?.count??0;a(d),i?.({mode:m.mode,durationMs:m.durationMs,inputCount:p,outputCount:y,polygonCount:c.length,usedWebGpu:m.usedWebGpu,candidateCount:m.candidateCount,bridgedToDraw:m.bridgedToDraw})};return(async()=>{if(t==="sync"){const d=performance.now(),m=dt(n,c);l(m,{mode:"sync",durationMs:performance.now()-d});return}if(t==="hybrid-webgpu"){const d=await si(n,c,{bridgeToDraw:!0});l(d.data,{mode:d.meta.mode,durationMs:d.meta.durationMs,usedWebGpu:d.meta.usedWebGpu,candidateCount:d.meta.candidateCount,bridgedToDraw:d.meta.bridgedToDraw});return}try{const d=await li(n,c);l(d.data,{mode:d.meta.mode,durationMs:d.meta.durationMs})}catch{const d=performance.now(),m=dt(n,c);l(m,{mode:"sync",durationMs:performance.now()-d})}})(),()=>{h=!0}},[e,t,n,c,i]),s}const Ys=24,Ws=1024,Xs=4,Lt=-1;function ct(e,t,n){return(e*73856093^t*19349663)>>>0&n}function Vs(e,t,n){if(e<=0||t<=0||n<=0)return 256;const r=Math.max(1,e*t),o=Math.sqrt(r/Math.max(1,n))*Xs;return Math.max(Ys,Math.min(Ws,o))}function Gs(e,t){if(!(e instanceof Uint32Array)||e.length===0)return null;let n=!0;for(let o=0;o<e.length;o+=1)if(!(e[o]<t)){n=!1;break}if(n)return e;const r=new Uint32Array(e.length);let i=0;for(let o=0;o<e.length;o+=1)e[o]>=t||(r[i]=e[o],i+=1);return i>0?r.subarray(0,i):null}function qs(e){const t=Math.max(0,Math.floor(e.count)),n=Math.floor(e.positions.length/2),r=Math.max(0,Math.min(t,n));if(r<=0)return null;const i=Gs(e.drawIndices??null,r),o=i?i.length:r;if(o===0)return null;const s=Vs(e.sourceWidth,e.sourceHeight,o),a=1/s,c=new Int32Array(o),u=new Int32Array(o);let h=0;if(i)for(let P=0;P<o;P+=1){const H=i[P],N=e.positions[H*2],k=e.positions[H*2+1];!Number.isFinite(N)||!Number.isFinite(k)||(c[h]=Math.floor(N*a),u[h]=Math.floor(k*a),h+=1)}else for(let P=0;P<r;P+=1){const H=e.positions[P*2],N=e.positions[P*2+1];!Number.isFinite(H)||!Number.isFinite(N)||(c[h]=Math.floor(H*a),u[h]=Math.floor(N*a),h+=1)}if(h===0)return null;let l=Math.min(h,Math.max(64,h>>>3));(!Number.isFinite(l)||l<=0)&&(l=h);let f=1;for(;f<l*2;)f<<=1;let d=f-1,m=new Int32Array(f*2),p=new Int32Array(f);m.fill(2147483647);let y=0;const b=new Int32Array(h);for(let P=0;P<h;P+=1){const H=c[P],N=u[P];let k=ct(H,N,d);for(;;){const Z=m[k*2];if(Z===2147483647){if(m[k*2]=H,m[k*2+1]=N,p[k]=1,b[P]=k,y+=1,y*4>f*3){const we=f;f<<=1,d=f-1;const se=new Int32Array(f*2),Re=new Int32Array(f);se.fill(2147483647);for(let Ce=0;Ce<we;Ce+=1){if(m[Ce*2]===2147483647)continue;const xe=m[Ce*2],M=m[Ce*2+1];let v=ct(xe,M,d);for(;se[v*2]!==2147483647;)v=v+1&d;se[v*2]=xe,se[v*2+1]=M,Re[v]=p[Ce]}for(m=se,p=Re,k=ct(H,N,d);m[k*2]!==H||m[k*2+1]!==N;)k=k+1&d;b[P]=k}break}if(Z===H&&m[k*2+1]===N){p[k]+=1,b[P]=k;break}k=k+1&d}}const x=new Int32Array(y*2),C=new Uint32Array(y),S=new Uint32Array(y),A=new Int32Array(f);A.fill(Lt);let I=0,O=0;for(let P=0;P<f;P+=1)m[P*2]!==2147483647&&(x[I*2]=m[P*2],x[I*2+1]=m[P*2+1],C[I]=O,S[I]=p[P],A[P]=I,O+=p[P],I+=1);const z=new Uint32Array(h),G=new Uint32Array(y);if(G.set(C),i)for(let P=0;P<h;P+=1){const H=A[b[P]];z[G[H]]=i[P],G[H]+=1}else{let P=0;for(let H=0;H<r;H+=1){const N=e.positions[H*2],k=e.positions[H*2+1];if(!Number.isFinite(N)||!Number.isFinite(k))continue;const Z=A[b[P]];z[G[Z]]=H,G[Z]+=1,P+=1}}let D=1;for(;D<y*2;)D<<=1;const q=D-1,re=new Int32Array(D);re.fill(Lt);for(let P=0;P<y;P+=1){const H=x[P*2],N=x[P*2+1];let k=ct(H,N,q);for(;re[k]!==Lt;)k=k+1&q;re[k]=P}return{cellSize:s,safeCount:r,cellCount:y,hashCapacity:D,hashTable:re,cellKeys:x,cellOffsets:C,cellLengths:S,pointIndices:z}}function ci(e,t,n){const{hashTable:r,cellKeys:i,hashMask:o}=e;let s=ct(t,n,o);for(;;){const a=r[s];if(a===Lt)return-1;if(i[a*2]===t&&i[a*2+1]===n)return a;s=s+1&o}}function Hs(e,t){if(e.safeCount<=0||e.cellCount<=0)return null;const n=e.safeCount;return{cellSize:e.cellSize,safeCount:n,positions:t.positions.subarray(0,n*2),ids:t.ids instanceof Uint32Array&&t.ids.length>=n?t.ids.subarray(0,n):null,hashCapacity:e.hashCapacity,hashMask:e.hashCapacity-1,hashTable:new Int32Array(e.hashTable),cellKeys:new Int32Array(e.cellKeys),cellOffsets:new Uint32Array(e.cellOffsets),cellLengths:new Uint32Array(e.cellLengths),pointIndices:new Uint32Array(e.pointIndices)}}const hn=new ai(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/point-hit-index-worker-CNFA6pZm.js").href:new URL("assets/point-hit-index-worker-CNFA6pZm.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:it&&it.tagName.toUpperCase()==="SCRIPT"&&it.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(e,t)=>{if(e.type==="point-hit-index-failure"){t.reject(new Error(e.error||"worker index build failed"));return}t.resolve(Hs(e,t.pointData))},rejectPending:(e,t)=>{e.reject(t)}});function Zs(){hn.terminate("worker terminated")}function $s(e,t){const n=et(e);if(n<=0)return null;const r=e.positions.subarray(0,n*2),i=qs({count:n,positions:r,drawIndices:e.drawIndices instanceof Uint32Array?e.drawIndices:null,sourceWidth:t?.width??0,sourceHeight:t?.height??0});return i?{cellSize:i.cellSize,safeCount:n,positions:r,ids:e.ids instanceof Uint32Array&&e.ids.length>=n?e.ids.subarray(0,n):null,hashCapacity:i.hashCapacity,hashMask:i.hashCapacity-1,hashTable:i.hashTable,cellKeys:i.cellKeys,cellOffsets:i.cellOffsets,cellLengths:i.cellLengths,pointIndices:i.pointIndices}:null}async function ui(e,t){if(!e||!e.positions||!e.paletteIndices)return null;const n=et(e);return n<=0?null:new Promise((r,i)=>{const o={resolve:r,reject:i,pointData:e},s=hn.beginRequest(o);if(!s||!s.worker){r($s(e,t));return}const a=e.positions.slice(0,n*2),c=e.drawIndices instanceof Uint32Array&&e.drawIndices.length>0?e.drawIndices.slice():void 0,u={type:"point-hit-index-request",id:s.id,count:n,positions:a.buffer,drawIndices:c?.buffer,sourceWidth:t?.width??0,sourceHeight:t?.height??0},h=[a.buffer];c&&h.push(c.buffer);try{s.worker.postMessage(u,h)}catch(l){const f=hn.cancelRequest(s.id);f?f.reject(l):i(l)}})}const Ks=.65,js=4;function Qs(e,t,n,r,i,o,s){const a=!!(n||r||i),[c,u]=g.useState(null),h=g.useRef(null),l=g.useRef(null);g.useEffect(()=>{if(!a||!e){u(null);return}let p=!1;return ui(e,t).then(y=>{p||u(y)}),()=>{p=!0}},[a,e,t]);const f=g.useCallback(p=>{const y=s.current;if(!y||!c)return null;const b=Number(p[0]),x=Number(p[1]);if(!Number.isFinite(b)||!Number.isFinite(x))return null;const C=Math.max(1e-6,y.getViewState().zoom),S=y.getPointSizeByZoom(),I=Math.max(js,S*Ks)/C;if(!Number.isFinite(I)||I<=0)return null;const{cellSize:O,cellOffsets:z,cellLengths:G,pointIndices:D,positions:q,safeCount:re}=c,P=Math.floor(b/O),H=Math.floor(x/O),N=Math.max(1,Math.ceil(I/O)),k=I*I;let Z=-1,we=k,se=0,Re=0;for(let xe=P-N;xe<=P+N;xe+=1)for(let M=H-N;M<=H+N;M+=1){const v=ci(c,xe,M);if(v<0)continue;const X=z[v],le=X+G[v];for(let Q=X;Q<le;Q+=1){const ie=D[Q];if(ie>=re)continue;const he=q[ie*2],me=q[ie*2+1],$=he-b,pe=me-x,ye=$*$+pe*pe;ye>we||(we=ye,Z=ie,se=he,Re=me)}}if(Z<0)return null;const Ce=c.ids?Number(c.ids[Z]):null;return{index:Z,id:Ce,coordinate:[b,x],pointCoordinate:[se,Re]}},[c]),d=g.useCallback((p,y)=>{if(!n)return;const b=p?.index??null,x=p?.id??null;h.current===b&&l.current===x||(h.current=b,l.current=x,n({index:b,id:x,coordinate:y,pointCoordinate:p?.pointCoordinate??null}))},[n]),m=g.useCallback((p,y)=>{if(!r)return;const b=f(p);b&&r({...b,button:y})},[r,f]);return g.useEffect(()=>{if(i)return i.current=f,()=>{i.current===f&&(i.current=null)}},[i,f]),g.useEffect(()=>{const p=h.current;p!==null&&(c&&p<c.safeCount||(h.current=null,l.current=null,n?.({index:null,id:null,coordinate:null,pointCoordinate:null})))},[c,n]),g.useEffect(()=>{},[o,n]),{getCellByCoordinates:f,emitPointHover:d,emitPointClick:m}}const Js=g.forwardRef(function({data:t=null,palette:n=null,sizeByZoom:r,strokeScale:i,innerFillOpacity:o,clipEnabled:s=!1,clipToRegions:a,clipMode:c="worker",onClipStats:u,onHover:h,onClick:l},f){const{rendererRef:d,rendererSerial:m,source:p}=ot(),y=g.useRef(null),x=Os(s,c,t,a??ea,u),{getCellByCoordinates:C}=Qs(x,p,h,l,y,"cursor",d);return g.useImperativeHandle(f,()=>({queryAt:C}),[C]),g.useEffect(()=>{const S=d.current;!S||!n||S.setPointPalette(n)},[m,n]),g.useEffect(()=>{const S=d.current;!S||r===void 0||S.setPointSizeByZoom(r)},[m,r]),g.useEffect(()=>{const S=d.current;!S||i===void 0||S.setPointStrokeScale(i)},[m,i]),g.useEffect(()=>{const S=d.current;!S||o===void 0||S.setPointInnerFillOpacity(o)},[m,o]),g.useEffect(()=>{const S=d.current;S&&S.setPointData(x)},[m,x]),null}),ea=[],ta=180,yr=20;function na(e){const t=W(e,0,1);return t*t*(3-2*t)}function ra(e,t,n){const[r,i]=g.useState(0),o=g.useRef(0),s=g.useRef({rafId:null,startMs:0,from:0,to:0}),a=g.useCallback(l=>{const f=W(l,0,yr);Math.abs(o.current-f)<1e-4||(o.current=f,i(f))},[]),c=g.useCallback(()=>{const l=s.current;l.rafId!==null&&(cancelAnimationFrame(l.rafId),l.rafId=null)},[]),u=g.useCallback(l=>{const f=W(l,0,yr),d=s.current,m=o.current;if(Math.abs(m-f)<1e-4){c(),d.to=f,a(f);return}c(),d.startMs=performance.now(),d.from=m,d.to=f;const p=y=>{const b=s.current,x=Math.max(0,y-b.startMs),C=W(x/ta,0,1),S=na(C),A=b.from+(b.to-b.from)*S;if(a(A),n.current?.(),C>=1){b.rafId=null,a(b.to);return}b.rafId=requestAnimationFrame(p)};d.rafId=requestAnimationFrame(p)},[a,c]),h=g.useCallback(l=>{const f=t.current;if(!f||typeof l!="number"||!Number.isFinite(l)){u(0);return}const d=Pn(e,l,f.getZoomRange());u(d)},[e,u]);return g.useEffect(()=>()=>{c()},[c]),{regionLabelAutoLiftOffsetPx:r,syncRegionLabelAutoLiftTarget:h,cancelRegionLabelAutoLiftAnimation:c,applyRegionLabelAutoLiftOffset:a}}const ia=6;function dn(e,t){return e.id??t}function oa(e,t,n,r,i,o){const s=i-n,a=o-r,c=s*s+a*a;if(c<=1e-12){const m=e-n,p=t-r;return m*m+p*p}const u=W(((e-n)*s+(t-r)*a)/c,0,1),h=n+s*u,l=r+a*u,f=e-h,d=t-l;return f*f+d*d}function br(e,t,n,r){for(let i=1;i<n.length;i+=1){const o=n[i-1],s=n[i];if(oa(e,t,o[0],o[1],s[0],s[1])<=r)return!0}return!1}function sa(e,t,n,r){if(e<n.minX-r||e>n.maxX+r||t<n.minY-r||t>n.maxY+r)return!1;const i=r*r;if(br(e,t,n.outer,i))return!0;for(const o of n.holes)if(br(e,t,o,i))return!0;return!1}function aa(e,t,n,r,i,o,s){if(!e.label||!e.labelAnchor)return!1;const a=En(n.worldToScreen(e.labelAnchor[0],e.labelAnchor[1]));if(!a)return!1;const u=Mn(e.label,r)+r.paddingX*2,h=r.fontSize+r.paddingY*2,l=a[0],f=a[1]-r.offsetY,d=s?W(l,u*.5+1,i-u*.5-1):l,m=s?W(f,h*.5+1,o-h*.5-1):f,p=d-u*.5,y=d+u*.5,b=m-h*.5,x=m+h*.5;return t[0]>=p&&t[0]<=y&&t[1]>=b&&t[1]<=x}function la(e,t="top-center"){const n=[];for(let r=0;r<e.length;r+=1){const i=e[r],o=yt([pt(i?.coordinates)]);if(o.length===0)continue;const s=typeof i?.label=="string"?i.label.trim():"";n.push({region:i,regionIndex:r,regionId:dn(i,r),polygons:o,label:s,labelAnchor:s?An(o,t):null})}return n}function wr(e,t,n,r,i,o,s,a,c,u=!0){const h=e[0],l=e[1],f=Math.max(1e-6,r.getViewState().zoom),d=Math.max(0,s),m=ia/f;for(let p=n.length-1;p>=0;p-=1){const y=n[p];for(const x of y.polygons)if(sa(h,l,x,m))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId};let b=Cn(i,o?.({region:y.region,regionId:y.regionId,regionIndex:y.regionIndex,zoom:f}));if(d>0&&(b={...b,offsetY:b.offsetY+d}),!!aa(y,t,r,b,a,c,u))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId}}return null}const xr=[],ca=[],Sr="__region_layer__",Er="__region_label__";function ua(e){return{color:Gr,width:qr,lineDash:Je,lineJoin:e.lineJoin,lineCap:e.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function fa({regions:e,polygons:t,strokeStyle:n,hoverStrokeStyle:r,activeStrokeStyle:i,resolveStrokeStyle:o,labelStyle:s,labelAnchor:a="top-center",autoLiftLabelAtMaxZoom:c=!1,clampLabelToViewport:u=!0,activeRegionId:h,onActiveChange:l,onHover:f,onClick:d}){const{rendererRef:m,rendererSerial:p,canvasRef:y,containerRef:b,registerDrawCallback:x,unregisterDrawCallback:C,requestOverlayRedraw:S,drawInvalidateRef:A,screenToWorld:I,worldToScreen:O,isInteractionLocked:z}=ot(),G=e??xr,D=t??ca,q=g.useMemo(()=>G.length>0?G:D.length===0?xr:D.map((U,V)=>({id:V,coordinates:U})),[G,D]),[re,P]=g.useState(null),[H,N]=g.useState(()=>h??null),k=h!==void 0,Z=k?h??null:H,we=g.useRef(null);g.useEffect(()=>{k&&N(h??null)},[k,h]);const se=g.useCallback(U=>{String(Z)!==String(U)&&(k||N(U),l?.(U))},[Z,k,l]),{regionLabelAutoLiftOffsetPx:Re,syncRegionLabelAutoLiftTarget:Ce}=ra(c,m,A),xe=g.useMemo(()=>Rn(n),[n]),M=g.useMemo(()=>Ve(xe,r),[xe,r]),v=g.useMemo(()=>Ve(xe,i),[xe,i]),{staticLabelStyle:X,labelStyleResolver:le}=g.useMemo(()=>typeof s=="function"?{staticLabelStyle:void 0,labelStyleResolver:s}:{staticLabelStyle:s,labelStyleResolver:void 0},[s]),Q=g.useMemo(()=>vn(X),[X]),ie=g.useMemo(()=>{const U=[];for(let V=0;V<q.length;V+=1){const ee=q[V],B=Wt(ee.coordinates);B.length!==0&&U.push({region:ee,regionIndex:V,regionKey:ee.id??V,polygons:B})}return U},[q]),he=g.useMemo(()=>la(q,a),[q,a]);g.useEffect(()=>{const U=m.current;U&&Ce(U.getViewState().zoom)},[p,Ce]),g.useEffect(()=>{!(Z===null?!0:q.some((B,te)=>String(dn(B,te))===String(Z)))&&Z!==null&&se(null);const V=we.current;!(V===null?!0:q.some((B,te)=>String(dn(B,te))===String(V)))&&V!==null&&(we.current=null,P(null),f?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[q,Z,f,se]);const me=g.useCallback(U=>{const V=m.current;if(!V||U.length===0)return[];const ee=new Array(U.length);for(let B=0;B<U.length;B+=1){const te=Oe(V.worldToScreen(U[B][0],U[B][1]));if(!te)return[];ee[B]=te}return ee},[]),$=g.useRef({preparedRegions:ie,hoveredRegionId:re,activeRegionId:Z,resolvedStrokeStyle:xe,resolvedHoverStrokeStyle:M,resolvedActiveStrokeStyle:v,resolveStrokeStyleProp:o,worldToScreenPoints:me});$.current={preparedRegions:ie,hoveredRegionId:re,activeRegionId:Z,resolvedStrokeStyle:xe,resolvedHoverStrokeStyle:M,resolvedActiveStrokeStyle:v,resolveStrokeStyleProp:o,worldToScreenPoints:me},g.useEffect(()=>(x(Sr,10,V=>{const{preparedRegions:ee,hoveredRegionId:B,activeRegionId:te,resolvedStrokeStyle:de,resolvedHoverStrokeStyle:ae,resolvedActiveStrokeStyle:Me,resolveStrokeStyleProp:Se,worldToScreenPoints:_}=$.current;for(const Y of ee){const{region:J,polygons:oe,regionIndex:L,regionKey:K}=Y,ce=Ot(te,K)?"active":Ot(B,K)?"hover":"default";let ne=ce==="active"?Me:ce==="hover"?ae:de;if(Se){const ze=Se({region:J,regionId:K,regionIndex:L,state:ce});ne=Ve(ne,ze||void 0)}const ue=ce==="default"?null:ua(ne);for(const ze of oe){const qe=_(ze.outer);qe.length>=4&&(ue&&Te(V,qe,ue,!0,!1),Te(V,qe,ne,!0,!1));for(const Gt of ze.holes){const st=_(Gt);st.length>=4&&(ue&&Te(V,st,ue,!0,!1),Te(V,st,ne,!0,!1))}}}}),()=>C(Sr)),[x,C]);const pe=g.useRef({preparedRegions:ie,resolvedLabelStyle:Q,labelStyleResolver:le,labelAnchor:a,autoLiftLabelAtMaxZoom:c,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:Re,rendererRef:m});pe.current={preparedRegions:ie,resolvedLabelStyle:Q,labelStyleResolver:le,labelAnchor:a,autoLiftLabelAtMaxZoom:c,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:Re,rendererRef:m},g.useEffect(()=>(x(Er,50,(V,ee,B)=>{const{preparedRegions:te,resolvedLabelStyle:de,labelStyleResolver:ae,labelAnchor:Me,autoLiftLabelAtMaxZoom:Se,clampLabelToViewport:_,regionLabelAutoLiftOffsetPx:Y,rendererRef:J}=pe.current;if(te.length===0)return;const oe=Math.max(1e-6,J.current?.getViewState?.().zoom??1),L=typeof Y=="number"&&Number.isFinite(Y)?Math.max(0,Y):Pn(Se,oe,J.current?.getZoomRange?.());for(const K of te){if(!K.region.label)continue;const ce=An(K.polygons,Me);if(!ce)continue;const ne=Oe(J.current?.worldToScreen(ce[0],ce[1])??[]);if(!ne)continue;let ue=Cn(de,ae?.({region:K.region,regionId:K.regionKey,regionIndex:K.regionIndex,zoom:oe}));L>0&&(ue={...ue,offsetY:ue.offsetY+L}),Qr(V,K.region.label,ne,ee,B,ue,_)}}),()=>C(Er)),[x,C]),g.useEffect(()=>{S()},[ie,re,Z,xe,Q,Re,S]);const ye=g.useRef({preparedRegionHits:he,resolvedLabelStyle:Q,labelStyleResolver:le,regionLabelAutoLiftOffsetPx:Re,clampLabelToViewport:u,onHover:f,onClick:d,commitActive:se});return ye.current={preparedRegionHits:he,resolvedLabelStyle:Q,labelStyleResolver:le,regionLabelAutoLiftOffsetPx:Re,clampLabelToViewport:u,onHover:f,onClick:d,commitActive:se},g.useEffect(()=>{const U=b.current;if(!U)return;const V=te=>{if(z())return;const de=m.current;if(!de)return;const{preparedRegionHits:ae,resolvedLabelStyle:Me,labelStyleResolver:Se,regionLabelAutoLiftOffsetPx:_,clampLabelToViewport:Y,onHover:J}=ye.current,oe=I(te.clientX,te.clientY);if(!oe)return;let L=null,K=null;if(ae.length>0){const ne=O(oe[0],oe[1]);if(ne){const ue=y.current?.getBoundingClientRect();K=wr(oe,ne,ae,de,Me,Se,typeof _=="number"?_:0,ue?.width??0,ue?.height??0,Y),L=K?.regionId??null}}const ce=we.current;String(ce)!==String(L)&&(we.current=L,P(L),J?.({region:K?.region??null,regionId:L,regionIndex:K?.regionIndex??-1,coordinate:oe}),S())},ee=te=>{if(z())return;const de=m.current;if(!de)return;const{preparedRegionHits:ae,resolvedLabelStyle:Me,labelStyleResolver:Se,regionLabelAutoLiftOffsetPx:_,clampLabelToViewport:Y,onClick:J,commitActive:oe}=ye.current;if(ae.length===0)return;const L=I(te.clientX,te.clientY);if(!L)return;const K=O(L[0],L[1]);if(!K)return;const ce=y.current?.getBoundingClientRect(),ne=wr(L,K,ae,de,Me,Se,typeof _=="number"?_:0,ce?.width??0,ce?.height??0,Y),ue=ne?.regionId??null;oe(ue),ne&&J&&J({region:ne.region,regionId:ne.regionId,regionIndex:ne.regionIndex,coordinate:L})},B=()=>{we.current!==null&&(we.current=null,P(null),ye.current.onHover?.({region:null,regionId:null,regionIndex:-1,coordinate:null}),S())};return U.addEventListener("pointermove",V),U.addEventListener("click",ee),U.addEventListener("pointerleave",B),()=>{U.removeEventListener("pointermove",V),U.removeEventListener("click",ee),U.removeEventListener("pointerleave",B)}},[b,m,y,I,O,z,S]),null}function ha({imageWidth:e,imageHeight:t,tiles:n,viewState:r,className:i,style:o}){const s=g.useRef(null),a=g.useRef(null),c=g.useMemo(()=>({width:"100%",height:"100%",display:"block",...o}),[o]);return g.useEffect(()=>{const u=s.current;if(!u)return;const h=new zr({canvas:u,imageWidth:e,imageHeight:t,initialViewState:r});return a.current=h,h.setTiles(n),()=>{h.destroy(),a.current=null}},[e,t]),g.useEffect(()=>{const u=a.current;u&&u.setTiles(n)},[n]),g.useEffect(()=>{const u=a.current;!u||!r||u.setViewState(r)},[r]),Ye.jsx("canvas",{ref:s,className:i,style:c})}function da(e,t){if(!t)return!1;try{const r=new URL(e,typeof window<"u"?window.location.href:void 0).hostname.toLowerCase();if(r.includes("amazonaws.com")||r.startsWith("s3.")||r.includes(".s3."))return!1}catch{}return!0}class fi{constructor(t){R(this,"maxConcurrency");R(this,"maxRetries");R(this,"retryBaseDelayMs");R(this,"retryMaxDelayMs");R(this,"onTileLoad");R(this,"onTileError");R(this,"onStateChange");R(this,"authToken");R(this,"destroyed",!1);R(this,"queue",[]);R(this,"queuedByKey",new Map);R(this,"inflight",new Map);R(this,"visibleKeys",new Set);R(this,"timerId",null);R(this,"abortedCount",0);R(this,"retryCount",0);R(this,"failedCount",0);this.maxConcurrency=Math.max(1,Math.floor(t.maxConcurrency??12)),this.maxRetries=Math.max(0,Math.floor(t.maxRetries??2)),this.retryBaseDelayMs=Math.max(10,Math.floor(t.retryBaseDelayMs??120)),this.retryMaxDelayMs=Math.max(this.retryBaseDelayMs,Math.floor(t.retryMaxDelayMs??1200)),this.authToken=t.authToken??"",this.onTileLoad=t.onTileLoad,this.onTileError=t.onTileError,this.onStateChange=t.onStateChange}setAuthToken(t){this.authToken=String(t??"")}schedule(t){if(this.destroyed)return;const n=new Set;for(const r of t)n.add(r.key);this.visibleKeys=n,this.dropInvisibleQueued(n),this.abortInvisibleInflight(n);for(const r of t){if(this.inflight.has(r.key)){const s=this.inflight.get(r.key);s&&(s.tile=r);continue}const i=this.queuedByKey.get(r.key);if(i){i.tile=r;continue}const o={tile:r,attempt:0,readyAt:be()};this.queue.push(o),this.queuedByKey.set(r.key,o)}this.sortQueue(),this.pump(),this.emitStateChange()}clear(){this.clearPumpTimer(),this.visibleKeys.clear(),this.queue=[],this.queuedByKey.clear();for(const[,t]of this.inflight)t.controller.abort();this.inflight.clear(),this.emitStateChange()}destroy(){this.destroyed||(this.destroyed=!0,this.clear())}getInflightCount(){return this.inflight.size}getSnapshot(){return{inflight:this.inflight.size,queued:this.queue.length,aborted:this.abortedCount,retries:this.retryCount,failed:this.failedCount}}dropInvisibleQueued(t){if(this.queue.length===0)return;const n=[];for(const r of this.queue){if(!t.has(r.tile.key)){this.queuedByKey.delete(r.tile.key);continue}n.push(r)}this.queue=n}abortInvisibleInflight(t){for(const[n,r]of this.inflight)t.has(n)||(this.inflight.delete(n),this.abortedCount+=1,r.controller.abort())}sortQueue(){this.queue.sort((t,n)=>t.readyAt!==n.readyAt?t.readyAt-n.readyAt:t.tile.distance2!==n.tile.distance2?t.tile.distance2-n.tile.distance2:t.tile.tier!==n.tile.tier?n.tile.tier-t.tile.tier:t.tile.key.localeCompare(n.tile.key))}pump(){if(this.destroyed)return;for(this.clearPumpTimer();this.inflight.size<this.maxConcurrency;){const r=this.takeNextReadyQueueItem();if(!r)break;this.startFetch(r)}if(this.inflight.size>=this.maxConcurrency||this.queue.length===0)return;const t=this.queue[0]?.readyAt;if(typeof t!="number")return;const n=Math.max(0,t-be());this.timerId=globalThis.setTimeout(()=>{this.timerId=null,this.pump()},n)}takeNextReadyQueueItem(){if(this.queue.length===0)return null;const t=be(),n=this.queue[0];return!n||n.readyAt>t?null:(this.queue.shift(),this.queuedByKey.delete(n.tile.key),n)}startFetch(t){const n=new AbortController,r={tile:t.tile,attempt:t.attempt,controller:n};this.inflight.set(t.tile.key,r),this.emitStateChange();const i=da(t.tile.url,this.authToken);fetch(t.tile.url,{signal:n.signal,headers:i?{Authorization:this.authToken}:void 0}).then(o=>{if(!o.ok)throw new Error(`HTTP ${o.status}`);return o.blob()}).then(o=>createImageBitmap(o)).then(o=>{if(this.destroyed||n.signal.aborted){o.close();return}if(!this.visibleKeys.has(t.tile.key)){o.close();return}this.onTileLoad(t.tile,o)}).catch(o=>{if(n.signal.aborted||this.destroyed)return;if(t.attempt<this.maxRetries&&this.visibleKeys.has(t.tile.key)){this.retryCount+=1;const a=t.attempt+1,c=this.getRetryDelay(a),u={tile:t.tile,attempt:a,readyAt:be()+c},h=this.queuedByKey.get(t.tile.key);h?(h.tile=u.tile,h.readyAt=Math.min(h.readyAt,u.readyAt),h.attempt=Math.max(h.attempt,u.attempt)):(this.queue.push(u),this.queuedByKey.set(u.tile.key,u)),this.sortQueue();return}this.failedCount+=1,this.onTileError?.(t.tile,o,t.attempt+1)}).finally(()=>{this.inflight.delete(t.tile.key),this.pump(),this.emitStateChange()})}getRetryDelay(t){const n=Math.max(0,t-1),r=Math.min(this.retryMaxDelayMs,this.retryBaseDelayMs*2**n),i=.85+Math.random()*.3;return Math.round(r*i)}clearPumpTimer(){this.timerId!==null&&(globalThis.clearTimeout(this.timerId),this.timerId=null)}emitStateChange(){this.onStateChange?.(this.getSnapshot())}}function ma(e,t){e.addEventListener("pointerdown",t.pointerDown),e.addEventListener("pointermove",t.pointerMove),e.addEventListener("pointerup",t.pointerUp),e.addEventListener("pointercancel",t.pointerUp),e.addEventListener("wheel",t.wheel,{passive:!1}),e.addEventListener("dblclick",t.doubleClick),e.addEventListener("contextmenu",t.contextMenu),e.addEventListener("webglcontextlost",t.contextLost),e.addEventListener("webglcontextrestored",t.contextRestored)}function ga(e,t){e.removeEventListener("pointerdown",t.pointerDown),e.removeEventListener("pointermove",t.pointerMove),e.removeEventListener("pointerup",t.pointerUp),e.removeEventListener("pointercancel",t.pointerUp),e.removeEventListener("wheel",t.wheel),e.removeEventListener("dblclick",t.doubleClick),e.removeEventListener("contextmenu",t.contextMenu),e.removeEventListener("webglcontextlost",t.contextLost),e.removeEventListener("webglcontextrestored",t.contextRestored)}function pa(e,t,n){const r=e.getBoundingClientRect(),i=Math.max(1,r.width||e.clientWidth||1),o=Math.max(1,r.height||e.clientHeight||1),s=Math.max(1,window.devicePixelRatio||1),a=Math.max(1,Math.round(i*s)),c=Math.max(1,Math.round(o*s));(e.width!==a||e.height!==c)&&(e.width=a,e.height=c),n.setViewport(i,o),t.viewport(0,0,a,c)}const mn=.35,gn=.5,ya=256,pn=[{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}],ba=.1,wa=5,xa=0,Sa=1,Ea=-100,Ra=100,Ma=2e3;function Vt(e){return e*Math.PI/180}function Pt(e,t){return!e||!t?e===t:e.buffer===t.buffer&&e.byteOffset===t.byteOffset&&e.byteLength===t.byteLength}function yn(e){return e.map(t=>({zoom:t.zoom,size:t.size}))}function Rr(e){if(!e)return yn(pn);const t=new Map;for(const[n,r]of Object.entries(e)){const i=Number(n),o=Number(r);!Number.isFinite(i)||!Number.isFinite(o)||o<=0||t.set(i,o)}return t.size===0?yn(pn):Array.from(t.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function Aa(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n].zoom!==t[n].zoom||e[n].size!==t[n].size)return!1;return!0}function va(e,t){if(!Number.isFinite(e))return t[0]?.size??gn;if(t.length===0)return gn;if(t.length===1||e<=t[0].zoom)return t[0].size;for(let s=1;s<t.length;s+=1){const a=t[s-1],c=t[s];if(e>c.zoom)continue;const u=Math.max(1e-6,c.zoom-a.zoom),h=W((e-a.zoom)/u,0,1);return a.size+(c.size-a.size)*h}const n=t[t.length-1],r=t[t.length-2],i=Math.max(1e-6,n.zoom-r.zoom),o=(n.size-r.size)/i;return n.size+(e-n.zoom)*o}function Mr(e){return typeof e!="number"||!Number.isFinite(e)?1:W(e,ba,wa)}function Ar(e){return typeof e!="number"||!Number.isFinite(e)?0:W(e,xa,Sa)}function Jt(e){return typeof e!="number"||!Number.isFinite(e)?0:W(e,Ea,Ra)}function vr(e){const t=Jt(e?.brightness),n=Jt(e?.contrast),r=Jt(e?.saturation);return{brightness:t/200,contrast:n/100,saturation:r/100}}function In(e){return e}function en(e){return typeof e!="number"||!Number.isFinite(e)?0:W(e,0,Ma)}function Tt(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:Math.max(1e-6,e)}function tn(e){return typeof e=="function"?e:In}function hi(e,t,n){const r=e.getBoundingClientRect(),i=t-r.left-r.width*.5,o=n-r.top-r.height*.5;return Math.atan2(o,i)}function di(e,t){if(t.pointerId!==null&&e.hasPointerCapture(t.pointerId))try{e.releasePointerCapture(t.pointerId)}catch{}t.dragging=!1,t.mode="none",t.rotateLastAngleRad=null,t.pointerId=null,e.classList.remove("dragging")}function Ca(e){const{event:t,canvas:n,state:r,config:i,cancelViewAnimation:o}=e,s=i.ctrlDragRotate&&(t.ctrlKey||t.metaKey);(t.button===0||s&&t.button===2)&&(o(),s&&t.preventDefault(),r.dragging=!0,r.mode=s?"rotate":"pan",r.pointerId=t.pointerId,r.lastPointerX=t.clientX,r.lastPointerY=t.clientY,r.rotateLastAngleRad=r.mode==="rotate"?hi(n,t.clientX,t.clientY):null,n.classList.add("dragging"),n.setPointerCapture(t.pointerId))}function Pa(e){const{event:t,canvas:n,state:r,config:i,camera:o,clampViewState:s,emitViewState:a,requestRender:c}=e;if(!r.dragging||t.pointerId!==r.pointerId)return;const u=t.clientX-r.lastPointerX,h=t.clientY-r.lastPointerY;if(r.lastPointerX=t.clientX,r.lastPointerY=t.clientY,r.mode==="rotate"){const l=hi(n,t.clientX,t.clientY),f=r.rotateLastAngleRad;if(r.rotateLastAngleRad=l,f!==null){const d=l-f,m=Math.atan2(Math.sin(d),Math.cos(d)),p=i.rotationDragSensitivityDegPerPixel/mn,y=o.getViewState();o.setViewState({rotationDeg:y.rotationDeg-m*180/Math.PI*p})}}else{const l=o.getViewState(),f=Math.max(1e-6,l.zoom),d=Vt(l.rotationDeg),m=Math.cos(d),p=Math.sin(d),y=(u*m-h*p)/f,b=(u*p+h*m)/f;o.setViewState({offsetX:l.offsetX-y,offsetY:l.offsetY-b})}s(),a(),c()}function Ta(e,t,n){e.pointerId===n.pointerId&&di(t,n)}function Ia(e){const{event:t,canvas:n,onZoomBy:r}=e;t.preventDefault();const i=n.getBoundingClientRect(),o=t.clientX-i.left,s=t.clientY-i.top,a=t.deltaY<0?1.12:.89;r(a,o,s)}const _a=4,Fa=300;function La(e){const{event:t,canvas:n,snapState:r,onSnapZoom:i}=e;t.preventDefault();const o=performance.now();if(o-r.lastSnapTimeMs<Fa){r.accumulatedDelta=0;return}if(r.accumulatedDelta!==0&&t.deltaY!==0&&Math.sign(r.accumulatedDelta)!==Math.sign(t.deltaY)&&(r.accumulatedDelta=0),r.accumulatedDelta+=t.deltaY,Math.abs(r.accumulatedDelta)<_a)return;const s=n.getBoundingClientRect(),a=t.clientX-s.left,c=t.clientY-s.top,u=r.accumulatedDelta>0?"out":"in";r.accumulatedDelta=0,r.lastSnapTimeMs=o,i(u,a,c)}function ka(e){const{event:t,canvas:n,onZoomBy:r}=e,i=n.getBoundingClientRect(),o=t.clientX-i.left,s=t.clientY-i.top;r(t.shiftKey?.8:1.25,o,s)}function Na(e,t){(t||e.ctrlKey||e.metaKey)&&e.preventDefault()}function Xt(e){const t=e.getViewCorners();let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[s,a]of t)s<n&&(n=s),s>i&&(i=s),a<r&&(r=a),a>o&&(o=a);return[n,r,i,o]}function kt(e,t){const n=Xt(e),r=Math.max(1e-6,n[2]-n[0]),i=Math.max(1e-6,n[3]-n[1]),o=r*.2,s=i*.2,[a,c]=e.getCenter(),u=r*.5,h=i*.5,l=u-o,f=t.width-u+o,d=h-s,m=t.height-h+s,p=l<=f?W(a,l,f):t.width*.5,y=d<=m?W(c,d,m):t.height*.5;e.setCenter(p,y)}function Ba(e,t){const n=Math.max(1e-6,e.getViewState().zoom),r=t.maxTierZoom+Math.log2(n);return W(Math.floor(r),0,t.maxTierZoom)}function za(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function mi(e,t,n){const r=Xt(e),i=Math.pow(2,t.maxTierZoom-n),o=Math.ceil(t.width/i),s=Math.ceil(t.height/i),a=Math.max(1,Math.ceil(o/t.tileSize)),c=Math.max(1,Math.ceil(s/t.tileSize)),u=r[0],h=r[1],l=r[2],f=r[3],d=W(Math.floor(u/i/t.tileSize),0,a-1),m=W(Math.floor((l-1)/i/t.tileSize),0,a-1),p=W(Math.floor(h/i/t.tileSize),0,c-1),y=W(Math.floor((f-1)/i/t.tileSize),0,c-1);if(d>m||p>y)return[];const b=(u+l)*.5/i/t.tileSize,x=(h+f)*.5/i/t.tileSize,C=[];for(let S=p;S<=y;S+=1)for(let A=d;A<=m;A+=1){const I=A*t.tileSize*i,O=S*t.tileSize*i,z=Math.min((A+1)*t.tileSize,o)*i,G=Math.min((S+1)*t.tileSize,s)*i,D=A-b,q=S-x;C.push({key:`${n}/${A}/${S}`,tier:n,x:A,y:S,bounds:[I,O,z,G],distance2:D*D+q*q,url:Tn(t,n,A,S)})}return C.sort((S,A)=>S.distance2-A.distance2),C}function Da(e,t){const n=Ba(e,t);return{tier:n,visible:mi(e,t,n)}}function Ua(e){e.interactionLocked||Ca({event:e.event,canvas:e.canvas,state:e.state,config:{ctrlDragRotate:e.ctrlDragRotate,rotationDragSensitivityDegPerPixel:e.rotationDragSensitivityDegPerPixel},cancelViewAnimation:e.cancelViewAnimation})}function Oa(e){e.interactionLocked||Pa({event:e.event,canvas:e.canvas,state:e.state,config:{ctrlDragRotate:e.ctrlDragRotate,rotationDragSensitivityDegPerPixel:e.rotationDragSensitivityDegPerPixel},camera:e.camera,clampViewState:()=>kt(e.camera,e.source),emitViewState:e.emitViewState,requestRender:e.requestRender})}function Ya(e){e.interactionLocked||Ta(e.event,e.canvas,e.state)}function Wa(e){e.interactionLocked||ka({event:e.event,canvas:e.canvas,onZoomBy:e.onZoomBy})}function Xa(e){Na(e.event,e.state.dragging)}function Va(e,t){di(e,t)}function Ga(e){return{pointerDown:t=>Ua({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state,ctrlDragRotate:e.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:e.getRotationDragSensitivityDegPerPixel(),cancelViewAnimation:e.cancelViewAnimation}),pointerMove:t=>Oa({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state,ctrlDragRotate:e.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:e.getRotationDragSensitivityDegPerPixel(),camera:e.camera,source:e.source,emitViewState:e.emitViewState,requestRender:e.requestRender}),pointerUp:t=>Ya({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state}),wheel:t=>{if(e.getInteractionLocked()){t.preventDefault();return}if(e.getUseZoomSnaps?.()&&e.onSnapZoom&&e.zoomSnapState){La({event:t,canvas:e.canvas,snapState:e.zoomSnapState,onSnapZoom:e.onSnapZoom});return}Ia({event:t,canvas:e.canvas,onZoomBy:e.zoomBy})},doubleClick:t=>Wa({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,onZoomBy:e.zoomBy}),contextMenu:t=>Xa({event:t,canvas:e.canvas,state:e.state})}}function qa(e){const{gl:t,cache:n,maxCacheTiles:r}=e;if(n.size<=r)return;const i=Math.max(0,Math.floor(r));for(;n.size>i;){let o=null,s=null;for(const[a,c]of n)(!s||c.lastUsed<s.lastUsed)&&(o=a,s=c);if(!o||!s)break;t.deleteTexture(s.texture),n.delete(o)}}function Ha(e,t){if(e.isContextLost())return null;const n=e.createTexture();return n?(e.bindTexture(e.TEXTURE_2D,n),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,1),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.bindTexture(e.TEXTURE_2D,null),n):null}function Za(e){const{gl:t,cache:n,tile:r,bitmap:i,frameSerial:o,maxCacheTiles:s,destroyed:a,contextLost:c,requestRender:u}=e;if(a||c||t.isContextLost()){i.close();return}if(n.has(r.key)){i.close();return}const h=Ha(t,i);i.close(),h&&(n.set(r.key,{key:r.key,texture:h,bounds:r.bounds,tier:r.tier,lastUsed:o}),qa({gl:t,cache:n,maxCacheTiles:s}),u())}function $a(e,t){for(const[,n]of t)e.deleteTexture(n.texture)}function Ka(e){const{event:t,destroyed:n,contextLost:r,cancelViewAnimation:i,cancelDrag:o,tileScheduler:s,cache:a,onContextLost:c}=e;if(t.preventDefault(),n||r)return{handled:!1,frame:e.frame};let u=e.frame;return u!==null&&(cancelAnimationFrame(u),u=null),i(),o(),s.clear(),a.clear(),c?.(),{handled:!0,frame:u}}function ja(e){if(e.destroyed)return{didDestroy:!1,frame:e.frame};let t=e.frame;return t!==null&&(cancelAnimationFrame(t),t=null),e.cancelViewAnimation(),e.resizeObserver.disconnect(),e.removeCanvasEventListeners(),e.cancelDrag(),e.tileScheduler.destroy(),!e.contextLost&&!e.gl.isContextLost()&&($a(e.gl,e.cache),e.gl.deleteBuffer(e.tileProgram.vbo),e.gl.deleteVertexArray(e.tileProgram.vao),e.gl.deleteProgram(e.tileProgram.program),e.gl.deleteBuffer(e.pointProgram.posBuffer),e.gl.deleteBuffer(e.pointProgram.termBuffer),e.gl.deleteBuffer(e.pointProgram.fillModeBuffer),e.gl.deleteBuffer(e.pointProgram.indexBuffer),e.gl.deleteTexture(e.pointProgram.paletteTexture),e.gl.deleteVertexArray(e.pointProgram.vao),e.gl.deleteProgram(e.pointProgram.program)),e.cache.clear(),{didDestroy:!0,frame:t}}function Qa(e,t){if(t<=0||e.length===0)return new Uint32Array(0);let n=e.length;for(let o=0;o<e.length;o+=1)e[o]<t||(n-=1);if(n===e.length)return e;if(n<=0)return new Uint32Array(0);const r=new Uint32Array(n);let i=0;for(let o=0;o<e.length;o+=1){const s=e[o];s>=t||(r[i]=s,i+=1)}return r}function Ja(e,t){return t<=0?new Uint8Array(0):e.length<t?new Uint8Array(t):e.subarray(0,t)}function el(e,t,n,r,i){if(!i||i.length===0)return{...e,lastPointPalette:null};const o=new Uint8Array(i);if(r||t.isContextLost())return{...e,lastPointPalette:o};const s=Math.max(1,Math.floor(o.length/4));return t.bindTexture(t.TEXTURE_2D,n.paletteTexture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,s,1,0,t.RGBA,t.UNSIGNED_BYTE,o),t.bindTexture(t.TEXTURE_2D,null),{...e,lastPointPalette:o,pointPaletteSize:s}}function tl(e,t,n,r,i){if(!i||!i.count||!i.positions||!i.paletteIndices)return{...e,lastPointData:null,pointCount:0,usePointIndices:!1};const o=i.fillModes instanceof Uint8Array?i.fillModes:null,s=o!==null,a=Math.max(0,Math.min(i.count,Math.floor(i.positions.length/2),i.paletteIndices.length,s?o.length:Number.MAX_SAFE_INTEGER)),c=i.positions.subarray(0,a*2),u=i.paletteIndices.subarray(0,a),h=s?o.subarray(0,a):void 0,l=i.drawIndices instanceof Uint32Array,f=l?Qa(i.drawIndices,a):null,d=e.lastPointData,m=d?.fillModes instanceof Uint8Array,p=e.pointBuffersDirty||!d||d.count!==a||!Pt(d.positions,c)||!Pt(d.paletteIndices,u)||m!==s||s&&(!d?.fillModes||!Pt(d.fillModes,h)),y=e.pointBuffersDirty||l&&(!d?.drawIndices||!Pt(d.drawIndices,f))||!l&&!!d?.drawIndices,b={...e,lastPointData:{count:a,positions:c,paletteIndices:u,fillModes:h,drawIndices:l?f??void 0:void 0}};if(r||t.isContextLost())return b;const x=b.lastPointData;if(!x)return b;if(p){t.bindBuffer(t.ARRAY_BUFFER,n.posBuffer),t.bufferData(t.ARRAY_BUFFER,x.positions,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,n.termBuffer),t.bufferData(t.ARRAY_BUFFER,x.paletteIndices,t.STATIC_DRAW);const C=Ja(b.zeroFillModes,a);t.bindBuffer(t.ARRAY_BUFFER,n.fillModeBuffer),t.bufferData(t.ARRAY_BUFFER,x.fillModes??C,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,null),b.zeroFillModes=C}return l&&y&&(t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,n.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,f??new Uint32Array(0),t.DYNAMIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null)),b.usePointIndices=l,b.pointCount=l?f?.length??0:x.count,(p||y)&&(b.pointBuffersDirty=!1),b}function nl(e){const{gl:t,camera:n,source:r,cache:i,frameSerial:o,tileProgram:s,pointProgram:a,imageColorSettings:c,pointCount:u,usePointIndices:h,pointPaletteSize:l,pointStrokeScale:f,pointInnerFillOpacity:d,pointSizePx:m,tileScheduler:p,getVisibleTiles:y,getVisibleTilesForTier:b,getViewBounds:x,intersectsBounds:C}=e;t.clearColor(.03,.06,.1,1),t.clear(t.COLOR_BUFFER_BIT);const{tier:S,visible:A}=y(),I=x(),O=new Set(A.map(N=>N.key));t.useProgram(s.program),t.bindVertexArray(s.vao),t.uniformMatrix3fv(s.uCamera,!1,n.getMatrix()),t.uniform1i(s.uTexture,0),t.uniform1f(s.uBrightness,c.brightness),t.uniform1f(s.uContrast,c.contrast),t.uniform1f(s.uSaturation,c.saturation);const z=[];for(const[,N]of i)O.has(N.key)||C(N.bounds,I)&&z.push(N);z.sort((N,k)=>N.tier-k.tier);for(const N of z)N.lastUsed=o,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,N.texture),t.uniform4f(s.uBounds,N.bounds[0],N.bounds[1],N.bounds[2],N.bounds[3]),t.drawArrays(t.TRIANGLE_STRIP,0,4);let G=0;const D=[];for(const N of A){const k=i.get(N.key);if(!k){D.push(N);continue}k.lastUsed=o,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,k.texture),t.uniform4f(s.uBounds,k.bounds[0],k.bounds[1],k.bounds[2],k.bounds[3]),t.drawArrays(t.TRIANGLE_STRIP,0,4),G+=1}const q=D.slice(),re=1e6,P=[];S>0&&P.push(S-1),S<r.maxTierZoom&&P.push(S+1);for(const N of P){const k=b(N);for(const Z of k)i.has(Z.key)||(Z.distance2+=re,q.push(Z))}p.schedule(q),t.bindTexture(t.TEXTURE_2D,null),t.bindVertexArray(null);let H=0;return u>0&&(t.enable(t.BLEND),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA),t.useProgram(a.program),t.bindVertexArray(a.vao),t.uniformMatrix3fv(a.uCamera,!1,n.getMatrix()),t.uniform1f(a.uPointSize,m),t.uniform1f(a.uPointStrokeScale,f),t.uniform1f(a.uPointInnerFillAlpha,d),t.uniform1f(a.uPaletteSize,l),t.uniform1i(a.uPalette,1),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,a.paletteTexture),h?t.drawElements(t.POINTS,u,t.UNSIGNED_INT,0):t.drawArrays(t.POINTS,0,u),t.bindTexture(t.TEXTURE_2D,null),t.bindVertexArray(null),H=u),{tier:S,visible:A.length,rendered:G,points:H,fallback:z.length,cacheHits:G,cacheMisses:D.length,drawCalls:z.length+G+(H>0?1:0)}}function Cr(e){const r=bn(e,`#version 300 es
64
+ `;function Ts(){if(typeof navigator>"u")return!1;const e=navigator;return typeof e.gpu=="object"&&e.gpu!==null}function ii(){if(!Ts())return null;const t=navigator.gpu;if(!t||typeof t!="object")return null;const n=t;return typeof n.requestAdapter!="function"?null:n}const At=globalThis.GPUShaderStage?.COMPUTE??4,Qt=globalThis.GPUBufferUsage?.STORAGE??128,vt=globalThis.GPUBufferUsage?.COPY_DST??8,_s=globalThis.GPUBufferUsage?.COPY_SRC??4,Fs=globalThis.GPUBufferUsage?.UNIFORM??64,Ls=globalThis.GPUBufferUsage?.MAP_READ??1,ks=globalThis.GPUMapMode?.READ??1;async function Ns(){const e=ii();if(!e)return{supported:!1,features:[]};const t=await e.requestAdapter();return t?{supported:!0,adapterName:t.info?.description??t.info?.vendor??"unknown",features:Array.from(t.features),limits:{maxStorageBufferBindingSize:Number(t.limits.maxStorageBufferBindingSize),maxComputeInvocationsPerWorkgroup:Number(t.limits.maxComputeInvocationsPerWorkgroup),maxComputeWorkgroupSizeX:Number(t.limits.maxComputeWorkgroupSizeX)}}:{supported:!1,features:[]}}async function Bs(){return Mt||(Mt=(async()=>{const e=ii();if(!e)return null;const t=await e.requestAdapter();if(!t)return null;const n=await t.requestDevice(),r=n.createBindGroupLayout({entries:[{binding:0,visibility:At,buffer:{type:"read-only-storage"}},{binding:1,visibility:At,buffer:{type:"read-only-storage"}},{binding:2,visibility:At,buffer:{type:"storage"}},{binding:3,visibility:At,buffer:{type:"uniform"}}]}),i=n.createComputePipeline({layout:n.createPipelineLayout({bindGroupLayouts:[r]}),compute:{module:n.createShaderModule({code:Ps}),entryPoint:"main"}});return{device:n,pipeline:i,bindGroupLayout:r}})(),Mt)}function Ct(e,t){return Math.ceil(e/t)*t}async function oi(e,t,n){const r=await Bs();if(!r)return null;const i=Math.max(0,Math.floor(t)),o=Math.max(0,Math.floor(n.length/4));if(i===0||o===0)return new Uint32Array(0);const s=Math.min(i,Math.floor(e.length/2));if(s===0)return new Uint32Array(0);const a=s*2*Float32Array.BYTES_PER_ELEMENT,c=o*4*Float32Array.BYTES_PER_ELEMENT,u=s*Uint32Array.BYTES_PER_ELEMENT,h=Number(r.device.limits.maxStorageBufferBindingSize);if(a>h||c>h||u>h)return null;const l=r.device.createBuffer({size:Ct(a,4),usage:Qt|vt}),f=r.device.createBuffer({size:Ct(c,4),usage:Qt|vt}),d=r.device.createBuffer({size:Ct(u,4),usage:Qt|_s}),m=r.device.createBuffer({size:16,usage:Fs|vt}),p=r.device.createBuffer({size:Ct(u,4),usage:vt|Ls});let y=!1;try{r.device.queue.writeBuffer(l,0,e.buffer,e.byteOffset,a),r.device.queue.writeBuffer(f,0,n.buffer,n.byteOffset,c),r.device.queue.writeBuffer(m,0,new Uint32Array([s,o,0,0]));const b=r.device.createBindGroup({layout:r.bindGroupLayout,entries:[{binding:0,resource:{buffer:l}},{binding:1,resource:{buffer:f}},{binding:2,resource:{buffer:d}},{binding:3,resource:{buffer:m}}]}),x=r.device.createCommandEncoder(),C=x.beginComputePass();C.setPipeline(r.pipeline),C.setBindGroup(0,b),C.dispatchWorkgroups(Math.ceil(s/256)),C.end(),x.copyBufferToBuffer(d,0,p,0,u),r.device.queue.submit([x.finish()]),await p.mapAsync(ks),y=!0;const S=p.getMappedRange();return new Uint32Array(S.slice(0))}finally{if(y)try{p.unmap()}catch{}l.destroy(),f.destroy(),d.destroy(),m.destroy(),p.destroy()}}async function si(e,t,n={}){const r=be(),i=n.bridgeToDraw===!0;if(!e||!e.count||!e.positions||!e.paletteIndices)return{data:null,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}};const o=yt(t??[]);if(o.length===0){const S={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return e.fillModes instanceof Uint8Array&&(S.fillModes=new Uint8Array(0)),e.ids instanceof Uint32Array&&(S.ids=new Uint32Array(0)),{data:S,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const s=et(e),a=e.fillModes instanceof Uint8Array&&e.fillModes.length>=s?e.fillModes:null,c=e.ids instanceof Uint32Array&&e.ids.length>=s?e.ids:null;if(s===0){const S={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(S.fillModes=new Uint8Array(0)),c&&(S.ids=new Uint32Array(0)),{data:S,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!1,candidateCount:0,bridgedToDraw:!1}}}const u=new Float32Array(o.length*4);for(let S=0;S<o.length;S+=1){const A=S*4,T=o[S];u[A]=T.minX,u[A+1]=T.minY,u[A+2]=T.maxX,u[A+3]=T.maxY}let h=null,l=!1;try{h=await oi(e.positions,s,u),l=!!h}catch{h=null,l=!1}if(!h)return{data:dt(e,t),meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!1,candidateCount:s,bridgedToDraw:!1}};let f=0;for(let S=0;S<s;S+=1)h[S]===1&&(f+=1);const d=new Uint32Array(f);if(f>0){let S=0;for(let A=0;A<s;A+=1)h[A]===1&&(d[S]=A,S+=1)}if(f===0){if(i){const A={count:s,positions:e.positions.subarray(0,s*2),paletteIndices:e.paletteIndices.subarray(0,s),drawIndices:new Uint32Array(0)};return a&&(A.fillModes=a.subarray(0,s)),c&&(A.ids=c.subarray(0,s)),{data:A,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!0}}}const S={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};return a&&(S.fillModes=new Uint8Array(0)),c&&(S.ids=new Uint32Array(0)),{data:S,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!0,candidateCount:0,bridgedToDraw:!1}}}if(i){const S=new Uint32Array(f);let A=0;for(let O=0;O<f;O+=1){const z=d[O]??0,G=e.positions[z*2],D=e.positions[z*2+1];zt(G,D,o)&&(S[A]=z,A+=1)}const T={count:s,positions:e.positions.subarray(0,s*2),paletteIndices:e.paletteIndices.subarray(0,s),drawIndices:S.subarray(0,A)};return a&&(T.fillModes=a.subarray(0,s)),c&&(T.ids=c.subarray(0,s)),{data:T,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!0,candidateCount:f,bridgedToDraw:!0}}}const m=new Float32Array(f*2),p=new Uint16Array(f),y=a?new Uint8Array(f):null,b=c?new Uint32Array(f):null;let x=0;for(let S=0;S<f;S+=1){const A=d[S]??0,T=e.positions[A*2],O=e.positions[A*2+1];zt(T,O,o)&&(m[x*2]=T,m[x*2+1]=O,p[x]=e.paletteIndices[A],y&&(y[x]=a[A]),b&&(b[x]=c[A]),x+=1)}const C={count:x,positions:m.subarray(0,x*2),paletteIndices:p.subarray(0,x)};return y&&(C.fillModes=y.subarray(0,x)),b&&(C.ids=b.subarray(0,x)),{data:C,meta:{mode:"hybrid-webgpu",durationMs:be()-r,usedWebGpu:!0,candidateCount:f,bridgedToDraw:!1}}}class ai{constructor(t,n){R(this,"worker",null);R(this,"supported",!0);R(this,"requestId",1);R(this,"pendingById",new Map);R(this,"handleMessage",t=>{const n=t.data;if(!n)return;const r=this.pendingById.get(n.id);r&&(this.pendingById.delete(n.id),this.handlers.onResponse(n,r))});R(this,"handleError",()=>{this.supported=!1,this.teardownWorker("worker crashed")});this.createWorker=t,this.handlers=n}beginRequest(t){const n=this.getOrCreateWorker();if(!n)return null;const r=this.requestId++;return this.pendingById.set(r,t),{id:r,worker:n}}cancelRequest(t){const n=this.pendingById.get(t);if(n)return this.pendingById.delete(t),n}terminate(t="worker terminated"){this.teardownWorker(t)}getOrCreateWorker(){if(!this.supported)return null;if(this.worker)return this.worker;try{const t=this.createWorker();return t.addEventListener("message",this.handleMessage),t.addEventListener("error",this.handleError),this.worker=t,t}catch{return this.supported=!1,null}}teardownWorker(t){this.worker&&(this.worker.removeEventListener("message",this.handleMessage),this.worker.removeEventListener("error",this.handleError),this.worker.terminate(),this.worker=null);const n=new Error(t);for(const[,r]of this.pendingById)this.handlers.rejectPending(r,n);this.pendingById.clear()}}const mt=new ai(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/roi-clip-worker-BuNuUQQg.js").href:new URL("assets/roi-clip-worker-BuNuUQQg.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:it&&it.tagName.toUpperCase()==="SCRIPT"&&it.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(e,t)=>{if(e.type==="roi-clip-failure"){t.reject(new Error(e.error||"worker clip failed"));return}if(e.type==="roi-clip-index-success"){if(t.kind!=="index"){t.reject(new Error("worker response mismatch: expected point data result"));return}const c=Math.max(0,Math.floor(e.count)),u=new Uint32Array(e.indices).subarray(0,c);t.resolve({indices:u,meta:{mode:"worker",durationMs:Number.isFinite(e.durationMs)?e.durationMs:be()-t.startMs}});return}if(t.kind!=="data"){t.reject(new Error("worker response mismatch: expected index result"));return}const n=Math.max(0,Math.floor(e.count)),r=new Float32Array(e.positions),i=new Uint16Array(e.paletteIndices),o=e.fillModes?new Uint8Array(e.fillModes):null,s=e.ids?new Uint32Array(e.ids):null,a={count:n,positions:r.subarray(0,n*2),paletteIndices:i.subarray(0,n)};o&&(a.fillModes=o.subarray(0,n)),s&&(a.ids=s.subarray(0,n)),t.resolve({data:a,meta:{mode:"worker",durationMs:Number.isFinite(e.durationMs)?e.durationMs:be()-t.startMs}})},rejectPending:(e,t)=>{e.reject(t)}});function zs(){mt.terminate("worker terminated")}async function li(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return{data:null,meta:{mode:"worker",durationMs:0}};const n=et(e),r=e.positions.slice(0,n*2),i=e.paletteIndices.slice(0,n),o=e.fillModes instanceof Uint8Array&&e.fillModes.length>=n?e.fillModes.slice(0,n):null,s=e.ids instanceof Uint32Array&&e.ids.length>=n?e.ids.slice(0,n):null;return new Promise((a,c)=>{const u=be(),h=mt.beginRequest({kind:"data",resolve:a,reject:c,startMs:u});if(!h){a({data:dt(e,t),meta:{mode:"sync",durationMs:be()-u}});return}const l={type:"roi-clip-request",id:h.id,count:n,positions:r.buffer,paletteIndices:i.buffer,fillModes:o?.buffer,ids:s?.buffer,polygons:t??[]},f=[r.buffer,i.buffer];o&&f.push(o.buffer),s&&f.push(s.buffer);try{h.worker.postMessage(l,f)}catch(d){const m=mt.cancelRequest(h.id);m?m.reject(d):c(d)}})}async function Ds(e,t){if(!e||!e.count||!e.positions||!e.paletteIndices)return{indices:new Uint32Array(0),meta:{mode:"worker",durationMs:0}};const n=et(e),r=e.positions.slice(0,n*2);return new Promise((i,o)=>{const s=be(),a=mt.beginRequest({kind:"index",resolve:i,reject:o,startMs:s});if(!a){i({indices:ri(e,t),meta:{mode:"sync",durationMs:be()-s}});return}const c={type:"roi-clip-index-request",id:a.id,count:n,positions:r.buffer,polygons:t??[]};try{a.worker.postMessage(c,[r.buffer])}catch(u){const h=mt.cancelRequest(a.id);h?h.reject(u):o(u)}})}const Us={count:0,positions:new Float32Array(0),paletteIndices:new Uint16Array(0)};function Os(e,t,n,r,i){const o=g.useRef(0),[s,a]=g.useState(n),c=g.useMemo(()=>r.map(u=>pt(u.coordinates)).filter(u=>u!=null),[r]);return g.useEffect(()=>{const u=++o.current;let h=!1;if(!e)return a(n),()=>{h=!0};if(!n||!n.count||!n.positions||!n.paletteIndices)return a(null),()=>{h=!0};if(c.length===0)return a(Us),i?.({mode:t,durationMs:0,inputCount:n.count,outputCount:0,polygonCount:0}),()=>{h=!0};const l=(d,m)=>{if(h||u!==o.current)return;const p=n.count,y=d?.drawIndices?d.drawIndices.length:d?.count??0;a(d),i?.({mode:m.mode,durationMs:m.durationMs,inputCount:p,outputCount:y,polygonCount:c.length,usedWebGpu:m.usedWebGpu,candidateCount:m.candidateCount,bridgedToDraw:m.bridgedToDraw})};return(async()=>{if(t==="sync"){const d=performance.now(),m=dt(n,c);l(m,{mode:"sync",durationMs:performance.now()-d});return}if(t==="hybrid-webgpu"){const d=await si(n,c,{bridgeToDraw:!0});l(d.data,{mode:d.meta.mode,durationMs:d.meta.durationMs,usedWebGpu:d.meta.usedWebGpu,candidateCount:d.meta.candidateCount,bridgedToDraw:d.meta.bridgedToDraw});return}try{const d=await li(n,c);l(d.data,{mode:d.meta.mode,durationMs:d.meta.durationMs})}catch{const d=performance.now(),m=dt(n,c);l(m,{mode:"sync",durationMs:performance.now()-d})}})(),()=>{h=!0}},[e,t,n,c,i]),s}const Ys=24,Ws=1024,Xs=4,Lt=-1;function ct(e,t,n){return(e*73856093^t*19349663)>>>0&n}function Vs(e,t,n){if(e<=0||t<=0||n<=0)return 256;const r=Math.max(1,e*t),o=Math.sqrt(r/Math.max(1,n))*Xs;return Math.max(Ys,Math.min(Ws,o))}function Gs(e,t){if(!(e instanceof Uint32Array)||e.length===0)return null;let n=!0;for(let o=0;o<e.length;o+=1)if(!(e[o]<t)){n=!1;break}if(n)return e;const r=new Uint32Array(e.length);let i=0;for(let o=0;o<e.length;o+=1)e[o]>=t||(r[i]=e[o],i+=1);return i>0?r.subarray(0,i):null}function qs(e){const t=Math.max(0,Math.floor(e.count)),n=Math.floor(e.positions.length/2),r=Math.max(0,Math.min(t,n));if(r<=0)return null;const i=Gs(e.drawIndices??null,r),o=i?i.length:r;if(o===0)return null;const s=Vs(e.sourceWidth,e.sourceHeight,o),a=1/s,c=new Int32Array(o),u=new Int32Array(o);let h=0;if(i)for(let I=0;I<o;I+=1){const H=i[I],N=e.positions[H*2],k=e.positions[H*2+1];!Number.isFinite(N)||!Number.isFinite(k)||(c[h]=Math.floor(N*a),u[h]=Math.floor(k*a),h+=1)}else for(let I=0;I<r;I+=1){const H=e.positions[I*2],N=e.positions[I*2+1];!Number.isFinite(H)||!Number.isFinite(N)||(c[h]=Math.floor(H*a),u[h]=Math.floor(N*a),h+=1)}if(h===0)return null;let l=Math.min(h,Math.max(64,h>>>3));(!Number.isFinite(l)||l<=0)&&(l=h);let f=1;for(;f<l*2;)f<<=1;let d=f-1,m=new Int32Array(f*2),p=new Int32Array(f);m.fill(2147483647);let y=0;const b=new Int32Array(h);for(let I=0;I<h;I+=1){const H=c[I],N=u[I];let k=ct(H,N,d);for(;;){const Z=m[k*2];if(Z===2147483647){if(m[k*2]=H,m[k*2+1]=N,p[k]=1,b[I]=k,y+=1,y*4>f*3){const we=f;f<<=1,d=f-1;const se=new Int32Array(f*2),Re=new Int32Array(f);se.fill(2147483647);for(let Ce=0;Ce<we;Ce+=1){if(m[Ce*2]===2147483647)continue;const xe=m[Ce*2],M=m[Ce*2+1];let v=ct(xe,M,d);for(;se[v*2]!==2147483647;)v=v+1&d;se[v*2]=xe,se[v*2+1]=M,Re[v]=p[Ce]}for(m=se,p=Re,k=ct(H,N,d);m[k*2]!==H||m[k*2+1]!==N;)k=k+1&d;b[I]=k}break}if(Z===H&&m[k*2+1]===N){p[k]+=1,b[I]=k;break}k=k+1&d}}const x=new Int32Array(y*2),C=new Uint32Array(y),S=new Uint32Array(y),A=new Int32Array(f);A.fill(Lt);let T=0,O=0;for(let I=0;I<f;I+=1)m[I*2]!==2147483647&&(x[T*2]=m[I*2],x[T*2+1]=m[I*2+1],C[T]=O,S[T]=p[I],A[I]=T,O+=p[I],T+=1);const z=new Uint32Array(h),G=new Uint32Array(y);if(G.set(C),i)for(let I=0;I<h;I+=1){const H=A[b[I]];z[G[H]]=i[I],G[H]+=1}else{let I=0;for(let H=0;H<r;H+=1){const N=e.positions[H*2],k=e.positions[H*2+1];if(!Number.isFinite(N)||!Number.isFinite(k))continue;const Z=A[b[I]];z[G[Z]]=H,G[Z]+=1,I+=1}}let D=1;for(;D<y*2;)D<<=1;const q=D-1,re=new Int32Array(D);re.fill(Lt);for(let I=0;I<y;I+=1){const H=x[I*2],N=x[I*2+1];let k=ct(H,N,q);for(;re[k]!==Lt;)k=k+1&q;re[k]=I}return{cellSize:s,safeCount:r,cellCount:y,hashCapacity:D,hashTable:re,cellKeys:x,cellOffsets:C,cellLengths:S,pointIndices:z}}function ci(e,t,n){const{hashTable:r,cellKeys:i,hashMask:o}=e;let s=ct(t,n,o);for(;;){const a=r[s];if(a===Lt)return-1;if(i[a*2]===t&&i[a*2+1]===n)return a;s=s+1&o}}function Hs(e,t){if(e.safeCount<=0||e.cellCount<=0)return null;const n=e.safeCount;return{cellSize:e.cellSize,safeCount:n,positions:t.positions.subarray(0,n*2),ids:t.ids instanceof Uint32Array&&t.ids.length>=n?t.ids.subarray(0,n):null,hashCapacity:e.hashCapacity,hashMask:e.hashCapacity-1,hashTable:new Int32Array(e.hashTable),cellKeys:new Int32Array(e.cellKeys),cellOffsets:new Uint32Array(e.cellOffsets),cellLengths:new Uint32Array(e.cellLengths),pointIndices:new Uint32Array(e.pointIndices)}}const hn=new ai(()=>new Worker(new URL(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/point-hit-index-worker-CNFA6pZm.js").href:new URL("assets/point-hit-index-worker-CNFA6pZm.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"?require("url").pathToFileURL(__filename).href:it&&it.tagName.toUpperCase()==="SCRIPT"&&it.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),{onResponse:(e,t)=>{if(e.type==="point-hit-index-failure"){t.reject(new Error(e.error||"worker index build failed"));return}t.resolve(Hs(e,t.pointData))},rejectPending:(e,t)=>{e.reject(t)}});function Zs(){hn.terminate("worker terminated")}function $s(e,t){const n=et(e);if(n<=0)return null;const r=e.positions.subarray(0,n*2),i=qs({count:n,positions:r,drawIndices:e.drawIndices instanceof Uint32Array?e.drawIndices:null,sourceWidth:t?.width??0,sourceHeight:t?.height??0});return i?{cellSize:i.cellSize,safeCount:n,positions:r,ids:e.ids instanceof Uint32Array&&e.ids.length>=n?e.ids.subarray(0,n):null,hashCapacity:i.hashCapacity,hashMask:i.hashCapacity-1,hashTable:i.hashTable,cellKeys:i.cellKeys,cellOffsets:i.cellOffsets,cellLengths:i.cellLengths,pointIndices:i.pointIndices}:null}async function ui(e,t){if(!e||!e.positions||!e.paletteIndices)return null;const n=et(e);return n<=0?null:new Promise((r,i)=>{const o={resolve:r,reject:i,pointData:e},s=hn.beginRequest(o);if(!s||!s.worker){r($s(e,t));return}const a=e.positions.slice(0,n*2),c=e.drawIndices instanceof Uint32Array&&e.drawIndices.length>0?e.drawIndices.slice():void 0,u={type:"point-hit-index-request",id:s.id,count:n,positions:a.buffer,drawIndices:c?.buffer,sourceWidth:t?.width??0,sourceHeight:t?.height??0},h=[a.buffer];c&&h.push(c.buffer);try{s.worker.postMessage(u,h)}catch(l){const f=hn.cancelRequest(s.id);f?f.reject(l):i(l)}})}const Ks=.65,js=4;function Qs(e,t,n,r,i,o,s){const a=!!(n||r||i),[c,u]=g.useState(null),h=g.useRef(null),l=g.useRef(null);g.useEffect(()=>{if(!a||!e){u(null);return}let p=!1;return ui(e,t).then(y=>{p||u(y)}),()=>{p=!0}},[a,e,t]);const f=g.useCallback(p=>{const y=s.current;if(!y||!c)return null;const b=Number(p[0]),x=Number(p[1]);if(!Number.isFinite(b)||!Number.isFinite(x))return null;const C=Math.max(1e-6,y.getViewState().zoom),S=y.getPointSizeByZoom(),T=Math.max(js,S*Ks)/C;if(!Number.isFinite(T)||T<=0)return null;const{cellSize:O,cellOffsets:z,cellLengths:G,pointIndices:D,positions:q,safeCount:re}=c,I=Math.floor(b/O),H=Math.floor(x/O),N=Math.max(1,Math.ceil(T/O)),k=T*T;let Z=-1,we=k,se=0,Re=0;for(let xe=I-N;xe<=I+N;xe+=1)for(let M=H-N;M<=H+N;M+=1){const v=ci(c,xe,M);if(v<0)continue;const X=z[v],le=X+G[v];for(let Q=X;Q<le;Q+=1){const ie=D[Q];if(ie>=re)continue;const he=q[ie*2],me=q[ie*2+1],$=he-b,pe=me-x,ye=$*$+pe*pe;ye>we||(we=ye,Z=ie,se=he,Re=me)}}if(Z<0)return null;const Ce=c.ids?Number(c.ids[Z]):null;return{index:Z,id:Ce,coordinate:[b,x],pointCoordinate:[se,Re]}},[c]),d=g.useCallback((p,y)=>{if(!n)return;const b=p?.index??null,x=p?.id??null;h.current===b&&l.current===x||(h.current=b,l.current=x,n({index:b,id:x,coordinate:y,pointCoordinate:p?.pointCoordinate??null}))},[n]),m=g.useCallback((p,y)=>{if(!r)return;const b=f(p);b&&r({...b,button:y})},[r,f]);return g.useEffect(()=>{if(i)return i.current=f,()=>{i.current===f&&(i.current=null)}},[i,f]),g.useEffect(()=>{const p=h.current;p!==null&&(c&&p<c.safeCount||(h.current=null,l.current=null,n?.({index:null,id:null,coordinate:null,pointCoordinate:null})))},[c,n]),g.useEffect(()=>{},[o,n]),{getCellByCoordinates:f,emitPointHover:d,emitPointClick:m}}const Js=g.forwardRef(function({data:t=null,palette:n=null,sizeByZoom:r,strokeScale:i,innerFillOpacity:o,clipEnabled:s=!1,clipToRegions:a,clipMode:c="worker",onClipStats:u,onHover:h,onClick:l},f){const{rendererRef:d,rendererSerial:m,source:p}=ot(),y=g.useRef(null),x=Os(s,c,t,a??ea,u),{getCellByCoordinates:C}=Qs(x,p,h,l,y,"cursor",d);return g.useImperativeHandle(f,()=>({queryAt:C}),[C]),g.useEffect(()=>{const S=d.current;!S||!n||S.setPointPalette(n)},[m,n]),g.useEffect(()=>{const S=d.current;!S||r===void 0||S.setPointSizeByZoom(r)},[m,r]),g.useEffect(()=>{const S=d.current;!S||i===void 0||S.setPointStrokeScale(i)},[m,i]),g.useEffect(()=>{const S=d.current;!S||o===void 0||S.setPointInnerFillOpacity(o)},[m,o]),g.useEffect(()=>{const S=d.current;S&&S.setPointData(x)},[m,x]),null}),ea=[],ta=180,yr=20;function na(e){const t=W(e,0,1);return t*t*(3-2*t)}function ra(e,t,n){const[r,i]=g.useState(0),o=g.useRef(0),s=g.useRef({rafId:null,startMs:0,from:0,to:0}),a=g.useCallback(l=>{const f=W(l,0,yr);Math.abs(o.current-f)<1e-4||(o.current=f,i(f))},[]),c=g.useCallback(()=>{const l=s.current;l.rafId!==null&&(cancelAnimationFrame(l.rafId),l.rafId=null)},[]),u=g.useCallback(l=>{const f=W(l,0,yr),d=s.current,m=o.current;if(Math.abs(m-f)<1e-4){c(),d.to=f,a(f);return}c(),d.startMs=performance.now(),d.from=m,d.to=f;const p=y=>{const b=s.current,x=Math.max(0,y-b.startMs),C=W(x/ta,0,1),S=na(C),A=b.from+(b.to-b.from)*S;if(a(A),n.current?.(),C>=1){b.rafId=null,a(b.to);return}b.rafId=requestAnimationFrame(p)};d.rafId=requestAnimationFrame(p)},[a,c]),h=g.useCallback(l=>{const f=t.current;if(!f||typeof l!="number"||!Number.isFinite(l)){u(0);return}const d=In(e,l,f.getZoomRange());u(d)},[e,u]);return g.useEffect(()=>()=>{c()},[c]),{regionLabelAutoLiftOffsetPx:r,syncRegionLabelAutoLiftTarget:h,cancelRegionLabelAutoLiftAnimation:c,applyRegionLabelAutoLiftOffset:a}}const ia=6;function dn(e,t){return e.id??t}function oa(e,t,n,r,i,o){const s=i-n,a=o-r,c=s*s+a*a;if(c<=1e-12){const m=e-n,p=t-r;return m*m+p*p}const u=W(((e-n)*s+(t-r)*a)/c,0,1),h=n+s*u,l=r+a*u,f=e-h,d=t-l;return f*f+d*d}function br(e,t,n,r){for(let i=1;i<n.length;i+=1){const o=n[i-1],s=n[i];if(oa(e,t,o[0],o[1],s[0],s[1])<=r)return!0}return!1}function sa(e,t,n,r){if(e<n.minX-r||e>n.maxX+r||t<n.minY-r||t>n.maxY+r)return!1;const i=r*r;if(br(e,t,n.outer,i))return!0;for(const o of n.holes)if(br(e,t,o,i))return!0;return!1}function aa(e,t,n,r,i,o,s){if(!e.label||!e.labelAnchor)return!1;const a=En(n.worldToScreen(e.labelAnchor[0],e.labelAnchor[1]));if(!a)return!1;const u=Mn(e.label,r)+r.paddingX*2,h=r.fontSize+r.paddingY*2,l=a[0],f=a[1]-r.offsetY,d=s?W(l,u*.5+1,i-u*.5-1):l,m=s?W(f,h*.5+1,o-h*.5-1):f,p=d-u*.5,y=d+u*.5,b=m-h*.5,x=m+h*.5;return t[0]>=p&&t[0]<=y&&t[1]>=b&&t[1]<=x}function la(e,t="top-center"){const n=[];for(let r=0;r<e.length;r+=1){const i=e[r],o=yt([pt(i?.coordinates)]);if(o.length===0)continue;const s=typeof i?.label=="string"?i.label.trim():"";n.push({region:i,regionIndex:r,regionId:dn(i,r),polygons:o,label:s,labelAnchor:s?An(o,t):null})}return n}function wr(e,t,n,r,i,o,s,a,c,u=!0){const h=e[0],l=e[1],f=Math.max(1e-6,r.getViewState().zoom),d=Math.max(0,s),m=ia/f;for(let p=n.length-1;p>=0;p-=1){const y=n[p];for(const x of y.polygons)if(sa(h,l,x,m))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId};let b=Cn(i,o?.({region:y.region,regionId:y.regionId,regionIndex:y.regionIndex,zoom:f}));if(d>0&&(b={...b,offsetY:b.offsetY+d}),!!aa(y,t,r,b,a,c,u))return{region:y.region,regionIndex:y.regionIndex,regionId:y.regionId}}return null}const xr=[],ca=[],Sr="__region_layer__",Er="__region_label__";function ua(e){return{color:Gr,width:qr,lineDash:Je,lineJoin:e.lineJoin,lineCap:e.lineCap,shadowColor:"rgba(0, 0, 0, 0)",shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0}}function fa({regions:e,polygons:t,strokeStyle:n,hoverStrokeStyle:r,activeStrokeStyle:i,resolveStrokeStyle:o,labelStyle:s,labelAnchor:a="top-center",autoLiftLabelAtMaxZoom:c=!1,clampLabelToViewport:u=!0,activeRegionId:h,onActiveChange:l,onHover:f,onClick:d}){const{rendererRef:m,rendererSerial:p,canvasRef:y,containerRef:b,registerDrawCallback:x,unregisterDrawCallback:C,requestOverlayRedraw:S,drawInvalidateRef:A,screenToWorld:T,worldToScreen:O,isInteractionLocked:z}=ot(),G=e??xr,D=t??ca,q=g.useMemo(()=>G.length>0?G:D.length===0?xr:D.map((U,V)=>({id:V,coordinates:U})),[G,D]),[re,I]=g.useState(null),[H,N]=g.useState(()=>h??null),k=h!==void 0,Z=k?h??null:H,we=g.useRef(null);g.useEffect(()=>{k&&N(h??null)},[k,h]);const se=g.useCallback(U=>{String(Z)!==String(U)&&(k||N(U),l?.(U))},[Z,k,l]),{regionLabelAutoLiftOffsetPx:Re,syncRegionLabelAutoLiftTarget:Ce}=ra(c,m,A),xe=g.useMemo(()=>Rn(n),[n]),M=g.useMemo(()=>Ve(xe,r),[xe,r]),v=g.useMemo(()=>Ve(xe,i),[xe,i]),{staticLabelStyle:X,labelStyleResolver:le}=g.useMemo(()=>typeof s=="function"?{staticLabelStyle:void 0,labelStyleResolver:s}:{staticLabelStyle:s,labelStyleResolver:void 0},[s]),Q=g.useMemo(()=>vn(X),[X]),ie=g.useMemo(()=>{const U=[];for(let V=0;V<q.length;V+=1){const ee=q[V],B=Wt(ee.coordinates);B.length!==0&&U.push({region:ee,regionIndex:V,regionKey:ee.id??V,polygons:B})}return U},[q]),he=g.useMemo(()=>la(q,a),[q,a]);g.useEffect(()=>{const U=m.current;U&&Ce(U.getViewState().zoom)},[p,Ce]),g.useEffect(()=>{!(Z===null?!0:q.some((B,te)=>String(dn(B,te))===String(Z)))&&Z!==null&&se(null);const V=we.current;!(V===null?!0:q.some((B,te)=>String(dn(B,te))===String(V)))&&V!==null&&(we.current=null,I(null),f?.({region:null,regionId:null,regionIndex:-1,coordinate:null}))},[q,Z,f,se]);const me=g.useCallback(U=>{const V=m.current;if(!V||U.length===0)return[];const ee=new Array(U.length);for(let B=0;B<U.length;B+=1){const te=Oe(V.worldToScreen(U[B][0],U[B][1]));if(!te)return[];ee[B]=te}return ee},[]),$=g.useRef({preparedRegions:ie,hoveredRegionId:re,activeRegionId:Z,resolvedStrokeStyle:xe,resolvedHoverStrokeStyle:M,resolvedActiveStrokeStyle:v,resolveStrokeStyleProp:o,worldToScreenPoints:me});$.current={preparedRegions:ie,hoveredRegionId:re,activeRegionId:Z,resolvedStrokeStyle:xe,resolvedHoverStrokeStyle:M,resolvedActiveStrokeStyle:v,resolveStrokeStyleProp:o,worldToScreenPoints:me},g.useEffect(()=>(x(Sr,10,V=>{const{preparedRegions:ee,hoveredRegionId:B,activeRegionId:te,resolvedStrokeStyle:de,resolvedHoverStrokeStyle:ae,resolvedActiveStrokeStyle:Me,resolveStrokeStyleProp:Se,worldToScreenPoints:_}=$.current;for(const Y of ee){const{region:J,polygons:oe,regionIndex:L,regionKey:K}=Y,ce=Ot(te,K)?"active":Ot(B,K)?"hover":"default";let ne=ce==="active"?Me:ce==="hover"?ae:de;if(Se){const ze=Se({region:J,regionId:K,regionIndex:L,state:ce});ne=Ve(ne,ze||void 0)}const ue=ce==="default"?null:ua(ne);for(const ze of oe){const qe=_(ze.outer);qe.length>=4&&(ue&&Pe(V,qe,ue,!0,!1),Pe(V,qe,ne,!0,!1));for(const Gt of ze.holes){const st=_(Gt);st.length>=4&&(ue&&Pe(V,st,ue,!0,!1),Pe(V,st,ne,!0,!1))}}}}),()=>C(Sr)),[x,C]);const pe=g.useRef({preparedRegions:ie,resolvedLabelStyle:Q,labelStyleResolver:le,labelAnchor:a,autoLiftLabelAtMaxZoom:c,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:Re,rendererRef:m});pe.current={preparedRegions:ie,resolvedLabelStyle:Q,labelStyleResolver:le,labelAnchor:a,autoLiftLabelAtMaxZoom:c,clampLabelToViewport:u,regionLabelAutoLiftOffsetPx:Re,rendererRef:m},g.useEffect(()=>(x(Er,50,(V,ee,B)=>{const{preparedRegions:te,resolvedLabelStyle:de,labelStyleResolver:ae,labelAnchor:Me,autoLiftLabelAtMaxZoom:Se,clampLabelToViewport:_,regionLabelAutoLiftOffsetPx:Y,rendererRef:J}=pe.current;if(te.length===0)return;const oe=Math.max(1e-6,J.current?.getViewState?.().zoom??1),L=typeof Y=="number"&&Number.isFinite(Y)?Math.max(0,Y):In(Se,oe,J.current?.getZoomRange?.());for(const K of te){if(!K.region.label)continue;const ce=An(K.polygons,Me);if(!ce)continue;const ne=Oe(J.current?.worldToScreen(ce[0],ce[1])??[]);if(!ne)continue;let ue=Cn(de,ae?.({region:K.region,regionId:K.regionKey,regionIndex:K.regionIndex,zoom:oe}));L>0&&(ue={...ue,offsetY:ue.offsetY+L}),Qr(V,K.region.label,ne,ee,B,ue,_)}}),()=>C(Er)),[x,C]),g.useEffect(()=>{S()},[ie,re,Z,xe,Q,Re,S]);const ye=g.useRef({preparedRegionHits:he,resolvedLabelStyle:Q,labelStyleResolver:le,regionLabelAutoLiftOffsetPx:Re,clampLabelToViewport:u,onHover:f,onClick:d,commitActive:se});return ye.current={preparedRegionHits:he,resolvedLabelStyle:Q,labelStyleResolver:le,regionLabelAutoLiftOffsetPx:Re,clampLabelToViewport:u,onHover:f,onClick:d,commitActive:se},g.useEffect(()=>{const U=b.current;if(!U)return;const V=te=>{if(z())return;const de=m.current;if(!de)return;const{preparedRegionHits:ae,resolvedLabelStyle:Me,labelStyleResolver:Se,regionLabelAutoLiftOffsetPx:_,clampLabelToViewport:Y,onHover:J}=ye.current,oe=T(te.clientX,te.clientY);if(!oe)return;let L=null,K=null;if(ae.length>0){const ne=O(oe[0],oe[1]);if(ne){const ue=y.current?.getBoundingClientRect();K=wr(oe,ne,ae,de,Me,Se,typeof _=="number"?_:0,ue?.width??0,ue?.height??0,Y),L=K?.regionId??null}}const ce=we.current;String(ce)!==String(L)&&(we.current=L,I(L),J?.({region:K?.region??null,regionId:L,regionIndex:K?.regionIndex??-1,coordinate:oe}),S())},ee=te=>{if(z())return;const de=m.current;if(!de)return;const{preparedRegionHits:ae,resolvedLabelStyle:Me,labelStyleResolver:Se,regionLabelAutoLiftOffsetPx:_,clampLabelToViewport:Y,onClick:J,commitActive:oe}=ye.current;if(ae.length===0)return;const L=T(te.clientX,te.clientY);if(!L)return;const K=O(L[0],L[1]);if(!K)return;const ce=y.current?.getBoundingClientRect(),ne=wr(L,K,ae,de,Me,Se,typeof _=="number"?_:0,ce?.width??0,ce?.height??0,Y),ue=ne?.regionId??null;oe(ue),ne&&J&&J({region:ne.region,regionId:ne.regionId,regionIndex:ne.regionIndex,coordinate:L})},B=()=>{we.current!==null&&(we.current=null,I(null),ye.current.onHover?.({region:null,regionId:null,regionIndex:-1,coordinate:null}),S())};return U.addEventListener("pointermove",V),U.addEventListener("click",ee),U.addEventListener("pointerleave",B),()=>{U.removeEventListener("pointermove",V),U.removeEventListener("click",ee),U.removeEventListener("pointerleave",B)}},[b,m,y,T,O,z,S]),null}function ha({imageWidth:e,imageHeight:t,tiles:n,viewState:r,className:i,style:o}){const s=g.useRef(null),a=g.useRef(null),c=g.useMemo(()=>({width:"100%",height:"100%",display:"block",...o}),[o]);return g.useEffect(()=>{const u=s.current;if(!u)return;const h=new zr({canvas:u,imageWidth:e,imageHeight:t,initialViewState:r});return a.current=h,h.setTiles(n),()=>{h.destroy(),a.current=null}},[e,t]),g.useEffect(()=>{const u=a.current;u&&u.setTiles(n)},[n]),g.useEffect(()=>{const u=a.current;!u||!r||u.setViewState(r)},[r]),Ye.jsx("canvas",{ref:s,className:i,style:c})}function da(e,t){if(!t)return!1;try{const r=new URL(e,typeof window<"u"?window.location.href:void 0).hostname.toLowerCase();if(r.includes("amazonaws.com")||r.startsWith("s3.")||r.includes(".s3."))return!1}catch{}return!0}class fi{constructor(t){R(this,"maxConcurrency");R(this,"maxRetries");R(this,"retryBaseDelayMs");R(this,"retryMaxDelayMs");R(this,"onTileLoad");R(this,"onTileError");R(this,"onStateChange");R(this,"authToken");R(this,"destroyed",!1);R(this,"queue",[]);R(this,"queuedByKey",new Map);R(this,"inflight",new Map);R(this,"visibleKeys",new Set);R(this,"timerId",null);R(this,"abortedCount",0);R(this,"retryCount",0);R(this,"failedCount",0);this.maxConcurrency=Math.max(1,Math.floor(t.maxConcurrency??12)),this.maxRetries=Math.max(0,Math.floor(t.maxRetries??2)),this.retryBaseDelayMs=Math.max(10,Math.floor(t.retryBaseDelayMs??120)),this.retryMaxDelayMs=Math.max(this.retryBaseDelayMs,Math.floor(t.retryMaxDelayMs??1200)),this.authToken=t.authToken??"",this.onTileLoad=t.onTileLoad,this.onTileError=t.onTileError,this.onStateChange=t.onStateChange}setAuthToken(t){this.authToken=String(t??"")}schedule(t){if(this.destroyed)return;const n=new Set;for(const r of t)n.add(r.key);this.visibleKeys=n,this.dropInvisibleQueued(n),this.abortInvisibleInflight(n);for(const r of t){if(this.inflight.has(r.key)){const s=this.inflight.get(r.key);s&&(s.tile=r);continue}const i=this.queuedByKey.get(r.key);if(i){i.tile=r;continue}const o={tile:r,attempt:0,readyAt:be()};this.queue.push(o),this.queuedByKey.set(r.key,o)}this.sortQueue(),this.pump(),this.emitStateChange()}clear(){this.clearPumpTimer(),this.visibleKeys.clear(),this.queue=[],this.queuedByKey.clear();for(const[,t]of this.inflight)t.controller.abort();this.inflight.clear(),this.emitStateChange()}destroy(){this.destroyed||(this.destroyed=!0,this.clear())}getInflightCount(){return this.inflight.size}getSnapshot(){return{inflight:this.inflight.size,queued:this.queue.length,aborted:this.abortedCount,retries:this.retryCount,failed:this.failedCount}}dropInvisibleQueued(t){if(this.queue.length===0)return;const n=[];for(const r of this.queue){if(!t.has(r.tile.key)){this.queuedByKey.delete(r.tile.key);continue}n.push(r)}this.queue=n}abortInvisibleInflight(t){for(const[n,r]of this.inflight)t.has(n)||(this.inflight.delete(n),this.abortedCount+=1,r.controller.abort())}sortQueue(){this.queue.sort((t,n)=>t.readyAt!==n.readyAt?t.readyAt-n.readyAt:t.tile.distance2!==n.tile.distance2?t.tile.distance2-n.tile.distance2:t.tile.tier!==n.tile.tier?n.tile.tier-t.tile.tier:t.tile.key.localeCompare(n.tile.key))}pump(){if(this.destroyed)return;for(this.clearPumpTimer();this.inflight.size<this.maxConcurrency;){const r=this.takeNextReadyQueueItem();if(!r)break;this.startFetch(r)}if(this.inflight.size>=this.maxConcurrency||this.queue.length===0)return;const t=this.queue[0]?.readyAt;if(typeof t!="number")return;const n=Math.max(0,t-be());this.timerId=globalThis.setTimeout(()=>{this.timerId=null,this.pump()},n)}takeNextReadyQueueItem(){if(this.queue.length===0)return null;const t=be(),n=this.queue[0];return!n||n.readyAt>t?null:(this.queue.shift(),this.queuedByKey.delete(n.tile.key),n)}startFetch(t){const n=new AbortController,r={tile:t.tile,attempt:t.attempt,controller:n};this.inflight.set(t.tile.key,r),this.emitStateChange();const i=da(t.tile.url,this.authToken);fetch(t.tile.url,{signal:n.signal,headers:i?{Authorization:this.authToken}:void 0}).then(o=>{if(!o.ok)throw new Error(`HTTP ${o.status}`);return o.blob()}).then(o=>createImageBitmap(o)).then(o=>{if(this.destroyed||n.signal.aborted){o.close();return}if(!this.visibleKeys.has(t.tile.key)){o.close();return}this.onTileLoad(t.tile,o)}).catch(o=>{if(n.signal.aborted||this.destroyed)return;if(t.attempt<this.maxRetries&&this.visibleKeys.has(t.tile.key)){this.retryCount+=1;const a=t.attempt+1,c=this.getRetryDelay(a),u={tile:t.tile,attempt:a,readyAt:be()+c},h=this.queuedByKey.get(t.tile.key);h?(h.tile=u.tile,h.readyAt=Math.min(h.readyAt,u.readyAt),h.attempt=Math.max(h.attempt,u.attempt)):(this.queue.push(u),this.queuedByKey.set(u.tile.key,u)),this.sortQueue();return}this.failedCount+=1,this.onTileError?.(t.tile,o,t.attempt+1)}).finally(()=>{this.inflight.delete(t.tile.key),this.pump(),this.emitStateChange()})}getRetryDelay(t){const n=Math.max(0,t-1),r=Math.min(this.retryMaxDelayMs,this.retryBaseDelayMs*2**n),i=.85+Math.random()*.3;return Math.round(r*i)}clearPumpTimer(){this.timerId!==null&&(globalThis.clearTimeout(this.timerId),this.timerId=null)}emitStateChange(){this.onStateChange?.(this.getSnapshot())}}function ma(e,t){e.addEventListener("pointerdown",t.pointerDown),e.addEventListener("pointermove",t.pointerMove),e.addEventListener("pointerup",t.pointerUp),e.addEventListener("pointercancel",t.pointerUp),e.addEventListener("wheel",t.wheel,{passive:!1}),e.addEventListener("dblclick",t.doubleClick),e.addEventListener("contextmenu",t.contextMenu),e.addEventListener("webglcontextlost",t.contextLost),e.addEventListener("webglcontextrestored",t.contextRestored)}function ga(e,t){e.removeEventListener("pointerdown",t.pointerDown),e.removeEventListener("pointermove",t.pointerMove),e.removeEventListener("pointerup",t.pointerUp),e.removeEventListener("pointercancel",t.pointerUp),e.removeEventListener("wheel",t.wheel),e.removeEventListener("dblclick",t.doubleClick),e.removeEventListener("contextmenu",t.contextMenu),e.removeEventListener("webglcontextlost",t.contextLost),e.removeEventListener("webglcontextrestored",t.contextRestored)}function pa(e,t,n){const r=e.getBoundingClientRect(),i=Math.max(1,r.width||e.clientWidth||1),o=Math.max(1,r.height||e.clientHeight||1),s=Math.max(1,window.devicePixelRatio||1),a=Math.max(1,Math.round(i*s)),c=Math.max(1,Math.round(o*s));(e.width!==a||e.height!==c)&&(e.width=a,e.height=c),n.setViewport(i,o),t.viewport(0,0,a,c)}const mn=.35,gn=.5,ya=256,pn=[{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}],ba=.1,wa=5,xa=0,Sa=1,Ea=-100,Ra=100,Ma=2e3;function Vt(e){return e*Math.PI/180}function It(e,t){return!e||!t?e===t:e.buffer===t.buffer&&e.byteOffset===t.byteOffset&&e.byteLength===t.byteLength}function yn(e){return e.map(t=>({zoom:t.zoom,size:t.size}))}function Rr(e){if(!e)return yn(pn);const t=new Map;for(const[n,r]of Object.entries(e)){const i=Number(n),o=Number(r);!Number.isFinite(i)||!Number.isFinite(o)||o<=0||t.set(i,o)}return t.size===0?yn(pn):Array.from(t.entries()).sort((n,r)=>n[0]-r[0]).map(([n,r])=>({zoom:n,size:r}))}function Aa(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n].zoom!==t[n].zoom||e[n].size!==t[n].size)return!1;return!0}function va(e,t){if(!Number.isFinite(e))return t[0]?.size??gn;if(t.length===0)return gn;if(t.length===1||e<=t[0].zoom)return t[0].size;for(let s=1;s<t.length;s+=1){const a=t[s-1],c=t[s];if(e>c.zoom)continue;const u=Math.max(1e-6,c.zoom-a.zoom),h=W((e-a.zoom)/u,0,1);return a.size+(c.size-a.size)*h}const n=t[t.length-1],r=t[t.length-2],i=Math.max(1e-6,n.zoom-r.zoom),o=(n.size-r.size)/i;return n.size+(e-n.zoom)*o}function Mr(e){return typeof e!="number"||!Number.isFinite(e)?1:W(e,ba,wa)}function Ar(e){return typeof e!="number"||!Number.isFinite(e)?0:W(e,xa,Sa)}function Jt(e){return typeof e!="number"||!Number.isFinite(e)?0:W(e,Ea,Ra)}function vr(e){const t=Jt(e?.brightness),n=Jt(e?.contrast),r=Jt(e?.saturation);return{brightness:t/200,contrast:n/100,saturation:r/100}}function Tn(e){return e}function en(e){return typeof e!="number"||!Number.isFinite(e)?0:W(e,0,Ma)}function Pt(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:Math.max(1e-6,e)}function tn(e){return typeof e=="function"?e:Tn}function hi(e,t,n){const r=e.getBoundingClientRect(),i=t-r.left-r.width*.5,o=n-r.top-r.height*.5;return Math.atan2(o,i)}function di(e,t){if(t.pointerId!==null&&e.hasPointerCapture(t.pointerId))try{e.releasePointerCapture(t.pointerId)}catch{}t.dragging=!1,t.mode="none",t.rotateLastAngleRad=null,t.pointerId=null,e.classList.remove("dragging")}function Ca(e){const{event:t,canvas:n,state:r,config:i,cancelViewAnimation:o}=e,s=i.ctrlDragRotate&&(t.ctrlKey||t.metaKey);(t.button===0||s&&t.button===2)&&(o(),s&&t.preventDefault(),r.dragging=!0,r.mode=s?"rotate":"pan",r.pointerId=t.pointerId,r.lastPointerX=t.clientX,r.lastPointerY=t.clientY,r.rotateLastAngleRad=r.mode==="rotate"?hi(n,t.clientX,t.clientY):null,n.classList.add("dragging"),n.setPointerCapture(t.pointerId))}function Ia(e){const{event:t,canvas:n,state:r,config:i,camera:o,clampViewState:s,emitViewState:a,requestRender:c}=e;if(!r.dragging||t.pointerId!==r.pointerId)return;const u=t.clientX-r.lastPointerX,h=t.clientY-r.lastPointerY;if(r.lastPointerX=t.clientX,r.lastPointerY=t.clientY,r.mode==="rotate"){const l=hi(n,t.clientX,t.clientY),f=r.rotateLastAngleRad;if(r.rotateLastAngleRad=l,f!==null){const d=l-f,m=Math.atan2(Math.sin(d),Math.cos(d)),p=i.rotationDragSensitivityDegPerPixel/mn,y=o.getViewState();o.setViewState({rotationDeg:y.rotationDeg-m*180/Math.PI*p})}}else{const l=o.getViewState(),f=Math.max(1e-6,l.zoom),d=Vt(l.rotationDeg),m=Math.cos(d),p=Math.sin(d),y=(u*m-h*p)/f,b=(u*p+h*m)/f;o.setViewState({offsetX:l.offsetX-y,offsetY:l.offsetY-b})}s(),a(),c()}function Pa(e,t,n){e.pointerId===n.pointerId&&di(t,n)}function Ta(e){const{event:t,canvas:n,onZoomBy:r}=e;t.preventDefault();const i=n.getBoundingClientRect(),o=t.clientX-i.left,s=t.clientY-i.top,a=t.deltaY<0?1.12:.89;r(a,o,s)}const _a=4;function Fa(e){const{event:t,canvas:n,snapState:r,onSnapZoom:i}=e;if(t.preventDefault(),r.accumulatedDelta!==0&&t.deltaY!==0&&Math.sign(r.accumulatedDelta)!==Math.sign(t.deltaY)&&(r.accumulatedDelta=0),r.accumulatedDelta+=t.deltaY,Math.abs(r.accumulatedDelta)<_a)return;const o=n.getBoundingClientRect(),s=t.clientX-o.left,a=t.clientY-o.top,c=r.accumulatedDelta>0?"out":"in";r.accumulatedDelta=0,i(c,s,a)}function La(e){const{event:t,canvas:n,onZoomBy:r}=e,i=n.getBoundingClientRect(),o=t.clientX-i.left,s=t.clientY-i.top;r(t.shiftKey?.8:1.25,o,s)}function ka(e,t){(t||e.ctrlKey||e.metaKey)&&e.preventDefault()}function Xt(e){const t=e.getViewCorners();let n=1/0,r=1/0,i=-1/0,o=-1/0;for(const[s,a]of t)s<n&&(n=s),s>i&&(i=s),a<r&&(r=a),a>o&&(o=a);return[n,r,i,o]}function kt(e,t){const n=Xt(e),r=Math.max(1e-6,n[2]-n[0]),i=Math.max(1e-6,n[3]-n[1]),o=r*.2,s=i*.2,[a,c]=e.getCenter(),u=r*.5,h=i*.5,l=u-o,f=t.width-u+o,d=h-s,m=t.height-h+s,p=l<=f?W(a,l,f):t.width*.5,y=d<=m?W(c,d,m):t.height*.5;e.setCenter(p,y)}function Na(e,t){const n=Math.max(1e-6,e.getViewState().zoom),r=t.maxTierZoom+Math.log2(n);return W(Math.floor(r),0,t.maxTierZoom)}function Ba(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function mi(e,t,n){const r=Xt(e),i=Math.pow(2,t.maxTierZoom-n),o=Math.ceil(t.width/i),s=Math.ceil(t.height/i),a=Math.max(1,Math.ceil(o/t.tileSize)),c=Math.max(1,Math.ceil(s/t.tileSize)),u=r[0],h=r[1],l=r[2],f=r[3],d=W(Math.floor(u/i/t.tileSize),0,a-1),m=W(Math.floor((l-1)/i/t.tileSize),0,a-1),p=W(Math.floor(h/i/t.tileSize),0,c-1),y=W(Math.floor((f-1)/i/t.tileSize),0,c-1);if(d>m||p>y)return[];const b=(u+l)*.5/i/t.tileSize,x=(h+f)*.5/i/t.tileSize,C=[];for(let S=p;S<=y;S+=1)for(let A=d;A<=m;A+=1){const T=A*t.tileSize*i,O=S*t.tileSize*i,z=Math.min((A+1)*t.tileSize,o)*i,G=Math.min((S+1)*t.tileSize,s)*i,D=A-b,q=S-x;C.push({key:`${n}/${A}/${S}`,tier:n,x:A,y:S,bounds:[T,O,z,G],distance2:D*D+q*q,url:Pn(t,n,A,S)})}return C.sort((S,A)=>S.distance2-A.distance2),C}function za(e,t){const n=Na(e,t);return{tier:n,visible:mi(e,t,n)}}function Da(e){e.interactionLocked||Ca({event:e.event,canvas:e.canvas,state:e.state,config:{ctrlDragRotate:e.ctrlDragRotate,rotationDragSensitivityDegPerPixel:e.rotationDragSensitivityDegPerPixel},cancelViewAnimation:e.cancelViewAnimation})}function Ua(e){e.interactionLocked||Ia({event:e.event,canvas:e.canvas,state:e.state,config:{ctrlDragRotate:e.ctrlDragRotate,rotationDragSensitivityDegPerPixel:e.rotationDragSensitivityDegPerPixel},camera:e.camera,clampViewState:()=>kt(e.camera,e.source),emitViewState:e.emitViewState,requestRender:e.requestRender})}function Oa(e){e.interactionLocked||Pa(e.event,e.canvas,e.state)}function Ya(e){e.interactionLocked||La({event:e.event,canvas:e.canvas,onZoomBy:e.onZoomBy})}function Wa(e){ka(e.event,e.state.dragging)}function Xa(e,t){di(e,t)}function Va(e){return{pointerDown:t=>Da({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state,ctrlDragRotate:e.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:e.getRotationDragSensitivityDegPerPixel(),cancelViewAnimation:e.cancelViewAnimation}),pointerMove:t=>Ua({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state,ctrlDragRotate:e.getCtrlDragRotate(),rotationDragSensitivityDegPerPixel:e.getRotationDragSensitivityDegPerPixel(),camera:e.camera,source:e.source,emitViewState:e.emitViewState,requestRender:e.requestRender}),pointerUp:t=>Oa({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,state:e.state}),wheel:t=>{if(e.getInteractionLocked()){t.preventDefault();return}if(e.getUseZoomSnaps?.()&&e.onSnapZoom&&e.zoomSnapState){Fa({event:t,canvas:e.canvas,snapState:e.zoomSnapState,onSnapZoom:e.onSnapZoom});return}Ta({event:t,canvas:e.canvas,onZoomBy:e.zoomBy})},doubleClick:t=>Ya({event:t,interactionLocked:e.getInteractionLocked(),canvas:e.canvas,onZoomBy:e.zoomBy}),contextMenu:t=>Wa({event:t,canvas:e.canvas,state:e.state})}}function Ga(e){const{gl:t,cache:n,maxCacheTiles:r}=e;if(n.size<=r)return;const i=Math.max(0,Math.floor(r));for(;n.size>i;){let o=null,s=null;for(const[a,c]of n)(!s||c.lastUsed<s.lastUsed)&&(o=a,s=c);if(!o||!s)break;t.deleteTexture(s.texture),n.delete(o)}}function qa(e,t){if(e.isContextLost())return null;const n=e.createTexture();return n?(e.bindTexture(e.TEXTURE_2D,n),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,1),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.bindTexture(e.TEXTURE_2D,null),n):null}function Ha(e){const{gl:t,cache:n,tile:r,bitmap:i,frameSerial:o,maxCacheTiles:s,destroyed:a,contextLost:c,requestRender:u}=e;if(a||c||t.isContextLost()){i.close();return}if(n.has(r.key)){i.close();return}const h=qa(t,i);i.close(),h&&(n.set(r.key,{key:r.key,texture:h,bounds:r.bounds,tier:r.tier,lastUsed:o}),Ga({gl:t,cache:n,maxCacheTiles:s}),u())}function Za(e,t){for(const[,n]of t)e.deleteTexture(n.texture)}function $a(e){const{event:t,destroyed:n,contextLost:r,cancelViewAnimation:i,cancelDrag:o,tileScheduler:s,cache:a,onContextLost:c}=e;if(t.preventDefault(),n||r)return{handled:!1,frame:e.frame};let u=e.frame;return u!==null&&(cancelAnimationFrame(u),u=null),i(),o(),s.clear(),a.clear(),c?.(),{handled:!0,frame:u}}function Ka(e){if(e.destroyed)return{didDestroy:!1,frame:e.frame};let t=e.frame;return t!==null&&(cancelAnimationFrame(t),t=null),e.cancelViewAnimation(),e.resizeObserver.disconnect(),e.removeCanvasEventListeners(),e.cancelDrag(),e.tileScheduler.destroy(),!e.contextLost&&!e.gl.isContextLost()&&(Za(e.gl,e.cache),e.gl.deleteBuffer(e.tileProgram.vbo),e.gl.deleteVertexArray(e.tileProgram.vao),e.gl.deleteProgram(e.tileProgram.program),e.gl.deleteBuffer(e.pointProgram.posBuffer),e.gl.deleteBuffer(e.pointProgram.termBuffer),e.gl.deleteBuffer(e.pointProgram.fillModeBuffer),e.gl.deleteBuffer(e.pointProgram.indexBuffer),e.gl.deleteTexture(e.pointProgram.paletteTexture),e.gl.deleteVertexArray(e.pointProgram.vao),e.gl.deleteProgram(e.pointProgram.program)),e.cache.clear(),{didDestroy:!0,frame:t}}function ja(e,t){if(t<=0||e.length===0)return new Uint32Array(0);let n=e.length;for(let o=0;o<e.length;o+=1)e[o]<t||(n-=1);if(n===e.length)return e;if(n<=0)return new Uint32Array(0);const r=new Uint32Array(n);let i=0;for(let o=0;o<e.length;o+=1){const s=e[o];s>=t||(r[i]=s,i+=1)}return r}function Qa(e,t){return t<=0?new Uint8Array(0):e.length<t?new Uint8Array(t):e.subarray(0,t)}function Ja(e,t,n,r,i){if(!i||i.length===0)return{...e,lastPointPalette:null};const o=new Uint8Array(i);if(r||t.isContextLost())return{...e,lastPointPalette:o};const s=Math.max(1,Math.floor(o.length/4));return t.bindTexture(t.TEXTURE_2D,n.paletteTexture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,s,1,0,t.RGBA,t.UNSIGNED_BYTE,o),t.bindTexture(t.TEXTURE_2D,null),{...e,lastPointPalette:o,pointPaletteSize:s}}function el(e,t,n,r,i){if(!i||!i.count||!i.positions||!i.paletteIndices)return{...e,lastPointData:null,pointCount:0,usePointIndices:!1};const o=i.fillModes instanceof Uint8Array?i.fillModes:null,s=o!==null,a=Math.max(0,Math.min(i.count,Math.floor(i.positions.length/2),i.paletteIndices.length,s?o.length:Number.MAX_SAFE_INTEGER)),c=i.positions.subarray(0,a*2),u=i.paletteIndices.subarray(0,a),h=s?o.subarray(0,a):void 0,l=i.drawIndices instanceof Uint32Array,f=l?ja(i.drawIndices,a):null,d=e.lastPointData,m=d?.fillModes instanceof Uint8Array,p=e.pointBuffersDirty||!d||d.count!==a||!It(d.positions,c)||!It(d.paletteIndices,u)||m!==s||s&&(!d?.fillModes||!It(d.fillModes,h)),y=e.pointBuffersDirty||l&&(!d?.drawIndices||!It(d.drawIndices,f))||!l&&!!d?.drawIndices,b={...e,lastPointData:{count:a,positions:c,paletteIndices:u,fillModes:h,drawIndices:l?f??void 0:void 0}};if(r||t.isContextLost())return b;const x=b.lastPointData;if(!x)return b;if(p){t.bindBuffer(t.ARRAY_BUFFER,n.posBuffer),t.bufferData(t.ARRAY_BUFFER,x.positions,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,n.termBuffer),t.bufferData(t.ARRAY_BUFFER,x.paletteIndices,t.STATIC_DRAW);const C=Qa(b.zeroFillModes,a);t.bindBuffer(t.ARRAY_BUFFER,n.fillModeBuffer),t.bufferData(t.ARRAY_BUFFER,x.fillModes??C,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,null),b.zeroFillModes=C}return l&&y&&(t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,n.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,f??new Uint32Array(0),t.DYNAMIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null)),b.usePointIndices=l,b.pointCount=l?f?.length??0:x.count,(p||y)&&(b.pointBuffersDirty=!1),b}function tl(e){const{gl:t,camera:n,source:r,cache:i,frameSerial:o,tileProgram:s,pointProgram:a,imageColorSettings:c,pointCount:u,usePointIndices:h,pointPaletteSize:l,pointStrokeScale:f,pointInnerFillOpacity:d,pointSizePx:m,tileScheduler:p,getVisibleTiles:y,getVisibleTilesForTier:b,getViewBounds:x,intersectsBounds:C}=e;t.clearColor(.03,.06,.1,1),t.clear(t.COLOR_BUFFER_BIT);const{tier:S,visible:A}=y(),T=x(),O=new Set(A.map(N=>N.key));t.useProgram(s.program),t.bindVertexArray(s.vao),t.uniformMatrix3fv(s.uCamera,!1,n.getMatrix()),t.uniform1i(s.uTexture,0),t.uniform1f(s.uBrightness,c.brightness),t.uniform1f(s.uContrast,c.contrast),t.uniform1f(s.uSaturation,c.saturation);const z=[];for(const[,N]of i)O.has(N.key)||C(N.bounds,T)&&z.push(N);z.sort((N,k)=>N.tier-k.tier);for(const N of z)N.lastUsed=o,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,N.texture),t.uniform4f(s.uBounds,N.bounds[0],N.bounds[1],N.bounds[2],N.bounds[3]),t.drawArrays(t.TRIANGLE_STRIP,0,4);let G=0;const D=[];for(const N of A){const k=i.get(N.key);if(!k){D.push(N);continue}k.lastUsed=o,t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,k.texture),t.uniform4f(s.uBounds,k.bounds[0],k.bounds[1],k.bounds[2],k.bounds[3]),t.drawArrays(t.TRIANGLE_STRIP,0,4),G+=1}const q=D.slice(),re=1e6,I=[];S>0&&I.push(S-1),S<r.maxTierZoom&&I.push(S+1);for(const N of I){const k=b(N);for(const Z of k)i.has(Z.key)||(Z.distance2+=re,q.push(Z))}p.schedule(q),t.bindTexture(t.TEXTURE_2D,null),t.bindVertexArray(null);let H=0;return u>0&&(t.enable(t.BLEND),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA),t.useProgram(a.program),t.bindVertexArray(a.vao),t.uniformMatrix3fv(a.uCamera,!1,n.getMatrix()),t.uniform1f(a.uPointSize,m),t.uniform1f(a.uPointStrokeScale,f),t.uniform1f(a.uPointInnerFillAlpha,d),t.uniform1f(a.uPaletteSize,l),t.uniform1i(a.uPalette,1),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,a.paletteTexture),h?t.drawElements(t.POINTS,u,t.UNSIGNED_INT,0):t.drawArrays(t.POINTS,0,u),t.bindTexture(t.TEXTURE_2D,null),t.bindVertexArray(null),H=u),{tier:S,visible:A.length,rendered:G,points:H,fallback:z.length,cacheHits:G,cacheMisses:D.length,drawCalls:z.length+G+(H>0?1:0)}}function Cr(e){const r=bn(e,`#version 300 es
65
65
  precision highp float;
66
66
  in vec2 aUnit;
67
67
  in vec2 aUv;
@@ -106,7 +106,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
106
106
 
107
107
  color.rgb = clamp(color.rgb + uBrightness, vec3(0.0), vec3(1.0));
108
108
  outColor = color;
109
- }`),i=_e(e,r,"uCamera"),o=_e(e,r,"uBounds"),s=_e(e,r,"uTexture"),a=_e(e,r,"uBrightness"),c=_e(e,r,"uContrast"),u=_e(e,r,"uSaturation"),h=e.createVertexArray(),l=e.createBuffer();if(!h||!l)throw new Error("buffer allocation failed");e.bindVertexArray(h),e.bindBuffer(e.ARRAY_BUFFER,l),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,0,0,1,0,1,0,0,1,0,1,1,1,1,1]),e.STATIC_DRAW);const f=e.getAttribLocation(r,"aUnit"),d=e.getAttribLocation(r,"aUv");if(f<0||d<0)throw new Error("tile attribute lookup failed");return e.enableVertexAttribArray(f),e.enableVertexAttribArray(d),e.vertexAttribPointer(f,2,e.FLOAT,!1,16,0),e.vertexAttribPointer(d,2,e.FLOAT,!1,16,8),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),{program:r,vao:h,vbo:l,uCamera:i,uBounds:o,uTexture:s,uBrightness:a,uContrast:c,uSaturation:u}}function Pr(e){const r=bn(e,`#version 300 es
109
+ }`),i=_e(e,r,"uCamera"),o=_e(e,r,"uBounds"),s=_e(e,r,"uTexture"),a=_e(e,r,"uBrightness"),c=_e(e,r,"uContrast"),u=_e(e,r,"uSaturation"),h=e.createVertexArray(),l=e.createBuffer();if(!h||!l)throw new Error("buffer allocation failed");e.bindVertexArray(h),e.bindBuffer(e.ARRAY_BUFFER,l),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,0,0,1,0,1,0,0,1,0,1,1,1,1,1]),e.STATIC_DRAW);const f=e.getAttribLocation(r,"aUnit"),d=e.getAttribLocation(r,"aUv");if(f<0||d<0)throw new Error("tile attribute lookup failed");return e.enableVertexAttribArray(f),e.enableVertexAttribArray(d),e.vertexAttribPointer(f,2,e.FLOAT,!1,16,0),e.vertexAttribPointer(d,2,e.FLOAT,!1,16,8),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),{program:r,vao:h,vbo:l,uCamera:i,uBounds:o,uTexture:s,uBrightness:a,uContrast:c,uSaturation:u}}function Ir(e){const r=bn(e,`#version 300 es
110
110
  precision highp float;
111
111
  in vec2 aPosition;
112
112
  in uint aTerm;
@@ -159,6 +159,6 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
159
159
  // Premultiplied alpha output: inner fill is black, so it only contributes alpha.
160
160
  outColor = vec4(color.rgb * ringAlpha, alpha);
161
161
  }
162
- }`),i=_e(e,r,"uCamera"),o=_e(e,r,"uPointSize"),s=_e(e,r,"uPointStrokeScale"),a=_e(e,r,"uPointInnerFillAlpha"),c=_e(e,r,"uPalette"),u=_e(e,r,"uPaletteSize"),h=e.createVertexArray(),l=e.createBuffer(),f=e.createBuffer(),d=e.createBuffer(),m=e.createBuffer(),p=e.createTexture();if(!h||!l||!f||!d||!m||!p)throw new Error("point buffer allocation failed");e.bindVertexArray(h),e.bindBuffer(e.ARRAY_BUFFER,l),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const y=e.getAttribLocation(r,"aPosition");if(y<0)throw new Error("point position attribute not found");e.enableVertexAttribArray(y),e.vertexAttribPointer(y,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,f),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const b=e.getAttribLocation(r,"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,d),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const x=e.getAttribLocation(r,"aFillMode");if(x<0)throw new Error("point fill mode attribute not found");return e.enableVertexAttribArray(x),e.vertexAttribIPointer(x,1,e.UNSIGNED_BYTE,0,0),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,m),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,p),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([160,160,160,255])),e.bindTexture(e.TEXTURE_2D,null),{program:r,vao:h,posBuffer:l,termBuffer:f,fillModeBuffer:d,indexBuffer:m,paletteTexture:p,uCamera:i,uPointSize:o,uPointStrokeScale:s,uPointInnerFillAlpha:a,uPalette:c,uPaletteSize:u}}function gi(e){e.animation=null,e.frame!==null&&(cancelAnimationFrame(e.frame),e.frame=null)}function rl(e){const{state:t,camera:n,target:r,durationMs:i,easing:o,onUpdate:s}=e,a=n.getViewState();gi(t),t.animation={startMs:be(),durationMs:Math.max(0,i),from:a,to:r,easing:o};const c=()=>{const u=t.animation;if(!u)return;const h=Math.max(0,be()-u.startMs),l=u.durationMs<=0?1:W(h/u.durationMs,0,1);let f=l;try{f=u.easing(l)}catch{f=l}if(Number.isFinite(f)||(f=l),f=W(f,0,1),n.setViewState({zoom:u.from.zoom+(u.to.zoom-u.from.zoom)*f,offsetX:u.from.offsetX+(u.to.offsetX-u.from.offsetX)*f,offsetY:u.from.offsetY+(u.to.offsetY-u.from.offsetY)*f,rotationDeg:u.from.rotationDeg+(u.to.rotationDeg-u.from.rotationDeg)*f}),s(),l>=1){t.animation=null,t.frame=null;return}t.frame=requestAnimationFrame(c)};t.frame=requestAnimationFrame(c)}function il(e){const t=Math.max(e*.5,1e-6),n=Math.max(1,e*8);return{minZoom:t,maxZoom:Math.max(t,n)}}function ol(e,t,n){const r=il(e);let i=t??r.minZoom,o=n??r.maxZoom;return i=Math.max(1e-6,i),o=Math.max(1e-6,o),i>o&&(i=o),{minZoom:i,maxZoom:o}}function sl(e,t,n,r,i){const o=e.getViewState(),s={zoom:typeof r.zoom=="number"&&Number.isFinite(r.zoom)?W(r.zoom,t,n):o.zoom,offsetX:typeof r.offsetX=="number"&&Number.isFinite(r.offsetX)?r.offsetX:o.offsetX,offsetY:typeof r.offsetY=="number"&&Number.isFinite(r.offsetY)?r.offsetY:o.offsetY,rotationDeg:typeof r.rotationDeg=="number"&&Number.isFinite(r.rotationDeg)?r.rotationDeg:o.rotationDeg};e.setViewState(s),i();const a=e.getViewState();return e.setViewState(o),a}function Tr(e,t,n,r,i){const o=Math.min(t/e.width,n/e.height),s=Number.isFinite(o)&&o>0?o:1,a=W(s,r,i),c=t/a,u=n/a;return{fitZoom:s,target:{zoom:a,offsetX:(e.width-c)*.5,offsetY:(e.height-u)*.5,rotationDeg:0}}}function al(e,t,n,r,i,o){const s=e.getViewState(),a=W(s.zoom*r,t,n);if(a===s.zoom)return null;const[c,u]=e.screenToWorld(i,o),h=e.getViewportSize(),l=i-h.width*.5,f=o-h.height*.5,d=Vt(s.rotationDeg),m=Math.cos(d),p=Math.sin(d),y=l/a*m-f/a*p,b=l/a*p+f/a*m,x=c-y,C=u-b;return{zoom:a,offsetX:x-h.width/(2*a),offsetY:C-h.height/(2*a)}}function ll(e,t,n,r,i,o){const s=e.getViewState(),a=W(r,t,n);if(a===s.zoom)return null;const[c,u]=e.screenToWorld(i,o),h=e.getViewportSize(),l=i-h.width*.5,f=o-h.height*.5,d=Vt(s.rotationDeg),m=Math.cos(d),p=Math.sin(d),y=l/a*m-f/a*p,b=l/a*p+f/a*m,x=c-y,C=u-b;return{zoom:a,offsetX:x-h.width/(2*a),offsetY:C-h.height/(2*a)}}const Ir=250;function _r(e,t){if(!e||e.length===0)return[];if(!t||t<=0)return[];const n=10/t;return e.map(r=>r/n).filter(r=>Number.isFinite(r)&&r>0).sort((r,i)=>r-i)}function cl(e,t,n,r){if(e.length===0)return null;const i=Math.max(t*.005,1e-8);if(n==="in"){for(const o of e)if(o>t+i)return{type:"snap",zoom:o};return null}for(let o=e.length-1;o>=0;o--)if(e[o]<t-i)return{type:"snap",zoom:e[o]};return r&&t<=e[0]+i?{type:"fit"}:null}function Fr(e,t,n,r,i){const o=e.camera.getViewState(),[s,a]=e.camera.screenToWorld(n,r),c=e.camera.getViewportSize(),u=W(t,e.minZoom,e.maxZoom);if(u===o.zoom)return;const h=Vt(o.rotationDeg),l=Math.cos(h),f=Math.sin(h),d=n-c.width*.5,m=r-c.height*.5;e.cancelViewAnimation();const p=x=>{const C=d/x*l-m/x*f,S=d/x*f+m/x*l;return{offsetX:s-C-c.width/(2*x),offsetY:a-S-c.height/(2*x)}},y=p(u);e.viewAnimationState.animation={startMs:be(),durationMs:Math.max(0,i),from:o,to:{zoom:u,offsetX:y.offsetX,offsetY:y.offsetY,rotationDeg:o.rotationDeg},easing:In};const b=()=>{const x=e.viewAnimationState.animation;if(!x)return;const C=Math.max(0,be()-x.startMs),S=W(C/i,0,1),A=W(S*S*(3-2*S),0,1),I=o.zoom+(u-o.zoom)*A,{offsetX:O,offsetY:z}=p(I);e.camera.setViewState({zoom:I,offsetX:O,offsetY:z,rotationDeg:o.rotationDeg});const G=S>=1;G&&(e.clampViewState(),e.viewAnimationState.animation=null,e.viewAnimationState.frame=null),e.onViewStateChange(e.camera.getViewState()),e.requestRender(),G||(e.viewAnimationState.frame=requestAnimationFrame(b))};e.viewAnimationState.frame=requestAnimationFrame(b)}class pi{constructor(t,n,r={}){R(this,"canvas");R(this,"source");R(this,"gl");R(this,"camera",new Br);R(this,"onViewStateChange");R(this,"onStats");R(this,"onTileError");R(this,"onContextLost");R(this,"onContextRestored");R(this,"resizeObserver");R(this,"tileProgram");R(this,"pointProgram");R(this,"tileScheduler");R(this,"authToken");R(this,"destroyed",!1);R(this,"contextLost",!1);R(this,"frame",null);R(this,"frameSerial",0);R(this,"interactionState",{dragging:!1,mode:"none",rotateLastAngleRad:null,pointerId:null,lastPointerX:0,lastPointerY:0});R(this,"interactionLocked",!1);R(this,"ctrlDragRotate",!0);R(this,"rotationDragSensitivityDegPerPixel",mn);R(this,"maxCacheTiles");R(this,"fitZoom",1);R(this,"minZoom",1e-6);R(this,"maxZoom",1);R(this,"minZoomOverride",null);R(this,"maxZoomOverride",null);R(this,"viewTransitionDurationMs",0);R(this,"viewTransitionEasing",In);R(this,"viewAnimationState",{animation:null,frame:null});R(this,"pointCount",0);R(this,"usePointIndices",!1);R(this,"pointBuffersDirty",!0);R(this,"pointPaletteSize",1);R(this,"pointSizeStops",yn(pn));R(this,"pointStrokeScale",1);R(this,"pointInnerFillOpacity",0);R(this,"imageColorSettings",{brightness:0,contrast:0,saturation:0});R(this,"lastPointData",null);R(this,"lastPointPalette",null);R(this,"zeroFillModes",new Uint8Array(0));R(this,"cache",new Map);R(this,"zoomSnaps",[]);R(this,"zoomSnapFitAsMin",!1);R(this,"zoomSnapState",{accumulatedDelta:0,lastSnapTimeMs:0});R(this,"boundPointerDown");R(this,"boundPointerMove");R(this,"boundPointerUp");R(this,"boundWheel");R(this,"boundDoubleClick");R(this,"boundContextMenu");R(this,"boundContextLost");R(this,"boundContextRestored");this.canvas=t,this.source=n,this.onViewStateChange=r.onViewStateChange,this.onStats=r.onStats,this.onTileError=r.onTileError,this.onContextLost=r.onContextLost,this.onContextRestored=r.onContextRestored,this.authToken=r.authToken??"",this.maxCacheTiles=Math.max(32,Math.floor(r.maxCacheTiles??320)),this.ctrlDragRotate=r.ctrlDragRotate??!0,this.rotationDragSensitivityDegPerPixel=typeof r.rotationDragSensitivityDegPerPixel=="number"&&Number.isFinite(r.rotationDragSensitivityDegPerPixel)?Math.max(0,r.rotationDragSensitivityDegPerPixel):mn,this.pointSizeStops=Rr(r.pointSizeByZoom),this.pointStrokeScale=Mr(r.pointStrokeScale),this.pointInnerFillOpacity=Ar(r.pointInnerFillOpacity),this.imageColorSettings=vr(r.imageColorSettings),this.minZoomOverride=Tt(r.minZoom),this.maxZoomOverride=Tt(r.maxZoom),this.viewTransitionDurationMs=en(r.viewTransition?.duration),this.viewTransitionEasing=tn(r.viewTransition?.easing),this.zoomSnaps=_r(r.zoomSnaps,this.source.mpp),this.zoomSnapFitAsMin=!!r.zoomSnapFitAsMin;const i=t.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,stencil:!1,powerPreference:"high-performance"});if(!i)throw new Error("WebGL2 not supported");this.gl=i,this.tileProgram=Cr(this.gl),this.pointProgram=Pr(this.gl),this.tileScheduler=new fi({authToken:this.authToken,maxConcurrency:r.tileScheduler?.maxConcurrency??12,maxRetries:r.tileScheduler?.maxRetries??2,retryBaseDelayMs:r.tileScheduler?.retryBaseDelayMs??120,retryMaxDelayMs:r.tileScheduler?.retryMaxDelayMs??1200,onTileLoad:(s,a)=>Za({gl:this.gl,cache:this.cache,tile:s,bitmap:a,frameSerial:this.frameSerial,maxCacheTiles:this.maxCacheTiles,destroyed:this.destroyed,contextLost:this.contextLost,requestRender:()=>this.requestRender()}),onTileError:(s,a,c)=>{this.onTileError?.({tile:s,error:a,attemptCount:c}),console.warn("tile load failed",s.url,a)}}),this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(t);const o=Ga({canvas:this.canvas,state:this.interactionState,getInteractionLocked:()=>this.interactionLocked,getCtrlDragRotate:()=>this.ctrlDragRotate,getRotationDragSensitivityDegPerPixel:()=>this.rotationDragSensitivityDegPerPixel,cancelViewAnimation:()=>this.cancelViewAnimation(),camera:this.camera,source:this.source,emitViewState:()=>this.onViewStateChange?.(this.camera.getViewState()),requestRender:()=>this.requestRender(),zoomBy:(s,a,c)=>this.zoomBy(s,a,c),getUseZoomSnaps:()=>this.zoomSnaps.length>0,onSnapZoom:(s,a,c)=>this.handleSnapZoom(s,a,c),zoomSnapState:this.zoomSnapState});this.boundPointerDown=o.pointerDown,this.boundPointerMove=o.pointerMove,this.boundPointerUp=o.pointerUp,this.boundWheel=o.wheel,this.boundDoubleClick=o.doubleClick,this.boundContextMenu=o.contextMenu,this.boundContextLost=s=>this.onWebGlContextLost(s),this.boundContextRestored=s=>this.onWebGlContextRestored(s),ma(t,this.getCanvasHandlers()),this.fitToImage({duration:0}),this.resize()}getCanvasHandlers(){return{pointerDown:this.boundPointerDown,pointerMove:this.boundPointerMove,pointerUp:this.boundPointerUp,wheel:this.boundWheel,doubleClick:this.boundDoubleClick,contextMenu:this.boundContextMenu,contextLost:this.boundContextLost,contextRestored:this.boundContextRestored}}applyZoomBounds(){const t=ol(this.fitZoom,this.minZoomOverride,this.maxZoomOverride);this.minZoom=t.minZoom,this.maxZoom=t.maxZoom}resolveTargetViewState(t){return sl(this.camera,this.minZoom,this.maxZoom,t,()=>kt(this.camera,this.source))}cancelViewAnimation(){gi(this.viewAnimationState)}startViewAnimation(t,n,r){rl({state:this.viewAnimationState,camera:this.camera,target:t,durationMs:n,easing:r,onUpdate:()=>{kt(this.camera,this.source),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}})}getPointBufferRuntime(){return{pointCount:this.pointCount,usePointIndices:this.usePointIndices,pointBuffersDirty:this.pointBuffersDirty,lastPointData:this.lastPointData,zeroFillModes:this.zeroFillModes,lastPointPalette:this.lastPointPalette,pointPaletteSize:this.pointPaletteSize}}applyPointBufferRuntime(t){this.pointCount=t.pointCount,this.usePointIndices=t.usePointIndices,this.pointBuffersDirty=t.pointBuffersDirty,this.lastPointData=t.lastPointData,this.zeroFillModes=t.zeroFillModes,this.lastPointPalette=t.lastPointPalette,this.pointPaletteSize=t.pointPaletteSize}applyViewStateAndRender(t,n=!0){n&&this.cancelViewAnimation(),this.camera.setViewState(t),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}setAuthToken(t){this.authToken=String(t??""),this.tileScheduler.setAuthToken(this.authToken)}setZoomRange(t,n){const r=Tt(t),i=Tt(n);if(this.minZoomOverride===r&&this.maxZoomOverride===i)return;this.minZoomOverride=r,this.maxZoomOverride=i,this.applyZoomBounds();const o=this.resolveTargetViewState({}),s=this.camera.getViewState();cn(s,o)||this.applyViewStateAndRender(o)}setViewTransition(t){this.viewTransitionDurationMs=en(t?.duration),this.viewTransitionEasing=tn(t?.easing)}setViewState(t,n){const r=this.resolveTargetViewState(t),i=this.camera.getViewState();if(cn(i,r))return;const o=en(n?.duration??this.viewTransitionDurationMs),s=tn(n?.easing??this.viewTransitionEasing);if(o<=0){this.applyViewStateAndRender(r);return}this.startViewAnimation(r,o,s)}getViewState(){return this.camera.getViewState()}getZoomRange(){return{minZoom:this.minZoom,maxZoom:this.maxZoom}}isViewAnimating(){return this.viewAnimationState.animation!==null}setPointPalette(t){const n=el(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,t);this.applyPointBufferRuntime(n),!(!t||t.length===0)&&this.requestRender()}setPointData(t){const n=tl(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,t);this.applyPointBufferRuntime(n),this.requestRender()}setInteractionLock(t){const n=!!t;this.interactionLocked!==n&&(this.interactionLocked=n,n&&this.cancelDrag())}setPointSizeByZoom(t){const n=Rr(t);Aa(this.pointSizeStops,n)||(this.pointSizeStops=n,this.requestRender())}setPointStrokeScale(t){const n=Mr(t);this.pointStrokeScale!==n&&(this.pointStrokeScale=n,this.requestRender())}setPointInnerFillOpacity(t){const n=Ar(t);this.pointInnerFillOpacity!==n&&(this.pointInnerFillOpacity=n,this.requestRender())}setImageColorSettings(t){const n=vr(t),r=this.imageColorSettings;r.brightness===n.brightness&&r.contrast===n.contrast&&r.saturation===n.saturation||(this.imageColorSettings=n,this.requestRender())}cancelDrag(){Va(this.canvas,this.interactionState)}screenToWorld(t,n){const r=this.canvas.getBoundingClientRect(),i=t-r.left,o=n-r.top;return this.camera.screenToWorld(i,o)}worldToScreen(t,n){return this.camera.worldToScreen(t,n)}setViewCenter(t,n,r){if(!Number.isFinite(t)||!Number.isFinite(n))return;const i=this.camera.getViewState(),o=Math.max(1e-6,i.zoom),s=this.camera.getViewportSize();this.setViewState({offsetX:t-s.width/(2*o),offsetY:n-s.height/(2*o)},r)}getViewCorners(){return this.camera.getViewCorners()}getViewBounds(){return Xt(this.camera)}resetRotation(t){const n=this.camera.getViewState();Math.abs(n.rotationDeg)<1e-6||this.setViewState({rotationDeg:0},t)}getPointSizeByZoom(){const t=Math.max(1e-6,this.camera.getViewState().zoom),n=this.source.maxTierZoom+Math.log2(t),r=va(n,this.pointSizeStops);return W(r,gn,ya)}fitToImage(t){const n=this.canvas.getBoundingClientRect(),r=Math.max(1,n.width||1),i=Math.max(1,n.height||1),o=Tr(this.source,r,i,this.minZoom,this.maxZoom);this.fitZoom=o.fitZoom,this.applyZoomBounds(),this.setViewState(o.target,t)}zoomBy(t,n,r,i){const o=al(this.camera,this.minZoom,this.maxZoom,t,n,r);o&&this.setViewState(o,i)}zoomTo(t,n,r,i){const o=ll(this.camera,this.minZoom,this.maxZoom,t,n,r);o&&this.setViewState(o,i)}setZoomSnaps(t,n){this.zoomSnaps=_r(t,this.source.mpp),this.zoomSnapFitAsMin=!!n}getZoomPivotAnimationContext(){return{camera:this.camera,viewAnimationState:this.viewAnimationState,minZoom:this.minZoom,maxZoom:this.maxZoom,cancelViewAnimation:()=>this.cancelViewAnimation(),clampViewState:()=>kt(this.camera,this.source),onViewStateChange:t=>this.onViewStateChange?.(t),requestRender:()=>this.requestRender()}}handleSnapZoom(t,n,r){const i=this.zoomSnaps.filter(s=>s>=this.minZoom&&s<=this.maxZoom),o=cl(i,this.camera.getViewState().zoom,t,this.zoomSnapFitAsMin);if(o){if(o.type==="fit"){const s=this.canvas.getBoundingClientRect(),a=Math.max(1,s.width||1),c=Math.max(1,s.height||1),u=Tr(this.source,a,c,this.minZoom,this.maxZoom);this.fitZoom=u.fitZoom,this.applyZoomBounds(),Fr(this.getZoomPivotAnimationContext(),u.target.zoom,n,r,Ir);return}Fr(this.getZoomPivotAnimationContext(),o.zoom,n,r,Ir)}}render(){if(this.destroyed||this.contextLost||this.gl.isContextLost())return;const t=this.onStats?be():0;this.frameSerial+=1;const n=nl({gl:this.gl,camera:this.camera,source:this.source,cache:this.cache,frameSerial:this.frameSerial,tileProgram:this.tileProgram,pointProgram:this.pointProgram,imageColorSettings:this.imageColorSettings,pointCount:this.pointCount,usePointIndices:this.usePointIndices,pointPaletteSize:this.pointPaletteSize,pointStrokeScale:this.pointStrokeScale,pointInnerFillOpacity:this.pointInnerFillOpacity,pointSizePx:this.getPointSizeByZoom()*Math.max(1,window.devicePixelRatio||1),tileScheduler:this.tileScheduler,getVisibleTiles:()=>Da(this.camera,this.source),getVisibleTilesForTier:r=>mi(this.camera,this.source,r),getViewBounds:()=>Xt(this.camera),intersectsBounds:za});if(this.onStats){const r=this.tileScheduler.getSnapshot();this.onStats({tier:n.tier,visible:n.visible,rendered:n.rendered,points:n.points,fallback:n.fallback,cache:this.cache.size,inflight:r.inflight,queued:r.queued,retries:r.retries,failed:r.failed,aborted:r.aborted,cacheHits:n.cacheHits,cacheMisses:n.cacheMisses,drawCalls:n.drawCalls,frameMs:be()-t})}}requestRender(){this.frame!==null||this.destroyed||this.contextLost||this.gl.isContextLost()||(this.frame=requestAnimationFrame(()=>{this.frame=null,this.render()}))}resize(){pa(this.canvas,this.gl,this.camera),this.requestRender()}onWebGlContextLost(t){const n=Ka({event:t,destroyed:this.destroyed,contextLost:this.contextLost,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,cache:this.cache,onContextLost:this.onContextLost});n.handled&&(this.frame=n.frame,this.contextLost=!0,this.pointBuffersDirty=!0)}onWebGlContextRestored(t){this.destroyed||(this.contextLost=!1,this.cache.clear(),this.tileProgram=Cr(this.gl),this.pointProgram=Pr(this.gl),this.pointBuffersDirty=!0,this.lastPointPalette&&this.lastPointPalette.length>0&&this.setPointPalette(this.lastPointPalette),this.lastPointData?this.setPointData(this.lastPointData):this.pointCount=0,this.resize(),this.onContextRestored?.())}destroy(){const t=ja({destroyed:this.destroyed,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),resizeObserver:this.resizeObserver,removeCanvasEventListeners:()=>ga(this.canvas,this.getCanvasHandlers()),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,contextLost:this.contextLost,gl:this.gl,cache:this.cache,tileProgram:this.tileProgram,pointProgram:this.pointProgram});t.didDestroy&&(this.destroyed=!0,this.frame=t.frame)}}const ul=[];function fl({source:e,viewState:t,onViewStateChange:n,onStats:r,onTileError:i,onContextLost:o,onContextRestored:s,imageColorSettings:a=null,fitNonce:c=0,rotationResetNonce:u=0,authToken:h="",ctrlDragRotate:l=!0,minZoom:f,maxZoom:d,viewTransition:m,zoomSnaps:p,zoomSnapFitAsMin:y,onPointerWorldMove:b,debugOverlay:x=!1,debugOverlayStyle:C,className:S,style:A,children:I}){const O=g.useRef(null),z=g.useRef(null),G=g.useRef(null),D=g.useRef(null),q=g.useRef(null),re=g.useRef(null),P=g.useRef(ul),H=g.useRef(!1),N=g.useRef(new Set),k=g.useRef(n),Z=g.useRef(r),we=g.useRef(i),se=g.useRef(o),Re=g.useRef(s),[Ce,xe]=g.useState(0),[M,v]=g.useState(null),X=g.useRef(x);g.useEffect(()=>{k.current=n},[n]),g.useEffect(()=>{Z.current=r},[r]),g.useEffect(()=>{we.current=i},[i]),g.useEffect(()=>{se.current=o},[o]),g.useEffect(()=>{Re.current=s},[s]),g.useEffect(()=>{X.current=x,x||v(null)},[x]);const le=g.useMemo(()=>({position:"relative",width:"100%",height:"100%",...A}),[A]),Q=g.useMemo(()=>({position:"absolute",top:8,left:8,zIndex:7,margin:0,padding:"8px 10px",maxWidth:"min(420px, 80%)",pointerEvents:"none",whiteSpace:"pre-wrap",lineHeight:1.35,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:11,color:"#cde6ff",background:"rgba(6, 12, 20, 0.82)",border:"1px solid rgba(173, 216, 255, 0.28)",borderRadius:8,boxShadow:"0 8px 22px rgba(0,0,0,0.35)",...C}),[C]),ie=g.useCallback(_=>{Z.current?.(_),X.current&&v(_)},[]),he=g.useMemo(()=>M?[`tier ${M.tier} | frame ${M.frameMs?.toFixed(2)??"-"} ms | drawCalls ${M.drawCalls??"-"}`,`tiles visible ${M.visible} | rendered ${M.rendered} | fallback ${M.fallback}`,`cache size ${M.cache} | hit ${M.cacheHits??"-"} | miss ${M.cacheMisses??"-"}`,`queue inflight ${M.inflight} | queued ${M.queued??"-"} | retries ${M.retries??"-"} | failed ${M.failed??"-"} | aborted ${M.aborted??"-"}`,`points ${M.points}`].join(`
163
- `):"stats: waiting for first frame...",[M]),me=g.useCallback(()=>{const _=G.current;if(!_)return;const Y=_.getContext("2d");if(!Y)return;const J=Math.max(1,window.devicePixelRatio||1),oe=_.getBoundingClientRect(),L=Math.max(1,Math.round(oe.width*J)),K=Math.max(1,Math.round(oe.height*J));(_.width!==L||_.height!==K)&&(_.width=L,_.height=K);const ce=oe.width,ne=oe.height;Y.setTransform(1,0,0,1,0,0),Y.clearRect(0,0,_.width,_.height),Y.setTransform(J,0,0,J,0,0);const ue=P.current;for(let ze=0;ze<ue.length;ze+=1)Y.save(),ue[ze].draw(Y,ce,ne),Y.restore()},[]),$=g.useCallback(()=>{H.current||(H.current=!0,requestAnimationFrame(()=>{H.current=!1,me()}))},[me]),pe=g.useCallback((_,Y,J)=>{const oe=P.current.filter(L=>L.id!==_);oe.push({id:_,priority:Y,draw:J}),oe.sort((L,K)=>L.priority-K.priority),P.current=oe,$()},[$]),ye=g.useCallback(_=>{P.current=P.current.filter(Y=>Y.id!==_),$()},[$]),U=g.useCallback((_,Y)=>{Y?N.current.add(_):N.current.delete(_),D.current?.setInteractionLock(N.current.size>0)},[]),V=g.useCallback(()=>N.current.size>0,[]),ee=g.useCallback((_,Y)=>{const J=D.current;return J?En(J.worldToScreen(_,Y)):null},[]),B=g.useCallback((_,Y)=>{const J=D.current;if(!J)return null;const oe=J.screenToWorld(_,Y);if(!Array.isArray(oe)||oe.length<2)return null;const L=Number(oe[0]),K=Number(oe[1]);return!Number.isFinite(L)||!Number.isFinite(K)?null:[L,K]},[]),te=g.useCallback(_=>{k.current?.(_),q.current?.(),re.current?.(),$()},[$]);g.useEffect(()=>{const _=z.current;if(!_||!e)return;const Y=new pi(_,e,{onViewStateChange:te,onStats:ie,onTileError:J=>{we.current?.(J)},onContextLost:()=>{se.current?.()},onContextRestored:()=>{Re.current?.()},authToken:h,imageColorSettings:a,ctrlDragRotate:l,minZoom:f,maxZoom:d,viewTransition:m,zoomSnaps:p,zoomSnapFitAsMin:y});return D.current=Y,xe(J=>J+1),t&&Y.setViewState(t),Y.setInteractionLock(N.current.size>0),()=>{Y.destroy(),D.current=null}},[e,ie,l,te]),g.useEffect(()=>{D.current?.setAuthToken(h)},[h]),g.useEffect(()=>{const _=D.current;!_||!t||_.isViewAnimating()||_.setViewState(t)},[t]),g.useEffect(()=>{D.current?.fitToImage()},[c]),g.useEffect(()=>{D.current?.resetRotation()},[u]),g.useEffect(()=>{D.current?.setZoomRange(f,d)},[f,d]),g.useEffect(()=>{D.current?.setViewTransition(m)},[m]),g.useEffect(()=>{D.current?.setZoomSnaps(p,y)},[p,y]),g.useEffect(()=>{D.current?.setImageColorSettings(a)},[a]),g.useEffect(()=>{const _=G.current;if(!_)return;q.current=$,$();const Y=new ResizeObserver(()=>$());return Y.observe(_),()=>{Y.disconnect(),q.current===$&&(q.current=null)}},[$]);const de=g.useMemo(()=>({source:e,rendererRef:D,rendererSerial:Ce,canvasRef:z,containerRef:O,drawInvalidateRef:q,overviewInvalidateRef:re,worldToScreen:ee,screenToWorld:B,registerDrawCallback:pe,unregisterDrawCallback:ye,requestOverlayRedraw:$,setInteractionLock:U,isInteractionLocked:V}),[e,Ce,ee,B,pe,ye,$,U,V]),ae=g.useRef(b);g.useEffect(()=>{ae.current=b},[b]);const Me=g.useCallback(_=>{const Y=ae.current;if(!Y)return;const J=B(_.clientX,_.clientY),oe=!!J&&J[0]>=0&&J[1]>=0&&!!e&&J[0]<=e.width&&J[1]<=e.height;Y({coordinate:J,clientX:_.clientX,clientY:_.clientY,insideImage:oe})},[B,e]),Se=g.useCallback(()=>{ae.current?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1})},[]);return Ye.jsx(bs,{value:de,children:Ye.jsxs("div",{ref:O,className:S,style:le,onPointerMove:b?Me:void 0,onPointerLeave:b?Se:void 0,children:[Ye.jsx("canvas",{ref:z,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none"}}),Ye.jsx("canvas",{ref:G,className:"wsi-overlay-canvas",style:{position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",pointerEvents:"none",touchAction:"none"}}),I,x&&Ye.jsx("pre",{"data-open-plant-debug-overlay":!0,style:Q,children:he})]})})}function hl(e){const t=[];for(let n=0;n<e.length;n+=1){const r=e[n],i=yt([pt(r?.coordinates)]);if(i.length===0)continue;let o=0,s=1/0,a=1/0,c=-1/0,u=-1/0;for(const h of i)o+=h.area,h.minX<s&&(s=h.minX),h.minY<a&&(a=h.minY),h.maxX>c&&(c=h.maxX),h.maxY>u&&(u=h.maxY);!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(c)||!Number.isFinite(u)||t.push({regionId:r.id??n,regionIndex:n,polygons:i,area:Math.max(1e-6,o),minX:s,minY:a,maxX:c,maxY:u})}return t}const dl=128,nn=[];function rt(e,t,n,r,i){if(i<=1||n<=t)return 0;const o=(e-t)/r;return!Number.isFinite(o)||o<=0?0:o>=i-1?i-1:Math.floor(o)}function ml(e){if(e.length===0)return null;let t=1/0,n=1/0,r=-1/0,i=-1/0;for(const h of e)h.minX<t&&(t=h.minX),h.minY<n&&(n=h.minY),h.maxX>r&&(r=h.maxX),h.maxY>i&&(i=h.maxY);if(!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i))return null;const o=Math.ceil(Math.sqrt(e.length*2)),s=Math.max(1,Math.min(dl,o)),a=r>t?(r-t)/s:1,c=i>n?(i-n)/s:1,u=Array.from({length:s*s},()=>[]);for(let h=0;h<e.length;h+=1){const l=e[h],f=rt(l.minX,t,r,a,s),d=rt(l.maxX,t,r,a,s),m=rt(l.minY,n,i,c,s),p=rt(l.maxY,n,i,c,s);for(let y=m;y<=p;y+=1)for(let b=f;b<=d;b+=1)u[y*s+b].push(h)}return{minX:t,minY:n,maxX:r,maxY:i,gridSize:s,cellWidth:a,cellHeight:c,buckets:u}}function gl(e,t,n){if(!e||t<e.minX||t>e.maxX||n<e.minY||n>e.maxY)return nn;const r=rt(t,e.minX,e.maxX,e.cellWidth,e.gridSize),i=rt(n,e.minY,e.maxY,e.cellHeight,e.gridSize);return e.buckets[i*e.gridSize+r]??nn}function pl(e,t){if(Array.isArray(t)){const n=t[e];if(typeof n=="string"&&n.length>0)return n}if(t instanceof Map){const n=t.get(e);if(typeof n=="string"&&n.length>0)return n}return String(e)}function yl(e,t,n={}){const r=Math.max(0,Math.min(Math.floor(e?.count??0),Math.floor((e?.positions?.length??0)/2),e?.paletteIndices?.length??0,e?.fillModes instanceof Uint8Array?e.fillModes.length:Number.MAX_SAFE_INTEGER));let i=null;if(e?.drawIndices instanceof Uint32Array){const d=e.drawIndices;let m=d.length;for(let p=0;p<d.length;p+=1)d[p]<r||(m-=1);if(m===d.length)i=d;else if(m>0){const p=new Uint32Array(m);let y=0;for(let b=0;b<d.length;b+=1){const x=d[b];x>=r||(p[y]=x,y+=1)}i=p}else i=new Uint32Array(0)}const o=i?i.length:r,s=hl(t??[]);if(!e||o===0||s.length===0)return{groups:[],inputPointCount:o,pointsInsideAnyRegion:0,unmatchedPointCount:o};const a=new Map,c=new Map,u=ml(s);let h=0;for(let d=0;d<o;d+=1){const m=i?i[d]:d,p=e.positions[m*2],y=e.positions[m*2+1];if(!Number.isFinite(p)||!Number.isFinite(y))continue;let b=null;const x=gl(u,p,y);if(x.length===0)continue;for(const A of x){const I=s[A];let O=!1;for(const z of I.polygons)if(Wr(p,y,z)){O=!0;break}O&&(!b||I.area<b.area)&&(b=I)}if(!b)continue;h+=1;const C=e.paletteIndices[m]??0,S=a.get(b.regionIndex)??new Map;S.set(C,(S.get(C)??0)+1),a.set(b.regionIndex,S),c.set(b.regionIndex,(c.get(b.regionIndex)??0)+1)}const l=n.includeEmptyRegions??!1,f=[];for(const d of s){const m=c.get(d.regionIndex)??0;if(!l&&m<=0)continue;const p=a.get(d.regionIndex)??new Map,y=Array.from(p.entries()).map(([b,x])=>({termId:pl(b,n.paletteIndexToTermId),paletteIndex:b,count:x})).sort((b,x)=>x.count-b.count||b.paletteIndex-x.paletteIndex);f.push({regionId:d.regionId,regionIndex:d.regionIndex,totalCount:m,termCounts:y})}return{groups:f,inputPointCount:o,pointsInsideAnyRegion:h,unmatchedPointCount:Math.max(0,o-h)}}function Lr(e,t,n,r){return[Math.min(e,n),Math.min(t,r),Math.max(e,n),Math.max(t,r)]}function kr(e,t){return!(e[2]<t[0]||e[0]>t[2]||e[3]<t[1]||e[1]>t[3])}class bl{constructor(t=16){R(this,"targetNodeSize");R(this,"items",[]);R(this,"globalBounds",[0,0,0,0]);R(this,"gridSize",1);R(this,"cellWidth",1);R(this,"cellHeight",1);R(this,"buckets",[]);R(this,"visited",new Uint32Array(0));R(this,"querySerial",1);const n=Number.isFinite(t)?Math.floor(t):16;this.targetNodeSize=Math.max(1,n)}load(t){if(!Array.isArray(t)||t.length===0){this.items=[],this.globalBounds=[0,0,0,0],this.gridSize=1,this.cellWidth=1,this.cellHeight=1,this.buckets=[],this.visited=new Uint32Array(0),this.querySerial=1;return}const n=[];let r=1/0,i=1/0,o=-1/0,s=-1/0;for(const h of t){if(!h||!Number.isFinite(h.minX)||!Number.isFinite(h.minY)||!Number.isFinite(h.maxX)||!Number.isFinite(h.maxY))continue;const l=Lr(h.minX,h.minY,h.maxX,h.maxY);r=Math.min(r,l[0]),i=Math.min(i,l[1]),o=Math.max(o,l[2]),s=Math.max(s,l[3]),n.push({minX:l[0],minY:l[1],maxX:l[2],maxY:l[3],value:h.value})}if(this.items=n,this.visited=new Uint32Array(n.length),this.querySerial=1,n.length===0||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(o)||!Number.isFinite(s)){this.globalBounds=[0,0,0,0],this.gridSize=1,this.cellWidth=1,this.cellHeight=1,this.buckets=[];return}this.globalBounds=[r,i,o,s],this.gridSize=Math.max(1,Math.ceil(Math.sqrt(n.length/this.targetNodeSize)));const a=Math.max(0,o-r),c=Math.max(0,s-i);this.cellWidth=a>0?a/this.gridSize:1,this.cellHeight=c>0?c/this.gridSize:1;const u=this.gridSize*this.gridSize;this.buckets=Array.from({length:u},()=>[]);for(let h=0;h<n.length;h+=1){const l=n[h],f=this.toCellX(l.minX),d=this.toCellX(l.maxX),m=this.toCellY(l.minY),p=this.toCellY(l.maxY);for(let y=m;y<=p;y+=1)for(let b=f;b<=d;b+=1)this.buckets[y*this.gridSize+b].push(h)}}search(t){if(this.items.length===0)return[];if(!Array.isArray(t)||t.length<4)return[];const n=Lr(t[0],t[1],t[2],t[3]);if(!kr(n,this.globalBounds))return[];const r=this.toCellX(n[0]),i=this.toCellX(n[2]),o=this.toCellY(n[1]),s=this.toCellY(n[3]),a=this.nextSerial(),c=[];for(let u=o;u<=s;u+=1)for(let h=r;h<=i;h+=1){const l=this.buckets[u*this.gridSize+h];if(!(!l||l.length===0))for(const f of l){if(this.visited[f]===a)continue;this.visited[f]=a;const d=this.items[f];kr(n,[d.minX,d.minY,d.maxX,d.maxY])&&c.push(d)}}return c}nextSerial(){return this.querySerial+=1,this.querySerial===4294967295&&(this.visited.fill(0),this.querySerial=1),this.querySerial}toCellX(t){const n=this.globalBounds[0],r=this.globalBounds[2];if(this.gridSize<=1||r<=n)return 0;const i=(t-n)/this.cellWidth;return!Number.isFinite(i)||i<=0?0:i>=this.gridSize-1?this.gridSize-1:Math.max(0,Math.min(this.gridSize-1,Math.floor(i)))}toCellY(t){const n=this.globalBounds[1],r=this.globalBounds[3];if(this.gridSize<=1||r<=n)return 0;const i=(t-n)/this.cellHeight;return!Number.isFinite(i)||i<=0?0:i>=this.gridSize-1?this.gridSize-1:Math.max(0,Math.min(this.gridSize-1,Math.floor(i)))}}function wl(e){return new bl(e)}function xl(e){return e.replace(/^\s*SRID\s*=\s*\d+\s*;\s*/i,"")}function Sl(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function El(e){return e>="0"&&e<="9"}function Nr(e){return e==="+"||e==="-"||e==="."||El(e)}class Rl{constructor(t){R(this,"text");R(this,"index",0);this.text=xl(t.trim())}parse(){if(!this.text)return null;const t=this.readWord();if(!t)return null;const n=t.toUpperCase();if(n!=="POLYGON"&&n!=="MULTIPOLYGON")return null;this.skipWhitespace();const r=this.peekWord();if(r){const s=r.toUpperCase();(s==="Z"||s==="M"||s==="ZM")&&(this.readWord(),this.skipWhitespace())}if(this.consumeWordIf("EMPTY"))return this.skipWhitespace(),this.isEof()?n==="POLYGON"?{type:"Polygon",coordinates:[]}:{type:"MultiPolygon",coordinates:[]}:null;let i;try{i=this.parseNestedList()}catch{return null}if(this.skipWhitespace(),!this.isEof())return null;if(n==="POLYGON"){const s=yi(i);return s?{type:"Polygon",coordinates:s}:null}const o=Al(i);return o?{type:"MultiPolygon",coordinates:o}:null}isEof(){return this.index>=this.text.length}currentChar(){return this.text[this.index]??""}skipWhitespace(){for(;!this.isEof()&&/\s/.test(this.currentChar());)this.index+=1}readWord(){if(this.skipWhitespace(),this.isEof())return null;const t=this.index;for(;!this.isEof()&&Sl(this.currentChar());)this.index+=1;return this.index===t?null:this.text.slice(t,this.index)}peekWord(){const t=this.index,n=this.readWord();return this.index=t,n}consumeWordIf(t){const n=this.index,r=this.readWord();return!r||r.toUpperCase()!==t.toUpperCase()?(this.index=n,!1):!0}parseNestedList(){if(this.skipWhitespace(),this.currentChar()!=="(")throw new Error("Expected '('");this.index+=1;const t=[];for(;;){this.skipWhitespace(),this.currentChar()==="("?t.push(this.parseNestedList()):t.push(this.parseCoordinateTuple()),this.skipWhitespace();const n=this.currentChar();if(n===","){this.index+=1;continue}if(n===")"){this.index+=1;break}throw new Error("Expected ',' or ')'")}return t}parseCoordinateTuple(){this.skipWhitespace();const t=[];for(;;){this.skipWhitespace();const n=this.currentChar();if(!n||!Nr(n))break;const r=this.readNumber();if(r===null)break;t.push(r),this.skipWhitespace();const i=this.currentChar();if(!i||i===","||i===")")break;if(!Nr(i))throw new Error("Invalid coordinate")}if(t.length<2)throw new Error("Coordinate requires at least x y");return[t[0],t[1]]}readNumber(){if(this.skipWhitespace(),this.isEof())return null;const n=this.text.slice(this.index).match(/^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/);if(!n)return null;const r=Number(n[0]);return Number.isFinite(r)?(this.index+=n[0].length,r):null}}function Ml(e){return Array.isArray(e)&&e.length>=2&&typeof e[0]=="number"&&Number.isFinite(e[0])&&typeof e[1]=="number"&&Number.isFinite(e[1])}function yi(e){if(!Array.isArray(e))return null;const t=[];for(const n of e){if(!Array.isArray(n))return null;const r=[];for(const i of n){if(!Ml(i))return null;r.push([i[0],i[1]])}t.push(r)}return t}function Al(e){if(!Array.isArray(e))return null;const t=[];for(const n of e){const r=yi(n);if(!r)return null;t.push(r)}return t}function vl(e){return typeof e!="string"?null:new Rl(e).parse()}exports.DEFAULT_POINT_COLOR=xn;exports.DrawLayer=ei;exports.DrawingLayer=ws;exports.M1TileRenderer=zr;exports.OverlayLayer=xs;exports.OverviewMap=vs;exports.PatchLayer=Ps;exports.PointLayer=Js;exports.RegionLayer=fa;exports.TileScheduler=fi;exports.TileViewerCanvas=ha;exports.WsiTileRenderer=pi;exports.WsiViewer=fl;exports.buildPointSpatialIndexAsync=ui;exports.buildTermPalette=no;exports.calcScaleLength=eo;exports.calcScaleResolution=Sn;exports.clamp=W;exports.closeRing=Fe;exports.computeRoiPointGroups=yl;exports.createCircle=fn;exports.createRectangle=Yt;exports.createSpatialIndex=wl;exports.filterPointDataByPolygons=dt;exports.filterPointDataByPolygonsHybrid=si;exports.filterPointDataByPolygonsInWorker=li;exports.filterPointIndicesByPolygons=ri;exports.filterPointIndicesByPolygonsInWorker=Ds;exports.getWebGpuCapabilities=Ns;exports.hexToRgba=Xr;exports.isSameViewState=cn;exports.lookupCellIndex=ci;exports.normalizeImageInfo=Es;exports.parseWkt=vl;exports.prefilterPointsByBoundsWebGpu=oi;exports.terminatePointHitIndexWorker=Zs;exports.terminateRoiClipWorker=zs;exports.toBearerToken=to;exports.toRoiGeometry=pt;exports.toTileUrl=Tn;exports.useViewerContext=ot;
162
+ }`),i=_e(e,r,"uCamera"),o=_e(e,r,"uPointSize"),s=_e(e,r,"uPointStrokeScale"),a=_e(e,r,"uPointInnerFillAlpha"),c=_e(e,r,"uPalette"),u=_e(e,r,"uPaletteSize"),h=e.createVertexArray(),l=e.createBuffer(),f=e.createBuffer(),d=e.createBuffer(),m=e.createBuffer(),p=e.createTexture();if(!h||!l||!f||!d||!m||!p)throw new Error("point buffer allocation failed");e.bindVertexArray(h),e.bindBuffer(e.ARRAY_BUFFER,l),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const y=e.getAttribLocation(r,"aPosition");if(y<0)throw new Error("point position attribute not found");e.enableVertexAttribArray(y),e.vertexAttribPointer(y,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,f),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const b=e.getAttribLocation(r,"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,d),e.bufferData(e.ARRAY_BUFFER,0,e.DYNAMIC_DRAW);const x=e.getAttribLocation(r,"aFillMode");if(x<0)throw new Error("point fill mode attribute not found");return e.enableVertexAttribArray(x),e.vertexAttribIPointer(x,1,e.UNSIGNED_BYTE,0,0),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,m),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,p),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([160,160,160,255])),e.bindTexture(e.TEXTURE_2D,null),{program:r,vao:h,posBuffer:l,termBuffer:f,fillModeBuffer:d,indexBuffer:m,paletteTexture:p,uCamera:i,uPointSize:o,uPointStrokeScale:s,uPointInnerFillAlpha:a,uPalette:c,uPaletteSize:u}}function gi(e){e.animation=null,e.frame!==null&&(cancelAnimationFrame(e.frame),e.frame=null)}function nl(e){const{state:t,camera:n,target:r,durationMs:i,easing:o,onUpdate:s}=e,a=n.getViewState();gi(t),t.animation={startMs:be(),durationMs:Math.max(0,i),from:a,to:r,easing:o};const c=()=>{const u=t.animation;if(!u)return;const h=Math.max(0,be()-u.startMs),l=u.durationMs<=0?1:W(h/u.durationMs,0,1);let f=l;try{f=u.easing(l)}catch{f=l}if(Number.isFinite(f)||(f=l),f=W(f,0,1),n.setViewState({zoom:u.from.zoom+(u.to.zoom-u.from.zoom)*f,offsetX:u.from.offsetX+(u.to.offsetX-u.from.offsetX)*f,offsetY:u.from.offsetY+(u.to.offsetY-u.from.offsetY)*f,rotationDeg:u.from.rotationDeg+(u.to.rotationDeg-u.from.rotationDeg)*f}),s(),l>=1){t.animation=null,t.frame=null;return}t.frame=requestAnimationFrame(c)};t.frame=requestAnimationFrame(c)}function rl(e){const t=Math.max(e*.5,1e-6),n=Math.max(1,e*8);return{minZoom:t,maxZoom:Math.max(t,n)}}function il(e,t,n){const r=rl(e);let i=t??r.minZoom,o=n??r.maxZoom;return i=Math.max(1e-6,i),o=Math.max(1e-6,o),i>o&&(i=o),{minZoom:i,maxZoom:o}}function ol(e,t,n,r,i){const o=e.getViewState(),s={zoom:typeof r.zoom=="number"&&Number.isFinite(r.zoom)?W(r.zoom,t,n):o.zoom,offsetX:typeof r.offsetX=="number"&&Number.isFinite(r.offsetX)?r.offsetX:o.offsetX,offsetY:typeof r.offsetY=="number"&&Number.isFinite(r.offsetY)?r.offsetY:o.offsetY,rotationDeg:typeof r.rotationDeg=="number"&&Number.isFinite(r.rotationDeg)?r.rotationDeg:o.rotationDeg};e.setViewState(s),i();const a=e.getViewState();return e.setViewState(o),a}function Pr(e,t,n,r,i){const o=Math.min(t/e.width,n/e.height),s=Number.isFinite(o)&&o>0?o:1,a=W(s,r,i),c=t/a,u=n/a;return{fitZoom:s,target:{zoom:a,offsetX:(e.width-c)*.5,offsetY:(e.height-u)*.5,rotationDeg:0}}}function sl(e,t,n,r,i,o){const s=e.getViewState(),a=W(s.zoom*r,t,n);if(a===s.zoom)return null;const[c,u]=e.screenToWorld(i,o),h=e.getViewportSize(),l=i-h.width*.5,f=o-h.height*.5,d=Vt(s.rotationDeg),m=Math.cos(d),p=Math.sin(d),y=l/a*m-f/a*p,b=l/a*p+f/a*m,x=c-y,C=u-b;return{zoom:a,offsetX:x-h.width/(2*a),offsetY:C-h.height/(2*a)}}function al(e,t,n,r,i,o){const s=e.getViewState(),a=W(r,t,n);if(a===s.zoom)return null;const[c,u]=e.screenToWorld(i,o),h=e.getViewportSize(),l=i-h.width*.5,f=o-h.height*.5,d=Vt(s.rotationDeg),m=Math.cos(d),p=Math.sin(d),y=l/a*m-f/a*p,b=l/a*p+f/a*m,x=c-y,C=u-b;return{zoom:a,offsetX:x-h.width/(2*a),offsetY:C-h.height/(2*a)}}const Tr=250;function _r(e,t){if(!e||e.length===0)return[];if(!t||t<=0)return[];const n=10/t;return e.map(r=>r/n).filter(r=>Number.isFinite(r)&&r>0).sort((r,i)=>r-i)}function ll(e,t,n,r){if(e.length===0)return null;const i=Math.max(t*.005,1e-8);if(n==="in"){for(const o of e)if(o>t+i)return{type:"snap",zoom:o};return null}for(let o=e.length-1;o>=0;o--)if(e[o]<t-i)return{type:"snap",zoom:e[o]};return r&&t<=e[0]+i?{type:"fit"}:null}function Fr(e,t,n,r,i){const o=e.camera.getViewState(),[s,a]=e.camera.screenToWorld(n,r),c=e.camera.getViewportSize(),u=W(t,e.minZoom,e.maxZoom);if(u===o.zoom)return;const h=Vt(o.rotationDeg),l=Math.cos(h),f=Math.sin(h),d=n-c.width*.5,m=r-c.height*.5;e.cancelViewAnimation();const p=x=>{const C=d/x*l-m/x*f,S=d/x*f+m/x*l;return{offsetX:s-C-c.width/(2*x),offsetY:a-S-c.height/(2*x)}},y=p(u);e.viewAnimationState.animation={startMs:be(),durationMs:Math.max(0,i),from:o,to:{zoom:u,offsetX:y.offsetX,offsetY:y.offsetY,rotationDeg:o.rotationDeg},easing:Tn};const b=()=>{const x=e.viewAnimationState.animation;if(!x)return;const C=Math.max(0,be()-x.startMs),S=W(C/i,0,1),A=W(S*S*(3-2*S),0,1),T=o.zoom+(u-o.zoom)*A,{offsetX:O,offsetY:z}=p(T);e.camera.setViewState({zoom:T,offsetX:O,offsetY:z,rotationDeg:o.rotationDeg});const G=S>=1;G&&(e.clampViewState(),e.viewAnimationState.animation=null,e.viewAnimationState.frame=null),e.onViewStateChange(e.camera.getViewState()),e.requestRender(),G||(e.viewAnimationState.frame=requestAnimationFrame(b))};e.viewAnimationState.frame=requestAnimationFrame(b)}class pi{constructor(t,n,r={}){R(this,"canvas");R(this,"source");R(this,"gl");R(this,"camera",new Br);R(this,"onViewStateChange");R(this,"onStats");R(this,"onTileError");R(this,"onContextLost");R(this,"onContextRestored");R(this,"resizeObserver");R(this,"tileProgram");R(this,"pointProgram");R(this,"tileScheduler");R(this,"zoomStack",{cnt:0,direction:null});R(this,"authToken");R(this,"destroyed",!1);R(this,"contextLost",!1);R(this,"frame",null);R(this,"frameSerial",0);R(this,"interactionState",{dragging:!1,mode:"none",rotateLastAngleRad:null,pointerId:null,lastPointerX:0,lastPointerY:0});R(this,"interactionLocked",!1);R(this,"ctrlDragRotate",!0);R(this,"rotationDragSensitivityDegPerPixel",mn);R(this,"maxCacheTiles");R(this,"fitZoom",1);R(this,"minZoom",1e-6);R(this,"maxZoom",1);R(this,"minZoomOverride",null);R(this,"maxZoomOverride",null);R(this,"viewTransitionDurationMs",0);R(this,"viewTransitionEasing",Tn);R(this,"viewAnimationState",{animation:null,frame:null});R(this,"pointCount",0);R(this,"usePointIndices",!1);R(this,"pointBuffersDirty",!0);R(this,"pointPaletteSize",1);R(this,"pointSizeStops",yn(pn));R(this,"pointStrokeScale",1);R(this,"pointInnerFillOpacity",0);R(this,"imageColorSettings",{brightness:0,contrast:0,saturation:0});R(this,"lastPointData",null);R(this,"lastPointPalette",null);R(this,"zeroFillModes",new Uint8Array(0));R(this,"cache",new Map);R(this,"zoomSnaps",[]);R(this,"zoomSnapFitAsMin",!1);R(this,"zoomSnapState",{accumulatedDelta:0,lastSnapTimeMs:0});R(this,"boundPointerDown");R(this,"boundPointerMove");R(this,"boundPointerUp");R(this,"boundWheel");R(this,"boundDoubleClick");R(this,"boundContextMenu");R(this,"boundContextLost");R(this,"boundContextRestored");this.canvas=t,this.source=n,this.onViewStateChange=r.onViewStateChange,this.onStats=r.onStats,this.onTileError=r.onTileError,this.onContextLost=r.onContextLost,this.onContextRestored=r.onContextRestored,this.authToken=r.authToken??"",this.maxCacheTiles=Math.max(32,Math.floor(r.maxCacheTiles??320)),this.ctrlDragRotate=r.ctrlDragRotate??!0,this.rotationDragSensitivityDegPerPixel=typeof r.rotationDragSensitivityDegPerPixel=="number"&&Number.isFinite(r.rotationDragSensitivityDegPerPixel)?Math.max(0,r.rotationDragSensitivityDegPerPixel):mn,this.pointSizeStops=Rr(r.pointSizeByZoom),this.pointStrokeScale=Mr(r.pointStrokeScale),this.pointInnerFillOpacity=Ar(r.pointInnerFillOpacity),this.imageColorSettings=vr(r.imageColorSettings),this.minZoomOverride=Pt(r.minZoom),this.maxZoomOverride=Pt(r.maxZoom),this.viewTransitionDurationMs=en(r.viewTransition?.duration),this.viewTransitionEasing=tn(r.viewTransition?.easing),this.zoomSnaps=_r(r.zoomSnaps,this.source.mpp),this.zoomSnapFitAsMin=!!r.zoomSnapFitAsMin;const i=t.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,stencil:!1,powerPreference:"high-performance"});if(!i)throw new Error("WebGL2 not supported");this.gl=i,this.tileProgram=Cr(this.gl),this.pointProgram=Ir(this.gl),this.tileScheduler=new fi({authToken:this.authToken,maxConcurrency:r.tileScheduler?.maxConcurrency??12,maxRetries:r.tileScheduler?.maxRetries??2,retryBaseDelayMs:r.tileScheduler?.retryBaseDelayMs??120,retryMaxDelayMs:r.tileScheduler?.retryMaxDelayMs??1200,onTileLoad:(s,a)=>Ha({gl:this.gl,cache:this.cache,tile:s,bitmap:a,frameSerial:this.frameSerial,maxCacheTiles:this.maxCacheTiles,destroyed:this.destroyed,contextLost:this.contextLost,requestRender:()=>this.requestRender()}),onTileError:(s,a,c)=>{this.onTileError?.({tile:s,error:a,attemptCount:c}),console.warn("tile load failed",s.url,a)}}),this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(t);const o=Va({canvas:this.canvas,state:this.interactionState,getInteractionLocked:()=>this.interactionLocked,getCtrlDragRotate:()=>this.ctrlDragRotate,getRotationDragSensitivityDegPerPixel:()=>this.rotationDragSensitivityDegPerPixel,cancelViewAnimation:()=>this.cancelViewAnimation(),camera:this.camera,source:this.source,emitViewState:()=>this.onViewStateChange?.(this.camera.getViewState()),requestRender:()=>this.requestRender(),zoomBy:(s,a,c)=>this.zoomBy(s,a,c),getUseZoomSnaps:()=>this.zoomSnaps.length>0,onSnapZoom:(s,a,c)=>this.handleSnapZoom(s,a,c),zoomSnapState:this.zoomSnapState});this.boundPointerDown=o.pointerDown,this.boundPointerMove=o.pointerMove,this.boundPointerUp=o.pointerUp,this.boundWheel=o.wheel,this.boundDoubleClick=o.doubleClick,this.boundContextMenu=o.contextMenu,this.boundContextLost=s=>this.onWebGlContextLost(s),this.boundContextRestored=s=>this.onWebGlContextRestored(s),ma(t,this.getCanvasHandlers()),this.fitToImage({duration:0}),this.resize()}getCanvasHandlers(){return{pointerDown:this.boundPointerDown,pointerMove:this.boundPointerMove,pointerUp:this.boundPointerUp,wheel:this.boundWheel,doubleClick:this.boundDoubleClick,contextMenu:this.boundContextMenu,contextLost:this.boundContextLost,contextRestored:this.boundContextRestored}}applyZoomBounds(){const t=il(this.fitZoom,this.minZoomOverride,this.maxZoomOverride);this.minZoom=t.minZoom,this.maxZoom=t.maxZoom}resolveTargetViewState(t){return ol(this.camera,this.minZoom,this.maxZoom,t,()=>kt(this.camera,this.source))}cancelViewAnimation(){gi(this.viewAnimationState)}startViewAnimation(t,n,r){nl({state:this.viewAnimationState,camera:this.camera,target:t,durationMs:n,easing:r,onUpdate:()=>{kt(this.camera,this.source),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}})}getPointBufferRuntime(){return{pointCount:this.pointCount,usePointIndices:this.usePointIndices,pointBuffersDirty:this.pointBuffersDirty,lastPointData:this.lastPointData,zeroFillModes:this.zeroFillModes,lastPointPalette:this.lastPointPalette,pointPaletteSize:this.pointPaletteSize}}applyPointBufferRuntime(t){this.pointCount=t.pointCount,this.usePointIndices=t.usePointIndices,this.pointBuffersDirty=t.pointBuffersDirty,this.lastPointData=t.lastPointData,this.zeroFillModes=t.zeroFillModes,this.lastPointPalette=t.lastPointPalette,this.pointPaletteSize=t.pointPaletteSize}applyViewStateAndRender(t,n=!0){n&&this.cancelViewAnimation(),this.camera.setViewState(t),this.onViewStateChange?.(this.camera.getViewState()),this.requestRender()}setAuthToken(t){this.authToken=String(t??""),this.tileScheduler.setAuthToken(this.authToken)}setZoomRange(t,n){const r=Pt(t),i=Pt(n);if(this.minZoomOverride===r&&this.maxZoomOverride===i)return;this.minZoomOverride=r,this.maxZoomOverride=i,this.applyZoomBounds();const o=this.resolveTargetViewState({}),s=this.camera.getViewState();cn(s,o)||this.applyViewStateAndRender(o)}setViewTransition(t){this.viewTransitionDurationMs=en(t?.duration),this.viewTransitionEasing=tn(t?.easing)}setViewState(t,n){const r=this.resolveTargetViewState(t),i=this.camera.getViewState();if(cn(i,r))return;const o=en(n?.duration??this.viewTransitionDurationMs),s=tn(n?.easing??this.viewTransitionEasing);if(o<=0){this.applyViewStateAndRender(r);return}this.startViewAnimation(r,o,s)}getViewState(){return this.camera.getViewState()}getZoomRange(){return{minZoom:this.minZoom,maxZoom:this.maxZoom}}isViewAnimating(){return this.viewAnimationState.animation!==null}setPointPalette(t){const n=Ja(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,t);this.applyPointBufferRuntime(n),!(!t||t.length===0)&&this.requestRender()}setPointData(t){const n=el(this.getPointBufferRuntime(),this.gl,this.pointProgram,this.contextLost,t);this.applyPointBufferRuntime(n),this.requestRender()}setInteractionLock(t){const n=!!t;this.interactionLocked!==n&&(this.interactionLocked=n,n&&this.cancelDrag())}setPointSizeByZoom(t){const n=Rr(t);Aa(this.pointSizeStops,n)||(this.pointSizeStops=n,this.requestRender())}setPointStrokeScale(t){const n=Mr(t);this.pointStrokeScale!==n&&(this.pointStrokeScale=n,this.requestRender())}setPointInnerFillOpacity(t){const n=Ar(t);this.pointInnerFillOpacity!==n&&(this.pointInnerFillOpacity=n,this.requestRender())}setImageColorSettings(t){const n=vr(t),r=this.imageColorSettings;r.brightness===n.brightness&&r.contrast===n.contrast&&r.saturation===n.saturation||(this.imageColorSettings=n,this.requestRender())}cancelDrag(){Xa(this.canvas,this.interactionState)}screenToWorld(t,n){const r=this.canvas.getBoundingClientRect(),i=t-r.left,o=n-r.top;return this.camera.screenToWorld(i,o)}worldToScreen(t,n){return this.camera.worldToScreen(t,n)}setViewCenter(t,n,r){if(!Number.isFinite(t)||!Number.isFinite(n))return;const i=this.camera.getViewState(),o=Math.max(1e-6,i.zoom),s=this.camera.getViewportSize();this.setViewState({offsetX:t-s.width/(2*o),offsetY:n-s.height/(2*o)},r)}getViewCorners(){return this.camera.getViewCorners()}getViewBounds(){return Xt(this.camera)}resetRotation(t){const n=this.camera.getViewState();Math.abs(n.rotationDeg)<1e-6||this.setViewState({rotationDeg:0},t)}getPointSizeByZoom(){const t=Math.max(1e-6,this.camera.getViewState().zoom),n=this.source.maxTierZoom+Math.log2(t),r=va(n,this.pointSizeStops);return W(r,gn,ya)}fitToImage(t){const n=this.canvas.getBoundingClientRect(),r=Math.max(1,n.width||1),i=Math.max(1,n.height||1),o=Pr(this.source,r,i,this.minZoom,this.maxZoom);this.fitZoom=o.fitZoom,this.applyZoomBounds(),this.setViewState(o.target,t)}zoomBy(t,n,r,i){const o=sl(this.camera,this.minZoom,this.maxZoom,t,n,r);o&&this.setViewState(o,i)}zoomTo(t,n,r,i){const o=al(this.camera,this.minZoom,this.maxZoom,t,n,r);o&&this.setViewState(o,i)}setZoomSnaps(t,n){this.zoomSnaps=_r(t,this.source.mpp),this.zoomSnapFitAsMin=!!n}getZoomPivotAnimationContext(){return{camera:this.camera,viewAnimationState:this.viewAnimationState,minZoom:this.minZoom,maxZoom:this.maxZoom,cancelViewAnimation:()=>this.cancelViewAnimation(),clampViewState:()=>kt(this.camera,this.source),onViewStateChange:t=>this.onViewStateChange?.(t),requestRender:()=>this.requestRender()}}handleSnapZoom(t,n,r){const i=this.viewAnimationState.animation,o=i?i.to.zoom:this.camera.getViewState().zoom,s=this.zoomSnaps.filter(u=>u>=this.minZoom&&u<=this.maxZoom),a=this.zoomStack;if(a.cnt>0&&s.length-1===a.cnt&&a.direction===t)return;a.direction!==t&&(a.cnt=0,a.direction=t),a.cnt+=1;const c=ll(s,o,t,this.zoomSnapFitAsMin);if(c){if(c.type==="fit"){const u=this.canvas.getBoundingClientRect(),h=Math.max(1,u.width||1),l=Math.max(1,u.height||1),f=Pr(this.source,h,l,this.minZoom,this.maxZoom);this.fitZoom=f.fitZoom,this.applyZoomBounds(),Fr(this.getZoomPivotAnimationContext(),f.target.zoom,n,r,Tr);return}Fr(this.getZoomPivotAnimationContext(),c.zoom,n,r,Tr)}}render(){if(this.destroyed||this.contextLost||this.gl.isContextLost())return;const t=this.onStats?be():0;this.frameSerial+=1;const n=tl({gl:this.gl,camera:this.camera,source:this.source,cache:this.cache,frameSerial:this.frameSerial,tileProgram:this.tileProgram,pointProgram:this.pointProgram,imageColorSettings:this.imageColorSettings,pointCount:this.pointCount,usePointIndices:this.usePointIndices,pointPaletteSize:this.pointPaletteSize,pointStrokeScale:this.pointStrokeScale,pointInnerFillOpacity:this.pointInnerFillOpacity,pointSizePx:this.getPointSizeByZoom()*Math.max(1,window.devicePixelRatio||1),tileScheduler:this.tileScheduler,getVisibleTiles:()=>za(this.camera,this.source),getVisibleTilesForTier:r=>mi(this.camera,this.source,r),getViewBounds:()=>Xt(this.camera),intersectsBounds:Ba});if(this.onStats){const r=this.tileScheduler.getSnapshot();this.onStats({tier:n.tier,visible:n.visible,rendered:n.rendered,points:n.points,fallback:n.fallback,cache:this.cache.size,inflight:r.inflight,queued:r.queued,retries:r.retries,failed:r.failed,aborted:r.aborted,cacheHits:n.cacheHits,cacheMisses:n.cacheMisses,drawCalls:n.drawCalls,frameMs:be()-t})}}requestRender(){this.frame!==null||this.destroyed||this.contextLost||this.gl.isContextLost()||(this.frame=requestAnimationFrame(()=>{this.frame=null,this.render()}))}resize(){pa(this.canvas,this.gl,this.camera),this.requestRender()}onWebGlContextLost(t){const n=$a({event:t,destroyed:this.destroyed,contextLost:this.contextLost,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,cache:this.cache,onContextLost:this.onContextLost});n.handled&&(this.frame=n.frame,this.contextLost=!0,this.pointBuffersDirty=!0)}onWebGlContextRestored(t){this.destroyed||(this.contextLost=!1,this.cache.clear(),this.tileProgram=Cr(this.gl),this.pointProgram=Ir(this.gl),this.pointBuffersDirty=!0,this.lastPointPalette&&this.lastPointPalette.length>0&&this.setPointPalette(this.lastPointPalette),this.lastPointData?this.setPointData(this.lastPointData):this.pointCount=0,this.resize(),this.onContextRestored?.())}destroy(){const t=Ka({destroyed:this.destroyed,frame:this.frame,cancelViewAnimation:()=>this.cancelViewAnimation(),resizeObserver:this.resizeObserver,removeCanvasEventListeners:()=>ga(this.canvas,this.getCanvasHandlers()),cancelDrag:()=>this.cancelDrag(),tileScheduler:this.tileScheduler,contextLost:this.contextLost,gl:this.gl,cache:this.cache,tileProgram:this.tileProgram,pointProgram:this.pointProgram});t.didDestroy&&(this.destroyed=!0,this.frame=t.frame)}}const cl=[];function ul({source:e,viewState:t,onViewStateChange:n,onStats:r,onTileError:i,onContextLost:o,onContextRestored:s,imageColorSettings:a=null,fitNonce:c=0,rotationResetNonce:u=0,authToken:h="",ctrlDragRotate:l=!0,minZoom:f,maxZoom:d,viewTransition:m,zoomSnaps:p,zoomSnapFitAsMin:y,onPointerWorldMove:b,debugOverlay:x=!1,debugOverlayStyle:C,className:S,style:A,children:T}){const O=g.useRef(null),z=g.useRef(null),G=g.useRef(null),D=g.useRef(null),q=g.useRef(null),re=g.useRef(null),I=g.useRef(cl),H=g.useRef(!1),N=g.useRef(new Set),k=g.useRef(n),Z=g.useRef(r),we=g.useRef(i),se=g.useRef(o),Re=g.useRef(s),[Ce,xe]=g.useState(0),[M,v]=g.useState(null),X=g.useRef(x);g.useEffect(()=>{k.current=n},[n]),g.useEffect(()=>{Z.current=r},[r]),g.useEffect(()=>{we.current=i},[i]),g.useEffect(()=>{se.current=o},[o]),g.useEffect(()=>{Re.current=s},[s]),g.useEffect(()=>{X.current=x,x||v(null)},[x]);const le=g.useMemo(()=>({position:"relative",width:"100%",height:"100%",...A}),[A]),Q=g.useMemo(()=>({position:"absolute",top:8,left:8,zIndex:7,margin:0,padding:"8px 10px",maxWidth:"min(420px, 80%)",pointerEvents:"none",whiteSpace:"pre-wrap",lineHeight:1.35,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:11,color:"#cde6ff",background:"rgba(6, 12, 20, 0.82)",border:"1px solid rgba(173, 216, 255, 0.28)",borderRadius:8,boxShadow:"0 8px 22px rgba(0,0,0,0.35)",...C}),[C]),ie=g.useCallback(_=>{Z.current?.(_),X.current&&v(_)},[]),he=g.useMemo(()=>M?[`tier ${M.tier} | frame ${M.frameMs?.toFixed(2)??"-"} ms | drawCalls ${M.drawCalls??"-"}`,`tiles visible ${M.visible} | rendered ${M.rendered} | fallback ${M.fallback}`,`cache size ${M.cache} | hit ${M.cacheHits??"-"} | miss ${M.cacheMisses??"-"}`,`queue inflight ${M.inflight} | queued ${M.queued??"-"} | retries ${M.retries??"-"} | failed ${M.failed??"-"} | aborted ${M.aborted??"-"}`,`points ${M.points}`].join(`
163
+ `):"stats: waiting for first frame...",[M]),me=g.useCallback(()=>{const _=G.current;if(!_)return;const Y=_.getContext("2d");if(!Y)return;const J=Math.max(1,window.devicePixelRatio||1),oe=_.getBoundingClientRect(),L=Math.max(1,Math.round(oe.width*J)),K=Math.max(1,Math.round(oe.height*J));(_.width!==L||_.height!==K)&&(_.width=L,_.height=K);const ce=oe.width,ne=oe.height;Y.setTransform(1,0,0,1,0,0),Y.clearRect(0,0,_.width,_.height),Y.setTransform(J,0,0,J,0,0);const ue=I.current;for(let ze=0;ze<ue.length;ze+=1)Y.save(),ue[ze].draw(Y,ce,ne),Y.restore()},[]),$=g.useCallback(()=>{H.current||(H.current=!0,requestAnimationFrame(()=>{H.current=!1,me()}))},[me]),pe=g.useCallback((_,Y,J)=>{const oe=I.current.filter(L=>L.id!==_);oe.push({id:_,priority:Y,draw:J}),oe.sort((L,K)=>L.priority-K.priority),I.current=oe,$()},[$]),ye=g.useCallback(_=>{I.current=I.current.filter(Y=>Y.id!==_),$()},[$]),U=g.useCallback((_,Y)=>{Y?N.current.add(_):N.current.delete(_),D.current?.setInteractionLock(N.current.size>0)},[]),V=g.useCallback(()=>N.current.size>0,[]),ee=g.useCallback((_,Y)=>{const J=D.current;return J?En(J.worldToScreen(_,Y)):null},[]),B=g.useCallback((_,Y)=>{const J=D.current;if(!J)return null;const oe=J.screenToWorld(_,Y);if(!Array.isArray(oe)||oe.length<2)return null;const L=Number(oe[0]),K=Number(oe[1]);return!Number.isFinite(L)||!Number.isFinite(K)?null:[L,K]},[]),te=g.useCallback(_=>{k.current?.(_),q.current?.(),re.current?.(),$()},[$]);g.useEffect(()=>{const _=z.current;if(!_||!e)return;const Y=new pi(_,e,{onViewStateChange:te,onStats:ie,onTileError:J=>{we.current?.(J)},onContextLost:()=>{se.current?.()},onContextRestored:()=>{Re.current?.()},authToken:h,imageColorSettings:a,ctrlDragRotate:l,minZoom:f,maxZoom:d,viewTransition:m,zoomSnaps:p,zoomSnapFitAsMin:y});return D.current=Y,xe(J=>J+1),t&&Y.setViewState(t),Y.setInteractionLock(N.current.size>0),()=>{Y.destroy(),D.current=null}},[e,ie,l,te]),g.useEffect(()=>{D.current?.setAuthToken(h)},[h]),g.useEffect(()=>{const _=D.current;!_||!t||_.isViewAnimating()||_.setViewState(t)},[t]),g.useEffect(()=>{D.current?.fitToImage()},[c]),g.useEffect(()=>{D.current?.resetRotation()},[u]),g.useEffect(()=>{D.current?.setZoomRange(f,d)},[f,d]),g.useEffect(()=>{D.current?.setViewTransition(m)},[m]),g.useEffect(()=>{D.current?.setZoomSnaps(p,y)},[p,y]),g.useEffect(()=>{D.current?.setImageColorSettings(a)},[a]),g.useEffect(()=>{const _=G.current;if(!_)return;q.current=$,$();const Y=new ResizeObserver(()=>$());return Y.observe(_),()=>{Y.disconnect(),q.current===$&&(q.current=null)}},[$]);const de=g.useMemo(()=>({source:e,rendererRef:D,rendererSerial:Ce,canvasRef:z,containerRef:O,drawInvalidateRef:q,overviewInvalidateRef:re,worldToScreen:ee,screenToWorld:B,registerDrawCallback:pe,unregisterDrawCallback:ye,requestOverlayRedraw:$,setInteractionLock:U,isInteractionLocked:V}),[e,Ce,ee,B,pe,ye,$,U,V]),ae=g.useRef(b);g.useEffect(()=>{ae.current=b},[b]);const Me=g.useCallback(_=>{const Y=ae.current;if(!Y)return;const J=B(_.clientX,_.clientY),oe=!!J&&J[0]>=0&&J[1]>=0&&!!e&&J[0]<=e.width&&J[1]<=e.height;Y({coordinate:J,clientX:_.clientX,clientY:_.clientY,insideImage:oe})},[B,e]),Se=g.useCallback(()=>{ae.current?.({coordinate:null,clientX:-1,clientY:-1,insideImage:!1})},[]);return Ye.jsx(bs,{value:de,children:Ye.jsxs("div",{ref:O,className:S,style:le,onPointerMove:b?Me:void 0,onPointerLeave:b?Se:void 0,children:[Ye.jsx("canvas",{ref:z,className:"wsi-render-canvas",style:{position:"absolute",inset:0,zIndex:1,width:"100%",height:"100%",display:"block",touchAction:"none"}}),Ye.jsx("canvas",{ref:G,className:"wsi-overlay-canvas",style:{position:"absolute",inset:0,zIndex:2,width:"100%",height:"100%",display:"block",pointerEvents:"none",touchAction:"none"}}),T,x&&Ye.jsx("pre",{"data-open-plant-debug-overlay":!0,style:Q,children:he})]})})}function fl(e){const t=[];for(let n=0;n<e.length;n+=1){const r=e[n],i=yt([pt(r?.coordinates)]);if(i.length===0)continue;let o=0,s=1/0,a=1/0,c=-1/0,u=-1/0;for(const h of i)o+=h.area,h.minX<s&&(s=h.minX),h.minY<a&&(a=h.minY),h.maxX>c&&(c=h.maxX),h.maxY>u&&(u=h.maxY);!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(c)||!Number.isFinite(u)||t.push({regionId:r.id??n,regionIndex:n,polygons:i,area:Math.max(1e-6,o),minX:s,minY:a,maxX:c,maxY:u})}return t}const hl=128,nn=[];function rt(e,t,n,r,i){if(i<=1||n<=t)return 0;const o=(e-t)/r;return!Number.isFinite(o)||o<=0?0:o>=i-1?i-1:Math.floor(o)}function dl(e){if(e.length===0)return null;let t=1/0,n=1/0,r=-1/0,i=-1/0;for(const h of e)h.minX<t&&(t=h.minX),h.minY<n&&(n=h.minY),h.maxX>r&&(r=h.maxX),h.maxY>i&&(i=h.maxY);if(!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i))return null;const o=Math.ceil(Math.sqrt(e.length*2)),s=Math.max(1,Math.min(hl,o)),a=r>t?(r-t)/s:1,c=i>n?(i-n)/s:1,u=Array.from({length:s*s},()=>[]);for(let h=0;h<e.length;h+=1){const l=e[h],f=rt(l.minX,t,r,a,s),d=rt(l.maxX,t,r,a,s),m=rt(l.minY,n,i,c,s),p=rt(l.maxY,n,i,c,s);for(let y=m;y<=p;y+=1)for(let b=f;b<=d;b+=1)u[y*s+b].push(h)}return{minX:t,minY:n,maxX:r,maxY:i,gridSize:s,cellWidth:a,cellHeight:c,buckets:u}}function ml(e,t,n){if(!e||t<e.minX||t>e.maxX||n<e.minY||n>e.maxY)return nn;const r=rt(t,e.minX,e.maxX,e.cellWidth,e.gridSize),i=rt(n,e.minY,e.maxY,e.cellHeight,e.gridSize);return e.buckets[i*e.gridSize+r]??nn}function gl(e,t){if(Array.isArray(t)){const n=t[e];if(typeof n=="string"&&n.length>0)return n}if(t instanceof Map){const n=t.get(e);if(typeof n=="string"&&n.length>0)return n}return String(e)}function pl(e,t,n={}){const r=Math.max(0,Math.min(Math.floor(e?.count??0),Math.floor((e?.positions?.length??0)/2),e?.paletteIndices?.length??0,e?.fillModes instanceof Uint8Array?e.fillModes.length:Number.MAX_SAFE_INTEGER));let i=null;if(e?.drawIndices instanceof Uint32Array){const d=e.drawIndices;let m=d.length;for(let p=0;p<d.length;p+=1)d[p]<r||(m-=1);if(m===d.length)i=d;else if(m>0){const p=new Uint32Array(m);let y=0;for(let b=0;b<d.length;b+=1){const x=d[b];x>=r||(p[y]=x,y+=1)}i=p}else i=new Uint32Array(0)}const o=i?i.length:r,s=fl(t??[]);if(!e||o===0||s.length===0)return{groups:[],inputPointCount:o,pointsInsideAnyRegion:0,unmatchedPointCount:o};const a=new Map,c=new Map,u=dl(s);let h=0;for(let d=0;d<o;d+=1){const m=i?i[d]:d,p=e.positions[m*2],y=e.positions[m*2+1];if(!Number.isFinite(p)||!Number.isFinite(y))continue;let b=null;const x=ml(u,p,y);if(x.length===0)continue;for(const A of x){const T=s[A];let O=!1;for(const z of T.polygons)if(Wr(p,y,z)){O=!0;break}O&&(!b||T.area<b.area)&&(b=T)}if(!b)continue;h+=1;const C=e.paletteIndices[m]??0,S=a.get(b.regionIndex)??new Map;S.set(C,(S.get(C)??0)+1),a.set(b.regionIndex,S),c.set(b.regionIndex,(c.get(b.regionIndex)??0)+1)}const l=n.includeEmptyRegions??!1,f=[];for(const d of s){const m=c.get(d.regionIndex)??0;if(!l&&m<=0)continue;const p=a.get(d.regionIndex)??new Map,y=Array.from(p.entries()).map(([b,x])=>({termId:gl(b,n.paletteIndexToTermId),paletteIndex:b,count:x})).sort((b,x)=>x.count-b.count||b.paletteIndex-x.paletteIndex);f.push({regionId:d.regionId,regionIndex:d.regionIndex,totalCount:m,termCounts:y})}return{groups:f,inputPointCount:o,pointsInsideAnyRegion:h,unmatchedPointCount:Math.max(0,o-h)}}function Lr(e,t,n,r){return[Math.min(e,n),Math.min(t,r),Math.max(e,n),Math.max(t,r)]}function kr(e,t){return!(e[2]<t[0]||e[0]>t[2]||e[3]<t[1]||e[1]>t[3])}class yl{constructor(t=16){R(this,"targetNodeSize");R(this,"items",[]);R(this,"globalBounds",[0,0,0,0]);R(this,"gridSize",1);R(this,"cellWidth",1);R(this,"cellHeight",1);R(this,"buckets",[]);R(this,"visited",new Uint32Array(0));R(this,"querySerial",1);const n=Number.isFinite(t)?Math.floor(t):16;this.targetNodeSize=Math.max(1,n)}load(t){if(!Array.isArray(t)||t.length===0){this.items=[],this.globalBounds=[0,0,0,0],this.gridSize=1,this.cellWidth=1,this.cellHeight=1,this.buckets=[],this.visited=new Uint32Array(0),this.querySerial=1;return}const n=[];let r=1/0,i=1/0,o=-1/0,s=-1/0;for(const h of t){if(!h||!Number.isFinite(h.minX)||!Number.isFinite(h.minY)||!Number.isFinite(h.maxX)||!Number.isFinite(h.maxY))continue;const l=Lr(h.minX,h.minY,h.maxX,h.maxY);r=Math.min(r,l[0]),i=Math.min(i,l[1]),o=Math.max(o,l[2]),s=Math.max(s,l[3]),n.push({minX:l[0],minY:l[1],maxX:l[2],maxY:l[3],value:h.value})}if(this.items=n,this.visited=new Uint32Array(n.length),this.querySerial=1,n.length===0||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(o)||!Number.isFinite(s)){this.globalBounds=[0,0,0,0],this.gridSize=1,this.cellWidth=1,this.cellHeight=1,this.buckets=[];return}this.globalBounds=[r,i,o,s],this.gridSize=Math.max(1,Math.ceil(Math.sqrt(n.length/this.targetNodeSize)));const a=Math.max(0,o-r),c=Math.max(0,s-i);this.cellWidth=a>0?a/this.gridSize:1,this.cellHeight=c>0?c/this.gridSize:1;const u=this.gridSize*this.gridSize;this.buckets=Array.from({length:u},()=>[]);for(let h=0;h<n.length;h+=1){const l=n[h],f=this.toCellX(l.minX),d=this.toCellX(l.maxX),m=this.toCellY(l.minY),p=this.toCellY(l.maxY);for(let y=m;y<=p;y+=1)for(let b=f;b<=d;b+=1)this.buckets[y*this.gridSize+b].push(h)}}search(t){if(this.items.length===0)return[];if(!Array.isArray(t)||t.length<4)return[];const n=Lr(t[0],t[1],t[2],t[3]);if(!kr(n,this.globalBounds))return[];const r=this.toCellX(n[0]),i=this.toCellX(n[2]),o=this.toCellY(n[1]),s=this.toCellY(n[3]),a=this.nextSerial(),c=[];for(let u=o;u<=s;u+=1)for(let h=r;h<=i;h+=1){const l=this.buckets[u*this.gridSize+h];if(!(!l||l.length===0))for(const f of l){if(this.visited[f]===a)continue;this.visited[f]=a;const d=this.items[f];kr(n,[d.minX,d.minY,d.maxX,d.maxY])&&c.push(d)}}return c}nextSerial(){return this.querySerial+=1,this.querySerial===4294967295&&(this.visited.fill(0),this.querySerial=1),this.querySerial}toCellX(t){const n=this.globalBounds[0],r=this.globalBounds[2];if(this.gridSize<=1||r<=n)return 0;const i=(t-n)/this.cellWidth;return!Number.isFinite(i)||i<=0?0:i>=this.gridSize-1?this.gridSize-1:Math.max(0,Math.min(this.gridSize-1,Math.floor(i)))}toCellY(t){const n=this.globalBounds[1],r=this.globalBounds[3];if(this.gridSize<=1||r<=n)return 0;const i=(t-n)/this.cellHeight;return!Number.isFinite(i)||i<=0?0:i>=this.gridSize-1?this.gridSize-1:Math.max(0,Math.min(this.gridSize-1,Math.floor(i)))}}function bl(e){return new yl(e)}function wl(e){return e.replace(/^\s*SRID\s*=\s*\d+\s*;\s*/i,"")}function xl(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function Sl(e){return e>="0"&&e<="9"}function Nr(e){return e==="+"||e==="-"||e==="."||Sl(e)}class El{constructor(t){R(this,"text");R(this,"index",0);this.text=wl(t.trim())}parse(){if(!this.text)return null;const t=this.readWord();if(!t)return null;const n=t.toUpperCase();if(n!=="POLYGON"&&n!=="MULTIPOLYGON")return null;this.skipWhitespace();const r=this.peekWord();if(r){const s=r.toUpperCase();(s==="Z"||s==="M"||s==="ZM")&&(this.readWord(),this.skipWhitespace())}if(this.consumeWordIf("EMPTY"))return this.skipWhitespace(),this.isEof()?n==="POLYGON"?{type:"Polygon",coordinates:[]}:{type:"MultiPolygon",coordinates:[]}:null;let i;try{i=this.parseNestedList()}catch{return null}if(this.skipWhitespace(),!this.isEof())return null;if(n==="POLYGON"){const s=yi(i);return s?{type:"Polygon",coordinates:s}:null}const o=Ml(i);return o?{type:"MultiPolygon",coordinates:o}:null}isEof(){return this.index>=this.text.length}currentChar(){return this.text[this.index]??""}skipWhitespace(){for(;!this.isEof()&&/\s/.test(this.currentChar());)this.index+=1}readWord(){if(this.skipWhitespace(),this.isEof())return null;const t=this.index;for(;!this.isEof()&&xl(this.currentChar());)this.index+=1;return this.index===t?null:this.text.slice(t,this.index)}peekWord(){const t=this.index,n=this.readWord();return this.index=t,n}consumeWordIf(t){const n=this.index,r=this.readWord();return!r||r.toUpperCase()!==t.toUpperCase()?(this.index=n,!1):!0}parseNestedList(){if(this.skipWhitespace(),this.currentChar()!=="(")throw new Error("Expected '('");this.index+=1;const t=[];for(;;){this.skipWhitespace(),this.currentChar()==="("?t.push(this.parseNestedList()):t.push(this.parseCoordinateTuple()),this.skipWhitespace();const n=this.currentChar();if(n===","){this.index+=1;continue}if(n===")"){this.index+=1;break}throw new Error("Expected ',' or ')'")}return t}parseCoordinateTuple(){this.skipWhitespace();const t=[];for(;;){this.skipWhitespace();const n=this.currentChar();if(!n||!Nr(n))break;const r=this.readNumber();if(r===null)break;t.push(r),this.skipWhitespace();const i=this.currentChar();if(!i||i===","||i===")")break;if(!Nr(i))throw new Error("Invalid coordinate")}if(t.length<2)throw new Error("Coordinate requires at least x y");return[t[0],t[1]]}readNumber(){if(this.skipWhitespace(),this.isEof())return null;const n=this.text.slice(this.index).match(/^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/);if(!n)return null;const r=Number(n[0]);return Number.isFinite(r)?(this.index+=n[0].length,r):null}}function Rl(e){return Array.isArray(e)&&e.length>=2&&typeof e[0]=="number"&&Number.isFinite(e[0])&&typeof e[1]=="number"&&Number.isFinite(e[1])}function yi(e){if(!Array.isArray(e))return null;const t=[];for(const n of e){if(!Array.isArray(n))return null;const r=[];for(const i of n){if(!Rl(i))return null;r.push([i[0],i[1]])}t.push(r)}return t}function Ml(e){if(!Array.isArray(e))return null;const t=[];for(const n of e){const r=yi(n);if(!r)return null;t.push(r)}return t}function Al(e){return typeof e!="string"?null:new El(e).parse()}exports.DEFAULT_POINT_COLOR=xn;exports.DrawLayer=ei;exports.DrawingLayer=ws;exports.M1TileRenderer=zr;exports.OverlayLayer=xs;exports.OverviewMap=vs;exports.PatchLayer=Is;exports.PointLayer=Js;exports.RegionLayer=fa;exports.TileScheduler=fi;exports.TileViewerCanvas=ha;exports.WsiTileRenderer=pi;exports.WsiViewer=ul;exports.buildPointSpatialIndexAsync=ui;exports.buildTermPalette=no;exports.calcScaleLength=eo;exports.calcScaleResolution=Sn;exports.clamp=W;exports.closeRing=Fe;exports.computeRoiPointGroups=pl;exports.createCircle=fn;exports.createRectangle=Yt;exports.createSpatialIndex=bl;exports.filterPointDataByPolygons=dt;exports.filterPointDataByPolygonsHybrid=si;exports.filterPointDataByPolygonsInWorker=li;exports.filterPointIndicesByPolygons=ri;exports.filterPointIndicesByPolygonsInWorker=Ds;exports.getWebGpuCapabilities=Ns;exports.hexToRgba=Xr;exports.isSameViewState=cn;exports.lookupCellIndex=ci;exports.normalizeImageInfo=Es;exports.parseWkt=Al;exports.prefilterPointsByBoundsWebGpu=oi;exports.terminatePointHitIndexWorker=Zs;exports.terminateRoiClipWorker=zs;exports.toBearerToken=to;exports.toRoiGeometry=pt;exports.toTileUrl=Pn;exports.useViewerContext=ot;
164
164
  //# sourceMappingURL=index.cjs.map