@idetik/core 0.45.0 → 0.45.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -462,7 +462,7 @@ void main() {
462
462
  }
463
463
  }`;const lE={projectedLine:{vertex:fQ,fragment:ME},points:{vertex:lQ,fragment:HE},wireframe:{vertex:qE,fragment:dE},floatScalarImage:{vertex:TI,fragment:UB},intScalarImage:{vertex:TI,fragment:UB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},uintScalarImage:{vertex:TI,fragment:UB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])},labelImage:{vertex:TI,fragment:pQ},intLabelImage:{vertex:TI,fragment:pQ,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},floatVolume:{vertex:kB,fragment:cB},intVolume:{vertex:kB,fragment:cB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},uintVolume:{vertex:kB,fragment:cB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])},meshDepth:{vertex:TI,fragment:WQ},pointsDepth:{vertex:lQ,fragment:fE},projectedLineDepth:{vertex:fQ,fragment:WQ}},mQ={debug:10,info:20,warn:30,error:40},pE={debug:"\x1B[90m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m"};function WE(){const B=typeof process<"u"&&typeof process.env?.NODE_ENV=="string"?process.env.NODE_ENV:void 0;if(B==="production"||B==="development"||B==="test")return B;if(typeof window<"u"){const{NODE_ENV:A}=window;if(A==="production"||A==="development"||A==="test")return A}return"development"}class O{static logLevel_=WE()==="production"?"warn":"debug";static setLogLevel(A){O.logLevel_=A}static debug(A,I,...g){O.log("debug",A,I,...g)}static info(A,I,...g){O.log("info",A,I,...g)}static warn(A,I,...g){O.log("warn",A,I,...g)}static error(A,I,...g){O.log("error",A,I,...g)}static log(A,I,g,...Q){if(mQ[A]<mQ[O.logLevel_])return;const C=new Date().toISOString(),E=pE[A],i=`[${C}][${A.toUpperCase()}][${I}]`,D=[`${E}${i}`,g,...Q];switch(A){case"debug":console.debug(...D);break;case"info":console.info(...D);break;case"warn":console.warn(...D);break;case"error":console.error(...D);break}}}class mE{gl_;program_;uniformInfo_=new Map;constructor(A,I,g){this.gl_=A;const Q=A.createProgram();if(!Q)throw new Error("Failed to create WebGL shader program");this.program_=Q;const C=[];try{C.push(this.addShader(I,A.VERTEX_SHADER)),C.push(this.addShader(g,A.FRAGMENT_SHADER)),this.link(),this.preprocessUniformLocations()}catch(E){throw A.deleteProgram(Q),E}finally{C.forEach(E=>this.gl_.deleteShader(E))}}setUniform(A,I){const[g,Q]=this.uniformInfo_.get(A)??[];if(!g||!Q)throw new Error(`Uniform "${A}" not found in shader program`);const C=Q.type;switch(C){case this.gl_.BOOL:case this.gl_.FLOAT:typeof I=="number"?this.gl_.uniform1f(g,I):this.gl_.uniform1fv(g,I);break;case this.gl_.INT:typeof I=="number"?this.gl_.uniform1i(g,I):this.gl_.uniform1iv(g,I);break;case this.gl_.FLOAT_VEC2:this.gl_.uniform2fv(g,I);break;case this.gl_.FLOAT_VEC3:this.gl_.uniform3fv(g,I);break;case this.gl_.FLOAT_VEC4:this.gl_.uniform4fv(g,I);break;case this.gl_.FLOAT_MAT4:this.gl_.uniformMatrix4fv(g,!1,I);break;case this.gl_.UNSIGNED_INT:this.gl_.uniform1ui(g,I);break;case this.gl_.SAMPLER_2D:case this.gl_.SAMPLER_CUBE:case this.gl_.SAMPLER_3D:case this.gl_.SAMPLER_2D_ARRAY:case this.gl_.SAMPLER_2D_SHADOW:case this.gl_.SAMPLER_CUBE_SHADOW:case this.gl_.SAMPLER_2D_ARRAY_SHADOW:case this.gl_.INT_SAMPLER_2D:case this.gl_.INT_SAMPLER_3D:case this.gl_.INT_SAMPLER_CUBE:case this.gl_.INT_SAMPLER_2D_ARRAY:case this.gl_.UNSIGNED_INT_SAMPLER_2D:case this.gl_.UNSIGNED_INT_SAMPLER_3D:case this.gl_.UNSIGNED_INT_SAMPLER_CUBE:case this.gl_.UNSIGNED_INT_SAMPLER_2D_ARRAY:this.gl_.uniform1i(g,I);break;default:{const E=C;throw new Error(`Unhandled uniform type: ${E}`)}}}preprocessUniformLocations(){const A=this.gl_.getProgramParameter(this.program_,this.gl_.ACTIVE_UNIFORMS);for(let I=0;I<A;I++){const g=this.gl_.getActiveUniform(this.program_,I);if(g){if(!xE.has(g.type))throw new Error(`Unsupported uniform type "${g.type}" (GLenum) found in shader program for uniform "${g.name}"`);const Q=this.gl_.getUniformLocation(this.program_,g.name);Q&&(this.uniformInfo_.set(g.name,[Q,g]),O.debug("WebGLShaderProgram","Uniform found:",g.name,g.type,g.size))}}}addShader(A,I){const g=this.gl_.createShader(I);if(!g)throw new Error(`Failed to create a new shader of type ${I}`);if(this.gl_.shaderSource(g,A),this.gl_.compileShader(g),!this.gl_.getShaderParameter(g,this.gl_.COMPILE_STATUS)){const Q=this.gl_.getShaderInfoLog(g);throw this.gl_.deleteShader(g),new Error(`Error compiling shader: ${Q}`)}return this.gl_.attachShader(this.program_,g),g}link(){if(this.gl_.linkProgram(this.program_),!this.getParameter(this.gl_.LINK_STATUS)){const A=this.gl_.getProgramInfoLog(this.program_);throw new Error(`Error linking program: ${A}`)}}use(){this.gl_.useProgram(this.program_)}getParameter(A){return this.gl_.getProgramParameter(this.program_,A)}get uniformNames(){return Array.from(this.uniformInfo_.keys())}}const TE=typeof window<"u"?[WebGL2RenderingContext.BOOL,WebGL2RenderingContext.FLOAT,WebGL2RenderingContext.INT,WebGL2RenderingContext.FLOAT_VEC2,WebGL2RenderingContext.FLOAT_VEC3,WebGL2RenderingContext.FLOAT_VEC4,WebGL2RenderingContext.FLOAT_MAT4,WebGL2RenderingContext.SAMPLER_2D,WebGL2RenderingContext.SAMPLER_CUBE,WebGL2RenderingContext.SAMPLER_3D,WebGL2RenderingContext.SAMPLER_2D_ARRAY,WebGL2RenderingContext.SAMPLER_2D_SHADOW,WebGL2RenderingContext.SAMPLER_CUBE_SHADOW,WebGL2RenderingContext.SAMPLER_2D_ARRAY_SHADOW,WebGL2RenderingContext.INT,WebGL2RenderingContext.INT_SAMPLER_2D,WebGL2RenderingContext.INT_SAMPLER_3D,WebGL2RenderingContext.INT_SAMPLER_CUBE,WebGL2RenderingContext.INT_SAMPLER_2D_ARRAY,WebGL2RenderingContext.UNSIGNED_INT,WebGL2RenderingContext.UNSIGNED_INT_SAMPLER_2D,WebGL2RenderingContext.UNSIGNED_INT_SAMPLER_3D,WebGL2RenderingContext.UNSIGNED_INT_SAMPLER_CUBE,WebGL2RenderingContext.UNSIGNED_INT_SAMPLER_2D_ARRAY]:[],xE=new Set(TE),LB="#pragma inject_defines";class ZE{gl_;programs_=new Map;constructor(A){this.gl_=A}use(A){let I=this.programs_.get(A);if(I===void 0){const g=lE[A],Q=TQ(g.vertex,g.vertexDefines),C=TQ(g.fragment,g.fragmentDefines);I=new mE(this.gl_,Q,C),I.use();const E=this.gl_.getError();if(E!==this.gl_.NO_ERROR)throw new Error(`Error using WebGL program: ${E}`);this.programs_.set(A,I)}else I.use();return I}}function TQ(B,A){if(A===void 0||A.size==0)return B;if(!B.includes(LB))throw new Error(`Shader source does not contain "${LB}" directive`);const I=Array.from(A.entries()).map(([E,i])=>`#define ${E} ${i}`).join(`
464
464
  `),Q=`#line __LINE__ + ${1-A.size}`,C=`${I}
465
- ${Q}`;return B.replace(LB,C)}const Tg={};function xQ(B){const A=B??"";return Tg[A]=(Tg[A]??0)+1,B?`${B}-${Tg[A]}`:String(Tg[A])}class xg{id=xQ()}var FA=1e-6,eA=typeof Float32Array<"u"?Float32Array:Array,uE=Math.PI/180;function bE(B){return B*uE}function ZQ(){var B=new eA(9);return eA!=Float32Array&&(B[1]=0,B[2]=0,B[3]=0,B[5]=0,B[6]=0,B[7]=0),B[0]=1,B[4]=1,B[8]=1,B}function PE(B,A){return B[0]=A[0],B[1]=A[1],B[2]=A[2],B[3]=A[4],B[4]=A[5],B[5]=A[6],B[6]=A[8],B[7]=A[9],B[8]=A[10],B}function VE(B,A,I,g,Q,C,E,i,D){var a=new eA(9);return a[0]=B,a[1]=A,a[2]=I,a[3]=g,a[4]=Q,a[5]=C,a[6]=E,a[7]=i,a[8]=D,a}function WA(){var B=new eA(16);return eA!=Float32Array&&(B[1]=0,B[2]=0,B[3]=0,B[4]=0,B[6]=0,B[7]=0,B[8]=0,B[9]=0,B[11]=0,B[12]=0,B[13]=0,B[14]=0),B[0]=1,B[5]=1,B[10]=1,B[15]=1,B}function Sg(B,A){var I=A[0],g=A[1],Q=A[2],C=A[3],E=A[4],i=A[5],D=A[6],a=A[7],G=A[8],R=A[9],t=A[10],J=A[11],n=A[12],e=A[13],K=A[14],l=A[15],V=I*i-g*E,x=I*D-Q*E,W=I*a-C*E,p=g*D-Q*i,T=g*a-C*i,$=Q*a-C*D,CA=G*e-R*n,BA=G*K-t*n,iA=G*l-J*n,sA=R*K-t*e,qA=R*l-J*e,kA=t*l-J*K,aA=V*kA-x*qA+W*sA+p*iA-T*BA+$*CA;return aA?(aA=1/aA,B[0]=(i*kA-D*qA+a*sA)*aA,B[1]=(Q*qA-g*kA-C*sA)*aA,B[2]=(e*$-K*T+l*p)*aA,B[3]=(t*T-R*$-J*p)*aA,B[4]=(D*iA-E*kA-a*BA)*aA,B[5]=(I*kA-Q*iA+C*BA)*aA,B[6]=(K*W-n*$-l*x)*aA,B[7]=(G*$-t*W+J*x)*aA,B[8]=(E*qA-i*iA+a*CA)*aA,B[9]=(g*iA-I*qA-C*CA)*aA,B[10]=(n*T-e*W+l*V)*aA,B[11]=(R*W-G*T-J*V)*aA,B[12]=(i*BA-E*sA-D*CA)*aA,B[13]=(I*sA-g*BA+Q*CA)*aA,B[14]=(e*x-n*p-K*V)*aA,B[15]=(G*p-R*x+t*V)*aA,B):null}function Zg(B,A,I){var g=A[0],Q=A[1],C=A[2],E=A[3],i=A[4],D=A[5],a=A[6],G=A[7],R=A[8],t=A[9],J=A[10],n=A[11],e=A[12],K=A[13],l=A[14],V=A[15],x=I[0],W=I[1],p=I[2],T=I[3];return B[0]=x*g+W*i+p*R+T*e,B[1]=x*Q+W*D+p*t+T*K,B[2]=x*C+W*a+p*J+T*l,B[3]=x*E+W*G+p*n+T*V,x=I[4],W=I[5],p=I[6],T=I[7],B[4]=x*g+W*i+p*R+T*e,B[5]=x*Q+W*D+p*t+T*K,B[6]=x*C+W*a+p*J+T*l,B[7]=x*E+W*G+p*n+T*V,x=I[8],W=I[9],p=I[10],T=I[11],B[8]=x*g+W*i+p*R+T*e,B[9]=x*Q+W*D+p*t+T*K,B[10]=x*C+W*a+p*J+T*l,B[11]=x*E+W*G+p*n+T*V,x=I[12],W=I[13],p=I[14],T=I[15],B[12]=x*g+W*i+p*R+T*e,B[13]=x*Q+W*D+p*t+T*K,B[14]=x*C+W*a+p*J+T*l,B[15]=x*E+W*G+p*n+T*V,B}function OE(B,A,I){var g=I[0],Q=I[1],C=I[2],E,i,D,a,G,R,t,J,n,e,K,l;return A===B?(B[12]=A[0]*g+A[4]*Q+A[8]*C+A[12],B[13]=A[1]*g+A[5]*Q+A[9]*C+A[13],B[14]=A[2]*g+A[6]*Q+A[10]*C+A[14],B[15]=A[3]*g+A[7]*Q+A[11]*C+A[15]):(E=A[0],i=A[1],D=A[2],a=A[3],G=A[4],R=A[5],t=A[6],J=A[7],n=A[8],e=A[9],K=A[10],l=A[11],B[0]=E,B[1]=i,B[2]=D,B[3]=a,B[4]=G,B[5]=R,B[6]=t,B[7]=J,B[8]=n,B[9]=e,B[10]=K,B[11]=l,B[12]=E*g+G*Q+n*C+A[12],B[13]=i*g+R*Q+e*C+A[13],B[14]=D*g+t*Q+K*C+A[14],B[15]=a*g+J*Q+l*C+A[15]),B}function uQ(B,A){return B[0]=A[0],B[1]=0,B[2]=0,B[3]=0,B[4]=0,B[5]=A[1],B[6]=0,B[7]=0,B[8]=0,B[9]=0,B[10]=A[2],B[11]=0,B[12]=0,B[13]=0,B[14]=0,B[15]=1,B}function XE(B,A,I,g){var Q=A[0],C=A[1],E=A[2],i=A[3],D=Q+Q,a=C+C,G=E+E,R=Q*D,t=Q*a,J=Q*G,n=C*a,e=C*G,K=E*G,l=i*D,V=i*a,x=i*G,W=g[0],p=g[1],T=g[2];return B[0]=(1-(n+K))*W,B[1]=(t+x)*W,B[2]=(J-V)*W,B[3]=0,B[4]=(t-x)*p,B[5]=(1-(R+K))*p,B[6]=(e+l)*p,B[7]=0,B[8]=(J+V)*T,B[9]=(e-l)*T,B[10]=(1-(R+n))*T,B[11]=0,B[12]=I[0],B[13]=I[1],B[14]=I[2],B[15]=1,B}function vE(B,A,I,g,Q){var C=1/Math.tan(A/2);if(B[0]=C/I,B[1]=0,B[2]=0,B[3]=0,B[4]=0,B[5]=C,B[6]=0,B[7]=0,B[8]=0,B[9]=0,B[11]=-1,B[12]=0,B[13]=0,B[15]=0,Q!=null&&Q!==1/0){var E=1/(g-Q);B[10]=(Q+g)*E,B[14]=2*Q*g*E}else B[10]=-1,B[14]=-2*g;return B}var jE=vE;function zE(B,A,I,g,Q,C,E){var i=1/(A-I),D=1/(g-Q),a=1/(C-E);return B[0]=-2*i,B[1]=0,B[2]=0,B[3]=0,B[4]=0,B[5]=-2*D,B[6]=0,B[7]=0,B[8]=0,B[9]=0,B[10]=2*a,B[11]=0,B[12]=(A+I)*i,B[13]=(Q+g)*D,B[14]=(E+C)*a,B[15]=1,B}var _E=zE;function $E(B,A,I,g){var Q=A[0],C=A[1],E=A[2],i=g[0],D=g[1],a=g[2],G=Q-I[0],R=C-I[1],t=E-I[2],J=G*G+R*R+t*t;J>0&&(J=1/Math.sqrt(J),G*=J,R*=J,t*=J);var n=D*t-a*R,e=a*G-i*t,K=i*R-D*G;return J=n*n+e*e+K*K,J>0&&(J=1/Math.sqrt(J),n*=J,e*=J,K*=J),B[0]=n,B[1]=e,B[2]=K,B[3]=0,B[4]=R*K-t*e,B[5]=t*n-G*K,B[6]=G*e-R*n,B[7]=0,B[8]=G,B[9]=R,B[10]=t,B[11]=0,B[12]=Q,B[13]=C,B[14]=E,B[15]=1,B}function Ai(B,A){var I=B[0],g=B[1],Q=B[2],C=B[3],E=B[4],i=B[5],D=B[6],a=B[7],G=B[8],R=B[9],t=B[10],J=B[11],n=B[12],e=B[13],K=B[14],l=B[15],V=A[0],x=A[1],W=A[2],p=A[3],T=A[4],$=A[5],CA=A[6],BA=A[7],iA=A[8],sA=A[9],qA=A[10],kA=A[11],aA=A[12],oI=A[13],II=A[14],DI=A[15];return Math.abs(I-V)<=FA*Math.max(1,Math.abs(I),Math.abs(V))&&Math.abs(g-x)<=FA*Math.max(1,Math.abs(g),Math.abs(x))&&Math.abs(Q-W)<=FA*Math.max(1,Math.abs(Q),Math.abs(W))&&Math.abs(C-p)<=FA*Math.max(1,Math.abs(C),Math.abs(p))&&Math.abs(E-T)<=FA*Math.max(1,Math.abs(E),Math.abs(T))&&Math.abs(i-$)<=FA*Math.max(1,Math.abs(i),Math.abs($))&&Math.abs(D-CA)<=FA*Math.max(1,Math.abs(D),Math.abs(CA))&&Math.abs(a-BA)<=FA*Math.max(1,Math.abs(a),Math.abs(BA))&&Math.abs(G-iA)<=FA*Math.max(1,Math.abs(G),Math.abs(iA))&&Math.abs(R-sA)<=FA*Math.max(1,Math.abs(R),Math.abs(sA))&&Math.abs(t-qA)<=FA*Math.max(1,Math.abs(t),Math.abs(qA))&&Math.abs(J-kA)<=FA*Math.max(1,Math.abs(J),Math.abs(kA))&&Math.abs(n-aA)<=FA*Math.max(1,Math.abs(n),Math.abs(aA))&&Math.abs(e-oI)<=FA*Math.max(1,Math.abs(e),Math.abs(oI))&&Math.abs(K-II)<=FA*Math.max(1,Math.abs(K),Math.abs(II))&&Math.abs(l-DI)<=FA*Math.max(1,Math.abs(l),Math.abs(DI))}function AA(){var B=new eA(3);return eA!=Float32Array&&(B[0]=0,B[1]=0,B[2]=0),B}function $A(B){var A=new eA(3);return A[0]=B[0],A[1]=B[1],A[2]=B[2],A}function JB(B){var A=B[0],I=B[1],g=B[2];return Math.sqrt(A*A+I*I+g*g)}function wA(B,A,I){var g=new eA(3);return g[0]=B,g[1]=A,g[2]=I,g}function rB(B,A){return B[0]=A[0],B[1]=A[1],B[2]=A[2],B}function LI(B,A,I,g){return B[0]=A,B[1]=I,B[2]=g,B}function ug(B,A,I){return B[0]=A[0]+I[0],B[1]=A[1]+I[1],B[2]=A[2]+I[2],B}function nB(B,A,I){return B[0]=A[0]-I[0],B[1]=A[1]-I[1],B[2]=A[2]-I[2],B}function Ii(B,A,I){return B[0]=A[0]*I[0],B[1]=A[1]*I[1],B[2]=A[2]*I[2],B}function YB(B,A,I){return B[0]=A[0]*I,B[1]=A[1]*I,B[2]=A[2]*I,B}function KB(B,A,I,g){return B[0]=A[0]+I[0]*g,B[1]=A[1]+I[1]*g,B[2]=A[2]+I[2]*g,B}function gi(B,A){var I=A[0]-B[0],g=A[1]-B[1],Q=A[2]-B[2];return I*I+g*g+Q*Q}function bQ(B,A){var I=A[0],g=A[1],Q=A[2],C=I*I+g*g+Q*Q;return C>0&&(C=1/Math.sqrt(C)),B[0]=A[0]*C,B[1]=A[1]*C,B[2]=A[2]*C,B}function bg(B,A){return B[0]*A[0]+B[1]*A[1]+B[2]*A[2]}function Pg(B,A,I){var g=A[0],Q=A[1],C=A[2],E=I[0],i=I[1],D=I[2];return B[0]=Q*D-C*i,B[1]=C*E-g*D,B[2]=g*i-Q*E,B}function eB(B,A,I){var g=A[0],Q=A[1],C=A[2],E=I[3]*g+I[7]*Q+I[11]*C+I[15];return E=E||1,B[0]=(I[0]*g+I[4]*Q+I[8]*C+I[12])/E,B[1]=(I[1]*g+I[5]*Q+I[9]*C+I[13])/E,B[2]=(I[2]*g+I[6]*Q+I[10]*C+I[14])/E,B}function PQ(B,A,I){var g=I[0],Q=I[1],C=I[2],E=I[3],i=A[0],D=A[1],a=A[2],G=Q*a-C*D,R=C*i-g*a,t=g*D-Q*i;return G=G+G,R=R+R,t=t+t,B[0]=i+E*G+Q*t-C*R,B[1]=D+E*R+C*G-g*t,B[2]=a+E*t+g*R-Q*G,B}function Bi(B){return B[0]=0,B[1]=0,B[2]=0,B}function MB(B,A){var I=B[0],g=B[1],Q=B[2],C=A[0],E=A[1],i=A[2];return Math.abs(I-C)<=FA*Math.max(1,Math.abs(I),Math.abs(C))&&Math.abs(g-E)<=FA*Math.max(1,Math.abs(g),Math.abs(E))&&Math.abs(Q-i)<=FA*Math.max(1,Math.abs(Q),Math.abs(i))}var HB=nB,Qi=JB;(function(){var B=AA();return function(A,I,g,Q,C,E){var i,D;for(I||(I=3),g||(g=0),Q?D=Math.min(Q*I+g,A.length):D=A.length,i=g;i<D;i+=I)B[0]=A[i],B[1]=A[i+1],B[2]=A[i+2],C(B,B,E),A[i]=B[0],A[i+1]=B[1],A[i+2]=B[2];return A}})();function xI(){var B=new eA(4);return eA!=Float32Array&&(B[0]=0,B[1]=0,B[2]=0,B[3]=0),B}function Ci(B){var A=new eA(4);return A[0]=B[0],A[1]=B[1],A[2]=B[2],A[3]=B[3],A}function Vg(B,A,I,g){var Q=new eA(4);return Q[0]=B,Q[1]=A,Q[2]=I,Q[3]=g,Q}function Ei(B,A){return B[0]=A[0],B[1]=A[1],B[2]=A[2],B[3]=A[3],B}function ii(B,A,I){return B[0]=A[0]*I,B[1]=A[1]*I,B[2]=A[2]*I,B[3]=A[3]*I,B}function oi(B,A){var I=A[0],g=A[1],Q=A[2],C=A[3],E=I*I+g*g+Q*Q+C*C;return E>0&&(E=1/Math.sqrt(E)),B[0]=I*E,B[1]=g*E,B[2]=Q*E,B[3]=C*E,B}function Rg(B,A,I){var g=A[0],Q=A[1],C=A[2],E=A[3];return B[0]=I[0]*g+I[4]*Q+I[8]*C+I[12]*E,B[1]=I[1]*g+I[5]*Q+I[9]*C+I[13]*E,B[2]=I[2]*g+I[6]*Q+I[10]*C+I[14]*E,B[3]=I[3]*g+I[7]*Q+I[11]*C+I[15]*E,B}(function(){var B=xI();return function(A,I,g,Q,C,E){var i,D;for(I||(I=4),g||(g=0),Q?D=Math.min(Q*I+g,A.length):D=A.length,i=g;i<D;i+=I)B[0]=A[i],B[1]=A[i+1],B[2]=A[i+2],B[3]=A[i+3],C(B,B,E),A[i]=B[0],A[i+1]=B[1],A[i+2]=B[2],A[i+3]=B[3];return A}})();function Og(){var B=new eA(4);return eA!=Float32Array&&(B[0]=0,B[1]=0,B[2]=0),B[3]=1,B}function Di(B,A,I){I=I*.5;var g=Math.sin(I);return B[0]=g*A[0],B[1]=g*A[1],B[2]=g*A[2],B[3]=Math.cos(I),B}function ai(B,A,I){var g=A[0],Q=A[1],C=A[2],E=A[3],i=I[0],D=I[1],a=I[2],G=I[3];return B[0]=g*G+E*i+Q*a-C*D,B[1]=Q*G+E*D+C*i-g*a,B[2]=C*G+E*a+g*D-Q*i,B[3]=E*G-g*i-Q*D-C*a,B}function qB(B,A,I,g){var Q=A[0],C=A[1],E=A[2],i=A[3],D=I[0],a=I[1],G=I[2],R=I[3],t,J,n,e,K;return J=Q*D+C*a+E*G+i*R,J<0&&(J=-J,D=-D,a=-a,G=-G,R=-R),1-J>FA?(t=Math.acos(J),n=Math.sin(t),e=Math.sin((1-g)*t)/n,K=Math.sin(g*t)/n):(e=1-g,K=g),B[0]=e*Q+K*D,B[1]=e*C+K*a,B[2]=e*E+K*G,B[3]=e*i+K*R,B}function dB(B,A){var I=A[0]+A[4]+A[8],g;if(I>0)g=Math.sqrt(I+1),B[3]=.5*g,g=.5/g,B[0]=(A[5]-A[7])*g,B[1]=(A[6]-A[2])*g,B[2]=(A[1]-A[3])*g;else{var Q=0;A[4]>A[0]&&(Q=1),A[8]>A[Q*3+Q]&&(Q=2);var C=(Q+1)%3,E=(Q+2)%3;g=Math.sqrt(A[Q*3+Q]-A[C*3+C]-A[E*3+E]+1),B[Q]=.5*g,g=.5/g,B[3]=(A[C*3+E]-A[E*3+C])*g,B[C]=(A[C*3+Q]+A[Q*3+C])*g,B[E]=(A[E*3+Q]+A[Q*3+E])*g}return B}var si=Ci,yi=Ei,Xg=oi;(function(){var B=AA(),A=wA(1,0,0),I=wA(0,1,0);return function(g,Q,C){var E=bg(Q,C);return E<-.999999?(Pg(B,A,Q),Qi(B)<1e-6&&Pg(B,I,Q),bQ(B,B),Di(g,B,Math.PI),g):E>.999999?(g[0]=0,g[1]=0,g[2]=0,g[3]=1,g):(Pg(B,Q,C),g[0]=B[0],g[1]=B[1],g[2]=B[2],g[3]=1+E,Xg(g,g))}})(),(function(){var B=Og(),A=Og();return function(I,g,Q,C,E,i){return qB(B,g,E,i),qB(A,Q,C,i),qB(I,B,A,2*i*(1-i)),I}})(),(function(){var B=ZQ();return function(A,I,g,Q){return B[0]=g[0],B[3]=g[1],B[6]=g[2],B[1]=Q[0],B[4]=Q[1],B[7]=Q[2],B[2]=-I[0],B[5]=-I[1],B[8]=-I[2],Xg(A,dB(A,B))}})();function VQ(){var B=new eA(2);return eA!=Float32Array&&(B[0]=0,B[1]=0),B}function OQ(B){var A=new eA(2);return A[0]=B[0],A[1]=B[1],A}function LA(B,A){var I=new eA(2);return I[0]=B,I[1]=A,I}function hi(B,A){var I=A[0]-B[0],g=A[1]-B[1];return Math.sqrt(I*I+g*g)}function Gi(B){var A=B[0],I=B[1];return A*A+I*I}function Fi(B,A,I,g){var Q=A[0],C=A[1];return B[0]=Q+g*(I[0]-Q),B[1]=C+g*(I[1]-C),B}function XQ(B,A){return B[0]===A[0]&&B[1]===A[1]}function vQ(B,A){var I=B[0],g=B[1],Q=A[0],C=A[1];return Math.abs(I-Q)<=FA*Math.max(1,Math.abs(I),Math.abs(Q))&&Math.abs(g-C)<=FA*Math.max(1,Math.abs(g),Math.abs(C))}(function(){var B=VQ();return function(A,I,g,Q,C,E){var i,D;for(I||(I=2),g||(g=0),Q?D=Math.min(Q*I+g,A.length):D=A.length,i=g;i<D;i+=I)B[0]=A[i],B[1]=A[i+1],C(B,B,E),A[i]=B[0],A[i+1]=B[1];return A}})();class ZI{min;max;constructor(A,I){this.min=A?$A(A):wA(1/0,1/0,1/0),this.max=I?$A(I):wA(-1/0,-1/0,-1/0)}clone(){return new ZI(this.min,this.max)}isEmpty(){return this.max[0]<=this.min[0]||this.max[1]<=this.min[1]||this.max[2]<=this.min[2]}static intersects(A,I){return!(A.max[0]<=I.min[0]||A.min[0]>=I.max[0]||A.max[1]<=I.min[1]||A.min[1]>=I.max[1]||A.max[2]<=I.min[2]||A.min[2]>=I.max[2])}expandWithPoint(A){A[0]<this.min[0]&&(this.min[0]=A[0]),A[1]<this.min[1]&&(this.min[1]=A[1]),A[2]<this.min[2]&&(this.min[2]=A[2]),A[0]>this.max[0]&&(this.max[0]=A[0]),A[1]>this.max[1]&&(this.max[1]=A[1]),A[2]>this.max[2]&&(this.max[2]=A[2])}applyTransform(A){const{min:I,max:g}=this,Q=[wA(I[0],I[1],I[2]),wA(I[0],I[1],g[2]),wA(I[0],g[1],I[2]),wA(I[0],g[1],g[2]),wA(g[0],I[1],I[2]),wA(g[0],I[1],g[2]),wA(g[0],g[1],I[2]),wA(g[0],g[1],g[2])];this.min=wA(1/0,1/0,1/0),this.max=wA(-1/0,-1/0,-1/0);const C=AA();for(const E of Q)eB(C,E,A),this.expandWithPoint(C)}}const wi={position:0,normal:1,uv:2,next_position:3,previous_position:4,direction:5,color:6,size:7,marker:8};class uI extends xg{instanceCount=null;boundingBox_=null;primitive_;attributes_;vertexData_;indexData_;constructor(A=[],I=[],g="triangles"){super(),this.vertexData_=new Float32Array(A),this.indexData_=new Uint32Array(I),this.primitive_=g,this.attributes_=[]}addAttribute(A){this.attributes_.push(A),this.boundingBox_=null}get vertexCount(){return this.vertexData_.byteLength/this.strideBytes}get stride(){return this.attributes_.reduce((A,I)=>A+I.itemSize,0)}get strideBytes(){return this.stride*Float32Array.BYTES_PER_ELEMENT}get primitive(){return this.primitive_}get vertexData(){return this.vertexData_}get indexData(){return this.indexData_}get attributes(){return this.attributes_}get boundingBox(){if(this.boundingBox_===null){const A=this.getAttribute("position");if(!A||this.vertexCount===0)throw new Error("Failed to generate bounding box");const I=(A.offset??0)/Float32Array.BYTES_PER_ELEMENT,g=new ZI,Q=AA();for(let C=0;C<this.vertexData_.length;C+=this.stride)Q[0]=this.vertexData_[C+I+0],Q[1]=this.vertexData_[C+I+1],Q[2]=this.vertexData_[C+I+2],g.expandWithPoint(Q);this.boundingBox_=g}return this.boundingBox_}get type(){return"Geometry"}getAttribute(A){return this.attributes_.find(I=>I.type===A)}}class Si{gl_;buffers_=new Map;currentGeometry_=null;constructor(A){this.gl_=A}bindGeometry(A){if(this.alreadyActive(A))return;this.buffers_.has(A)||this.generateBuffers(A);const I=this.buffers_.get(A);if(!I)throw new Error("Failed to retrieve buffer handles for object");this.gl_.bindVertexArray(I.vao),this.currentGeometry_=A}disposeObject(A){const I=this.buffers_.get(A);I&&(this.gl_.deleteVertexArray(I.vao),this.gl_.deleteBuffer(I.vbo),I.ebo&&this.gl_.deleteBuffer(I.ebo),this.buffers_.delete(A),this.currentGeometry_===A&&(this.currentGeometry_=null))}disposeAll(){for(const A of this.buffers_.keys())this.disposeObject(A)}alreadyActive(A){return this.currentGeometry_===A}generateBuffers(A){const I=this.gl_.createVertexArray();if(!I)throw new Error("Failed to create vertex array object (VAO)");this.gl_.bindVertexArray(I);const{vertexData:g}=A,Q=this.gl_.ARRAY_BUFFER,C=this.gl_.createBuffer();if(!C)throw new Error("Failed to create vertex buffer (VBO)");this.gl_.bindBuffer(Q,C),this.gl_.bufferData(Q,g,this.gl_.STATIC_DRAW);const{attributes:E,strideBytes:i}=A;E.forEach(G=>{const R=wi[G.type];this.gl_.vertexAttribPointer(R,G.itemSize,this.gl_.FLOAT,!1,i,G.offset),this.gl_.enableVertexAttribArray(R)});const D={vao:I,vbo:C},{indexData:a}=A;if(a.length){const G=this.gl_.ELEMENT_ARRAY_BUFFER,R=this.gl_.createBuffer();if(!R)throw new Error("Failed to create index buffer (EBO)");this.gl_.bindBuffer(G,R),this.gl_.bufferData(G,a,this.gl_.STATIC_DRAW),D.ebo=R}this.buffers_.set(A,D),this.gl_.bindVertexArray(null)}}function Ri(B){return B===1||B===2||B===4||B===8}function fB(B){if(B instanceof Int8Array)return"byte";if(B instanceof Int16Array)return"short";if(B instanceof Int32Array)return"int";if(B instanceof Uint8Array)return"unsigned_byte";if(B instanceof Uint16Array)return"unsigned_short";if(B instanceof Uint32Array)return"unsigned_int";if(B instanceof Float32Array)return"float";throw new Error("Unsupported buffer type.")}function Ni(B){switch(B.dataFormat){case"scalar":return 1;case"rgb":return 3;case"rgba":return 4}}function ti(B){switch(B.dataType){case"byte":case"unsigned_byte":return 1;case"short":case"unsigned_short":return 2;case"int":case"unsigned_int":case"float":return 4}}function lB(B){const A=Ni(B)*ti(B),I=Math.max(1,B.mipmapLevels);let g=Math.max(1,B.width),Q=Math.max(1,B.height),C=Math.max(1,B.depth),E=0;for(let i=0;i<I;++i)E+=A*C*g*Q,g=Math.max(1,g>>1),Q=Math.max(1,Q>>1),B.type==="Texture3D"&&(C=Math.max(1,C>>1));return E}function Ui(B){if(B.dataFormat==="rgb"||B.dataFormat==="rgba")return[0,1];switch(B.dataType){case"byte":return[-128,127];case"short":return[-32768,32767];case"int":return[-2147483648,2147483647];case"unsigned_byte":return[0,255];case"unsigned_short":return[0,65535];case"unsigned_int":return[0,4294967295];case"float":return[0,1]}}class pB extends xg{dataFormat="rgba";dataType="unsigned_byte";maxFilter="nearest";minFilter="nearest";mipmapLevels=1;unpackAlignment=4;wrapR="clamp_to_edge";wrapS="clamp_to_edge";wrapT="clamp_to_edge";needsUpdate=!0;readTexel;data_=null;get data(){return this.data_}set data(A){this.data_=A,this.needsUpdate=!0}releaseCpuData(){this.data_=null}get depth(){return 1}get type(){return"Texture"}}class ki{gl_;textures_=new Map;currentTexture_=null;maxTextureUnits_;nextPersistentUnit_;gpuTextureBytes_=0;textureCount_=0;readFramebuffer_=null;constructor(A){this.gl_=A,this.maxTextureUnits_=A.getParameter(A.MAX_TEXTURE_IMAGE_UNITS),this.nextPersistentUnit_=this.maxTextureUnits_-1}get gpuTextureBytes(){return this.gpuTextureBytes_}get textureCount(){return this.textureCount_}reservePersistentUnit(){if(this.nextPersistentUnit_<0)throw new Error(`No texture units left to reserve (${this.maxTextureUnits_} total)`);return this.nextPersistentUnit_--}bindTexture(A,I){if(this.alreadyActive(A))return;if(I<0||I>this.nextPersistentUnit_)throw new Error(`Texture index ${I} must be in [0, ${this.nextPersistentUnit_}]; units above that are reserved`);const g=this.textures_.get(A);g&&!A.needsUpdate?(this.gl_.activeTexture(this.gl_.TEXTURE0+I),this.gl_.bindTexture(this.getTextureType(A),g)):this.uploadTexture(A,I),this.currentTexture_=A}readTexel(A,I,g,Q){const C=this.gl_,E=this.textures_.get(A);if(!E)throw new Error("readTexel called on a texture that is not resident");this.readFramebuffer_??=C.createFramebuffer(),C.bindFramebuffer(C.READ_FRAMEBUFFER,this.readFramebuffer_),C.framebufferTextureLayer(C.READ_FRAMEBUFFER,C.COLOR_ATTACHMENT0,E,0,Q);const{format:i,type:D,out:a}=this.readbackParams(A.dataType);return C.readPixels(I,g,1,1,i,D,a),C.bindFramebuffer(C.READ_FRAMEBUFFER,null),a[0]}readbackParams(A){const I=this.gl_;switch(A){case"byte":case"short":case"int":return{format:I.RGBA_INTEGER,type:I.INT,out:new Int32Array(4)};case"unsigned_byte":case"unsigned_short":case"unsigned_int":return{format:I.RGBA_INTEGER,type:I.UNSIGNED_INT,out:new Uint32Array(4)};case"float":return{format:I.RGBA,type:I.FLOAT,out:new Float32Array(4)}}}uploadTexture(A,I=0){if(this.textures_.has(A)&&!A.needsUpdate)return;if(A.data===null)throw new Error("Cannot upload a texture that has no CPU data");const g=this.getTextureType(A),Q=this.getDataFormatInfo(A.dataFormat,A.dataType);this.gl_.activeTexture(this.gl_.TEXTURE0+I),this.textures_.has(A)||this.generateTexture(A,Q,g);const C=this.textures_.get(A);if(!C)throw new Error("Failed to retrieve texture ID");this.gl_.bindTexture(g,C),this.configureTextureParameters(A,g),this.uploadTextureData(A,Q,g),this.currentTexture_=null,A.needsUpdate=!1}dispose(A){const I=this.textures_.get(A);if(I){this.gl_.deleteTexture(I),this.textures_.delete(A),A.readTexel=void 0,this.currentTexture_===A&&(this.currentTexture_=null);const g=lB(A);this.gpuTextureBytes_=Math.max(0,this.gpuTextureBytes_-g),this.textureCount_=Math.max(0,this.textureCount_-1)}}disposeAll(){for(const A of Array.from(this.textures_.keys()))this.dispose(A);this.gpuTextureBytes_=0,this.textureCount_=0}alreadyActive(A){return this.currentTexture_===A&&!A.needsUpdate}generateTexture(A,I,g){const Q=this.gl_.createTexture();if(!Q)throw new Error("Failed to create texture");if(this.gl_.bindTexture(g,Q),this.isTexture2D(A))this.gl_.texStorage2D(g,A.mipmapLevels,I.internalFormat,A.width,A.height);else if(this.isTextureStorage3D(A))this.gl_.texStorage3D(g,A.mipmapLevels,I.internalFormat,A.width,A.height,A.depth);else throw new Error(`Unknown texture type ${A.type}`);this.gpuTextureBytes_+=lB(A),this.textureCount_+=1,this.textures_.set(A,Q),this.gl_.bindTexture(g,null),A.readTexel=(C,E,i)=>Promise.resolve(this.readTexel(A,C,E,i))}configureTextureParameters(A,I){const g=this.gl_,Q=this.getFilter(A.minFilter,A),C=this.getFilter(A.maxFilter,A);g.pixelStorei(g.UNPACK_ALIGNMENT,A.unpackAlignment),g.texParameteri(I,g.TEXTURE_MIN_FILTER,Q),g.texParameteri(I,g.TEXTURE_MAG_FILTER,C),g.texParameteri(I,g.TEXTURE_WRAP_S,this.getWrapMode(A.wrapS)),g.texParameteri(I,g.TEXTURE_WRAP_T,this.getWrapMode(A.wrapT)),g.texParameteri(I,g.TEXTURE_WRAP_R,this.getWrapMode(A.wrapR))}uploadTextureData(A,I,g){const C={x:0,y:0,z:0};if(this.isTexture2D(A))this.gl_.texSubImage2D(g,0,C.x,C.y,A.width,A.height,I.format,I.type,A.data);else if(this.isTextureStorage3D(A))this.gl_.texSubImage3D(g,0,C.x,C.y,C.z,A.width,A.height,A.depth,I.format,I.type,A.data);else throw new Error("Attempting to upload data for an unsupported texture type")}getFilter(A,I){const{dataFormat:g,dataType:Q}=I;if(g==="scalar"&&Q!=="float"&&A!=="nearest")return O.warn("WebGLTexture","Integer values are not filterable. Using gl.NEAREST instead."),this.gl_.NEAREST;switch(A){case"nearest":return this.gl_.NEAREST;case"linear":return this.gl_.LINEAR;default:throw new Error(`Unsupported texture filter: ${A}`)}}getTextureType(A){if(this.isTexture2D(A))return this.gl_.TEXTURE_2D;if(this.isTexture2DArray(A))return this.gl_.TEXTURE_2D_ARRAY;if(this.isTexture3D(A))return this.gl_.TEXTURE_3D;throw new Error(`Unknown texture type ${A.type}`)}getWrapMode(A){switch(A){case"repeat":return this.gl_.REPEAT;case"clamp_to_edge":return this.gl_.CLAMP_TO_EDGE;default:throw new Error(`Unsupported wrap mode: ${A}`)}}getDataFormatInfo(A,I){if(A==="rgba"&&I==="unsigned_byte")return{internalFormat:this.gl_.RGBA8,format:this.gl_.RGBA,type:this.gl_.UNSIGNED_BYTE};if(A==="rgba"&&I==="unsigned_int")return{internalFormat:this.gl_.RGBA32UI,format:this.gl_.RGBA_INTEGER,type:this.gl_.UNSIGNED_INT};if(A==="rgb"&&I==="unsigned_byte")return{internalFormat:this.gl_.RGB8,format:this.gl_.RGB,type:this.gl_.UNSIGNED_BYTE};if(A==="scalar")switch(I){case"byte":return{internalFormat:this.gl_.R8I,format:this.gl_.RED_INTEGER,type:this.gl_.BYTE};case"short":return{internalFormat:this.gl_.R16I,format:this.gl_.RED_INTEGER,type:this.gl_.SHORT};case"int":return{internalFormat:this.gl_.R32I,format:this.gl_.RED_INTEGER,type:this.gl_.INT};case"unsigned_byte":return{internalFormat:this.gl_.R8UI,format:this.gl_.RED_INTEGER,type:this.gl_.UNSIGNED_BYTE};case"unsigned_short":return{internalFormat:this.gl_.R16UI,format:this.gl_.RED_INTEGER,type:this.gl_.UNSIGNED_SHORT};case"unsigned_int":return{internalFormat:this.gl_.R32UI,format:this.gl_.RED_INTEGER,type:this.gl_.UNSIGNED_INT};case"float":return{internalFormat:this.gl_.R32F,format:this.gl_.RED,type:this.gl_.FLOAT};default:throw new Error(`Unsupported scalar type: ${I}`)}throw new Error(`Unsupported format/type: ${A}/${I}`)}isTextureStorage3D(A){return this.isTexture2DArray(A)||this.isTexture3D(A)}isTexture2D(A){return A.type==="Texture2D"}isTexture2DArray(A){return A.type==="Texture2DArray"}isTexture3D(A){return A.type==="Texture3D"}}class mA{min;max;constructor(A,I){this.min=A?OQ(A):LA(1/0,1/0),this.max=I?OQ(I):LA(-1/0,-1/0)}clone(){return new mA(this.min,this.max)}isEmpty(){return this.max[0]<=this.min[0]||this.max[1]<=this.min[1]}static intersects(A,I){return!(A.max[0]<=I.min[0]||A.min[0]>=I.max[0]||A.max[1]<=I.min[1]||A.min[1]>=I.max[1])}static equals(A,I){return XQ(A.min,I.min)&&XQ(A.max,I.max)}floor(){return new mA(LA(Math.floor(this.min[0]),Math.floor(this.min[1])),LA(Math.floor(this.max[0]),Math.floor(this.max[1])))}toRect(){const A=this.min[0],I=this.min[1],g=this.max[0]-this.min[0],Q=this.max[1]-this.min[1];return{x:A,y:I,width:g,height:Q}}}class ci{gl_;enabledCapabilities_=new Map;depthMaskEnabled_=null;colorMaskEnabled_=null;depthFunc_=null;blendSrcFactor_=null;blendDstFactor_=null;currentBlendingMode_=null;currentViewport_=null;currentScissor_=null;currentCullingMode_=null;stencilFunc_=null;stencilRef_=null;stencilFuncMask_=null;polygonOffsetSet_=!1;constructor(A){this.gl_=A,this.gl_.frontFace(this.gl_.CW),this.gl_.stencilMask(255),this.gl_.stencilOp(this.gl_.KEEP,this.gl_.KEEP,this.gl_.REPLACE)}enable(A){this.enabledCapabilities_.get(A)||(this.gl_.enable(A),this.enabledCapabilities_.set(A,!0))}disable(A){this.enabledCapabilities_.get(A)&&(this.gl_.disable(A),this.enabledCapabilities_.set(A,!1))}setBlendFunc(A,I){(this.blendSrcFactor_!==A||this.blendDstFactor_!==I)&&(this.gl_.blendFunc(A,I),this.blendSrcFactor_=A,this.blendDstFactor_=I)}setDepthTesting(A){A?this.enable(this.gl_.DEPTH_TEST):this.disable(this.gl_.DEPTH_TEST)}setBlending(A){A?this.enable(this.gl_.BLEND):this.disable(this.gl_.BLEND)}setDepthMask(A){this.depthMaskEnabled_!==A&&(this.gl_.depthMask(A),this.depthMaskEnabled_=A)}get stencilTestEnabled(){return this.enabledCapabilities_.get(this.gl_.STENCIL_TEST)??!1}get blendingMode(){return this.currentBlendingMode_}setColorMask(A){this.colorMaskEnabled_!==A&&(this.gl_.colorMask(A,A,A,A),this.colorMaskEnabled_=A)}setPolygonOffset(A){if(!A){this.disable(this.gl_.POLYGON_OFFSET_FILL);return}this.enable(this.gl_.POLYGON_OFFSET_FILL),this.polygonOffsetSet_||(this.gl_.polygonOffset(1,1),this.polygonOffsetSet_=!0)}setDepthFunc(A){this.depthFunc_!==A&&(this.gl_.depthFunc(A),this.depthFunc_=A)}setBlendingMode(A){if(this.currentBlendingMode_!==A){if(A==="none")this.setBlending(!1);else switch(this.setBlending(!0),A){case"additive":this.setBlendFunc(this.gl_.SRC_ALPHA,this.gl_.ONE);break;case"multiply":this.setBlendFunc(this.gl_.DST_COLOR,this.gl_.ZERO);break;case"subtractive":this.setBlendFunc(this.gl_.ZERO,this.gl_.ONE_MINUS_SRC_COLOR);break;case"premultipliedOver":this.setBlendFunc(this.gl_.ONE,this.gl_.ONE_MINUS_SRC_ALPHA);break;case"normal":default:this.setBlendFunc(this.gl_.SRC_ALPHA,this.gl_.ONE_MINUS_SRC_ALPHA);break}this.currentBlendingMode_=A}}setViewport(A){const I=A.floor();if(this.currentViewport_&&mA.equals(I,this.currentViewport_))return;const{x:g,y:Q,width:C,height:E}=I.toRect();this.gl_.viewport(g,Q,C,E),this.currentViewport_=I}setScissorTest(A){A?this.enable(this.gl_.SCISSOR_TEST):(this.disable(this.gl_.SCISSOR_TEST),this.currentScissor_=null)}setScissor(A){const I=A.floor();if(this.currentScissor_&&mA.equals(I,this.currentScissor_))return;const{x:g,y:Q,width:C,height:E}=I.toRect();this.gl_.scissor(g,Q,C,E),this.currentScissor_=I}setCullFace(A){A?this.enable(this.gl_.CULL_FACE):this.disable(this.gl_.CULL_FACE)}setCullFaceMode(A){if(this.currentCullingMode_!==A){if(A==="none")this.setCullFace(!1);else switch(this.setCullFace(!0),A){case"front":this.gl_.cullFace(this.gl_.FRONT);break;case"back":this.gl_.cullFace(this.gl_.BACK);break;case"both":this.gl_.cullFace(this.gl_.FRONT_AND_BACK);break}this.currentCullingMode_=A}}setStencilTest(A){A?this.enable(this.gl_.STENCIL_TEST):this.disable(this.gl_.STENCIL_TEST)}setStencilFunc(A,I,g){(this.stencilFunc_!==A||this.stencilRef_!==I||this.stencilFuncMask_!==g)&&(this.gl_.stencilFunc(A,I,g),this.stencilFunc_=A,this.stencilRef_=I,this.stencilFuncMask_=g)}}class Li{textureUnit;gl_;framebuffer_=null;texture_=null;width_=0;height_=0;constructor(A,I){this.gl_=A,this.textureUnit=I}bind(A,I){this.hasValidTarget(A,I)||this.createRenderTarget(A,I),this.gl_.bindFramebuffer(this.gl_.FRAMEBUFFER,this.framebuffer_)}unbind(){this.gl_.bindFramebuffer(this.gl_.FRAMEBUFFER,null)}dispose(){this.texture_&&this.gl_.deleteTexture(this.texture_),this.framebuffer_&&this.gl_.deleteFramebuffer(this.framebuffer_),this.texture_=null,this.framebuffer_=null,this.width_=0,this.height_=0}hasValidTarget(A,I){return this.texture_!==null&&this.width_===A&&this.height_===I}createRenderTarget(A,I){const g=this.gl_;if(this.texture_&&g.deleteTexture(this.texture_),this.framebuffer_??=g.createFramebuffer(),!this.framebuffer_)throw new Error("Failed to create scene depth framebuffer");const Q=this.createDepthTexture(A,I);g.bindFramebuffer(g.FRAMEBUFFER,this.framebuffer_),g.framebufferTexture2D(g.FRAMEBUFFER,g.DEPTH_ATTACHMENT,g.TEXTURE_2D,Q,0),g.drawBuffers([g.NONE]),g.readBuffer(g.NONE),g.bindFramebuffer(g.FRAMEBUFFER,null),this.texture_=Q,this.width_=A,this.height_=I}createDepthTexture(A,I){const g=this.gl_,Q=g.createTexture();if(!Q)throw new Error("Failed to create scene depth texture");return g.activeTexture(g.TEXTURE0+this.textureUnit),g.bindTexture(g.TEXTURE_2D,Q),g.texImage2D(g.TEXTURE_2D,0,g.DEPTH_COMPONENT24,A,I,0,g.DEPTH_COMPONENT,g.UNSIGNED_INT,null),g.texParameteri(g.TEXTURE_2D,g.TEXTURE_MIN_FILTER,g.NEAREST),g.texParameteri(g.TEXTURE_2D,g.TEXTURE_MAG_FILTER,g.NEAREST),g.texParameteri(g.TEXTURE_2D,g.TEXTURE_WRAP_S,g.CLAMP_TO_EDGE),g.texParameteri(g.TEXTURE_2D,g.TEXTURE_WRAP_T,g.CLAMP_TO_EDGE),Q}}const Ji=uQ(WA(),[1,-1,1]);class ri extends wg{gl_;bindings_;depthTarget_;programs_;state_;textures_;renderedObjectsPerFrame_=0;stencilRef_=0;currentViewportSize_=[0,0];currentViewportHasSceneDepth_=!1;constructor(A){super(A);const I=this.canvas.getContext("webgl2",{depth:!0,antialias:!1,stencil:!0});if(!I)throw new Error("Failed to initialize WebGL2 context");this.gl_=I,O.info("WebGLRenderer",`WebGL version ${I.getParameter(I.VERSION)}`),I.getExtension("EXT_color_buffer_float"),this.programs_=new ZE(I),this.bindings_=new Si(I),this.textures_=new ki(I),this.state_=new ci(I),this.depthTarget_=new Li(I,this.textures_.reservePersistentUnit()),this.resize(this.canvas.width,this.canvas.height)}get gpuTextureBytes(){return this.textures_.gpuTextureBytes}get gpuTextureCount(){return this.textures_.textureCount}render(A){this.renderedObjects_=0,this.renderedObjectsPerFrame_=0,this.stencilRef_=0;for(const G of A.layers)G.update(A);if(getComputedStyle(A.element).visibility==="hidden")return;const I=A.getBoxRelativeTo(this.canvas),g=new mA(LA(0,0),LA(this.width,this.height)),Q=mA.equals(I.floor(),g.floor()),C=mA.intersects(I,g);if(Q)this.state_.setScissorTest(!1);else if(C)this.state_.setScissorTest(!0),this.state_.setScissor(I);else{O.warn("WebGLRenderer",`Viewport ${A.id} is entirely outside canvas bounds, skipping render`);return}this.state_.setViewport(I),this.resetState(),this.clear();const E=I.toRect();this.currentViewportSize_=[E.width,E.height];const i=A.camera.frustum,D=[],a=[];for(const G of A.layers)G.state==="ready"&&(G.occludes?D:a).push(G);this.currentViewportHasSceneDepth_=D.length>0&&a.some(G=>G.requiresSceneDepth),this.primeDepthBuffer(D,A.camera,i),this.currentViewportHasSceneDepth_&&this.renderDepthTexture(D,A.camera,i),this.state_.setDepthMask(!1);for(const G of[...D,...a])this.renderLayer(G,A.camera,i);this.resetState(),this.renderedObjects_=this.renderedObjectsPerFrame_}primeDepthBuffer(A,I,g){this.state_.setColorMask(!1),this.state_.setDepthFunc(this.gl_.LESS),this.state_.setPolygonOffset(!0),this.drawDepthOnly(A,I,g),this.resetState()}renderDepthTexture(A,I,g){this.depthTarget_.bind(this.width,this.height),this.state_.setDepthMask(!0),this.state_.setDepthFunc(this.gl_.LESS),this.gl_.clear(this.gl_.DEPTH_BUFFER_BIT),this.drawDepthOnly(A,I,g),this.depthTarget_.unbind(),this.resetState()}drawDepthOnly(A,I,g){for(const Q of A)for(const C of Q.coverageGroups.values())for(const E of C){if(!E.depthProgramName||!E.depthTest||!g.intersectsWithBox3(E.boundingBox))continue;this.state_.setCullFaceMode(E.cullFaceMode),this.bindings_.bindGeometry(E.geometry),E.textures.forEach((D,a)=>{this.textures_.bindTexture(D,a)});const i=this.programs_.use(E.depthProgramName);this.drawGeometry(E.geometry,E,Q,i,I)}}setCoverageStencil(A){this.state_.setStencilTest(A!==null),A!==null&&(this.stencilRef_+=1,this.stencilRef_>255&&O.warn("WebGLRenderer","Exceeded 255 stencil coverage groups in one frame; dedup may be incorrect"),this.state_.setStencilFunc(this.gl_.NOTEQUAL,this.stencilRef_,255))}renderLayer(A,I,g){this.state_.setBlendingMode(A.blendMode);for(const[Q,C]of A.coverageGroups){this.setCoverageStencil(Q);for(const E of C)g.intersectsWithBox3(E.boundingBox)&&(this.renderObject(A,E,I),this.renderedObjectsPerFrame_+=1)}}renderObject(A,I,g){if(I.popStaleTextures().forEach(C=>{this.textures_.dispose(C)}),!I.programName)return;this.state_.setCullFaceMode(I.cullFaceMode),this.state_.setDepthTesting(I.depthTest),this.bindings_.bindGeometry(I.geometry),I.textures.forEach((C,E)=>{this.textures_.bindTexture(C,E)});const Q=this.programs_.use(I.programName);if(this.drawGeometry(I.geometry,I,A,Q,g),I.wireframeEnabled){const C=this.state_.stencilTestEnabled,E=this.state_.blendingMode;this.state_.setStencilTest(!1),this.state_.setBlendingMode("none"),this.bindings_.bindGeometry(I.wireframeGeometry);const i=this.programs_.use("wireframe");i.setUniform("u_wireframeColor",I.wireframeColor.rgb),this.drawGeometry(I.wireframeGeometry,I,A,i,g),E!==null&&this.state_.setBlendingMode(E),this.state_.setStencilTest(C)}}drawGeometry(A,I,g,Q,C){const E=Zg(WA(),C.viewMatrix,I.transform.matrix),i=Zg(WA(),Ji,C.projectionMatrix),D=this.currentViewportSize_,a=I.getUniforms(),R={...g.getUniforms(),...a};for(const e of Q.uniformNames)switch(e){case"u_modelView":Q.setUniform(e,E);break;case"u_model":Q.setUniform(e,I.transform.matrix);break;case"u_projection":Q.setUniform(e,i);break;case"u_resolution":Q.setUniform(e,D);break;case"u_hasSceneDepth":Q.setUniform(e,Number(g.requiresSceneDepth&&this.currentViewportHasSceneDepth_));break;case"u_sceneDepth":Q.setUniform(e,this.depthTarget_.textureUnit);break;case"u_mvpInverse":{const K=Zg(WA(),i,E),l=Sg(WA(),K);Q.setUniform(e,l);break}case"u_opacity":Q.setUniform(e,g.opacity*(a.Opacity??1));break;case"u_cameraPositionModel":{const K=Sg(WA(),E),l=Vg(0,0,0,1),V=Rg(xI(),l,K);Q.setUniform(e,wA(V[0],V[1],V[2]));break}default:e in R&&Q.setUniform(e,R[e])}const t=this.glGetPrimitive(A.primitive),J=A.indexData,{instanceCount:n}=A;n!==null?J.length?this.gl_.drawElementsInstanced(t,J.length,this.gl_.UNSIGNED_INT,0,n):this.gl_.drawArraysInstanced(t,0,A.vertexCount,n):J.length?this.gl_.drawElements(t,J.length,this.gl_.UNSIGNED_INT,0):this.gl_.drawArrays(t,0,A.vertexCount)}uploadTexture(A){this.textures_.uploadTexture(A)}disposeTexture(A){this.textures_.dispose(A)}glGetPrimitive(A){switch(A){case"points":return this.gl_.POINTS;case"triangles":return this.gl_.TRIANGLES;case"lines":return this.gl_.LINES;default:{const I=A;throw new Error(`Unknown Primitive type: ${I}`)}}}resize(A,I){const g=new mA(LA(0,0),LA(A,I));this.state_.setViewport(g)}clear(){this.gl_.clearColor(0,0,0,0),this.gl_.clearStencil(0),this.gl_.clear(this.gl_.COLOR_BUFFER_BIT|this.gl_.DEPTH_BUFFER_BIT|this.gl_.STENCIL_BUFFER_BIT)}resetState(){this.state_.setColorMask(!0),this.state_.setDepthMask(!0),this.state_.setDepthTesting(!0),this.state_.setDepthFunc(this.gl_.LEQUAL),this.state_.setPolygonOffset(!1),this.state_.setStencilTest(!1),this.state_.setBlendingMode("none")}}function Ng(B,A){const I=B.priority??Number.MAX_SAFE_INTEGER,g=A.priority??Number.MAX_SAFE_INTEGER;return I===g?(B.orderKey??Number.MAX_SAFE_INTEGER)-(A.orderKey??Number.MAX_SAFE_INTEGER):I-g}class ni{maxConcurrent_;pending_=[];running_=new Map;constructor(A){this.maxConcurrent_=Math.max(1,A)}enqueue(A,I){this.running_.has(A)||this.pending_.some(g=>g.chunk===A)||this.pending_.push({chunk:A,fn:I})}flush(){this.pump()}cancel(A){const I=this.pending_.findIndex(Q=>Q.chunk===A);if(I>=0){this.pending_.splice(I,1),O.debug("ChunkQueue","Cancelled pending request");return}const g=this.running_.get(A);g&&(g.controller.abort(),O.debug("ChunkQueue","Cancelled fetch request"))}get pendingCount(){return this.pending_.length}get runningCount(){return this.running_.size}pump(){if(!(this.running_.size>=this.maxConcurrent_||this.pending_.length===0))for(this.pending_.sort((A,I)=>Ng(A.chunk,I.chunk));this.running_.size<this.maxConcurrent_&&this.pending_.length>0;)this.start(this.pending_.shift())}start(A){const{chunk:I,fn:g}=A;I.state="loading";const Q=new AbortController,C=Promise.resolve().then(()=>g(Q.signal)).then(()=>{I.state==="loading"&&(I.state="loaded")},E=>{I.state==="loading"&&(I.state="unloaded"),E.name!=="AbortError"&&O.error("ChunkQueue",String(E))}).finally(()=>{this.running_.delete(I),this.pump()});this.running_.set(I,{controller:Q,promise:C})}}let vg=0,jg=0;function Yi(B,A){B.data&&(vg-=B.data.byteLength,jg-=1),B.data=A,vg+=A.byteLength,jg+=1}function jQ(B){B.data&&(vg-=B.data.byteLength,jg-=1),B.data=void 0,B.texture?.releaseCpuData()}function Ki(){return{cpuChunkBytes:vg,cpuChunkCount:jg}}function zQ(B,A,I=1e-6){return Math.abs(B-A)<=I}const RA={x:0,y:1,z:2};function bI(B){switch(B){case"XY":return{u:"x",v:"y",w:"z"};case"XZ":return{u:"x",v:"z",w:"y"};case"YZ":return{u:"y",v:"z",w:"x"}}}function PI(B){const A=AA(),I=AA();A[RA[B.u]]=1,I[RA[B.v]]=1;const g=Pg(AA(),A,I),Q=VE(A[0],A[1],A[2],I[0],I[1],I[2],g[0],g[1],g[2]),C=dB(Og(),Q);return Xg(C,C)}const _Q=[Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array];function ei(B){if(_Q.some(I=>B instanceof I))return!0;const A=_Q.map(I=>I.name);return O.debug("Chunk",`Unsupported chunk data type: ${B}. Supported data types: ${A}`),!1}function Mi(B,A){return Math.round((A-B.translation)/B.scale)}function $Q(B,A){const I=AA(),g=AA();for(const C of["x","y","z"]){const E=C===A.w?.5*B.scale[C]:0,i=RA[C];I[i]=1/(B.scale[C]*B.shape[C]),g[i]=E-B.offset[C]}const Q=uQ(WA(),I);return OE(Q,Q,g)}function QI(B,A,I){return Math.max(A,Math.min(I,B))}const zg=Symbol("INTERNAL_POLICY_KEY"),AC=1e-6;class Hi{store_;policy_;policyChanged_=!1;targetLOD_=0;axes_;scale0_;mode_=null;lastViewBounds2D_=null;lastViewProjection_=null;lastSliceCoordW_;lastTCoord_;lastCCoords_;sourceMaxSquareDistance2D_;chunkViewStates_=new Map;isDisposed_=!1;constructor(A,I,g={u:"x",v:"y",w:"z"}){this.store_=A,this.policy_=I,this.axes_=g,O.info("ChunkStoreView","Using image source policy:",this.policy_.profile);const Q=this.store_.dimensions,C=Q[this.axes_.u],E=Q[this.axes_.v];if(C===void 0||E===void 0)throw new Error(`Source is missing dimensions for slice plane axes "${this.axes_.u}" and "${this.axes_.v}"`);const i=C.lods[0],D=E.lods[0];this.scale0_=i.scale,this.sourceMaxSquareDistance2D_=Gi(LA(i.size*i.scale,D.size*D.scale))}get chunkViewStates(){return this.chunkViewStates_}get isDisposed(){return this.isDisposed_}get lodCount(){return this.store_.lodCount}get channelCount(){return this.store_.channelCount}getWholePlaneRect(){const A=this.store_.dimensions,I=A[this.axes_.u].lods[0],g=A[this.axes_.v].lods[0];return new mA(LA(I.translation,g.translation),LA(I.translation+I.size*I.scale,g.translation+g.size*g.scale))}getChunksToRender(){const A=this.mode_==="image"?this.residentChunksForSlice():this.residentChunksMarkedVisible(),I=this.targetLOD_;return A.sort((g,Q)=>Math.abs(g.lod-I)-Math.abs(Q.lod-I)||Q.lod-g.lod)}residentChunksMarkedVisible(){const A=[];for(const[I,g]of this.chunkViewStates_)g.visible&&I.state==="loaded"&&I.texture&&A.push(I);return A}residentChunksForSlice(){const A=this.timeIndex(this.lastTCoord_),I=new Set(this.channelsOfInterest(this.lastCCoords_)),{min:g,max:Q}=this.lodRange(),C=new IC(this.axes_,this.lastSliceCoordW_,this.lastViewBounds2D_,this.store_.dimensions[this.axes_.w]),E=[];for(const i of this.store_.residentChunks)i.lod<g||i.lod>Q||i.chunkIndex.t===A&&I.has(i.chunkIndex.c)&&C.contains(i)&&E.push(i);return E}updateChunksForImage(A,I){const g=I.worldViewRect,C=Math.abs(g.max[0]-g.min[0])/I.bufferWidthPx,E=Math.log2(1/C),i=this.setLOD(E),D=this.getSliceAxisBounds(A);if(!(this.policyChanged_||i||this.viewBounds2DChanged(g)||this.lastSliceCoordW_!==A[this.axes_.w]||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const G=this.timeIndex(A.t);if(!this.store_.hasChunksAtTime(G)){O.warn("ChunkStoreView","updateChunkViewStates called with no chunks initialized"),this.mode_=null,this.chunkViewStates_.forEach(tg);return}const R=VQ();Fi(R,g.min,g.max,.5);const t=this.makeViewBounds3D(g,D);this.chunkViewStates_.forEach(tg);const J=this.channelsOfInterest(A.c),n=this.lodRange().max,e=this.getPaddedBounds(t),K=new IC(this.axes_,A[this.axes_.w],g,this.store_.dimensions[this.axes_.w]),l=this.currentLOD,V=l===n?[l]:[l,n];for(const x of V){const W=x===l,p=x===n;this.iterateChunksInBox(G,x,J,e,T=>{const $=K.contains(T),CA=W&&!$,BA=this.computePriority(p,W,$,CA,!0);BA!==null&&this.chunkViewStates_.set(T,{visible:$,prefetch:CA,priority:BA,orderKey:this.squareDistance2D(T,R)})})}this.markTimeChunksForPrefetchImage(G,A,t,R),this.policyChanged_=!1,this.mode_="image",this.lastViewBounds2D_=g.clone(),this.lastSliceCoordW_=A[this.axes_.w],this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0}updateChunksForVolume(A,I){if(!(this.policyChanged_||this.hasViewProjectionChanged(I)||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const Q=this.timeIndex(A.t);if(!this.store_.hasChunksAtTime(Q)){O.warn("ChunkStoreView","updateChunksForVolume called with no chunks initialized"),this.mode_=null,this.chunkViewStates_.forEach(tg);return}this.targetLOD_=this.policy_.lod.min,this.chunkViewStates_.forEach(tg);const C=this.channelsOfInterest(A.c),E=this.lodRange().max,i=this.currentLOD,D=a=>{const G=a.lod===E,R=a.lod===i,t=this.computePriority(G,R,!0,!1,!0);t!==null&&this.chunkViewStates_.set(a,{visible:!0,prefetch:!1,priority:t,orderKey:0})};this.iterateAllChunksAtLod(Q,i,C,D),i!==E&&this.iterateAllChunksAtLod(Q,E,C,D),this.markTimeChunksForPrefetchVolume(Q,A),this.policyChanged_=!1,this.mode_="volume",this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0,this.lastViewProjection_=I}allVisibleFallbackLODLoaded(){const A=this.lodRange().max;let I=!1;for(const[g,Q]of this.chunkViewStates_)if(!(!Q.visible||g.lod!==A)&&(I=!0,g.texture===void 0))return!1;return I}get currentLOD(){const{min:A,max:I}=this.lodRange();return QI(Math.round(this.targetLOD_),A,I)}maybeForgetChunk(A){const I=this.chunkViewStates_.get(A);I&&(I.visible||I.prefetch||I.priority!==null)||this.chunkViewStates_.delete(A)}dispose(){this.isDisposed_=!0,this.mode_=null,this.chunkViewStates_.forEach(tg)}setImageSourcePolicy(A,I){if(I!==zg)throw new Error("Unauthorized policy mutation");this.policy_!==A&&(this.policy_=A,this.policyChanged_=!0,O.info("ChunkStoreView","Using image source policy:",this.policy_.profile))}setLOD(A){const I=this.policy_.lod.bias,g=-Math.log2(this.scale0_)-A,Q=this.currentLOD;return this.targetLOD_=I-.5+g,this.currentLOD!==Q}markTimeChunksForPrefetchImage(A,I,g,Q){const C=this.store_.dimensions.t?.lods[0].size??1,E=Math.min(this.policy_.prefetch.t,C-1),i=this.policy_.priorityMap.prefetchTime,D=this.channelsOfInterest(I.c);for(let a=1;a<=E;++a){const G=(A+a)%C;this.iterateChunksInBox(G,this.currentLOD,D,g,R=>{const t=this.squareDistance2D(R,Q),J=QI(t/this.sourceMaxSquareDistance2D_,0,1-Number.EPSILON),n=a+J;this.chunkViewStates_.set(R,{visible:!1,prefetch:!0,priority:i,orderKey:n})})}}markTimeChunksForPrefetchVolume(A,I){const g=this.store_.dimensions.t?.lods[0].size??1,Q=Math.min(this.policy_.prefetch.t,g-1),C=this.policy_.priorityMap.prefetchTime,E=this.channelsOfInterest(I.c);for(let i=1;i<=Q;++i){const D=(A+i)%g;this.iterateAllChunksAtLod(D,this.currentLOD,E,a=>{const G=i;this.chunkViewStates_.set(a,{visible:!1,prefetch:!0,priority:C,orderKey:G})})}}computePriority(A,I,g,Q,C){if(!C)return null;const E=this.policy_.priorityMap;return A&&g?E.fallbackVisible:I&&g?E.visibleCurrent:A?E.fallbackBackground:I&&Q?E.prefetchSpace:null}channelsOfInterest(A){return A??Array.from({length:this.store_.channelCount},(I,g)=>g)}chunkIndexRange(A,I){const g=this.store_.dimensions,Q=g.x.lods[I],C=g.y.lods[I],E=g.z?.lods[I],i=Math.ceil(Q.size/Q.chunkSize),D=Math.ceil(C.size/C.chunkSize),a=E?Math.ceil(E.size/E.chunkSize):1,G=Q.chunkSize*Q.scale,R=C.chunkSize*C.scale,t=E?E.chunkSize*E.scale:1,J=Q.translation,n=C.translation,e=E?.translation??0,K=Math.max(0,WB((A.min[0]-J)/G)),l=Math.min(i,mB((A.max[0]-J)/G)),V=Math.max(0,WB((A.min[1]-n)/R)),x=Math.min(D,mB((A.max[1]-n)/R)),W=E?Math.max(0,WB((A.min[2]-e)/t)):0,p=E?Math.min(a,mB((A.max[2]-e)/t)):1;return K>=l||V>=x||W>=p?null:{xMin:K,xMax:l,yMin:V,yMax:x,zMin:W,zMax:p}}iterateChunksInBox(A,I,g,Q,C){const E=this.chunkIndexRange(Q,I);if(E)for(const i of g){const D=this.store_.getChunkGrid(I,A,i);if(D)for(let a=E.zMin;a<E.zMax;++a){const G=D[a];for(let R=E.yMin;R<E.yMax;++R){const t=G[R];for(let J=E.xMin;J<E.xMax;++J){const n=t[J];C(n)}}}}}iterateAllChunksAtLod(A,I,g,Q){for(const C of g){const E=this.store_.getChunkGrid(I,A,C);if(E)for(const i of E)for(const D of i)for(const a of D)Q(a)}}lodRange(){const A=this.store_.getLowestResLOD(),I=Math.max(0,Math.min(A,this.policy_.lod.min)),g=Math.max(I,Math.min(A,this.policy_.lod.max));return{min:I,max:g}}timeIndex(A){const I=this.store_.dimensions.t;return A===void 0||I===void 0?0:Mi(I.lods[0],A)}getSliceAxisBounds(A){const I=this.store_.dimensions[this.axes_.w];if(I===void 0)return[0,1];const g=I.lods[this.currentLOD],Q=A[this.axes_.w];if(Q===void 0)return[g.translation,g.translation+g.size*g.scale];const C=g.size,E=g.scale,i=g.translation,D=Math.floor((Q-i)/E),a=g.chunkSize,G=Math.max(0,Math.min(Math.floor(D/a),Math.ceil(C/a)-1));return[i+G*a*E,i+(G+1)*a*E]}makeViewBounds3D(A,I){const g=AA(),Q=AA();return g[RA[this.axes_.u]]=A.min[0],Q[RA[this.axes_.u]]=A.max[0],g[RA[this.axes_.v]]=A.min[1],Q[RA[this.axes_.v]]=A.max[1],g[RA[this.axes_.w]]=I[0],Q[RA[this.axes_.w]]=I[1],new ZI(g,Q)}viewBounds2DChanged(A){return this.lastViewBounds2D_===null||!vQ(this.lastViewBounds2D_.min,A.min)||!vQ(this.lastViewBounds2D_.max,A.max)}hasViewProjectionChanged(A){return this.lastViewProjection_===null||!Ai(this.lastViewProjection_,A)}cCoordsChanged(A){return!this.lastCCoords_&&!A?!1:!this.lastCCoords_||!A||this.lastCCoords_.length!==A.length?!0:!this.lastCCoords_.every((I,g)=>I===A[g])}getPaddedBounds(A){const{u:I,v:g,w:Q}=this.axes_,C=this.store_.dimensions,E=C[I].lods[this.currentLOD],i=C[g].lods[this.currentLOD],D=C[Q]?.lods[this.currentLOD],a=AA();return a[RA[I]]=E.chunkSize*E.scale*this.policy_.prefetch.x,a[RA[g]]=i.chunkSize*i.scale*this.policy_.prefetch.y,D&&(a[RA[Q]]=D.chunkSize*D.scale*this.policy_.prefetch.z),new ZI(nB(AA(),A.min,a),ug(AA(),A.max,a))}squareDistance2D(A,I){function g(D){return A.offset[D]+.5*A.shape[D]*A.scale[D]}const{u:Q,v:C}=this.axes_,E=g(Q)-I[0],i=g(C)-I[1];return E*E+i*i}}class IC{axes_;viewRect_;chunkRect_=new mA;sliceCoordByLod_;constructor(A,I,g,Q){this.axes_=A,this.viewRect_=g,I!==void 0&&Q!==void 0&&(this.sliceCoordByLod_=Q.lods.map(C=>QI(I,C.translation,C.translation+(C.size-1)*C.scale)))}contains(A){const{u:I,v:g,w:Q}=this.axes_,C=this.sliceCoordByLod_?.[A.lod];return C!==void 0&&(C<A.offset[Q]||C>=TB(A,Q))?!1:(this.chunkRect_.min[0]=A.offset[I],this.chunkRect_.min[1]=A.offset[g],this.chunkRect_.max[0]=TB(A,I),this.chunkRect_.max[1]=TB(A,g),mA.intersects(this.chunkRect_,this.viewRect_))}}function WB(B){return Math.floor(B+AC)}function mB(B){return Math.ceil(B-AC)}function TB(B,A){return B.offset[A]+B.shape[A]*B.scale[A]}function tg(B){B.visible=!1,B.prefetch=!1,B.priority=null,B.orderKey=null}class qi{chunks_;lowestResLOD_;dimensions_;views_=[];hasHadViews_=!1;resident_=new Set;constructor(A){this.dimensions_=A,this.lowestResLOD_=this.dimensions_.numLods-1,this.validateXYScaleRatios();const{size:I}=this.getAndValidateTimeDimension(),{size:g}=this.getAndValidateChannelDimension(),Q=this.dimensions_.numLods;this.chunks_=new Array(Q);for(let C=0;C<Q;++C){const E=this.dimensions_.x.lods[C],i=this.dimensions_.y.lods[C],D=this.dimensions_.z?.lods[C],a=E.chunkSize,G=i.chunkSize,R=D?.chunkSize??1,t=Math.ceil(E.size/a),J=Math.ceil(i.size/G),n=D?Math.ceil(D.size/R):1,e=new Array(I);this.chunks_[C]=e;for(let K=0;K<I;++K){const l=new Array(g);e[K]=l;for(let V=0;V<g;++V){const x=new Array(n);l[V]=x;for(let W=0;W<n;++W){const p=D!==void 0?D.translation+W*R*D.scale:0,T=new Array(J);x[W]=T;for(let $=0;$<J;++$){const CA=i.translation+$*G*i.scale,BA=new Array(t);T[$]=BA;for(let iA=0;iA<t;++iA){const sA=E.translation+iA*a*E.scale;BA[iA]={state:"unloaded",lod:C,visible:!1,prefetch:!1,priority:null,orderKey:null,shape:{x:Math.min(a,E.size-iA*a),y:Math.min(G,i.size-$*G),z:Math.min(R,(D?.size??1)-W*R),c:1},rowAlignmentBytes:1,chunkIndex:{x:iA,y:$,z:W,c:V,t:K},scale:{x:E.scale,y:i.scale,z:D?.scale??1},offset:{x:sA,y:CA,z:p}}}}}}}}}getChunkGrid(A,I,g){return this.chunks_[A]?.[I]?.[g]}hasChunksAtTime(A){return this.chunks_[0]?.[A]!==void 0}get lodCount(){return this.lowestResLOD_+1}get channelCount(){return this.dimensions_.c?.lods[0].size??1}get dimensions(){return this.dimensions_}getLowestResLOD(){return this.lowestResLOD_}addView(A,I){const g=new Hi(this,A,I);return this.views_.push(g),this.hasHadViews_=!0,g}get views(){return this.views_}get residentChunks(){return this.resident_}setChunkTexture(A,I){A.texture=I,this.resident_.add(A)}clearChunkTexture(A){const I=A.texture;return A.texture=void 0,this.resident_.delete(A),I}canDispose(){return this.hasHadViews_&&this.views_.length===0}updateAndCollectChunkChanges(){const A=new Set;for(const I of this.views_)for(const[g,Q]of I.chunkViewStates)A.add(g);for(const I of A)this.aggregateChunkViewStates(I);return this.removeDisposedViews(),A}removeDisposedViews(){for(let A=this.views_.length-1;A>=0;A--)this.views_[A].isDisposed&&this.views_.splice(A,1)}aggregateChunkViewStates(A){let I=!1,g=!1,Q=null,C=null;for(const D of this.views_){const a=D.chunkViewStates.get(A);a&&(a.visible&&(I=!0),a.prefetch&&(g=!0),a.priority!==null&&(Q===null||a.priority<Q)&&(Q=a.priority,C=a.orderKey),!a.visible&&!a.prefetch&&a.priority===null&&D.maybeForgetChunk(A))}if(A.visible=I,A.prefetch=g,A.priority=Q,A.orderKey=C,A.priority!==null&&A.state==="unloaded"){A.state="queued";return}A.priority===null&&A.state==="queued"&&(A.state="unloaded")}validateXYScaleRatios(){const A=this.dimensions_.x,I=this.dimensions_.y;for(let g=1;g<this.dimensions_.numLods;g++){const Q=A.lods[g].scale/A.lods[g-1].scale,C=I.lods[g].scale/I.lods[g-1].scale;if(!zQ(Q,2,.02)||!zQ(C,2,.02))throw new Error(`Invalid downsampling factor between levels ${g-1} → ${g}: expected (2× in X and Y), but got (${Q.toFixed(2)}×, ${C.toFixed(2)}×) from scale [${A.lods[g-1].scale}, ${I.lods[g-1].scale}] → [${A.lods[g].scale}, ${I.lods[g].scale}]`)}}getAndValidateTimeDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.t?.lods[A];if(!I)continue;const g=this.dimensions_.t?.lods[A-1];if(g&&I.size!==g.size)throw new Error(`ChunkStore does not support downsampling in t. Found ${g.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.t?.lods[0].size??1}}getAndValidateChannelDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.c?.lods[A];if(!I)continue;if(I.scale!==1&&O.warn("ChunkStore",`Idetik does not make use of non-unity scale in c. Found ${I.scale} at LOD ${A}`),I.translation!==0)throw new Error(`ChunkStore does not support translation in c. Found ${I.translation} at LOD ${A}`);const g=this.dimensions_.c?.lods[A-1];if(g&&I.size!==g.size)throw new Error(`ChunkStore does not support downsampling in c. Found ${g.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.c?.lods[0].size??1}}}function di(B,A){const I=A.dimensions.t?.lods[0].size??1,g={requested:new Uint32Array(I),resident:new Uint32Array(I)};let Q=0,C=0;const E=A.views;for(let i=0;i<E.length;i++)for(const[D,a]of E[i].chunkViewStates){if(a.priority===null||fi(D,E,i))continue;const G=D.chunkIndex.t;Q+=1,g.requested[G]+=1,D.texture!==void 0&&(C+=1,g.resident[G]+=1)}return{source:B,requested:Q,resident:C,timepoints:g}}function fi(B,A,I){for(let g=0;g<I;g++){const Q=A[g].chunkViewStates.get(B);if(Q!==void 0&&Q.priority!==null)return!0}return!1}function li(B,A){let I=0,g=0;const Q={requested:0,resident:0};for(const C of A){const E=C.currentLOD;for(const[i,D]of C.chunkViewStates){if(D.priority===null)continue;const a=i.texture!==void 0;I+=1,a&&(g+=1),!(!D.visible||i.lod!==E)&&(Q.requested+=1,a&&(Q.resident+=1))}}return{viewportId:B,requested:I,resident:g,current:Q}}class xB extends pB{width_;height_;depth_;constructor(A,I,g,Q){super(),this.dataFormat="scalar",this.dataType=fB(A),this.data_=A,this.width_=I,this.height_=g,this.depth_=Q}get type(){return"Texture3D"}get width(){return this.width_}get height(){return this.height_}get depth(){return this.depth_}static createWithChunk(A){const I=A.data;if(!I)throw new Error("Unable to create texture, chunk data is not initialized.");const g=new xB(I,A.shape.x,A.shape.y,A.shape.z);return g.unpackAlignment=A.rowAlignmentBytes,g}}const pi=8,Wi=4;class mi{stores_=[];queue_;uploadTexture_;disposeTexture_;getGpuResidentBytes_;memoryLimitBytes_;maxGpuUploadsPerUpdate_;constructor(A,I,g=()=>0,Q=1/0,C=pi,E=Wi){this.uploadTexture_=A,this.disposeTexture_=I,this.getGpuResidentBytes_=g,this.memoryLimitBytes_=Q,this.maxGpuUploadsPerUpdate_=Math.max(1,E),this.queue_=new ni(C)}get memoryLimitBytes(){return this.memoryLimitBytes_}set memoryLimitBytes(A){this.memoryLimitBytes_=A}get queueStats(){return{pending:this.queue_.pendingCount,running:this.queue_.runningCount}}get memoryStats(){return Ki()}get sourceChunkStats(){return this.stores_.map(({source:A,store:I})=>di(A,I))}addView(A,I,g){let Q=this.stores_.find(C=>C.source===A)?.store;return Q||(Q=new qi(A.loader.getSourceDimensionMap()),this.stores_.push({source:A,store:Q})),Q.addView(I,g)}update(){const A=[];for(const{source:I,store:g}of this.stores_){const Q=g.updateAndCollectChunkChanges();for(const C of Q)C.priority===null?this.releaseChunk(C):(C.releasedAt=void 0,C.state==="queued"&&A.push({source:I,chunk:C}));this.uploadLoadedChunks(g,Q)}this.enqueueWithinBudget(A),this.queue_.flush();for(let I=this.stores_.length-1;I>=0;I--){const{store:g}=this.stores_[I];if(g.canDispose()){for(const Q of[...g.residentChunks])this.disposeChunkTexture(g,Q),Q.state="unloaded";this.stores_.splice(I,1)}}}releaseChunk(A){if(this.queue_.cancel(A),A.texture!==void 0){A.releasedAt??=performance.now();return}jQ(A),A.state==="loaded"&&(A.state="unloaded")}enqueueWithinBudget(A){if(A.length===0)return;A.sort((Q,C)=>Ng(Q.chunk,C.chunk));let I=this.getGpuResidentBytes_();const g=this.evictionCandidates();for(const{source:Q,chunk:C}of A){const E=this.chunkBytes(Q,C);E>this.memoryLimitBytes_||(I+E>this.memoryLimitBytes_&&(I=this.evictWorseChunks(I,E,C,g)),!(I+E>this.memoryLimitBytes_)&&(I+=E,this.queue_.enqueue(C,i=>Q.loader.loadChunkData(C,i))))}}evictionCandidates(){const A=[];for(const{store:I}of this.stores_){const g=new Set(I.views.flatMap(Q=>Q.getChunksToRender()));for(const Q of I.residentChunks)Q.visible||A.push({store:I,chunk:Q,drawn:g.has(Q)})}return A.sort((I,g)=>{if(I.drawn!==g.drawn)return I.drawn?1:-1;const Q=-Ng(I.chunk,g.chunk);return Q!==0?Q:(I.chunk.releasedAt??0)-(g.chunk.releasedAt??0)})}evictWorseChunks(A,I,g,Q){for(;A+I>this.memoryLimitBytes_&&Q.length>0&&Ng(Q[0].chunk,g)>0&&(!Q[0].drawn||g.visible);){const C=Q.shift();C.chunk.texture!==void 0&&(A-=lB(C.chunk.texture),this.disposeChunkTexture(C.store,C.chunk),C.chunk.state="unloaded",C.chunk.releasedAt=void 0)}return A}chunkBytes(A,I){const g=A.loader.getBytesPerElement();return I.shape.x*I.shape.y*I.shape.z*g}uploadLoadedChunks(A,I){if(!this.uploadTexture_)return;const g=[];for(const C of I)C.state==="loaded"&&C.texture===void 0&&g.push(C);if(g.length===0)return;g.sort(Ng);const Q=Math.min(g.length,this.maxGpuUploadsPerUpdate_);for(let C=0;C<Q;C++){const E=g[C],i=xB.createWithChunk(E);this.uploadTexture_(i),A.setChunkTexture(E,i),jQ(E)}}disposeChunkTexture(A,I){const g=A.clearChunkTexture(I);g!==void 0&&this.disposeTexture_?.(g)}}class Ug{blendMode;occludes;requiresSceneDepth_=!1;coverageGroups_=new Map;state_="initialized";attached_=!1;callbacks_=[];opacity_;constructor({opacity:A=1,blendMode:I="none",occludes:g}={}){this.opacity_=QI(A,0,1),this.blendMode=I,this.occludes=g??I==="none"}get requiresSceneDepth(){return this.requiresSceneDepth_}get opacity(){return this.opacity_}set opacity(A){(A<0||A>1)&&O.warn("Layer",`Opacity out of bounds: ${A} — clamping to [0.0, 1.0]`),this.opacity_=QI(A,0,1)}onEvent(A){}onAttached(A){if(this.attached_)throw new Error(`${this.type} cannot be attached to multiple viewports simultaneously.`);if(this.occludes&&this.requiresSceneDepth_)throw new Error(`${this.type} cannot both occlude and read scene depth.`);this.attach(A),this.attached_=!0}onDetached(A){this.attached_&&(this.detach(A),this.attached_=!1)}attach(A){}detach(A){}get coverageGroups(){return this.coverageGroups_}get state(){return this.state_}addStateChangeCallback(A){this.callbacks_.push(A)}removeStateChangeCallback(A){const I=this.callbacks_.indexOf(A);if(I===-1)throw new Error(`Callback to remove could not be found: ${A}`);this.callbacks_.splice(I,1)}setState(A){const I=this.state_;this.state_=A,this.callbacks_.forEach(g=>g(A,I))}addObject(A,I=null){const g=this.coverageGroups_.get(I);g?g.push(A):this.coverageGroups_.set(I,[A])}clearObjects(){this.coverageGroups_.clear()}getUniforms(){return{}}}const gC=["fallbackVisible","prefetchTime","visibleCurrent","fallbackBackground","prefetchSpace"];function _g(B={}){return $g(ZB({profile:"exploration",prefetch:{x:1,y:1,z:1,t:0},priorityOrder:["fallbackVisible","visibleCurrent","prefetchSpace","prefetchTime","fallbackBackground"]},B))}function Ti(B={}){return $g(ZB({profile:"playback",prefetch:{x:0,y:0,z:0,t:20},priorityOrder:["fallbackVisible","visibleCurrent","prefetchTime","fallbackBackground","prefetchSpace"]},B))}function xi(B={}){return $g(ZB({profile:"no-prefetch",prefetch:{x:0,y:0,z:0,t:0},priorityOrder:["fallbackVisible","visibleCurrent","fallbackBackground","prefetchSpace","prefetchTime"]},B))}function $g(B){Zi(B);const A={x:B.prefetch.x,y:B.prefetch.y,z:B.prefetch.z??0,t:B.prefetch.t??0},I=Object.freeze(gC.reduce((C,E)=>{const i=B.priorityOrder.indexOf(E);return C[E]=i,C},{})),g={min:B.lod?.min??0,max:B.lod?.max??Number.MAX_SAFE_INTEGER,bias:B.lod?.bias??.5},Q={profile:B.profile??"custom",prefetch:A,priorityOrder:Object.freeze([...B.priorityOrder]),priorityMap:I,lod:g};return Object.freeze(Q)}function Zi(B){for(const[g,Q]of Object.entries(B.prefetch))if(Q!==void 0&&Q<0)throw new Error(`prefetch.${g} must be a non-negative number`);const A=B.lod;if(A?.min!==void 0&&A?.max!==void 0&&A.min>A.max)throw new Error("lod.min must be <= lod.max");const I=B.priorityOrder;if(I.length!==gC.length||new Set(I).size!==I.length)throw new Error("priorityOrder must include all categories exactly once")}function ZB(B,A={}){return{profile:A.profile??B.profile,prefetch:{...B.prefetch,...A.prefetch??{}},lod:{...B.lod,...A.lod??{}},priorityOrder:A.priorityOrder??B.priorityOrder}}class GA{static RED=new GA(1,0,0);static GREEN=new GA(0,1,0);static BLUE=new GA(0,0,1);static YELLOW=new GA(1,1,0);static MAGENTA=new GA(1,0,1);static CYAN=new GA(0,1,1);static BLACK=new GA(0,0,0);static WHITE=new GA(1,1,1);static TRANSPARENT=new GA(0,0,0,0);rgba_;constructor(A,I,g,Q){if(A<0||A>1||I<0||I>1||g<0||g>1)throw new Error("RGB values must be in the range [0, 1]");if(Q!==void 0&&(Q<0||Q>1))throw new Error("Alpha value must be in the range [0, 1]");this.rgba_=[A,I,g,Q??1]}get rgb(){return[this.rgba_[0],this.rgba_[1],this.rgba_[2]]}get rgba(){return this.rgba_}get r(){return this.rgba_[0]}get g(){return this.rgba_[1]}get b(){return this.rgba_[2]}get a(){return this.rgba_[3]}get rgbHex(){return`#${this.toHexComponent(this.r)}${this.toHexComponent(this.g)}${this.toHexComponent(this.b)}`}get packed(){return Math.round(this.r*255)<<24|Math.round(this.g*255)<<16|Math.round(this.b*255)<<8|Math.round(this.a*255)}static from(A){if(A instanceof GA)return A;if(Array.isArray(A))return new GA(A[0],A[1],A[2],A[3]);if(typeof A=="string")return GA.fromRgbHex(A);throw new Error("Unsupported color format")}static fromRgbHex(A){const I=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(A);if(!I)throw new Error("Invalid RGB hex, use form '#RRGGBB'");return new GA(parseInt(I[1],16)/255,parseInt(I[2],16)/255,parseInt(I[3],16)/255,1)}toHexComponent(A){const I=Math.round(A*255).toString(16).padStart(2,"0");return I.length===1?"0"+I:I}}const BC=32;function kg(B,{visible:A,color:I,contrastLimits:g,opacity:Q}){return A??=!0,I=I===void 0?GA.WHITE:GA.from(I),Q=Q===void 0?1:QI(Q,0,1),B!==null?g=ui(g,B):g===void 0&&(O.debug("Channel","No texture provided, defaulting channel contrast limits to [0, 1]."),g=[0,1]),{visible:A,color:I,contrastLimits:g,opacity:Q}}function uB(B,A){if(A.length>BC)throw new Error(`Maximum number of channels is ${BC}`);return A.map(I=>kg(B,I))}function QC(B,A){if(B&&B.length!==A)throw new Error(`channelProps length (${B.length}) must match source channel count (${A}).`)}function ui(B,A){if(B===void 0)return Ui(A);if(B[1]<=B[0])throw new Error(`Contrast limits must be strictly increasing: ${B}.`);return B}class bi extends uI{constructor(A){if(super(),A.primitive!="triangles"){O.warn("WireframeGeometry","Only indexed geometries are supported");return}if(A.indexData.length==0){O.warn("WireframeGeometry","Only triangulated geometries are supported");return}this.primitive_="lines",this.vertexData_=A.vertexData,this.attributes_=A.attributes;const I=new Set,g=[],Q=(E,i)=>{const D=Math.min(E,i),a=Math.max(E,i);I.has({i0:D,i1:a})||(I.add({i0:D,i1:a}),g.push(D,a))},C=A.indexData;for(let E=0;E<C.length;E+=3){const i=C[E],D=C[E+1],a=C[E+2];Q(i,D),Q(D,a),Q(a,i)}this.indexData_=new Uint32Array(g)}}const Pi=wA(0,1,0);class bB{dirty_=!0;matrix_=WA();rotation_=Og();translation_=AA();scale_=wA(1,1,1);addRotation(A){ai(this.rotation_,this.rotation_,A),this.dirty_=!0}setRotation(A){yi(this.rotation_,A),this.dirty_=!0}get rotation(){return si(this.rotation_)}addTranslation(A){ug(this.translation_,this.translation_,A),this.dirty_=!0}setTranslation(A){rB(this.translation_,A),this.dirty_=!0}get translation(){return $A(this.translation_)}addScale(A){Ii(this.scale_,this.scale_,A),this.dirty_=!0}setScale(A){rB(this.scale_,A),this.dirty_=!0}targetTo(A){MB(this.translation_,A)&&(A=$A(A),A[2]+=FA);const I=$E(WA(),this.translation_,A,Pi),g=PE(ZQ(),I);dB(this.rotation_,g),Xg(this.rotation_,this.rotation_),this.dirty_=!0}get scale(){return $A(this.scale_)}get matrix(){return this.dirty_&&(this.computeMatrix(),this.dirty_=!1),this.matrix_}get inverse(){return Sg(WA(),this.matrix)}computeMatrix(){XE(this.matrix_,this.rotation_,this.translation_,this.scale_)}}class VI extends xg{wireframeEnabled=!1;wireframeColor=GA.WHITE;depthTest=!0;textures_=[];staleTextures_=[];transform_=new bB;geometry_=new uI;wireframeGeometry_=null;programName_=null;depthProgramName_=null;cullFaceMode_="none";setTexture(A,I){this.textures_[A]=I}clearTextures(){this.textures_.length=0}markStaleTexture(A){A!==void 0&&this.staleTextures_.push(A)}popStaleTextures(){const A=this.staleTextures_;return this.staleTextures_=[],A}get geometry(){return this.geometry_}get wireframeGeometry(){return this.wireframeGeometry_??=new bi(this.geometry),this.wireframeGeometry_}get textures(){return this.textures_}get transform(){return this.transform_}set geometry(A){this.geometry_=A,this.wireframeGeometry_=null}get programName(){return this.programName_}get depthProgramName(){return this.depthProgramName_}get boundingBox(){const A=this.geometry_.boundingBox.clone();return A.applyTransform(this.transform_.matrix),A}set programName(A){this.programName_=A}set depthProgramName(A){this.depthProgramName_=A}get cullFaceMode(){return this.cullFaceMode_}set cullFaceMode(A){this.cullFaceMode_=A}getUniforms(){return{}}}class CC extends uI{constructor(A,I,g,Q){super();const C=[],E=[],i=g,D=Q,a=i+1,G=D+1,R=A/i,t=I/D;for(let J=0;J<G;++J){const n=J*t;for(let e=0;e<a;++e){const K=e*R,l=e/i,V=J/D,x=[K,n,0],W=[0,0,1],p=[l,V];C.push(...x,...W,...p)}}for(let J=0;J<D;++J)for(let n=0;n<i;++n){const e=n+a*J,K=n+a*(J+1),l=n+1+a*(J+1),V=n+1+a*J;E.push(e,K,V),E.push(K,l,V)}this.vertexData_=new Float32Array(C),this.indexData_=new Uint32Array(E),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}}class EC extends VI{worldToTexCoord=WA();channels_;constructor({width:A,height:I,texture:g,channelProps:Q=[]}){super(),this.geometry=new CC(A,I,1,1),this.setTexture(0,g),this.channels_=uB(g,Q),this.programName=Vi(g),this.depthProgramName="meshDepth"}get type(){return"ImageRenderable"}setChannelProps(A){this.channels_=uB(this.textures[0],A)}setChannelProperty(A,I,g){const Q=kg(this.textures[0],{...this.channels_[A],[I]:g});this.channels_[A]=Q}getUniforms(){const A=this.textures[0];if(!A)throw new Error("No texture set");const{color:I,contrastLimits:g,opacity:Q}=this.channels_[0]??kg(A,{});return{u_imageSampler:0,u_color:I.rgb,u_valueOffset:-g[0],u_valueScale:1/(g[1]-g[0]),Opacity:Q,u_worldToTexCoord:this.worldToTexCoord}}}function Vi(B){switch(B.dataType){case"byte":case"int":case"short":return"intScalarImage";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintScalarImage";case"float":return"floatScalarImage"}}class CI{normal;signedDistance;constructor(A=wA(0,1,0),I=0){this.normal=$A(A),this.signedDistance=I}static fromPointAndNormal(A,I){return new CI(I,-bg(I,A))}set(A,I){this.normal=$A(A),this.signedDistance=I}signedDistanceToPoint(A){return bg(this.normal,A)+this.signedDistance}normalize(){const A=JB(this.normal);if(A>0){const I=1/A;YB(this.normal,this.normal,I),this.signedDistance*=I}}}function iC(B,A,I,g,Q=3){switch(B.type){case"pointerdown":{const C=B.event;return LA(C.clientX,C.clientY)}case"pointerup":{if(!A)return A;const C=B.event,E=LA(C.clientX,C.clientY);if(hi(A,E)<Q){if(!g)return null;const D=B.worldRay;return D&&I(D).then(a=>{a!==null&&g(a)}).catch(a=>{O.error("PointPicking",`Failed to read value: ${a}`)}),null}return A}case"pointercancel":return null;default:return A}}class PB{bins_=new Map;acquire(A){const g=this.bins_.get(A)?.pop();return g&&O.debug("RenderablePool","Renderable object acquired"),g}release(A,I){let g=this.bins_.get(A);g||(g=[],this.bins_.set(A,g)),g.push(I),O.debug("RenderablePool","Renderable object released")}clearAll(A){if(A)for(const I of this.bins_.values())I.forEach(A);this.bins_.clear()}}class AB extends Ug{type="ImageLayer";source_;sliceCoords_;axes_;planeRotation_;orientation_;onPickValue_;visibleChunks_=new Map;orderedChunks_=[];pool_=new PB;initialChannelProps_;channelChangeCallbacks_=[];policy_;channelProps_;chunkStoreView_;context_;pointerDownPos_=null;debugMode_=!1;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;wireframeColors_=[new GA(.6,.3,.3),new GA(.3,.6,.4),new GA(.4,.4,.7),new GA(.6,.5,.3)];constructor({source:A,sliceCoords:I,policy:g,orientation:Q,channelProps:C,onPickValue:E,...i}){super({blendMode:"additive",occludes:!0,...i}),this.setState("initialized"),this.source_=A,this.policy_=g??_g(),this.sliceCoords_=I,this.orientation_=Q??"XY",this.axes_=bI(this.orientation_),this.planeRotation_=PI(this.axes_),this.channelProps_=C,this.initialChannelProps_=C,this.onPickValue_=E}attach(A){this.context_=A,this.chunkStoreView_=A.chunkManager.addView(this.source_,this.policy_,this.axes_),QC(this.channelProps_,this.chunkStoreView_.channelCount)}detach(A){this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.orderedChunks_=[],this.clearObjects(),this.chunkStoreView_?.dispose(),this.chunkStoreView_=void 0,this.context_=void 0}update(A){if(!A||!this.chunkStoreView_)return;const I=A.camera,g=I.type==="OrthographicCamera"?I.getWorldViewRect():this.chunkStoreView_.getWholePlaneRect();this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,{worldViewRect:g,bufferWidthPx:A.getBufferRect().width}),this.updateChunks();for(const[Q,C]of this.visibleChunks_)this.updateSlicePosition(C,Q)}get orientation(){return this.orientation_}setOrientation(A){A!==this.orientation_&&(this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.orderedChunks_=[],this.clearObjects(),this.chunkStoreView_?.dispose(),this.lastPresentationTimeStamp_=void 0,this.lastPresentationTimeCoord_=void 0,this.orientation_=A,this.axes_=bI(A),this.planeRotation_=PI(this.axes_),this.context_&&(this.chunkStoreView_=this.context_.chunkManager.addView(this.source_,this.policy_,this.axes_)))}updateChunks(){if(!this.chunkStoreView_)return;this.state!=="ready"&&this.setState("ready");const A=Array.from(this.visibleChunks_.keys()).every(C=>C.texture!==void 0);if(this.visibleChunks_.size>0&&A&&!this.chunkStoreView_.allVisibleFallbackLODLoaded()&&!this.isPresentationStale())return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const I=this.chunkStoreView_.getChunksToRender(),g=new Set(I),Q=Array.from(this.visibleChunks_.keys()).filter(C=>!g.has(C));this.releaseAndRemoveChunks(Q);for(const C of I)this.visibleChunks_.set(C,this.getImageForChunk(C,C.texture));this.orderedChunks_=I,this.rebuildRenderGroups()}rebuildRenderGroups(){this.clearObjects();for(const A of this.orderedChunks_){const I=this.visibleChunks_.get(A),g=A.chunkIndex.c;I===void 0||this.channelProps_?.[g]?.visible===!1||this.addObject(I,g)}}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>AB.STALE_PRESENTATION_MS_}onEvent(A){this.pointerDownPos_=iC(A,this.pointerDownPos_,I=>this.pickAtRay(I),this.onPickValue_)}async pickAtRay(A){const I=this.visibleChunks_.values().next();if(I.done)return null;const g=I.value.transform,Q=PQ(AA(),wA(0,0,1),g.rotation),C=CI.fromPointAndNormal(g.translation,Q),E=A.intersectWithPlane(C);if(!E)return null;const i=await this.getValueAtWorld(E);return i===null?null:{world:E,value:i}}get chunkStoreView(){return this.chunkStoreView_}get sliceCoords(){return this.sliceCoords_}get source(){return this.source_}get imageSourcePolicy(){return this.policy_}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,zg))}getImageForChunk(A,I){const g=this.visibleChunks_.get(A);if(g)return g;const Q=this.pool_.acquire(IB(A,this.axes_));return Q?(Q.setTexture(0,I),Q.setChannelProps(this.getChannelPropsForChunk(A)),this.updateImageChunk(Q,A),Q):this.createImage(A,I)}getChannelPropsForChunk(A){return this.channelProps_?[this.channelProps_[A.chunkIndex.c]??{}]:[{}]}createImage(A,I){const g=new EC({width:A.shape[this.axes_.u],height:A.shape[this.axes_.v],texture:I,channelProps:this.getChannelPropsForChunk(A)});return this.updateImageChunk(g,A),g}updateSlicePosition(A,I){const{u:g,v:Q,w:C}=this.axes_,E=AA();E[RA[g]]=I.offset[g],E[RA[Q]]=I.offset[Q],E[RA[C]]=this.sliceCoords_[C]??I.offset[C],A.transform.setTranslation(E)}sliceIndexForChunk(A){const I=this.axes_.w,g=this.sliceCoords_[I];if(g===void 0)return 0;const Q=(g-A.offset[I])/A.scale[I];return QI(Math.round(Q),0,A.shape[I]-1)}updateImageChunk(A,I){this.debugMode_?(A.wireframeEnabled=!0,A.wireframeColor=this.wireframeColors_[I.lod%this.wireframeColors_.length]):A.wireframeEnabled=!1;const{u:g,v:Q}=this.axes_;A.transform.setScale([I.scale[g],I.scale[Q],1]),A.transform.setRotation(this.planeRotation_),this.updateSlicePosition(A,I),A.worldToTexCoord=$Q(I,this.axes_)}async getValueAtWorld(A){const I=this.chunkStoreView_?.currentLOD??0;for(const g of[!0,!1])for(const[Q,C]of this.visibleChunks_){if(Q.lod===I!==g)continue;const E=await this.readValueFromChunk(Q,C,A);if(E!==null)return E}return null}async readValueFromChunk(A,I,g){const Q=eB(AA(),g,I.transform.inverse),{u:C,v:E,w:i}=this.axes_,D=Math.floor(Q[0]),a=Math.floor(Q[1]);if(D<0||D>=A.shape[C]||a<0||a>=A.shape[E])return null;const G={x:0,y:0,z:0};return G[C]=D,G[E]=a,G[i]=this.sliceIndexForChunk(A),await I.textures[0].readTexel?.(G.x,G.y,G.z)??null}get debugMode(){return this.debugMode_}set debugMode(A){this.debugMode_=A,this.visibleChunks_.forEach((I,g)=>{I.wireframeEnabled=this.debugMode_,this.debugMode_&&(I.wireframeColor=this.wireframeColors_[g.lod%this.wireframeColors_.length])})}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.visibleChunks_.forEach((I,g)=>{I.setChannelProps(this.getChannelPropsForChunk(g))}),this.rebuildRenderGroups(),this.channelChangeCallbacks_.forEach(I=>{I()})}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===-1)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}releaseAndRemoveChunks(A){for(const I of A){const g=this.visibleChunks_.get(I);g&&(this.pool_.release(IB(I,this.axes_),g),this.visibleChunks_.delete(I))}}}function IB(B,A){return[`plane${A.u}${A.v}`,`lod${B.lod}`,`shape${B.shape.x}x${B.shape.y}x${B.shape.z}`,`align${B.rowAlignmentBytes}`].join(":")}class oC extends pB{width_;height_;constructor(A,I,g){super(),this.dataFormat="scalar",this.dataType=fB(A),this.data_=A,this.width_=I,this.height_=g}get type(){return"Texture2D"}get width(){return this.width_}get height(){return this.height_}}const Oi=[[1,.5,.5],[.5,1,.5],[.5,.5,1],[.5,1,1],[1,.5,1],[1,1,.5]];function Xi(B){return B=B??new Map,new Map(Array.from(B.entries()).map(([A,I])=>[A,GA.from(I)]))}function vi(B){return B=B??Oi,B.map(GA.from)}function gB(B={}){return{lookupTable:Xi(B.lookupTable),cycle:vi(B.cycle)}}const DC=new Set(["byte","short","int"]),ji=new Set(["unsigned_byte","unsigned_short","unsigned_int"]);function zi(B){if(B.dataFormat!=="scalar")throw new Error(`Image data format must be scalar, instead found: ${B.dataFormat}`);if(!DC.has(B.dataType)&&!ji.has(B.dataType))throw new Error(`Image data type must be an integer, instead found: ${B.dataType}`);return B}function _i(B){return DC.has(B.dataType)?"intLabelImage":"labelImage"}class aC extends VI{worldToTexCoord=WA();outlineSelected_;selectedValue_;constructor(A){super(),this.geometry=new CC(A.width,A.height,1,1),this.setTexture(0,zi(A.imageData));const I=gB(A.colorMap);this.setTexture(1,this.makeColorCycleTexture(I.cycle)),this.setTexture(2,this.makeColorLookupTableTexture(I.lookupTable)),this.outlineSelected_=A.outlineSelected??!1,this.selectedValue_=A.selectedValue??null,this.programName=_i(A.imageData),this.depthProgramName="meshDepth"}get type(){return"LabelImageRenderable"}getUniforms(){return{u_imageSampler:0,u_colorCycleSampler:1,u_colorLookupTableSampler:2,u_outlineSelected:this.outlineSelected_?1:0,u_selectedValue:this.selectedValue_??-1,u_worldToTexCoord:this.worldToTexCoord}}setColorMap(A){const I=gB(A);this.markStaleTexture(this.textures[1]),this.markStaleTexture(this.textures[2]),this.setTexture(1,this.makeColorCycleTexture(I.cycle)),this.setTexture(2,this.makeColorLookupTableTexture(I.lookupTable))}setSelectedValue(A){this.selectedValue_=A}makeColorCycleTexture(A){const I=new Uint8Array(A.flatMap(Q=>Q.rgba).map(Q=>Math.round(Q*255))),g=new oC(I,A.length,1);return g.dataFormat="rgba",g}makeColorLookupTableTexture(A){A===void 0?A=new Map([[0,GA.TRANSPARENT]]):A.has(0)||(A=new Map([[0,GA.TRANSPARENT],...A]));const I=Array.from(A.keys()),g=Array.from(A.values()).map(E=>E.packed),Q=A.size,C=new Uint32Array(Q*2);return C.set(I,0),C.set(g,Q),new oC(C,Q,2)}}class BB extends Ug{type="LabelLayer";source_;sliceCoords_;axes_;planeRotation_;orientation_;onPickValue_;outlineSelected_;visibleChunks_=new Map;pool_=new PB;colorMap_;selectedValue_=null;policy_;chunkStoreView_;context_;pointerDownPos_=null;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;constructor({source:A,sliceCoords:I,policy:g,orientation:Q,colorMap:C={},onPickValue:E,outlineSelected:i=!1,...D}){super(D),this.setState("initialized"),this.source_=A,this.policy_=g??_g(),this.sliceCoords_=I,this.orientation_=Q??"XY",this.axes_=bI(this.orientation_),this.planeRotation_=PI(this.axes_),this.colorMap_=gB(C),this.onPickValue_=E,this.outlineSelected_=i}attach(A){if(this.context_=A,this.chunkStoreView_=A.chunkManager.addView(this.source_,this.policy_,this.axes_),this.chunkStoreView_.channelCount>1)throw new Error(`LabelLayer does not support multi-channel sources (found ${this.chunkStoreView_.channelCount} channels). Label data must be single-channel.`)}detach(A){this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_?.dispose(),this.chunkStoreView_=void 0,this.context_=void 0}update(A){if(!A||!this.chunkStoreView_)return;const I=A.camera,g=I.type==="OrthographicCamera"?I.getWorldViewRect():this.chunkStoreView_.getWholePlaneRect();this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,{worldViewRect:g,bufferWidthPx:A.getBufferRect().width}),this.updateChunks();for(const[Q,C]of this.visibleChunks_)this.updateSlicePosition(C,Q)}get orientation(){return this.orientation_}setOrientation(A){A!==this.orientation_&&(this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_?.dispose(),this.lastPresentationTimeStamp_=void 0,this.lastPresentationTimeCoord_=void 0,this.orientation_=A,this.axes_=bI(A),this.planeRotation_=PI(this.axes_),this.context_&&(this.chunkStoreView_=this.context_.chunkManager.addView(this.source_,this.policy_,this.axes_)))}updateChunks(){if(!this.chunkStoreView_)return;this.state!=="ready"&&this.setState("ready");const A=Array.from(this.visibleChunks_.keys()).every(C=>C.texture!==void 0);if(this.visibleChunks_.size>0&&A&&!this.chunkStoreView_.allVisibleFallbackLODLoaded()&&!this.isPresentationStale())return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const I=this.chunkStoreView_.getChunksToRender(),g=new Set(I),Q=Array.from(this.visibleChunks_.keys()).filter(C=>!g.has(C));this.releaseAndRemoveChunks(Q),this.clearObjects();for(const C of I){const E=this.getLabelForChunk(C,C.texture);this.visibleChunks_.set(C,E),this.addObject(E,0)}}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>BB.STALE_PRESENTATION_MS_}onEvent(A){this.pointerDownPos_=iC(A,this.pointerDownPos_,I=>this.pickAtRay(I),this.outlineSelected_?I=>{this.setSelectedValue(I.value),this.onPickValue_?.(I)}:this.onPickValue_)}async pickAtRay(A){const I=this.visibleChunks_.values().next();if(I.done)return null;const g=I.value.transform,Q=PQ(AA(),wA(0,0,1),g.rotation),C=CI.fromPointAndNormal(g.translation,Q),E=A.intersectWithPlane(C);if(!E)return null;const i=await this.getValueAtWorld(E);return i===null?null:{world:E,value:i}}get colorMap(){return this.colorMap_}setColorMap(A){this.colorMap_=gB(A),this.visibleChunks_.forEach(I=>{I.setColorMap(this.colorMap_)})}setSelectedValue(A){this.selectedValue_=A,this.visibleChunks_.forEach(I=>{I.setSelectedValue(this.selectedValue_)})}get sliceCoords(){return this.sliceCoords_}get source(){return this.source_}get imageSourcePolicy(){return this.policy_}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,zg))}get chunkStoreView(){return this.chunkStoreView_}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}async getValueAtWorld(A){const I=this.chunkStoreView_?.currentLOD??0;for(const g of[!0,!1])for(const[Q,C]of this.visibleChunks_){if(Q.lod===I!==g)continue;const E=await this.readValueFromChunk(Q,C,A);if(E!==null)return E}return null}async readValueFromChunk(A,I,g){const Q=eB(AA(),g,I.transform.inverse),{u:C,v:E,w:i}=this.axes_,D=Math.floor(Q[0]),a=Math.floor(Q[1]);if(D<0||D>=A.shape[C]||a<0||a>=A.shape[E])return null;const G={x:0,y:0,z:0};return G[C]=D,G[E]=a,G[i]=this.sliceIndexForChunk(A),await I.textures[0].readTexel?.(G.x,G.y,G.z)??null}getLabelForChunk(A,I){const g=this.visibleChunks_.get(A);if(g)return g;const Q=this.pool_.acquire(IB(A,this.axes_));return Q?(Q.setTexture(0,I),Q.setColorMap(this.colorMap_),Q.setSelectedValue(this.selectedValue_),this.updateLabelChunk(Q,A),Q):this.createLabel(A,I)}createLabel(A,I){const g=new aC({width:A.shape[this.axes_.u],height:A.shape[this.axes_.v],imageData:I,colorMap:this.colorMap_,outlineSelected:this.outlineSelected_,selectedValue:this.selectedValue_});return this.updateLabelChunk(g,A),g}updateSlicePosition(A,I){const{u:g,v:Q,w:C}=this.axes_,E=AA();E[RA[g]]=I.offset[g],E[RA[Q]]=I.offset[Q],E[RA[C]]=this.sliceCoords_[C]??I.offset[C],A.transform.setTranslation(E)}sliceIndexForChunk(A){const I=this.axes_.w,g=this.sliceCoords_[I];if(g===void 0)return 0;const Q=(g-A.offset[I])/A.scale[I];return QI(Math.round(Q),0,A.shape[I]-1)}updateLabelChunk(A,I){const{u:g,v:Q}=this.axes_;A.transform.setScale([I.scale[g],I.scale[Q],1]),A.transform.setRotation(this.planeRotation_),this.updateSlicePosition(A,I),A.worldToTexCoord=$Q(I,this.axes_)}releaseAndRemoveChunks(A){for(const I of A){const g=this.visibleChunks_.get(I);g&&(this.pool_.release(IB(I,this.axes_),g),this.visibleChunks_.delete(I))}}}class $i extends uI{constructor(A,I,g,Q,C,E){super();const i=[],D=[],a=Math.floor(Q),G=Math.floor(C),R=Math.floor(E);this.buildFace("z","y","x",-1,-1,g,I,A,R,G,1,i,D),this.buildFace("z","y","x",1,-1,g,I,A,R,G,-1,i,D),this.buildFace("x","z","y",1,1,A,g,I,a,R,1,i,D),this.buildFace("x","z","y",1,-1,A,g,I,a,R,-1,i,D),this.buildFace("x","y","z",1,-1,A,I,g,a,G,1,i,D),this.buildFace("x","y","z",-1,-1,A,I,g,a,G,-1,i,D),this.vertexData_=new Float32Array(i),this.indexData_=new Uint32Array(D),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}buildFace(A,I,g,Q,C,E,i,D,a,G,R,t,J){const n=E/a,e=i/G,K=E/2,l=i/2,V=D/2*R,x=a+1,W=G+1,p=t.length/8;for(let T=0;T<W;T++){const $=-l+T*e;for(let CA=0;CA<x;CA++){const BA=-K+CA*n,iA={x:0,y:0,z:0};iA[A]=BA*Q,iA[I]=$*C,iA[g]=V;const sA={x:0,y:0,z:0};sA[g]=R;const qA=CA/a,kA=1-T/G;t.push(iA.x,iA.y,iA.z,sA.x,sA.y,sA.z,qA,kA)}}for(let T=0;T<G;T++)for(let $=0;$<a;$++){const CA=p+$+x*T,BA=p+$+x*(T+1),iA=p+($+1)+x*(T+1),sA=p+($+1)+x*T;J.push(CA,BA,sA,BA,iA,sA)}}}class sC extends VI{voxelScale=wA(1,1,1);channels_;loadedChannels_=new Set;channelToTextureIndex_=new Map;constructor({channelProps:A=[]}={}){super(),this.geometry=new $i(1,1,1,1,1,1),this.cullFaceMode="front",this.depthTest=!1,this.channels_=[],this.setChannelProps(A)}get type(){return"VolumeRenderable"}updateVolumeWithChunk(A){if(!A.texture)return;const I=A.chunkIndex.c,g=this.channelToTextureIndex_.get(I);g!==void 0?this.updateChannelTexture(g,A.texture):this.addChannelTexture(I,A.texture),this.loadedChannels_.add(I)}addChannelTexture(A,I){const g=this.textures.length;this.setTexture(g,I),this.channelToTextureIndex_.set(A,g);const Q=Ao(I.dataType);if(this.programName&&this.programName!==Q)throw new Error(`Volume renderable does not support multiple channels with different data types. Existing program: ${this.programName}, new channel data type: ${I.dataType} and program: ${Q}`);this.programName=Q}updateChannelTexture(A,I){this.setTexture(A,I)}clearLoadedChannels(){this.loadedChannels_=new Set}reset(){this.clearTextures(),this.channelToTextureIndex_.clear(),this.clearLoadedChannels()}getUniforms(){const A=[0,0,0,0],I=[1,1,1,1,1,1,1,1,1,1,1,1],g=[0,0,0,0],Q=[1,1,1,1],C=[1,1,1,1],E=[],i=Math.max(this.channels_.length,this.channelToTextureIndex_.size);for(let D=0;D<i&&E.length<4;D++){const a=this.channelToTextureIndex_.get(D);if(a===void 0||!this.loadedChannels_.has(D))continue;const G=this.textures[a],R=kg(G,this.channels_[D]||{});if(!R.visible)continue;const t=E.length;I[t*3]=R.color.rgb[0],I[t*3+1]=R.color.rgb[1],I[t*3+2]=R.color.rgb[2],E.push(a),g[t]=-R.contrastLimits[0],Q[t]=1/(R.contrastLimits[1]-R.contrastLimits[0]),A[t]=1,C[t]=R.opacity}return E.reduce((D,a,G)=>(D[`u_channel${G}Sampler`]=a,D),{u_visible:A,"u_color[0]":I,u_valueOffset:g,u_valueScale:Q,u_channelOpacity:C,u_voxelScale:[this.voxelScale[0],this.voxelScale[1],this.voxelScale[2]]})}getAvailableChannelTexture(A){if(A!==void 0){const g=this.channelToTextureIndex_.get(A);if(g!==void 0)return this.textures[g]}const I=this.channelToTextureIndex_.values().next().value;return I!==void 0?this.textures[I]:null}setChannelProps(A){this.channels_=uB(this.getAvailableChannelTexture(),A)}setChannelProperty(A,I,g){const Q=kg(this.getAvailableChannelTexture(A),{...this.channels_[A],[I]:g});this.channels_[A]=Q}}function Ao(B){switch(B){case"byte":case"int":case"short":return"intVolume";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintVolume";case"float":return"floatVolume"}}const Io=2;class yC extends Ug{type="VolumeLayer";debugShowDegenerateRays=!1;relativeStepSize=1;opacityMultiplier=1;earlyTerminationAlpha=.99;requiresSceneDepth_=!0;source_;sliceCoords_;currentVolumes_=new Map;volumeToPoolKey_=new Map;pool_=new PB;initialChannelProps_;channelChangeCallbacks_=[];policy_;chunkStoreView_;channelProps_;lastLoadedTime_=void 0;lastNumRenderedChannelChunks_=void 0;interactiveStepSizeScale_=1;debugShowWireframes_=!1;get debugShowWireframes(){return this.debugShowWireframes_}set debugShowWireframes(A){if(this.debugShowWireframes_!==A){for(const I of this.currentVolumes_.values())I.wireframeEnabled=A;this.debugShowWireframes_=A}}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,zg))}setChannelProps(A){this.channelProps_=A;for(const I of this.currentVolumes_.values())I.setChannelProps(A);this.channelChangeCallbacks_.forEach(I=>{I()})}get channelProps(){return this.channelProps_}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===-1)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}constructor({source:A,sliceCoords:I,policy:g,channelProps:Q}){super({blendMode:"premultipliedOver"}),this.source_=A,this.sliceCoords_=I,this.policy_=g??_g(),this.initialChannelProps_=Q,this.channelProps_=Q,this.setState("initialized")}getOrCreateVolume(A,I){const g=this.currentVolumes_.get(A);if(g){for(const E of I)g.updateVolumeWithChunk(E);return g}const Q=Qo(I[0]),C=this.pool_.acquire(Q)??new sC;C.setChannelProps(this.channelProps_??[]),this.volumeToPoolKey_.set(C,Q);for(const E of I)C.updateVolumeWithChunk(E);return this.updateVolumeTransform(C,I[0]),C}attach(A){this.chunkStoreView_=A.chunkManager.addView(this.source_,this.policy_),QC(this.channelProps_,this.chunkStoreView_.channelCount)}detach(A){for(const I of this.currentVolumes_.values())this.releaseAndRemoveVolume(I);this.currentVolumes_.clear(),this.clearObjects(),this.chunkStoreView_?.dispose(),this.chunkStoreView_=void 0}updateChunks(){if(!this.chunkStoreView_)return;this.state!=="ready"&&this.setState("ready");const A=this.chunkStoreView_.getChunksToRender(),I=this.sliceCoords_.t??-1,g=Bo(A);if(this.lastLoadedTime_!==I||g.size!==this.currentVolumes_.size||this.lastNumRenderedChannelChunks_!==A.length){for(const[C,E]of this.currentVolumes_)g.has(C)||(this.releaseAndRemoveVolume(E),this.currentVolumes_.delete(C));for(const[C,E]of g){const i=this.getOrCreateVolume(C,E);i.wireframeEnabled=this.debugShowWireframes,this.currentVolumes_.set(C,i)}this.lastLoadedTime_=I,this.lastNumRenderedChannelChunks_=A.length}}updateVolumeTransform(A,I){const g={x:I.shape.x*I.scale.x,y:I.shape.y*I.scale.y,z:I.shape.z*I.scale.z};A.transform.setScale([g.x,g.y,g.z]),LI(A.voxelScale,I.scale.x,I.scale.y,I.scale.z);const Q={x:I.shape.x*I.scale.x/2,y:I.shape.y*I.scale.y/2,z:I.shape.z*I.scale.z/2};A.transform.setTranslation([I.offset.x+Q.x,I.offset.y+Q.y,I.offset.z+Q.z])}releaseAndRemoveVolume(A){A.reset(),this.pool_.release(this.volumeToPoolKey_.get(A),A),this.volumeToPoolKey_.delete(A)}update(A){if(!A||!this.chunkStoreView_)return;this.chunkStoreView_.updateChunksForVolume(this.sliceCoords_,A.camera.getViewProjection());const I=A.cameraControls?.isMoving??!1;this.interactiveStepSizeScale_=I?Io:1,this.updateChunks(),this.rebuildObjects(A.camera)}rebuildObjects(A){const I=Array.from(this.currentVolumes_.values());Co(I,A),this.clearObjects();for(const g of I)this.addObject(g)}get chunkStoreView(){return this.chunkStoreView_}getUniforms(){return{u_debugShowDegenerateRays:Number(this.debugShowDegenerateRays),u_relativeStepSize:this.relativeStepSize*this.interactiveStepSizeScale_,u_opacityMultiplier:this.opacityMultiplier,u_earlyTerminationAlpha:this.earlyTerminationAlpha}}}function go(B){const{x:A,y:I,z:g,t:Q}=B.chunkIndex;return`${A}:${I}:${g}:${Q}`}function Bo(B){const A=new Map;for(const I of B){const g=go(I);let Q=A.get(g);Q||(Q=[],A.set(g,Q)),Q.push(I)}return A}function Qo(B){return[`lod${B.lod}`,`shape${B.shape.x}x${B.shape.y}x${B.shape.z}`,`align${B.rowAlignmentBytes}`].join(":")}function Co(B,A){const I=A.position,g=new Map;for(const Q of B){const C=Q.transform.translation;g.set(Q,gi(I,C))}B.sort((Q,C)=>g.get(C)-g.get(Q))}var cg=function(B=1){var A=0,I=document.createElement("div");I.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",I.addEventListener("click",function(R){R.preventDefault(),Q(++A%I.children.length)},!1);function g(R){return I.appendChild(R.dom),R}function Q(R){for(var t=0;t<I.children.length;t++)I.children[t].style.display=t===R?"block":"none";A=R}var C=(performance||Date).now(),E=C,i=0,D=g(new cg.Panel("FPS","#0ff","#002",B)),a=g(new cg.Panel("MS","#0f0","#020",B));if(self.performance&&self.performance.memory)var G=g(new cg.Panel("MB","#f08","#201",B));return Q(0),{REVISION:16,dom:I,addPanel:g,showPanel:Q,begin:function(){C=(performance||Date).now()},end:function(){i++;var R=(performance||Date).now();if(a.update(R-C,200),R>=E+1e3&&(D.update(i*1e3/(R-E),100),E=R,i=0,G)){var t=performance.memory;G.update(t.usedJSHeapSize/1048576,t.jsHeapSizeLimit/1048576)}return R},update:function(){C=this.end()},domElement:I,setMode:Q}};cg.Panel=function(B,A,I,g){var Q=1/0,C=0,E=Math.round,i=E(window.devicePixelRatio||1),D=E(80*i*g),a=E(48*i*g),G=E(3*i*g),R=E(2*i*g),t=E(3*i*g),J=E(15*i*g),n=E(74*i*g),e=E(30*i*g),K=document.createElement("canvas");K.width=D,K.height=a,K.style.cssText=`width:${E(g*80)}px;height:${E(g*48)}px`;var l=K.getContext("2d");return l.font="bold "+E(9*i*g)+"px Helvetica,Arial,sans-serif",l.textBaseline="top",l.fillStyle=I,l.fillRect(0,0,D,a),l.fillStyle=A,l.fillText(B,G,R),l.fillRect(t,J,n,e),l.fillStyle=I,l.globalAlpha=.9,l.fillRect(t,J,n,e),{dom:K,update:function(V,x){Q=Math.min(Q,V),C=Math.max(C,V),l.fillStyle=I,l.globalAlpha=1,l.fillRect(0,0,D,J),l.fillStyle=A,l.fillText(E(V)+" "+B+" ("+E(Q)+"-"+E(C)+")",G,R),l.drawImage(K,t+i,J,n-i,e,t,J,n-i,e),l.fillRect(t+n-i,J,i,e),l.fillStyle=I,l.globalAlpha=.9,l.fillRect(t+n-i,J,i,E((1-V/x)*e))}}};function Eo({scale:B}={scale:1.5}){const A=new cg(B);return A.showPanel(0),document.body.appendChild(A.dom),A}const VB=["pointerdown","pointermove","pointerup","pointercancel","wheel"];function io(B){return VB.includes(B)}class oo{propagationStopped_=!1;type;event;worldPos;worldRay;clipPos;constructor(A,I){this.type=A,this.event=I}get propagationStopped(){return this.propagationStopped_}stopPropagation(){this.propagationStopped_=!0}}class Do{listeners_=[];element_;isConnected_=!1;constructor(A){this.element_=A}addEventListener(A){this.listeners_.push(A)}removeEventListener(A){const I=this.listeners_.indexOf(A);if(I===-1)throw new Error(`Listener to remove could not be found: ${A}`);this.listeners_.splice(I,1)}connect(){if(this.isConnected_){O.warn("EventDispatcher","Attempted to connect already connected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!0,VB.forEach(A=>{this.element_.addEventListener(A,this.handleEvent,{passive:!1})})}disconnect(){if(!this.isConnected_){O.debug("EventDispatcher","Attempted to disconnect already disconnected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!1,VB.forEach(A=>{this.element_.removeEventListener(A,this.handleEvent)})}handleEvent=A=>{if(!io(A.type)){O.error("EventDispatcher",`Unsupported event type ${A.type}`);return}const I=new oo(A.type,A);for(const g of this.listeners_)if(g(I),I.propagationStopped)break}}const ao=1e-12;class so{origin;direction;constructor(A,I){this.origin=$A(A),this.direction=bQ(AA(),I)}intersectWithPlane(A){const I=bg(this.direction,A.normal);if(Math.abs(I)<ao)return null;const g=-A.signedDistanceToPoint(this.origin)/I;return KB(AA(),this.origin,this.direction,g)}}class hC{id;element;camera;events;cameraControls;context_;layers_=[];constructor(A){this.id=A.id,this.element=A.element,this.camera=A.camera,this.context_=A.context,this.cameraControls=A.cameraControls,this.updateAspectRatio(),this.events=new Do(this.element),this.events.addEventListener(I=>{if(I.event instanceof PointerEvent||I.event instanceof WheelEvent){const{clientX:g,clientY:Q}=I.event,C=LA(g,Q);I.clipPos=this.clientToClip(C,0),I.worldPos=this.camera.clipToWorld(I.clipPos);const E=this.camera.clipToWorld(this.clientToClip(C,-1)),i=this.camera.clipToWorld(this.clientToClip(C,1));I.worldRay=new so(E,nB(AA(),i,E))}for(const g of this.layers_)if(g.onEvent(I),I.propagationStopped)return;this.cameraControls?.onEvent(I)});for(const I of A.layers??[])this.addLayer(I)}get layers(){return this.layers_}addLayer(A){A.onAttached(this.context_),this.layers_.push(A)}removeLayer(A){const I=this.layers_.indexOf(A);if(I===-1)throw new Error(`Layer to remove not found: ${A}`);this.layers_.splice(I,1),A.onDetached(this.context_)}removeAllLayers(){for(const A of this.layers_)A.onDetached(this.context_);this.layers_=[]}updateSize(){this.updateAspectRatio()}getBoxRelativeTo(A){const I=this.getBox().toRect(),g=A.getBoundingClientRect(),Q=window.devicePixelRatio||1,C=g.left*Q,E=g.top*Q,i=g.height*Q,D=I.x-C,a=I.y-E,G=Math.floor(D),R=Math.floor(i-a-I.height),t=Math.floor(I.width),J=Math.floor(I.height);return new mA(LA(G,R),LA(G+t,R+J))}getBufferRect(){return this.getBoxRelativeTo(this.element).toRect()}clientToClip(A,I=0){const[g,Q]=A,C=this.element.getBoundingClientRect();return wA(2*(g-C.x)/C.width-1,2*(Q-C.y)/C.height-1,I)}clientToWorld(A,I=0){const g=this.clientToClip(A,I);return this.camera.clipToWorld(g)}getBox(){const A=this.element.getBoundingClientRect(),I=window.devicePixelRatio||1,g=A.left*I,Q=A.top*I,C=A.width*I,E=A.height*I;return new mA(LA(g,Q),LA(g+C,Q+E))}updateAspectRatio(){const{width:A,height:I}=this.getBox().toRect();if(A<=0||I<=0){O.debug("Viewport",`Skipping aspect ratio update for viewport ${this.id}: invalid dimensions ${A}x${I}`);return}const g=A/I;this.camera.setAspectRatio(g)}}function GC(B,A){for(const I of A){if(I.id===B.id)throw new Error(`Duplicate viewport ID "${B.id}". Each viewport must have a unique ID.`);if(I.element===B.element){const g=B.element.tagName.toLowerCase()+(B.element.id?`#${B.element.id}`:"[element has no id]");throw new Error(`Multiple viewports cannot share the same HTML element: viewports "${I.id}" and "${B.id}" both use ${g}`)}}}function yo(B){for(let A=0;A<B.length;A++)GC(B[A],B.slice(0,A))}function FC(B,A,I){const g=B.map(Q=>{const C=Q.element??A;return{...Q,element:C,id:Q.id??C.id??xQ("viewport"),context:I}});return yo(g),g.map(Q=>new hC(Q))}class ho{elements_;resizeObserver_;mediaQuery_;onMediaQueryChange_;onChange_;constructor(A=[],I){this.elements_=[...A],this.onChange_=I}connect(){if(this.resizeObserver_){O.warn("PixelSizeObserver","Attempted to connect already connected observer");return}this.resizeObserver_=new ResizeObserver(()=>{this.onChange_()});for(const A of this.elements_)this.resizeObserver_.observe(A);this.startDevicePixelRatioObserver()}startDevicePixelRatioObserver(){this.mediaQuery_=matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this.onMediaQueryChange_=()=>{this.onChange_(),this.startDevicePixelRatioObserver()},this.mediaQuery_.addEventListener("change",this.onMediaQueryChange_,{once:!0})}disconnect(){if(!this.resizeObserver_){O.warn("PixelSizeObserver","Attempted to disconnect already disconnected observer");return}this.resizeObserver_?.disconnect(),this.mediaQuery_&&this.onMediaQueryChange_&&this.mediaQuery_.removeEventListener("change",this.onMediaQueryChange_)}observe(A){if(this.elements_.includes(A)){O.warn("PixelSizeObserver","Element already being observed");return}this.elements_.push(A),this.resizeObserver_&&this.resizeObserver_.observe(A)}unobserve(A){const I=this.elements_.indexOf(A);if(I===-1){O.warn("PixelSizeObserver","Element not being observed");return}this.elements_.splice(I,1),this.resizeObserver_&&this.resizeObserver_.unobserve(A)}}const Go=2048;class Fo{canvas;overlays;chunkManager_;context_;renderer_;viewports_;stats_;sizeObserver_;lastAnimationId_;lastTimestamp_=0;constructor(A){this.canvas=A.canvas,this.renderer_=new ri(this.canvas);const g=(A.memoryLimitMB??Go)*1024*1024;this.chunkManager_=new mi(C=>this.renderer_.uploadTexture(C),C=>this.renderer_.disposeTexture(C),()=>this.renderer_.gpuTextureBytes,g,A.maxConcurrentRequests,A.maxGpuUploadsPerUpdate),this.context_={chunkManager:this.chunkManager_},this.viewports_=FC(A.viewports??[],this.canvas,this.context_),this.overlays=[...A.overlays??[]],A.showStats&&(this.stats_=Eo());const Q=[this.canvas];for(const C of this.viewports_)C.element!==this.canvas&&Q.push(C.element);this.sizeObserver_=new ho(Q,()=>{this.renderer_.updateSize(),this.renderer_.beginFrame();for(const C of this.viewports_)C.updateSize(),this.renderer_.render(C)})}get chunkQueueStats(){return this.chunkManager_.queueStats}get chunkStats(){const A=[];for(const I of this.viewports_){const g=[];for(const Q of I.layers)!(Q instanceof AB)&&!(Q instanceof BB)&&!(Q instanceof yC)||Q.chunkStoreView&&g.push(Q.chunkStoreView);g.length!==0&&A.push(li(I.id,g))}return{sources:this.chunkManager_.sourceChunkStats,viewports:A}}get memoryStats(){const A=performance.memory;return{...this.chunkManager_.memoryStats,gpuTextureBytes:this.renderer_.gpuTextureBytes,gpuTextureCount:this.renderer_.gpuTextureCount,jsHeapUsedBytes:A?.usedJSHeapSize,jsHeapLimitBytes:A?.jsHeapSizeLimit}}get renderedObjects(){return this.renderer_.renderedObjects}get width(){return this.renderer_.width}get height(){return this.renderer_.height}get viewports(){return this.viewports_}get running(){return this.lastAnimationId_!==void 0}getViewport(A){return this.viewports_.find(I=>I.id===A)}addViewport(A){const[I]=FC([A],this.canvas,this.context_);return GC(I,this.viewports_),this.viewports_.push(I),this.running&&(I.events.connect(),I.element!==this.canvas&&this.sizeObserver_.observe(I.element)),O.info("Idetik",`Added viewport "${I.id}"`),I}removeViewport(A){const I=this.viewports_.indexOf(A);return I===-1?(O.warn("Idetik",`Viewport "${A.id}" not found, nothing to remove`),!1):(this.running&&(A.events.disconnect(),A.element!==this.canvas&&this.sizeObserver_.unobserve(A.element)),this.viewports_.splice(I,1),O.info("Idetik",`Removed viewport "${A.id}"`),!0)}addOverlay(A){this.overlays.push(A)}removeOverlay(A){const I=this.overlays.indexOf(A);return I===-1?(O.warn("Idetik","Overlay not found, nothing to remove"),!1):(this.overlays.splice(I,1),!0)}setMemoryLimitMB(A){this.chunkManager_.memoryLimitBytes=A*1024*1024}start(){if(O.info("Idetik","Idetik runtime starting"),this.running)O.warn("Idetik","Idetik runtime already started");else{for(const A of this.viewports_)A.events.connect();this.sizeObserver_.connect(),this.lastAnimationId_=requestAnimationFrame(A=>{this.lastTimestamp_=A,this.animate(A)})}return this}animate(A){this.stats_&&this.stats_.begin();const I=Math.min(A-this.lastTimestamp_,100)/1e3;this.lastTimestamp_=A,this.renderer_.beginFrame();for(const g of this.viewports_)g.cameraControls?.onUpdate(I),this.renderer_.render(g);this.chunkManager_.update();for(const g of this.overlays)g.update(this);this.stats_&&this.stats_.end(),this.lastAnimationId_=requestAnimationFrame(g=>this.animate(g))}stop(){if(O.info("Idetik","Idetik runtime stopping"),!this.running)O.warn("Idetik","Idetik runtime not started");else{this.sizeObserver_.disconnect();for(const A of this.viewports_)A.events.disconnect();cancelAnimationFrame(this.lastAnimationId_),this.lastAnimationId_=void 0}}}function wo(B,A){return{...B,...A,headers:{...B.headers,...A.headers}}}function wC(B,A){const I=typeof B=="string"?new URL(B):B;I.pathname.endsWith("/")||(I.pathname+="/");const g=new URL(A.slice(1),I);return g.search=I.search,g}async function SC(B){if(B.status!==404){if(B.status===200||B.status===206)return new Uint8Array(await B.arrayBuffer());throw new Error(`Unexpected response status ${B.status} ${B.statusText}`)}}class Lg{url;#A;#I;#g;constructor(A,I={}){this.url=A,this.#A=I.fetch??(g=>fetch(g)),this.#I=I.overrides??{},this.#g=I.useSuffixRequest??!1}#B(A,I){return new Request(A,wo(this.#I,I))}async get(A,I={}){let g=wC(this.url,A).href,Q=this.#B(g,I),C=await this.#A(Q);return SC(C)}async getRange(A,I,g={}){let Q=wC(this.url,A),C;if("suffixLength"in I)C=await this.#Q(Q,I.suffixLength,g);else{let E={...g,headers:{...g.headers,Range:`bytes=${I.offset}-${I.offset+I.length-1}`}},i=this.#B(Q,E);C=await this.#A(i)}return SC(C)}async#Q(A,I,g){if(this.#g){let G={...g,headers:{...g.headers,Range:`bytes=-${I}`}};return this.#A(this.#B(A,G))}let Q=this.#B(A,{...g,method:"HEAD"}),C=await this.#A(Q);if(!C.ok)return C;let E=C.headers.get("Content-Length"),i=Number(E),D=i-I,a={...g,headers:{...g.headers,Range:`bytes=${D}-${i-1}`}};return this.#A(this.#B(A,a))}}class Jg extends Error{}class OI extends Jg{_tag="NotFoundError";name="NotFoundError";path;found;constructor(A,I={}){super(`Not found: ${A}`,{cause:I.cause}),this.path=I.path,this.found=I.found}}class JA extends Jg{_tag="InvalidMetadataError";name="InvalidMetadataError";path;constructor(A,I={}){super(A,{cause:I.cause}),this.path=I.path}}class So extends Jg{_tag="UnknownCodecError";name="UnknownCodecError";codec;constructor(A){super(`Unknown codec: ${A}`),this.codec=A}}class Ro extends Jg{_tag="CodecPipelineError";name="CodecPipelineError";direction;codec;chunkPath;constructor(A){const I=[`Failed to ${A.direction} chunk`,A.codec&&`via codec "${A.codec}"`,A.chunkPath&&`at ${A.chunkPath}`].filter(Boolean);super(I.join(" "),{cause:A.cause}),this.direction=A.direction,this.codec=A.codec,this.chunkPath=A.chunkPath}}class OB extends Jg{_tag="UnsupportedError";name="UnsupportedError";feature;constructor(A){super(`Unsupported: ${A}`),this.feature=A}}function JI(B){return()=>{throw new OB(`${B} encode`)}}class QB{kind="array_to_array";constructor(A,I){if(A.keepbits<0)throw new JA("keepbits must be zero or positive")}static fromConfig(A,I){return new QB(A,I)}encode=JI("bitround");decode(A){return A}}function XB(B){return B instanceof ArrayBuffer||B instanceof SharedArrayBuffer}class RC{#A;constructor(A,I,g){typeof A=="number"?this.#A=new Uint8Array(A):XB(A)?this.#A=new Uint8Array(A,I,g):this.#A=new Uint8Array(Array.from(A,Q=>Q?1:0))}get BYTES_PER_ELEMENT(){return 1}get byteOffset(){return this.#A.byteOffset}get byteLength(){return this.#A.byteLength}get buffer(){return this.#A.buffer}get length(){return this.#A.length}get(A){let I=this.#A[A];return typeof I=="number"?I!==0:I}set(A,I){this.#A[A]=I?1:0}fill(A){this.#A.fill(A?1:0)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class vB{_data;chars;#A;constructor(A,I,g,Q){if(this.chars=A,this.#A=new TextEncoder,typeof I=="number")this._data=new Uint8Array(I*A);else if(XB(I))Q&&(Q=Q*A),this._data=new Uint8Array(I,g,Q);else{let C=Array.from(I);this._data=new Uint8Array(C.length*A);for(let E=0;E<C.length;E++)this.set(E,C[E])}}get BYTES_PER_ELEMENT(){return this.chars}get byteOffset(){return this._data.byteOffset}get byteLength(){return this._data.byteLength}get buffer(){return this._data.buffer}get length(){return this.byteLength/this.BYTES_PER_ELEMENT}get(A){const I=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);return new TextDecoder().decode(I).replace(/\x00/g,"")}set(A,I){const g=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);g.fill(0),g.set(this.#A.encode(I))}fill(A){const I=this.#A.encode(A);for(let g=0;g<this.length;g++)this._data.set(I,g*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class rg{#A;chars;constructor(A,I,g,Q){if(this.chars=A,typeof I=="number")this.#A=new Int32Array(I*A);else if(XB(I))Q&&(Q*=A),this.#A=new Int32Array(I,g,Q);else{const C=I,E=new rg(A,1);this.#A=new Int32Array((function*(){for(let i of C)E.set(0,i),yield*E.#A})())}}get BYTES_PER_ELEMENT(){return this.#A.BYTES_PER_ELEMENT*this.chars}get byteLength(){return this.#A.byteLength}get byteOffset(){return this.#A.byteOffset}get buffer(){return this.#A.buffer}get length(){return this.#A.length/this.chars}get(A){const I=this.chars*A;let g="";for(let Q=0;Q<this.chars;Q++)g+=String.fromCodePoint(this.#A[I+Q]);return g.replace(/\u0000/g,"")}set(A,I){const g=this.chars*A,Q=this.#A.subarray(g,g+this.chars);Q.fill(0);for(let C=0;C<this.chars;C++)Q[C]=I.codePointAt(C)??0}fill(A){this.set(0,A);let I=this.#A.subarray(0,this.chars);for(let g=1;g<this.length;g++)this.#A.set(I,g*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}function No(){if(typeof SharedArrayBuffer>"u")throw new Error("SharedArrayBuffer is not available. In browsers, this requires Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers to be set.")}function to(B,A){return new SharedArrayBuffer(B)}function ng(B){const A=new TextDecoder().decode(B);try{return JSON.parse(A)}catch(I){throw new JA("Failed to decode JSON",{cause:I})}}function NC(B,A){const I=A/2,g=A-1;let Q=0;for(let C=0;C<B.length;C+=A)for(let E=0;E<I;E+=1)Q=B[C+E],B[C+E]=B[C+g-E],B[C+g-E]=Q}function XI(B){if(B==="v2:object")return globalThis.Array;let A=B.match(/v2:([US])(\d+)/);if(A){let[,g,Q]=A;return(g==="U"?rg:vB).bind(null,Number(Q))}if(B==="string")return globalThis.Array;let I={int8:Int8Array,int16:Int16Array,int32:Int32Array,int64:globalThis.BigInt64Array,uint8:Uint8Array,uint16:Uint16Array,uint32:Uint32Array,uint64:globalThis.BigUint64Array,float16:globalThis.Float16Array,float32:Float32Array,float64:Float64Array,bool:RC}[B];if(!I)throw new JA(`Unknown or unsupported dataType: ${B}`);return I}function rI(B,A){const I=B.length;typeof A=="string"&&(A=A==="C"?Array.from({length:I},(C,E)=>E):Array.from({length:I},(C,E)=>I-1-E)),VA(I===A.length,"Order length must match the number of dimensions.");let g=1,Q=new Array(I);for(let C=A.length-1;C>=0;C--)Q[A[C]]=g,g*=B[A[C]];return Q}function Uo({name:B,configuration:A}){if(B==="default"){const I=A?.separator??"/";return g=>["c",...g].join(I)}if(B==="v2"){const I=A?.separator??".";return g=>g.join(I)||"0"}throw new JA(`Unknown chunk key encoding: ${B}`)}function tC(B){if(B==="|O")return{dataType:"v2:object"};let A=B.match(/^([<|>])(.*)$/);if(!A)throw new JA(`Invalid dtype: ${B}`);let[,I,g]=A,Q={b1:"bool",i1:"int8",u1:"uint8",i2:"int16",u2:"uint16",i4:"int32",u4:"uint32",i8:"int64",u8:"uint64",f2:"float16",f4:"float32",f8:"float64"}[g]??(g.startsWith("S")||g.startsWith("U")?`v2:${g}`:void 0);if(!Q)throw new JA(`Unsupported or unknown dtype: ${B}`);return I==="|"?{dataType:Q}:{dataType:Q,endian:I==="<"?"little":"big"}}function ko(B){return(B.id==="fixedscaleoffset"||B.id==="numcodecs.fixedscaleoffset")&&typeof B.scale=="number"&&typeof B.offset=="number"&&(B.astype===void 0||typeof B.astype=="string")&&(B.dtype===void 0||typeof B.dtype=="string")}function co(B,A={}){let I=[],g=tC(B.dtype);B.order==="F"&&I.push({name:"transpose",configuration:{order:"F"}});for(let C of B.filters??[]){if(C.id==="fixedscaleoffset"||C.id==="numcodecs.fixedscaleoffset"){if(!ko(C))throw new JA(`Invalid fixedscaleoffset filter: ${JSON.stringify(C)}`);I.push({name:"scale_offset",configuration:{scale:C.scale,offset:C.offset}});let D=C.astype??C.dtype;if(D!==void 0&&D!==B.dtype){let a=tC(D).dataType;if(!jB(a,"number")&&!jB(a,"bigint"))throw new JA(`fixedscaleoffset astype must be a numeric data type, got ${D}`);I.push({name:"cast_value",configuration:{data_type:a,rounding:"nearest-even",out_of_range:"wrap"}})}continue}let{id:E,...i}=C;I.push({name:`numcodecs.${E}`,configuration:i})}if("endian"in g&&g.endian==="big"&&I.push({name:"bytes",configuration:{endian:"big"}}),B.compressor){let{id:C,...E}=B.compressor;I.push({name:`numcodecs.${C}`,configuration:E})}let Q;return globalThis.Array.isArray(A._ARRAY_DIMENSIONS)&&(Q=A._ARRAY_DIMENSIONS),{zarr_format:3,node_type:"array",shape:B.shape,data_type:g.dataType,chunk_grid:{name:"regular",configuration:{chunk_shape:B.chunks}},chunk_key_encoding:{name:"v2",configuration:{separator:B.dimension_separator??"."}},codecs:I,fill_value:B.fill_value,dimension_names:Q,attributes:A}}function Lo(B,A={}){return{zarr_format:3,node_type:"group",attributes:A}}function jB(B,A){if(A!=="number"&&A!=="bigint"&&A!=="boolean"&&A!=="object"&&A!=="string")return B===A;let I=B==="bool";if(A==="boolean")return I;let g=B.startsWith("v2:U")||B.startsWith("v2:S")||B==="string";if(A==="string")return g;let Q=B==="int64"||B==="uint64";if(A==="bigint")return Q;let C=B==="v2:object";return A==="object"?C:!g&&!Q&&!I&&!C}function Jo(B){return B?.name==="sharding_indexed"}function UC(B){if((B.data_type==="uint64"||B.data_type==="int64")&&B.fill_value!=null)return BigInt(B.fill_value);let A=B.data_type==="float16"||B.data_type==="float32"||B.data_type==="float64";if(typeof B.fill_value=="string"&&A){let I={NaN:NaN,Infinity:1/0,"-Infinity":-1/0};if(B.fill_value in I)return I[B.fill_value]}return B.fill_value}function kC(B,...A){if(!A.some(I=>B instanceof I))throw B}function VA(B,A=""){if(!B)throw new Error(A)}async function cC(B,{format:A,signal:I}){let g;if(B instanceof ArrayBuffer)g=new Response(B);else{let Q=new Uint8Array(B.buffer,B.byteOffset,B.byteLength);g=new Response(Q.slice().buffer)}VA(g.body,"Response does not contain body.");try{return await new Response(g.body.pipeThrough(new DecompressionStream(A),{signal:I})).arrayBuffer()}catch{throw I?.throwIfAborted(),new Error(`Failed to decode ${A}`)}}const LC=ro();function ro(){const B=new Uint32Array([305419896]);return new Uint8Array(B.buffer,B.byteOffset,B.byteLength)[0]!==18}function JC(B){return"BYTES_PER_ELEMENT"in B?B.BYTES_PER_ELEMENT:4}class CB{kind="array_to_bytes";#A;#I;#g;#B;#Q;constructor(A,I){this.#Q=A?.endian,this.#I=XI(I.dataType),this.#B=I.shape,this.#A=rI(I.shape,"C");const g=new this.#I(0);this.#g=g.BYTES_PER_ELEMENT}static fromConfig(A,I){return new CB(A,I)}encode(A){let I=new Uint8Array(A.data.buffer);return LC&&this.#Q==="big"&&NC(I,JC(this.#I)),I}computeEncodedSize(A){return A}decode(A){return LC&&this.#Q==="big"&&NC(A,JC(this.#I)),{data:new this.#I(A.buffer,A.byteOffset,A.byteLength/this.#g),shape:this.#B,stride:this.#A}}}const rC={NaN:NaN,Infinity:1/0,"-Infinity":-1/0},nC={float16:2,float32:4,float64:8};function EB(B){return B in nC}function zB(B){return B==="int64"||B==="uint64"}function no(B,A){const I=BigInt(B),g=new ArrayBuffer(A),Q=new DataView(g);if(A===2){if(typeof Q.getFloat16!="function")throw new OB("float16 hex-encoded scalar decoding (requires DataView.prototype.getFloat16)");return Q.setUint16(0,Number(I)),Q.getFloat16(0)}return A===4?(Q.setUint32(0,Number(I)),Q.getFloat32(0)):(Q.setBigUint64(0,I),Q.getFloat64(0))}function iB(B,A){if(zB(B)){if(typeof A!="number"||!Number.isInteger(A))throw new JA(`Expected an integer value for data type "${B}", got ${JSON.stringify(A)}`);return BigInt(A)}if(typeof A=="number"){if(!EB(B)&&!Number.isInteger(A))throw new JA(`Expected an integer value for data type "${B}", got ${A}`);return A}if(!EB(B))throw new JA(`String-encoded scalar "${A}" is not valid for non-float data type "${B}"`);return A in rC?rC[A]:no(A,nC[B])}const YC=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]),_B={int8:[-128,2**7-1],uint8:[0,2**8-1],int16:[-32768,2**15-1],uint16:[0,2**16-1],int32:[-2147483648,2**31-1],uint32:[0,2**32-1]},$B={int64:[-(2n**63n),2n**63n-1n],uint64:[0n,2n**64n-1n]};function KC(B,A,I){return B.map(([g,Q])=>({src:iB(A,g),tgt:iB(I,Q)}))}function Yo(B,A){for(const I of A)if(typeof I.src=="number"&&Number.isNaN(I.src)){if(typeof B=="number"&&Number.isNaN(B))return I.tgt}else if(B===I.src)return I.tgt}function Ko(B){if(!Number.isFinite(B))return B;if(Math.abs(B-Math.trunc(B))===.5){const A=Math.floor(B),I=Math.ceil(B);return A%2===0?A:I}return Math.round(B)}function eo(B){return Math.sign(B)*Math.floor(Math.abs(B)+.5)}function eC(B){switch(B){case"nearest-even":return Ko;case"towards-zero":return Math.trunc;case"towards-positive":return Math.ceil;case"towards-negative":return Math.floor;case"nearest-away":return eo}}function AQ(B,A,I){const g=A-B+1;switch(I){case"clamp":return Q=>Q<B?B:Q>A?A:Q;case"wrap":return Q=>Q>=B&&Q<=A?Q:((Q-B)%g+g)%g+B;default:return Q=>{if(Q>=B&&Q<=A)return Q;throw new Error(`Value ${Q} out of range [${B}, ${A}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}function IQ(B,A,I){const g=A-B+1n;switch(I){case"clamp":return Q=>Q<B?B:Q>A?A:Q;case"wrap":return Q=>Q>=B&&Q<=A?Q:((Q-B)%g+g)%g+B;default:return Q=>{if(Q>=B&&Q<=A)return Q;throw new Error(`Value ${Q} out of range [${B}, ${A}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}class gQ{kind="array_to_array";#A;#I;#g;#B;constructor(A,I,g,Q,C,E){this.#A=I,this.#I=XI(A),this.#g=MC(I,A,g,Q,C),this.#B=MC(A,I,g,Q,E)}getEncodedMeta(A){let I=A.fillValue;return I!=null&&(I=this.#B(I)),{...A,dataType:this.#A,fillValue:I}}static fromConfig(A,I){const g=I.dataType,Q=A.data_type;if(!YC.has(g))throw new JA(`cast_value codec does not support array data type: ${g}`);if(!YC.has(Q))throw new JA(`cast_value codec does not support encoded data type: ${Q}`);const C=A.rounding??"nearest-even",E=A.scalar_map?.decode?KC(A.scalar_map.decode,Q,g):[],i=A.scalar_map?.encode?KC(A.scalar_map.encode,g,Q):[];return new gQ(g,Q,C,A.out_of_range,E,i)}encode=JI("cast_value");decode(A){const I=A.data,g=new this.#I(I.length);for(let Q=0;Q<I.length;Q++)g[Q]=this.#g(I[Q]);return{data:g,shape:A.shape,stride:A.stride}}}function MC(B,A,I,g,Q){const C=EB(B),E=zB(B),i=EB(A),D=zB(A);let a;if(C&&i){if(I!=="nearest-even")throw new JA(`cast_value float -> float only supports "nearest-even" rounding, got "${I}"`);a=R=>R}else if(C&&!i&&!D){const R=eC(I),t=AQ(..._B[A],g);a=J=>{if(!Number.isFinite(J))throw new Error(`Cannot cast ${J} to integer type without scalar_map`);return t(R(J))}}else if(C&&D){const R=eC(I),t=IQ(...$B[A],g);a=J=>{if(!Number.isFinite(J))throw new Error(`Cannot cast ${J} to integer type without scalar_map`);return t(BigInt(R(J)))}}else if(!C&&!E&&i)a=R=>R;else if(E&&i)a=R=>Number(R);else if(!C&&!E&&!i&&!D)a=AQ(..._B[A],g);else if(!C&&!E&&D){const R=IQ(...$B[A],g);a=t=>R(BigInt(t))}else if(E&&!i&&!D){const R=AQ(..._B[A],g);a=t=>R(Number(t))}else if(E&&D)a=IQ(...$B[A],g);else throw new Error(`Unhandled type combination: ${B} -> ${A}`);return Q.length===0?a:R=>{const t=Yo(R,Q);return t!==void 0?t:a(R)}}class BQ{kind="bytes_to_bytes";static fromConfig(){return new BQ}encode=JI("crc32c");decode(A){return new Uint8Array(A.buffer,A.byteOffset,A.byteLength-4)}computeEncodedSize(A){return A+4}}const Mo=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);function HC(B,A){const I=B.length;let g=I===0||A[I-1]===1;for(let C=I-2;C>=0&&g;C--)g=A[C]===A[C+1]*B[C+1];if(g)return;let Q=I===0||A[0]===1;for(let C=1;C<I&&Q;C++)Q=A[C]===A[C-1]*B[C-1];if(!Q)throw new Error(`DeltaCodec requires C- or Fortran-contiguous strides, got shape=${JSON.stringify(B)} stride=${JSON.stringify(A)}`)}class QQ{kind="array_to_array";#A;constructor(A){this.#A=A}static fromConfig(A,I){if(!Mo.has(I.dataType))throw new JA(`Delta codec does not support data type: ${I.dataType}`);return new QQ(XI(I.dataType))}encode(A){HC(A.shape,A.stride);const I=A.data,g=new this.#A(I.length);g[0]=I[0];for(let Q=1;Q<I.length;Q++)g[Q]=I[Q]-I[Q-1];return{data:g,shape:A.shape,stride:A.stride}}decode(A){HC(A.shape,A.stride);const I=A.data,g=new this.#A(I.length);g[0]=I[0];for(let Q=1;Q<I.length;Q++)g[Q]=g[Q-1]+I[Q];return{data:g,shape:A.shape,stride:A.stride}}}class CQ{kind="bytes_to_bytes";static fromConfig(A){return new CQ}encode=JI("gzip");async decode(A){const I=await cC(A,{format:"gzip"});return new Uint8Array(I)}}function Ho(B,A){return VA(!Number.isNaN(A),"JsonCodec allow_nan is false but NaN was encountered during encoding."),VA(A!==Number.POSITIVE_INFINITY,"JsonCodec allow_nan is false but Infinity was encountered during encoding."),VA(A!==Number.NEGATIVE_INFINITY,"JsonCodec allow_nan is false but -Infinity was encountered during encoding."),A}function qo(B,A){return A instanceof Object&&!Array.isArray(A)?Object.keys(A).sort().reduce((I,g)=>(I[g]=A[g],I),{}):A}class oB{configuration;kind="array_to_bytes";#A;#I;constructor(A={}){this.configuration=A;const{encoding:I="utf-8",skipkeys:g=!1,ensure_ascii:Q=!0,check_circular:C=!0,allow_nan:E=!0,sort_keys:i=!0,indent:D,strict:a=!0}=A;let G=A.separators;G||(D?G=[", ",": "]:G=[",",":"]),this.#A={encoding:I,skipkeys:g,ensure_ascii:Q,check_circular:C,allow_nan:E,indent:D,separators:G,sort_keys:i},this.#I={strict:a}}static fromConfig(A){return new oB(A)}encode(A){const{indent:I,encoding:g,ensure_ascii:Q,check_circular:C,allow_nan:E,sort_keys:i}=this.#A;VA(g==="utf-8","JsonCodec does not yet support non-utf-8 encoding.");const D=[];VA(C,"JsonCodec does not yet support skipping the check for circular references during encoding."),E||D.push(Ho),i&&D.push(qo);const a=Array.from(A.data);a.push("|O"),a.push(A.shape);let G;D.length&&(G=(t,J)=>{let n=J;for(let e of D)n=e(t,n);return n});let R=JSON.stringify(a,G,I);return Q&&(R=R.replace(/[\u007F-\uFFFF]/g,t=>{const J=`0000${t.charCodeAt(0).toString(16)}`;return`\\u${J.substring(J.length-4)}`})),new TextEncoder().encode(R)}decode(A){const{strict:I}=this.#I;VA(I,"JsonCodec does not yet support non-strict decoding.");const g=ng(A),Q=g.pop();g.pop(),VA(Q,"0D not implemented for JsonCodec.");const C=rI(Q,"C");return{data:g,shape:Q,stride:C}}}const fo=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);class EQ{kind="array_to_array";#A;#I;#g;constructor(A,I,g){this.#I=A,this.#g=I,this.#A=g}static fromConfig(A,I){if(!fo.has(I.dataType))throw new JA(`scale_offset codec does not support data type: ${I.dataType}`);return new EQ(iB(I.dataType,A.scale??1),iB(I.dataType,A.offset??0),XI(I.dataType))}encode=JI("scale_offset");decode(A){const I=A.data,g=new this.#A(I.length);for(let Q=0;Q<I.length;Q++)g[Q]=I[Q]/this.#I+this.#g;return{data:g,shape:A.shape,stride:A.stride}}}class iQ{kind="bytes_to_bytes";#A;constructor(A,I){if(I){let g=new(XI(I.dataType))(0);VA("BYTES_PER_ELEMENT"in g,`Shuffle codec requires a fixed-size dtype, got "${I.dataType}"`),this.#A=g.BYTES_PER_ELEMENT}else this.#A=A.elementsize??4}static fromConfig(A,I){return new iQ(A,I)}encode(A){return lo(A,this.#A)}decode(A){return po(A,this.#A)}}function lo(B,A){let I=B.length,g=Math.floor(I/A),Q=new Uint8Array(I);for(let C=0;C<A;C++)for(let E=0;E<g;E++)Q[C*g+E]=B[E*A+C];return Q}function po(B,A){let I=B.length,g=Math.floor(I/A),Q=new Uint8Array(I);for(let C=0;C<A;C++)for(let E=0;E<g;E++)Q[E*A+C]=B[C*g+E];return Q}function qC(B){return B instanceof RC||B instanceof vB||B instanceof rg?new Proxy(B,{get(I,g){return I.get(Number(g))},set(I,g,Q){return I.set(Number(g),Q),!0}}):B}function Wo(B,A){let I;return B.data instanceof vB||B.data instanceof rg?I=new B.constructor(B.data.length,B.data.chars):I=new B.constructor(B.data.length),{data:I,shape:B.shape,stride:rI(B.shape,A)}}function mo(B,A){let I=Wo(B,A),g=B.shape.length,Q=B.data.length,C=Array(g).fill(0),E=qC(B.data),i=qC(I.data);for(let D=0;D<Q;D++){let a=0;for(let G=0;G<g;G++)a+=C[G]*I.stride[G];i[a]=E[D],C[0]+=1;for(let G=0;G<g;G++)if(C[G]===B.shape[G]){if(G+1===g)break;C[G]=0,C[G+1]+=1}}return I}function To(B){let A=B.shape.length;return VA(A===B.stride.length,"Shape and stride must have the same length."),B.stride.map((I,g)=>({stride:I,index:g})).sort((I,g)=>g.stride-I.stride).map(I=>I.index)}function xo(B,A){let I=To(B);return VA(I.length===A.length,"Orders must match"),I.every((g,Q)=>g===A[Q])}class oQ{kind="array_to_array";#A;#I;constructor(A,I){let g=A.order??"C",Q=I.shape.length,C=new Array(Q),E=new Array(Q);if(g==="C")for(let i=0;i<Q;++i)C[i]=i,E[i]=i;else if(g==="F")for(let i=0;i<Q;++i)C[i]=Q-i-1,E[i]=Q-i-1;else C=g,C.forEach((i,D)=>{VA(E[i]===void 0,`Invalid permutation: ${JSON.stringify(g)}`),E[i]=D});this.#A=C,this.#I=E}static fromConfig(A,I){return new oQ(A,I)}encode(A){return xo(A,this.#I)?A:mo(A,this.#I)}decode(A){return{data:A.data,shape:A.shape,stride:rI(A.shape,this.#A)}}}class DB{kind="array_to_bytes";#A;#I;constructor(A){this.#A=A,this.#I=rI(A,"C")}static fromConfig(A,I){return new DB(I.shape)}encode=JI("vlen-utf8");decode(A){let I=new TextDecoder,g=new DataView(A.buffer),Q=Array(g.getUint32(0,!0)),C=4;for(let E=0;E<Q.length;E++){let i=g.getUint32(C,!0);C+=4,Q[E]=I.decode(A.buffer.slice(C,C+i)),C+=i}return{data:Q,shape:this.#A,stride:this.#I}}}class DQ{kind="bytes_to_bytes";static fromConfig(A){return new DQ}encode=JI("zlib");async decode(A){const I=await cC(A,{format:"deflate"});return new Uint8Array(I)}}function Zo(){let B=()=>Promise.resolve().then(()=>la).then(C=>C.default),A=()=>Promise.resolve().then(()=>Za).then(C=>C.default),I=()=>Promise.resolve().then(()=>Xa).then(C=>C.default),g=()=>CQ,Q=()=>DQ;return new Map().set("blosc",B).set("lz4",A).set("zstd",I).set("gzip",g).set("zlib",Q).set("transpose",()=>oQ).set("bytes",()=>CB).set("crc32c",()=>BQ).set("vlen-utf8",()=>DB).set("json2",()=>oB).set("bitround",()=>QB).set("cast_value",()=>gQ).set("scale_offset",()=>EQ).set("numcodecs.blosc",B).set("numcodecs.lz4",A).set("numcodecs.zstd",I).set("numcodecs.gzip",g).set("numcodecs.zlib",Q).set("numcodecs.vlen-utf8",()=>DB).set("numcodecs.shuffle",()=>iQ).set("numcodecs.delta",()=>QQ).set("numcodecs.bitround",()=>QB).set("numcodecs.json2",()=>oB)}const uo=Zo();function aQ(B){let A;function I(){return A||(A=bo(B)),A}async function g(Q,C,E){try{return await E()}catch(i){throw new Ro({direction:Q,codec:C,cause:i})}}return{async encode(Q){let C=await I();for(const{name:i,codec:D}of C.arrayToArray)Q=await g("encode",i,()=>D.encode(Q));let E=await g("encode",C.arrayToBytes.name,()=>C.arrayToBytes.codec.encode(Q));for(const{name:i,codec:D}of C.bytesToBytes)E=await g("encode",i,()=>D.encode(E));return E},async decode(Q){let C=await I();for(let i=C.bytesToBytes.length-1;i>=0;i--){const{name:D,codec:a}=C.bytesToBytes[i];Q=await g("decode",D,()=>a.decode(Q))}let E=await g("decode",C.arrayToBytes.name,()=>C.arrayToBytes.codec.decode(Q));for(let i=C.arrayToArray.length-1;i>=0;i--){const{name:D,codec:a}=C.arrayToArray[i];E=await g("decode",D,()=>a.decode(E))}return E},async computeEncodedSize(Q){let C=await I(),E=dC(C.arrayToBytes.name,C.arrayToBytes.codec,Q);for(const{name:i,codec:D}of C.bytesToBytes)E=dC(i,D,E);return E}}}function dC(B,A,I){if(!A.computeEncodedSize)throw new JA(`Codec "${B}" cannot compute its encoded size; it is not a fixed-size codec and cannot be used in a sharding index pipeline`);return A.computeEncodedSize(I)}async function bo(B){let A=B.codecs.map(async E=>{let i=await uo.get(E.name)?.();if(!i)throw new So(E.name);return{Codec:i,meta:E}}),I=[],g,Q=[],C={...B};for await(let{Codec:E,meta:i}of A){let D=E.fromConfig(i.configuration,C);switch(D.kind){case"array_to_array":I.push({name:i.name,codec:D}),D.getEncodedMeta&&(C=D.getEncodedMeta(C));break;case"array_to_bytes":g={name:i.name,codec:D};break;default:Q.push({name:i.name,codec:D})}}if(!g){if(!Po(C))throw new JA(`Cannot encode ${C.dataType} to bytes without a codec`);g={name:"bytes",codec:CB.fromConfig({endian:"little"},C)}}return{arrayToArray:I,arrayToBytes:g,bytesToBytes:Q}}function Po(B){return B.dataType!=="v2:object"&&B.dataType!=="string"}const fC=18446744073709551615n;function Vo(B,A,I,g){if(!B.store.getRange)throw new OB("sharding requires a store with getRange");let Q=B.store.getRange.bind(B.store),C=A.map((a,G)=>a/g.chunk_shape[G]),E=aQ({dataType:"uint64",shape:[...C,2],codecs:g.index_codecs,fillValue:null}),i=16*C.reduce((a,G)=>a*G,1),D={};return async(a,G)=>{let R=a.map((W,p)=>Math.floor(W/C[p])),t=B.resolve(I(R)).path;t in D||(D[t]=(async()=>{let W=await E.computeEncodedSize(i),p=await Q(t,{suffixLength:W},G);return p?await E.decode(p):null})().catch(W=>{throw delete D[t],W}));let J=await D[t];if(J===null)return;let{data:n,shape:e,stride:K}=J,l=a.map((W,p)=>W%e[p]).reduce((W,p,T)=>W+p*K[T],0),V=n[l],x=n[l+1];if(!(V===fC&&x===fC))return Q(t,{offset:Number(V),length:Number(x)},G)}}class vA{store;path;constructor(A,I="/"){this.store=A,this.path=I}resolve(A){let I=new URL(`file://${this.path.endsWith("/")?this.path:`${this.path}/`}`);return new vA(this.store,decodeURIComponent(new URL(A,I).pathname))}}class sQ extends vA{kind="group";#A;constructor(A,I,g){super(A,I),this.#A=g}get attrs(){return this.#A.attributes}}function lC(B){return B.find(I=>I.name==="transpose")?.configuration?.order??"C"}const aB=Symbol("zarrita.context");function Oo(B,A){let{configuration:I}=A.codecs.find(Jo)??{},g={encodeChunkKey:Uo(A.chunk_key_encoding),TypedArray:XI(A.data_type),fillValue:A.fill_value};if(I){let C=lC(I.codecs);return{...g,kind:"sharded",chunkShape:I.chunk_shape,codec:aQ({dataType:A.data_type,shape:I.chunk_shape,codecs:I.codecs,fillValue:A.fill_value}),getStrides(E){return rI(E,C)},getChunkBytes:Vo(B,A.chunk_grid.configuration.chunk_shape,g.encodeChunkKey,I)}}let Q=lC(A.codecs);return{...g,kind:"regular",chunkShape:A.chunk_grid.configuration.chunk_shape,codec:aQ({dataType:A.data_type,shape:A.chunk_grid.configuration.chunk_shape,codecs:A.codecs,fillValue:A.fill_value}),getStrides(C){return rI(C,Q)},async getChunkBytes(C,E){let i=g.encodeChunkKey(C),D=B.resolve(i).path;return B.store.get(D,E)}}}let sB=class extends vA{kind="array";#A;[aB];constructor(A,I,g){super(A,I),this.#A={...g,fill_value:UC(g)},this[aB]=Oo(this,this.#A)}get attrs(){return this.#A.attributes}get dimensionNames(){return this.#A.dimension_names}get fillValue(){return this.#A.fill_value}get shape(){return this.#A.shape}get chunks(){return this[aB].chunkShape}get dtype(){return this.#A.data_type}async getChunk(A,I,g){g?.useSharedArrayBuffer&&No();let Q=this[aB],C=await Q.getChunkBytes(A,I);if(!C){let E=Q.chunkShape.reduce((D,a)=>D*a,1),i;if(g?.useSharedArrayBuffer){let D=new Q.TypedArray(0);if(!("BYTES_PER_ELEMENT"in D))console.warn("zarrita: useSharedArrayBuffer is not supported for non-buffer-backed data types."),i=new Q.TypedArray(E);else{let a=to(E*D.BYTES_PER_ELEMENT);i=new Q.TypedArray(a,0,E)}}else i=new Q.TypedArray(E);return i.fill(Q.fillValue),{data:i,shape:Q.chunkShape,stride:Q.getStrides(Q.chunkShape)}}return Q.codec.decode(C)}is(A){return jB(this.dtype,A)}};function Xo(B,A){let I=B;for(let g of A)I instanceof Promise?I=I.then(Q=>g(Q)):I=g(I);return I}function vo(B,...A){return Xo(B,A)}async function pC(B){let A=B.store.arrayExtensions;return A?.length?await vo(B,...A):B}let yB=jo();function jo(){let B=new WeakMap;function A(I){let g=B.get(I)??{v2:0,v3:0};return B.set(I,g),g}return{increment(I,g){A(I)[g]+=1},versionMax(I){let g=A(I);return g.v3>g.v2?"v3":"v2"}}}async function zo(B,A){let I=await B.store.get(B.resolve(".zattrs").path,{signal:A});return I?ng(I):{}}async function _o(B,A={}){let I="store"in B?B:new vA(B),{signal:g}=A,Q={};return(A.attrs??!0)&&(Q=await zo(I,g)),g?.throwIfAborted(),A.kind==="array"?WC(I,Q,g):A.kind==="group"?mC(I,Q,g):WC(I,Q,g).catch(C=>(kC(C,OI,JA),mC(I,Q,g)))}async function WC(B,A,I){let{path:g}=B.resolve(".zarray"),Q=await B.store.get(g,{signal:I});if(!Q)throw new OI("v2 array",{path:g});return yB.increment(B.store,"v2"),pC(new sB(B.store,B.path,co(ng(Q),A)))}async function mC(B,A,I){let{path:g}=B.resolve(".zgroup"),Q=await B.store.get(g,{signal:I});if(!Q)throw new OI("v2 group",{path:g});return yB.increment(B.store,"v2"),new sQ(B.store,B.path,Lo(ng(Q),A))}async function $o(B,A){let{store:I,path:g}=B.resolve("zarr.json"),Q=await B.store.get(g,{signal:A});if(!Q)throw new OI("v3 array or group",{path:g});let C=ng(Q);return C.node_type==="array"&&(C.fill_value=UC(C)),C.node_type==="array"?pC(new sB(I,B.path,C)):new sQ(I,B.path,C)}async function AD(B,A={}){let I="store"in B?B:new vA(B),g=await $o(I,A.signal);if(yB.increment(I.store,"v3"),A.kind===void 0||A.kind==="array"&&g instanceof sB||A.kind==="group"&&g instanceof sQ)return g;let Q=g instanceof sB?"array":"group";throw new OI(`${A.kind} at ${I.path}`,{path:I.path,found:Q})}async function jA(B,A={}){let I="store"in B?B.store:B,g=yB.versionMax(I),Q=g==="v2"?jA.v2:jA.v3,C=g==="v2"?jA.v3:jA.v2;return Q(B,A).catch(E=>(kC(E,OI,JA),C(B,A)))}jA.v2=_o,jA.v3=AD;async function ID(B,A){const I=A.split("/"),g=I.pop();if(!g)throw new Error("Invalid path");for(const Q of I)B=await B.getDirectoryHandle(Q);return B.getFileHandle(g)}class yQ{#A;constructor(A){this.#A=A}get directoryHandle(){return this.#A}async get(A){const I=await ID(this.#A,A.slice(1)).catch(()=>{});if(!I)return;const Q=await(await I.getFile()).arrayBuffer();return new Uint8Array(Q)}}async function Yg(B,A){if(A==="v2")try{return jA.v2(B,{kind:"group",attrs:!0})}catch{throw new Error(`Failed to open Zarr v2 group at ${B}`)}if(A==="v3")try{return jA.v3(B,{kind:"group"})}catch{throw new Error(`Failed to open Zarr v3 group at ${B}`)}try{return jA(B,{kind:"group"})}catch{throw new Error(`Failed to open Zarr group at ${B}`)}}async function gD(B,A){if(A==="v2")try{return jA.v2(B,{kind:"array",attrs:!1})}catch{throw new Error(`Failed to open Zarr v2 array at ${B}`)}if(A==="v3")try{return jA.v3(B,{kind:"array"})}catch{throw new Error(`Failed to open Zarr v3 array at ${B}`)}try{return jA(B,{kind:"array"})}catch{throw new Error(`Failed to open Zarr array at ${B}`)}}async function BD(B){let A;switch(B.type){case"fetch":{const g=new Lg(B.url);A=new vA(g);break}case"filesystem":{A=new vA(new yQ(B.directoryHandle),B.path);break}default:{const g=B;throw new Error(`Unsupported store type: ${g}`)}}const I=B.arrayPath?A.resolve(B.arrayPath):A;return gD(I,B.zarrVersion)}function QD(B,A,I){if(B.store instanceof Lg)return{type:"fetch",arrayPath:A,zarrVersion:I,url:B.store.url.toString()};if(B.store instanceof yQ)return{type:"filesystem",arrayPath:A,zarrVersion:I,directoryHandle:B.store.directoryHandle,path:B.path};throw new Error(`Unsupported store type: ${B.store.constructor.name}`)}function CD(B,A,I,g){return ED(B,A,I,g)}function ED(B,A,I,g){const{targetShape:Q,chunkIndex:C,dimIndices:E}=g;let i=1;for(let p=A.length-1;p>=0;p--){if(I[p]!==i)throw new Error(`Chunk data is not tightly packed, stride=${JSON.stringify(I)}, shape=${JSON.stringify(A)}`);i*=A[p]}const D={x:A[E.x],y:A[E.y],z:E.z!==void 0?A[E.z]:Q.z};if(D.x<Q.x||D.y<Q.y||D.z<Q.z)throw new Error(`Received chunk too small: expected ${JSON.stringify(Q)}, got ${JSON.stringify(D)}`);const a=g.cChunkSize?C.c%g.cChunkSize:0,G=g.tChunkSize?C.t%g.tChunkSize:0,R=Q.x*Q.y*Q.z,t=E.c!==void 0?I[E.c]:0,J=E.t!==void 0?I[E.t]:0,n=G*J+a*t,e=D.x===Q.x&&D.y===Q.y&&D.z===Q.z;if(n===0&&B.length===R&&e)return B;const l=new B.constructor(R),V=E.z!==void 0?I[E.z]:0,x=I[E.y];let W=0;for(let p=0;p<Q.z;p++){const T=n+p*V;for(let $=0;$<Q.y;$++){const CA=T+$*x,BA=CA+Q.x;l.set(B.subarray(CA,BA),W),W+=Q.x}}return l}const TC=`function xg(B, A) {
465
+ ${Q}`;return B.replace(LB,C)}const Tg={};function xQ(B){const A=B??"";return Tg[A]=(Tg[A]??0)+1,B?`${B}-${Tg[A]}`:String(Tg[A])}class xg{id=xQ()}var FA=1e-6,eA=typeof Float32Array<"u"?Float32Array:Array,uE=Math.PI/180;function bE(B){return B*uE}function ZQ(){var B=new eA(9);return eA!=Float32Array&&(B[1]=0,B[2]=0,B[3]=0,B[5]=0,B[6]=0,B[7]=0),B[0]=1,B[4]=1,B[8]=1,B}function PE(B,A){return B[0]=A[0],B[1]=A[1],B[2]=A[2],B[3]=A[4],B[4]=A[5],B[5]=A[6],B[6]=A[8],B[7]=A[9],B[8]=A[10],B}function VE(B,A,I,g,Q,C,E,i,D){var a=new eA(9);return a[0]=B,a[1]=A,a[2]=I,a[3]=g,a[4]=Q,a[5]=C,a[6]=E,a[7]=i,a[8]=D,a}function WA(){var B=new eA(16);return eA!=Float32Array&&(B[1]=0,B[2]=0,B[3]=0,B[4]=0,B[6]=0,B[7]=0,B[8]=0,B[9]=0,B[11]=0,B[12]=0,B[13]=0,B[14]=0),B[0]=1,B[5]=1,B[10]=1,B[15]=1,B}function Sg(B,A){var I=A[0],g=A[1],Q=A[2],C=A[3],E=A[4],i=A[5],D=A[6],a=A[7],G=A[8],R=A[9],t=A[10],J=A[11],n=A[12],e=A[13],K=A[14],l=A[15],V=I*i-g*E,x=I*D-Q*E,W=I*a-C*E,p=g*D-Q*i,T=g*a-C*i,$=Q*a-C*D,CA=G*e-R*n,BA=G*K-t*n,iA=G*l-J*n,sA=R*K-t*e,qA=R*l-J*e,kA=t*l-J*K,aA=V*kA-x*qA+W*sA+p*iA-T*BA+$*CA;return aA?(aA=1/aA,B[0]=(i*kA-D*qA+a*sA)*aA,B[1]=(Q*qA-g*kA-C*sA)*aA,B[2]=(e*$-K*T+l*p)*aA,B[3]=(t*T-R*$-J*p)*aA,B[4]=(D*iA-E*kA-a*BA)*aA,B[5]=(I*kA-Q*iA+C*BA)*aA,B[6]=(K*W-n*$-l*x)*aA,B[7]=(G*$-t*W+J*x)*aA,B[8]=(E*qA-i*iA+a*CA)*aA,B[9]=(g*iA-I*qA-C*CA)*aA,B[10]=(n*T-e*W+l*V)*aA,B[11]=(R*W-G*T-J*V)*aA,B[12]=(i*BA-E*sA-D*CA)*aA,B[13]=(I*sA-g*BA+Q*CA)*aA,B[14]=(e*x-n*p-K*V)*aA,B[15]=(G*p-R*x+t*V)*aA,B):null}function Zg(B,A,I){var g=A[0],Q=A[1],C=A[2],E=A[3],i=A[4],D=A[5],a=A[6],G=A[7],R=A[8],t=A[9],J=A[10],n=A[11],e=A[12],K=A[13],l=A[14],V=A[15],x=I[0],W=I[1],p=I[2],T=I[3];return B[0]=x*g+W*i+p*R+T*e,B[1]=x*Q+W*D+p*t+T*K,B[2]=x*C+W*a+p*J+T*l,B[3]=x*E+W*G+p*n+T*V,x=I[4],W=I[5],p=I[6],T=I[7],B[4]=x*g+W*i+p*R+T*e,B[5]=x*Q+W*D+p*t+T*K,B[6]=x*C+W*a+p*J+T*l,B[7]=x*E+W*G+p*n+T*V,x=I[8],W=I[9],p=I[10],T=I[11],B[8]=x*g+W*i+p*R+T*e,B[9]=x*Q+W*D+p*t+T*K,B[10]=x*C+W*a+p*J+T*l,B[11]=x*E+W*G+p*n+T*V,x=I[12],W=I[13],p=I[14],T=I[15],B[12]=x*g+W*i+p*R+T*e,B[13]=x*Q+W*D+p*t+T*K,B[14]=x*C+W*a+p*J+T*l,B[15]=x*E+W*G+p*n+T*V,B}function OE(B,A,I){var g=I[0],Q=I[1],C=I[2],E,i,D,a,G,R,t,J,n,e,K,l;return A===B?(B[12]=A[0]*g+A[4]*Q+A[8]*C+A[12],B[13]=A[1]*g+A[5]*Q+A[9]*C+A[13],B[14]=A[2]*g+A[6]*Q+A[10]*C+A[14],B[15]=A[3]*g+A[7]*Q+A[11]*C+A[15]):(E=A[0],i=A[1],D=A[2],a=A[3],G=A[4],R=A[5],t=A[6],J=A[7],n=A[8],e=A[9],K=A[10],l=A[11],B[0]=E,B[1]=i,B[2]=D,B[3]=a,B[4]=G,B[5]=R,B[6]=t,B[7]=J,B[8]=n,B[9]=e,B[10]=K,B[11]=l,B[12]=E*g+G*Q+n*C+A[12],B[13]=i*g+R*Q+e*C+A[13],B[14]=D*g+t*Q+K*C+A[14],B[15]=a*g+J*Q+l*C+A[15]),B}function uQ(B,A){return B[0]=A[0],B[1]=0,B[2]=0,B[3]=0,B[4]=0,B[5]=A[1],B[6]=0,B[7]=0,B[8]=0,B[9]=0,B[10]=A[2],B[11]=0,B[12]=0,B[13]=0,B[14]=0,B[15]=1,B}function XE(B,A,I,g){var Q=A[0],C=A[1],E=A[2],i=A[3],D=Q+Q,a=C+C,G=E+E,R=Q*D,t=Q*a,J=Q*G,n=C*a,e=C*G,K=E*G,l=i*D,V=i*a,x=i*G,W=g[0],p=g[1],T=g[2];return B[0]=(1-(n+K))*W,B[1]=(t+x)*W,B[2]=(J-V)*W,B[3]=0,B[4]=(t-x)*p,B[5]=(1-(R+K))*p,B[6]=(e+l)*p,B[7]=0,B[8]=(J+V)*T,B[9]=(e-l)*T,B[10]=(1-(R+n))*T,B[11]=0,B[12]=I[0],B[13]=I[1],B[14]=I[2],B[15]=1,B}function vE(B,A,I,g,Q){var C=1/Math.tan(A/2);if(B[0]=C/I,B[1]=0,B[2]=0,B[3]=0,B[4]=0,B[5]=C,B[6]=0,B[7]=0,B[8]=0,B[9]=0,B[11]=-1,B[12]=0,B[13]=0,B[15]=0,Q!=null&&Q!==1/0){var E=1/(g-Q);B[10]=(Q+g)*E,B[14]=2*Q*g*E}else B[10]=-1,B[14]=-2*g;return B}var jE=vE;function zE(B,A,I,g,Q,C,E){var i=1/(A-I),D=1/(g-Q),a=1/(C-E);return B[0]=-2*i,B[1]=0,B[2]=0,B[3]=0,B[4]=0,B[5]=-2*D,B[6]=0,B[7]=0,B[8]=0,B[9]=0,B[10]=2*a,B[11]=0,B[12]=(A+I)*i,B[13]=(Q+g)*D,B[14]=(E+C)*a,B[15]=1,B}var _E=zE;function $E(B,A,I,g){var Q=A[0],C=A[1],E=A[2],i=g[0],D=g[1],a=g[2],G=Q-I[0],R=C-I[1],t=E-I[2],J=G*G+R*R+t*t;J>0&&(J=1/Math.sqrt(J),G*=J,R*=J,t*=J);var n=D*t-a*R,e=a*G-i*t,K=i*R-D*G;return J=n*n+e*e+K*K,J>0&&(J=1/Math.sqrt(J),n*=J,e*=J,K*=J),B[0]=n,B[1]=e,B[2]=K,B[3]=0,B[4]=R*K-t*e,B[5]=t*n-G*K,B[6]=G*e-R*n,B[7]=0,B[8]=G,B[9]=R,B[10]=t,B[11]=0,B[12]=Q,B[13]=C,B[14]=E,B[15]=1,B}function Ai(B,A){var I=B[0],g=B[1],Q=B[2],C=B[3],E=B[4],i=B[5],D=B[6],a=B[7],G=B[8],R=B[9],t=B[10],J=B[11],n=B[12],e=B[13],K=B[14],l=B[15],V=A[0],x=A[1],W=A[2],p=A[3],T=A[4],$=A[5],CA=A[6],BA=A[7],iA=A[8],sA=A[9],qA=A[10],kA=A[11],aA=A[12],oI=A[13],II=A[14],DI=A[15];return Math.abs(I-V)<=FA*Math.max(1,Math.abs(I),Math.abs(V))&&Math.abs(g-x)<=FA*Math.max(1,Math.abs(g),Math.abs(x))&&Math.abs(Q-W)<=FA*Math.max(1,Math.abs(Q),Math.abs(W))&&Math.abs(C-p)<=FA*Math.max(1,Math.abs(C),Math.abs(p))&&Math.abs(E-T)<=FA*Math.max(1,Math.abs(E),Math.abs(T))&&Math.abs(i-$)<=FA*Math.max(1,Math.abs(i),Math.abs($))&&Math.abs(D-CA)<=FA*Math.max(1,Math.abs(D),Math.abs(CA))&&Math.abs(a-BA)<=FA*Math.max(1,Math.abs(a),Math.abs(BA))&&Math.abs(G-iA)<=FA*Math.max(1,Math.abs(G),Math.abs(iA))&&Math.abs(R-sA)<=FA*Math.max(1,Math.abs(R),Math.abs(sA))&&Math.abs(t-qA)<=FA*Math.max(1,Math.abs(t),Math.abs(qA))&&Math.abs(J-kA)<=FA*Math.max(1,Math.abs(J),Math.abs(kA))&&Math.abs(n-aA)<=FA*Math.max(1,Math.abs(n),Math.abs(aA))&&Math.abs(e-oI)<=FA*Math.max(1,Math.abs(e),Math.abs(oI))&&Math.abs(K-II)<=FA*Math.max(1,Math.abs(K),Math.abs(II))&&Math.abs(l-DI)<=FA*Math.max(1,Math.abs(l),Math.abs(DI))}function AA(){var B=new eA(3);return eA!=Float32Array&&(B[0]=0,B[1]=0,B[2]=0),B}function $A(B){var A=new eA(3);return A[0]=B[0],A[1]=B[1],A[2]=B[2],A}function JB(B){var A=B[0],I=B[1],g=B[2];return Math.sqrt(A*A+I*I+g*g)}function wA(B,A,I){var g=new eA(3);return g[0]=B,g[1]=A,g[2]=I,g}function rB(B,A){return B[0]=A[0],B[1]=A[1],B[2]=A[2],B}function LI(B,A,I,g){return B[0]=A,B[1]=I,B[2]=g,B}function ug(B,A,I){return B[0]=A[0]+I[0],B[1]=A[1]+I[1],B[2]=A[2]+I[2],B}function nB(B,A,I){return B[0]=A[0]-I[0],B[1]=A[1]-I[1],B[2]=A[2]-I[2],B}function Ii(B,A,I){return B[0]=A[0]*I[0],B[1]=A[1]*I[1],B[2]=A[2]*I[2],B}function YB(B,A,I){return B[0]=A[0]*I,B[1]=A[1]*I,B[2]=A[2]*I,B}function KB(B,A,I,g){return B[0]=A[0]+I[0]*g,B[1]=A[1]+I[1]*g,B[2]=A[2]+I[2]*g,B}function gi(B,A){var I=A[0]-B[0],g=A[1]-B[1],Q=A[2]-B[2];return I*I+g*g+Q*Q}function bQ(B,A){var I=A[0],g=A[1],Q=A[2],C=I*I+g*g+Q*Q;return C>0&&(C=1/Math.sqrt(C)),B[0]=A[0]*C,B[1]=A[1]*C,B[2]=A[2]*C,B}function bg(B,A){return B[0]*A[0]+B[1]*A[1]+B[2]*A[2]}function Pg(B,A,I){var g=A[0],Q=A[1],C=A[2],E=I[0],i=I[1],D=I[2];return B[0]=Q*D-C*i,B[1]=C*E-g*D,B[2]=g*i-Q*E,B}function eB(B,A,I){var g=A[0],Q=A[1],C=A[2],E=I[3]*g+I[7]*Q+I[11]*C+I[15];return E=E||1,B[0]=(I[0]*g+I[4]*Q+I[8]*C+I[12])/E,B[1]=(I[1]*g+I[5]*Q+I[9]*C+I[13])/E,B[2]=(I[2]*g+I[6]*Q+I[10]*C+I[14])/E,B}function PQ(B,A,I){var g=I[0],Q=I[1],C=I[2],E=I[3],i=A[0],D=A[1],a=A[2],G=Q*a-C*D,R=C*i-g*a,t=g*D-Q*i;return G=G+G,R=R+R,t=t+t,B[0]=i+E*G+Q*t-C*R,B[1]=D+E*R+C*G-g*t,B[2]=a+E*t+g*R-Q*G,B}function Bi(B){return B[0]=0,B[1]=0,B[2]=0,B}function MB(B,A){var I=B[0],g=B[1],Q=B[2],C=A[0],E=A[1],i=A[2];return Math.abs(I-C)<=FA*Math.max(1,Math.abs(I),Math.abs(C))&&Math.abs(g-E)<=FA*Math.max(1,Math.abs(g),Math.abs(E))&&Math.abs(Q-i)<=FA*Math.max(1,Math.abs(Q),Math.abs(i))}var HB=nB,Qi=JB;(function(){var B=AA();return function(A,I,g,Q,C,E){var i,D;for(I||(I=3),g||(g=0),Q?D=Math.min(Q*I+g,A.length):D=A.length,i=g;i<D;i+=I)B[0]=A[i],B[1]=A[i+1],B[2]=A[i+2],C(B,B,E),A[i]=B[0],A[i+1]=B[1],A[i+2]=B[2];return A}})();function xI(){var B=new eA(4);return eA!=Float32Array&&(B[0]=0,B[1]=0,B[2]=0,B[3]=0),B}function Ci(B){var A=new eA(4);return A[0]=B[0],A[1]=B[1],A[2]=B[2],A[3]=B[3],A}function Vg(B,A,I,g){var Q=new eA(4);return Q[0]=B,Q[1]=A,Q[2]=I,Q[3]=g,Q}function Ei(B,A){return B[0]=A[0],B[1]=A[1],B[2]=A[2],B[3]=A[3],B}function ii(B,A,I){return B[0]=A[0]*I,B[1]=A[1]*I,B[2]=A[2]*I,B[3]=A[3]*I,B}function oi(B,A){var I=A[0],g=A[1],Q=A[2],C=A[3],E=I*I+g*g+Q*Q+C*C;return E>0&&(E=1/Math.sqrt(E)),B[0]=I*E,B[1]=g*E,B[2]=Q*E,B[3]=C*E,B}function Rg(B,A,I){var g=A[0],Q=A[1],C=A[2],E=A[3];return B[0]=I[0]*g+I[4]*Q+I[8]*C+I[12]*E,B[1]=I[1]*g+I[5]*Q+I[9]*C+I[13]*E,B[2]=I[2]*g+I[6]*Q+I[10]*C+I[14]*E,B[3]=I[3]*g+I[7]*Q+I[11]*C+I[15]*E,B}(function(){var B=xI();return function(A,I,g,Q,C,E){var i,D;for(I||(I=4),g||(g=0),Q?D=Math.min(Q*I+g,A.length):D=A.length,i=g;i<D;i+=I)B[0]=A[i],B[1]=A[i+1],B[2]=A[i+2],B[3]=A[i+3],C(B,B,E),A[i]=B[0],A[i+1]=B[1],A[i+2]=B[2],A[i+3]=B[3];return A}})();function Og(){var B=new eA(4);return eA!=Float32Array&&(B[0]=0,B[1]=0,B[2]=0),B[3]=1,B}function Di(B,A,I){I=I*.5;var g=Math.sin(I);return B[0]=g*A[0],B[1]=g*A[1],B[2]=g*A[2],B[3]=Math.cos(I),B}function ai(B,A,I){var g=A[0],Q=A[1],C=A[2],E=A[3],i=I[0],D=I[1],a=I[2],G=I[3];return B[0]=g*G+E*i+Q*a-C*D,B[1]=Q*G+E*D+C*i-g*a,B[2]=C*G+E*a+g*D-Q*i,B[3]=E*G-g*i-Q*D-C*a,B}function qB(B,A,I,g){var Q=A[0],C=A[1],E=A[2],i=A[3],D=I[0],a=I[1],G=I[2],R=I[3],t,J,n,e,K;return J=Q*D+C*a+E*G+i*R,J<0&&(J=-J,D=-D,a=-a,G=-G,R=-R),1-J>FA?(t=Math.acos(J),n=Math.sin(t),e=Math.sin((1-g)*t)/n,K=Math.sin(g*t)/n):(e=1-g,K=g),B[0]=e*Q+K*D,B[1]=e*C+K*a,B[2]=e*E+K*G,B[3]=e*i+K*R,B}function dB(B,A){var I=A[0]+A[4]+A[8],g;if(I>0)g=Math.sqrt(I+1),B[3]=.5*g,g=.5/g,B[0]=(A[5]-A[7])*g,B[1]=(A[6]-A[2])*g,B[2]=(A[1]-A[3])*g;else{var Q=0;A[4]>A[0]&&(Q=1),A[8]>A[Q*3+Q]&&(Q=2);var C=(Q+1)%3,E=(Q+2)%3;g=Math.sqrt(A[Q*3+Q]-A[C*3+C]-A[E*3+E]+1),B[Q]=.5*g,g=.5/g,B[3]=(A[C*3+E]-A[E*3+C])*g,B[C]=(A[C*3+Q]+A[Q*3+C])*g,B[E]=(A[E*3+Q]+A[Q*3+E])*g}return B}var si=Ci,yi=Ei,Xg=oi;(function(){var B=AA(),A=wA(1,0,0),I=wA(0,1,0);return function(g,Q,C){var E=bg(Q,C);return E<-.999999?(Pg(B,A,Q),Qi(B)<1e-6&&Pg(B,I,Q),bQ(B,B),Di(g,B,Math.PI),g):E>.999999?(g[0]=0,g[1]=0,g[2]=0,g[3]=1,g):(Pg(B,Q,C),g[0]=B[0],g[1]=B[1],g[2]=B[2],g[3]=1+E,Xg(g,g))}})(),(function(){var B=Og(),A=Og();return function(I,g,Q,C,E,i){return qB(B,g,E,i),qB(A,Q,C,i),qB(I,B,A,2*i*(1-i)),I}})(),(function(){var B=ZQ();return function(A,I,g,Q){return B[0]=g[0],B[3]=g[1],B[6]=g[2],B[1]=Q[0],B[4]=Q[1],B[7]=Q[2],B[2]=-I[0],B[5]=-I[1],B[8]=-I[2],Xg(A,dB(A,B))}})();function VQ(){var B=new eA(2);return eA!=Float32Array&&(B[0]=0,B[1]=0),B}function OQ(B){var A=new eA(2);return A[0]=B[0],A[1]=B[1],A}function LA(B,A){var I=new eA(2);return I[0]=B,I[1]=A,I}function hi(B,A){var I=A[0]-B[0],g=A[1]-B[1];return Math.sqrt(I*I+g*g)}function Gi(B){var A=B[0],I=B[1];return A*A+I*I}function Fi(B,A,I,g){var Q=A[0],C=A[1];return B[0]=Q+g*(I[0]-Q),B[1]=C+g*(I[1]-C),B}function XQ(B,A){return B[0]===A[0]&&B[1]===A[1]}function vQ(B,A){var I=B[0],g=B[1],Q=A[0],C=A[1];return Math.abs(I-Q)<=FA*Math.max(1,Math.abs(I),Math.abs(Q))&&Math.abs(g-C)<=FA*Math.max(1,Math.abs(g),Math.abs(C))}(function(){var B=VQ();return function(A,I,g,Q,C,E){var i,D;for(I||(I=2),g||(g=0),Q?D=Math.min(Q*I+g,A.length):D=A.length,i=g;i<D;i+=I)B[0]=A[i],B[1]=A[i+1],C(B,B,E),A[i]=B[0],A[i+1]=B[1];return A}})();class ZI{min;max;constructor(A,I){this.min=A?$A(A):wA(1/0,1/0,1/0),this.max=I?$A(I):wA(-1/0,-1/0,-1/0)}clone(){return new ZI(this.min,this.max)}isEmpty(){return this.max[0]<=this.min[0]||this.max[1]<=this.min[1]||this.max[2]<=this.min[2]}static intersects(A,I){return!(A.max[0]<=I.min[0]||A.min[0]>=I.max[0]||A.max[1]<=I.min[1]||A.min[1]>=I.max[1]||A.max[2]<=I.min[2]||A.min[2]>=I.max[2])}expandWithPoint(A){A[0]<this.min[0]&&(this.min[0]=A[0]),A[1]<this.min[1]&&(this.min[1]=A[1]),A[2]<this.min[2]&&(this.min[2]=A[2]),A[0]>this.max[0]&&(this.max[0]=A[0]),A[1]>this.max[1]&&(this.max[1]=A[1]),A[2]>this.max[2]&&(this.max[2]=A[2])}applyTransform(A){const{min:I,max:g}=this,Q=[wA(I[0],I[1],I[2]),wA(I[0],I[1],g[2]),wA(I[0],g[1],I[2]),wA(I[0],g[1],g[2]),wA(g[0],I[1],I[2]),wA(g[0],I[1],g[2]),wA(g[0],g[1],I[2]),wA(g[0],g[1],g[2])];this.min=wA(1/0,1/0,1/0),this.max=wA(-1/0,-1/0,-1/0);const C=AA();for(const E of Q)eB(C,E,A),this.expandWithPoint(C)}}const wi={position:0,normal:1,uv:2,next_position:3,previous_position:4,direction:5,color:6,size:7,marker:8};class uI extends xg{instanceCount=null;boundingBox_=null;primitive_;attributes_;vertexData_;indexData_;constructor(A=[],I=[],g="triangles"){super(),this.vertexData_=new Float32Array(A),this.indexData_=new Uint32Array(I),this.primitive_=g,this.attributes_=[]}addAttribute(A){this.attributes_.push(A),this.boundingBox_=null}get vertexCount(){return this.vertexData_.byteLength/this.strideBytes}get stride(){return this.attributes_.reduce((A,I)=>A+I.itemSize,0)}get strideBytes(){return this.stride*Float32Array.BYTES_PER_ELEMENT}get primitive(){return this.primitive_}get vertexData(){return this.vertexData_}get indexData(){return this.indexData_}get attributes(){return this.attributes_}get boundingBox(){if(this.boundingBox_===null){const A=this.getAttribute("position");if(!A||this.vertexCount===0)throw new Error("Failed to generate bounding box");const I=(A.offset??0)/Float32Array.BYTES_PER_ELEMENT,g=new ZI,Q=AA();for(let C=0;C<this.vertexData_.length;C+=this.stride)Q[0]=this.vertexData_[C+I+0],Q[1]=this.vertexData_[C+I+1],Q[2]=this.vertexData_[C+I+2],g.expandWithPoint(Q);this.boundingBox_=g}return this.boundingBox_}get type(){return"Geometry"}getAttribute(A){return this.attributes_.find(I=>I.type===A)}}class Si{gl_;buffers_=new Map;currentGeometry_=null;constructor(A){this.gl_=A}bindGeometry(A){if(this.alreadyActive(A))return;this.buffers_.has(A)||this.generateBuffers(A);const I=this.buffers_.get(A);if(!I)throw new Error("Failed to retrieve buffer handles for object");this.gl_.bindVertexArray(I.vao),this.currentGeometry_=A}disposeObject(A){const I=this.buffers_.get(A);I&&(this.gl_.deleteVertexArray(I.vao),this.gl_.deleteBuffer(I.vbo),I.ebo&&this.gl_.deleteBuffer(I.ebo),this.buffers_.delete(A),this.currentGeometry_===A&&(this.currentGeometry_=null))}disposeAll(){for(const A of this.buffers_.keys())this.disposeObject(A)}alreadyActive(A){return this.currentGeometry_===A}generateBuffers(A){const I=this.gl_.createVertexArray();if(!I)throw new Error("Failed to create vertex array object (VAO)");this.gl_.bindVertexArray(I);const{vertexData:g}=A,Q=this.gl_.ARRAY_BUFFER,C=this.gl_.createBuffer();if(!C)throw new Error("Failed to create vertex buffer (VBO)");this.gl_.bindBuffer(Q,C),this.gl_.bufferData(Q,g,this.gl_.STATIC_DRAW);const{attributes:E,strideBytes:i}=A;E.forEach(G=>{const R=wi[G.type];this.gl_.vertexAttribPointer(R,G.itemSize,this.gl_.FLOAT,!1,i,G.offset),this.gl_.enableVertexAttribArray(R)});const D={vao:I,vbo:C},{indexData:a}=A;if(a.length){const G=this.gl_.ELEMENT_ARRAY_BUFFER,R=this.gl_.createBuffer();if(!R)throw new Error("Failed to create index buffer (EBO)");this.gl_.bindBuffer(G,R),this.gl_.bufferData(G,a,this.gl_.STATIC_DRAW),D.ebo=R}this.buffers_.set(A,D),this.gl_.bindVertexArray(null)}}function Ri(B){return B===1||B===2||B===4||B===8}function fB(B){if(B instanceof Int8Array)return"byte";if(B instanceof Int16Array)return"short";if(B instanceof Int32Array)return"int";if(B instanceof Uint8Array)return"unsigned_byte";if(B instanceof Uint16Array)return"unsigned_short";if(B instanceof Uint32Array)return"unsigned_int";if(B instanceof Float32Array)return"float";throw new Error("Unsupported buffer type.")}function Ni(B){switch(B.dataFormat){case"scalar":return 1;case"rgb":return 3;case"rgba":return 4}}function ti(B){switch(B.dataType){case"byte":case"unsigned_byte":return 1;case"short":case"unsigned_short":return 2;case"int":case"unsigned_int":case"float":return 4}}function lB(B){const A=Ni(B)*ti(B),I=Math.max(1,B.mipmapLevels);let g=Math.max(1,B.width),Q=Math.max(1,B.height),C=Math.max(1,B.depth),E=0;for(let i=0;i<I;++i)E+=A*C*g*Q,g=Math.max(1,g>>1),Q=Math.max(1,Q>>1),B.type==="Texture3D"&&(C=Math.max(1,C>>1));return E}function Ui(B){if(B.dataFormat==="rgb"||B.dataFormat==="rgba")return[0,1];switch(B.dataType){case"byte":return[-128,127];case"short":return[-32768,32767];case"int":return[-2147483648,2147483647];case"unsigned_byte":return[0,255];case"unsigned_short":return[0,65535];case"unsigned_int":return[0,4294967295];case"float":return[0,1]}}class pB extends xg{dataFormat="rgba";dataType="unsigned_byte";maxFilter="nearest";minFilter="nearest";mipmapLevels=1;unpackAlignment=4;wrapR="clamp_to_edge";wrapS="clamp_to_edge";wrapT="clamp_to_edge";needsUpdate=!0;readTexel;data_=null;get data(){return this.data_}set data(A){this.data_=A,this.needsUpdate=!0}releaseCpuData(){this.data_=null}get depth(){return 1}get type(){return"Texture"}}class ki{gl_;textures_=new Map;currentTexture_=null;maxTextureUnits_;nextPersistentUnit_;gpuTextureBytes_=0;textureCount_=0;readFramebuffer_=null;constructor(A){this.gl_=A,this.maxTextureUnits_=A.getParameter(A.MAX_TEXTURE_IMAGE_UNITS),this.nextPersistentUnit_=this.maxTextureUnits_-1}get gpuTextureBytes(){return this.gpuTextureBytes_}get textureCount(){return this.textureCount_}reservePersistentUnit(){if(this.nextPersistentUnit_<0)throw new Error(`No texture units left to reserve (${this.maxTextureUnits_} total)`);return this.nextPersistentUnit_--}bindTexture(A,I){if(this.alreadyActive(A))return;if(I<0||I>this.nextPersistentUnit_)throw new Error(`Texture index ${I} must be in [0, ${this.nextPersistentUnit_}]; units above that are reserved`);const g=this.textures_.get(A);g&&!A.needsUpdate?(this.gl_.activeTexture(this.gl_.TEXTURE0+I),this.gl_.bindTexture(this.getTextureType(A),g)):this.uploadTexture(A,I),this.currentTexture_=A}readTexel(A,I,g,Q){const C=this.gl_,E=this.textures_.get(A);if(!E)throw new Error("readTexel called on a texture that is not resident");this.readFramebuffer_??=C.createFramebuffer(),C.bindFramebuffer(C.READ_FRAMEBUFFER,this.readFramebuffer_),C.framebufferTextureLayer(C.READ_FRAMEBUFFER,C.COLOR_ATTACHMENT0,E,0,Q);const{format:i,type:D,out:a}=this.readbackParams(A.dataType);return C.readPixels(I,g,1,1,i,D,a),C.bindFramebuffer(C.READ_FRAMEBUFFER,null),a[0]}readbackParams(A){const I=this.gl_;switch(A){case"byte":case"short":case"int":return{format:I.RGBA_INTEGER,type:I.INT,out:new Int32Array(4)};case"unsigned_byte":case"unsigned_short":case"unsigned_int":return{format:I.RGBA_INTEGER,type:I.UNSIGNED_INT,out:new Uint32Array(4)};case"float":return{format:I.RGBA,type:I.FLOAT,out:new Float32Array(4)}}}uploadTexture(A,I=0){if(this.textures_.has(A)&&!A.needsUpdate)return;if(A.data===null)throw new Error("Cannot upload a texture that has no CPU data");const g=this.getTextureType(A),Q=this.getDataFormatInfo(A.dataFormat,A.dataType);this.gl_.activeTexture(this.gl_.TEXTURE0+I),this.textures_.has(A)||this.generateTexture(A,Q,g);const C=this.textures_.get(A);if(!C)throw new Error("Failed to retrieve texture ID");this.gl_.bindTexture(g,C),this.configureTextureParameters(A,g),this.uploadTextureData(A,Q,g),this.currentTexture_=null,A.needsUpdate=!1}dispose(A){const I=this.textures_.get(A);if(I){this.gl_.deleteTexture(I),this.textures_.delete(A),A.readTexel=void 0,this.currentTexture_===A&&(this.currentTexture_=null);const g=lB(A);this.gpuTextureBytes_=Math.max(0,this.gpuTextureBytes_-g),this.textureCount_=Math.max(0,this.textureCount_-1)}}disposeAll(){for(const A of Array.from(this.textures_.keys()))this.dispose(A);this.gpuTextureBytes_=0,this.textureCount_=0}alreadyActive(A){return this.currentTexture_===A&&!A.needsUpdate}generateTexture(A,I,g){const Q=this.gl_.createTexture();if(!Q)throw new Error("Failed to create texture");if(this.gl_.bindTexture(g,Q),this.isTexture2D(A))this.gl_.texStorage2D(g,A.mipmapLevels,I.internalFormat,A.width,A.height);else if(this.isTextureStorage3D(A))this.gl_.texStorage3D(g,A.mipmapLevels,I.internalFormat,A.width,A.height,A.depth);else throw new Error(`Unknown texture type ${A.type}`);this.gpuTextureBytes_+=lB(A),this.textureCount_+=1,this.textures_.set(A,Q),this.gl_.bindTexture(g,null),A.readTexel=(C,E,i)=>Promise.resolve(this.readTexel(A,C,E,i))}configureTextureParameters(A,I){const g=this.gl_,Q=this.getFilter(A.minFilter,A),C=this.getFilter(A.maxFilter,A);g.pixelStorei(g.UNPACK_ALIGNMENT,A.unpackAlignment),g.texParameteri(I,g.TEXTURE_MIN_FILTER,Q),g.texParameteri(I,g.TEXTURE_MAG_FILTER,C),g.texParameteri(I,g.TEXTURE_WRAP_S,this.getWrapMode(A.wrapS)),g.texParameteri(I,g.TEXTURE_WRAP_T,this.getWrapMode(A.wrapT)),g.texParameteri(I,g.TEXTURE_WRAP_R,this.getWrapMode(A.wrapR))}uploadTextureData(A,I,g){const C={x:0,y:0,z:0};if(this.isTexture2D(A))this.gl_.texSubImage2D(g,0,C.x,C.y,A.width,A.height,I.format,I.type,A.data);else if(this.isTextureStorage3D(A))this.gl_.texSubImage3D(g,0,C.x,C.y,C.z,A.width,A.height,A.depth,I.format,I.type,A.data);else throw new Error("Attempting to upload data for an unsupported texture type")}getFilter(A,I){const{dataFormat:g,dataType:Q}=I;if(g==="scalar"&&Q!=="float"&&A!=="nearest")return O.warn("WebGLTexture","Integer values are not filterable. Using gl.NEAREST instead."),this.gl_.NEAREST;switch(A){case"nearest":return this.gl_.NEAREST;case"linear":return this.gl_.LINEAR;default:throw new Error(`Unsupported texture filter: ${A}`)}}getTextureType(A){if(this.isTexture2D(A))return this.gl_.TEXTURE_2D;if(this.isTexture2DArray(A))return this.gl_.TEXTURE_2D_ARRAY;if(this.isTexture3D(A))return this.gl_.TEXTURE_3D;throw new Error(`Unknown texture type ${A.type}`)}getWrapMode(A){switch(A){case"repeat":return this.gl_.REPEAT;case"clamp_to_edge":return this.gl_.CLAMP_TO_EDGE;default:throw new Error(`Unsupported wrap mode: ${A}`)}}getDataFormatInfo(A,I){if(A==="rgba"&&I==="unsigned_byte")return{internalFormat:this.gl_.RGBA8,format:this.gl_.RGBA,type:this.gl_.UNSIGNED_BYTE};if(A==="rgba"&&I==="unsigned_int")return{internalFormat:this.gl_.RGBA32UI,format:this.gl_.RGBA_INTEGER,type:this.gl_.UNSIGNED_INT};if(A==="rgb"&&I==="unsigned_byte")return{internalFormat:this.gl_.RGB8,format:this.gl_.RGB,type:this.gl_.UNSIGNED_BYTE};if(A==="scalar")switch(I){case"byte":return{internalFormat:this.gl_.R8I,format:this.gl_.RED_INTEGER,type:this.gl_.BYTE};case"short":return{internalFormat:this.gl_.R16I,format:this.gl_.RED_INTEGER,type:this.gl_.SHORT};case"int":return{internalFormat:this.gl_.R32I,format:this.gl_.RED_INTEGER,type:this.gl_.INT};case"unsigned_byte":return{internalFormat:this.gl_.R8UI,format:this.gl_.RED_INTEGER,type:this.gl_.UNSIGNED_BYTE};case"unsigned_short":return{internalFormat:this.gl_.R16UI,format:this.gl_.RED_INTEGER,type:this.gl_.UNSIGNED_SHORT};case"unsigned_int":return{internalFormat:this.gl_.R32UI,format:this.gl_.RED_INTEGER,type:this.gl_.UNSIGNED_INT};case"float":return{internalFormat:this.gl_.R32F,format:this.gl_.RED,type:this.gl_.FLOAT};default:throw new Error(`Unsupported scalar type: ${I}`)}throw new Error(`Unsupported format/type: ${A}/${I}`)}isTextureStorage3D(A){return this.isTexture2DArray(A)||this.isTexture3D(A)}isTexture2D(A){return A.type==="Texture2D"}isTexture2DArray(A){return A.type==="Texture2DArray"}isTexture3D(A){return A.type==="Texture3D"}}class mA{min;max;constructor(A,I){this.min=A?OQ(A):LA(1/0,1/0),this.max=I?OQ(I):LA(-1/0,-1/0)}clone(){return new mA(this.min,this.max)}isEmpty(){return this.max[0]<=this.min[0]||this.max[1]<=this.min[1]}static intersects(A,I){return!(A.max[0]<=I.min[0]||A.min[0]>=I.max[0]||A.max[1]<=I.min[1]||A.min[1]>=I.max[1])}static equals(A,I){return XQ(A.min,I.min)&&XQ(A.max,I.max)}floor(){return new mA(LA(Math.floor(this.min[0]),Math.floor(this.min[1])),LA(Math.floor(this.max[0]),Math.floor(this.max[1])))}toRect(){const A=this.min[0],I=this.min[1],g=this.max[0]-this.min[0],Q=this.max[1]-this.min[1];return{x:A,y:I,width:g,height:Q}}}class ci{gl_;enabledCapabilities_=new Map;depthMaskEnabled_=null;colorMaskEnabled_=null;depthFunc_=null;blendSrcFactor_=null;blendDstFactor_=null;currentBlendingMode_=null;currentViewport_=null;currentScissor_=null;currentCullingMode_=null;stencilFunc_=null;stencilRef_=null;stencilFuncMask_=null;polygonOffsetSet_=!1;constructor(A){this.gl_=A,this.gl_.frontFace(this.gl_.CW),this.gl_.stencilMask(255),this.gl_.stencilOp(this.gl_.KEEP,this.gl_.KEEP,this.gl_.REPLACE)}enable(A){this.enabledCapabilities_.get(A)||(this.gl_.enable(A),this.enabledCapabilities_.set(A,!0))}disable(A){this.enabledCapabilities_.get(A)&&(this.gl_.disable(A),this.enabledCapabilities_.set(A,!1))}setBlendFunc(A,I){(this.blendSrcFactor_!==A||this.blendDstFactor_!==I)&&(this.gl_.blendFunc(A,I),this.blendSrcFactor_=A,this.blendDstFactor_=I)}setDepthTesting(A){A?this.enable(this.gl_.DEPTH_TEST):this.disable(this.gl_.DEPTH_TEST)}setBlending(A){A?this.enable(this.gl_.BLEND):this.disable(this.gl_.BLEND)}setDepthMask(A){this.depthMaskEnabled_!==A&&(this.gl_.depthMask(A),this.depthMaskEnabled_=A)}get stencilTestEnabled(){return this.enabledCapabilities_.get(this.gl_.STENCIL_TEST)??!1}get blendingMode(){return this.currentBlendingMode_}setColorMask(A){this.colorMaskEnabled_!==A&&(this.gl_.colorMask(A,A,A,A),this.colorMaskEnabled_=A)}setPolygonOffset(A){if(!A){this.disable(this.gl_.POLYGON_OFFSET_FILL);return}this.enable(this.gl_.POLYGON_OFFSET_FILL),this.polygonOffsetSet_||(this.gl_.polygonOffset(1,1),this.polygonOffsetSet_=!0)}setDepthFunc(A){this.depthFunc_!==A&&(this.gl_.depthFunc(A),this.depthFunc_=A)}setBlendingMode(A){if(this.currentBlendingMode_!==A){if(A==="none")this.setBlending(!1);else switch(this.setBlending(!0),A){case"additive":this.setBlendFunc(this.gl_.SRC_ALPHA,this.gl_.ONE);break;case"multiply":this.setBlendFunc(this.gl_.DST_COLOR,this.gl_.ZERO);break;case"subtractive":this.setBlendFunc(this.gl_.ZERO,this.gl_.ONE_MINUS_SRC_COLOR);break;case"premultipliedOver":this.setBlendFunc(this.gl_.ONE,this.gl_.ONE_MINUS_SRC_ALPHA);break;case"normal":default:this.setBlendFunc(this.gl_.SRC_ALPHA,this.gl_.ONE_MINUS_SRC_ALPHA);break}this.currentBlendingMode_=A}}setViewport(A){const I=A.floor();if(this.currentViewport_&&mA.equals(I,this.currentViewport_))return;const{x:g,y:Q,width:C,height:E}=I.toRect();this.gl_.viewport(g,Q,C,E),this.currentViewport_=I}setScissorTest(A){A?this.enable(this.gl_.SCISSOR_TEST):(this.disable(this.gl_.SCISSOR_TEST),this.currentScissor_=null)}setScissor(A){const I=A.floor();if(this.currentScissor_&&mA.equals(I,this.currentScissor_))return;const{x:g,y:Q,width:C,height:E}=I.toRect();this.gl_.scissor(g,Q,C,E),this.currentScissor_=I}setCullFace(A){A?this.enable(this.gl_.CULL_FACE):this.disable(this.gl_.CULL_FACE)}setCullFaceMode(A){if(this.currentCullingMode_!==A){if(A==="none")this.setCullFace(!1);else switch(this.setCullFace(!0),A){case"front":this.gl_.cullFace(this.gl_.FRONT);break;case"back":this.gl_.cullFace(this.gl_.BACK);break;case"both":this.gl_.cullFace(this.gl_.FRONT_AND_BACK);break}this.currentCullingMode_=A}}setStencilTest(A){A?this.enable(this.gl_.STENCIL_TEST):this.disable(this.gl_.STENCIL_TEST)}setStencilFunc(A,I,g){(this.stencilFunc_!==A||this.stencilRef_!==I||this.stencilFuncMask_!==g)&&(this.gl_.stencilFunc(A,I,g),this.stencilFunc_=A,this.stencilRef_=I,this.stencilFuncMask_=g)}}class Li{textureUnit;gl_;framebuffer_=null;texture_=null;width_=0;height_=0;constructor(A,I){this.gl_=A,this.textureUnit=I}bind(A,I){this.hasValidTarget(A,I)||this.createRenderTarget(A,I),this.gl_.bindFramebuffer(this.gl_.FRAMEBUFFER,this.framebuffer_)}unbind(){this.gl_.bindFramebuffer(this.gl_.FRAMEBUFFER,null)}dispose(){this.texture_&&this.gl_.deleteTexture(this.texture_),this.framebuffer_&&this.gl_.deleteFramebuffer(this.framebuffer_),this.texture_=null,this.framebuffer_=null,this.width_=0,this.height_=0}hasValidTarget(A,I){return this.texture_!==null&&this.width_===A&&this.height_===I}createRenderTarget(A,I){const g=this.gl_;if(this.texture_&&g.deleteTexture(this.texture_),this.framebuffer_??=g.createFramebuffer(),!this.framebuffer_)throw new Error("Failed to create scene depth framebuffer");const Q=this.createDepthTexture(A,I);g.bindFramebuffer(g.FRAMEBUFFER,this.framebuffer_),g.framebufferTexture2D(g.FRAMEBUFFER,g.DEPTH_ATTACHMENT,g.TEXTURE_2D,Q,0),g.drawBuffers([g.NONE]),g.readBuffer(g.NONE),g.bindFramebuffer(g.FRAMEBUFFER,null),this.texture_=Q,this.width_=A,this.height_=I}createDepthTexture(A,I){const g=this.gl_,Q=g.createTexture();if(!Q)throw new Error("Failed to create scene depth texture");return g.activeTexture(g.TEXTURE0+this.textureUnit),g.bindTexture(g.TEXTURE_2D,Q),g.texImage2D(g.TEXTURE_2D,0,g.DEPTH_COMPONENT24,A,I,0,g.DEPTH_COMPONENT,g.UNSIGNED_INT,null),g.texParameteri(g.TEXTURE_2D,g.TEXTURE_MIN_FILTER,g.NEAREST),g.texParameteri(g.TEXTURE_2D,g.TEXTURE_MAG_FILTER,g.NEAREST),g.texParameteri(g.TEXTURE_2D,g.TEXTURE_WRAP_S,g.CLAMP_TO_EDGE),g.texParameteri(g.TEXTURE_2D,g.TEXTURE_WRAP_T,g.CLAMP_TO_EDGE),Q}}const Ji=uQ(WA(),[1,-1,1]);class ri extends wg{gl_;bindings_;depthTarget_;programs_;state_;textures_;renderedObjectsPerFrame_=0;stencilRef_=0;currentViewportSize_=[0,0];currentViewportHasSceneDepth_=!1;constructor(A){super(A);const I=this.canvas.getContext("webgl2",{depth:!0,antialias:!1,stencil:!0});if(!I)throw new Error("Failed to initialize WebGL2 context");this.gl_=I,O.info("WebGLRenderer",`WebGL version ${I.getParameter(I.VERSION)}`),I.getExtension("EXT_color_buffer_float"),this.programs_=new ZE(I),this.bindings_=new Si(I),this.textures_=new ki(I),this.state_=new ci(I),this.depthTarget_=new Li(I,this.textures_.reservePersistentUnit()),this.resize(this.canvas.width,this.canvas.height)}get gpuTextureBytes(){return this.textures_.gpuTextureBytes}get gpuTextureCount(){return this.textures_.textureCount}render(A){this.renderedObjects_=0,this.renderedObjectsPerFrame_=0,this.stencilRef_=0;for(const G of A.layers)G.update(A);if(getComputedStyle(A.element).visibility==="hidden")return;const I=A.getBoxRelativeTo(this.canvas),g=new mA(LA(0,0),LA(this.width,this.height)),Q=mA.equals(I.floor(),g.floor()),C=mA.intersects(I,g);if(Q)this.state_.setScissorTest(!1);else if(C)this.state_.setScissorTest(!0),this.state_.setScissor(I);else{O.warn("WebGLRenderer",`Viewport ${A.id} is entirely outside canvas bounds, skipping render`);return}this.state_.setViewport(I),this.resetState(),this.clear();const E=I.toRect();this.currentViewportSize_=[E.width,E.height];const i=A.camera.frustum,D=[],a=[];for(const G of A.layers)G.state==="ready"&&(G.occludes?D:a).push(G);this.currentViewportHasSceneDepth_=D.length>0&&a.some(G=>G.requiresSceneDepth),this.primeDepthBuffer(D,A.camera,i),this.currentViewportHasSceneDepth_&&this.renderDepthTexture(D,A.camera,i),this.state_.setDepthMask(!1);for(const G of[...D,...a])this.renderLayer(G,A.camera,i);this.resetState(),this.renderedObjects_=this.renderedObjectsPerFrame_}primeDepthBuffer(A,I,g){this.state_.setColorMask(!1),this.state_.setDepthFunc(this.gl_.LESS),this.state_.setPolygonOffset(!0),this.drawDepthOnly(A,I,g),this.resetState()}renderDepthTexture(A,I,g){this.depthTarget_.bind(this.width,this.height),this.state_.setDepthMask(!0),this.state_.setDepthFunc(this.gl_.LESS),this.gl_.clear(this.gl_.DEPTH_BUFFER_BIT),this.drawDepthOnly(A,I,g),this.depthTarget_.unbind(),this.resetState()}drawDepthOnly(A,I,g){for(const Q of A)for(const C of Q.coverageGroups.values())for(const E of C){if(!E.depthProgramName||!E.depthTest||!g.intersectsWithBox3(E.boundingBox))continue;this.state_.setCullFaceMode(E.cullFaceMode),this.bindings_.bindGeometry(E.geometry),E.textures.forEach((D,a)=>{this.textures_.bindTexture(D,a)});const i=this.programs_.use(E.depthProgramName);this.drawGeometry(E.geometry,E,Q,i,I)}}setCoverageStencil(A){this.state_.setStencilTest(A!==null),A!==null&&(this.stencilRef_+=1,this.stencilRef_>255&&O.warn("WebGLRenderer","Exceeded 255 stencil coverage groups in one frame; dedup may be incorrect"),this.state_.setStencilFunc(this.gl_.NOTEQUAL,this.stencilRef_,255))}renderLayer(A,I,g){this.state_.setBlendingMode(A.blendMode);for(const[Q,C]of A.coverageGroups){this.setCoverageStencil(Q);for(const E of C)g.intersectsWithBox3(E.boundingBox)&&(this.renderObject(A,E,I),this.renderedObjectsPerFrame_+=1)}}renderObject(A,I,g){if(I.popStaleTextures().forEach(C=>{this.textures_.dispose(C)}),!I.programName)return;this.state_.setCullFaceMode(I.cullFaceMode),this.state_.setDepthTesting(I.depthTest),this.bindings_.bindGeometry(I.geometry),I.textures.forEach((C,E)=>{this.textures_.bindTexture(C,E)});const Q=this.programs_.use(I.programName);if(this.drawGeometry(I.geometry,I,A,Q,g),I.wireframeEnabled){const C=this.state_.stencilTestEnabled,E=this.state_.blendingMode;this.state_.setStencilTest(!1),this.state_.setBlendingMode("none"),this.bindings_.bindGeometry(I.wireframeGeometry);const i=this.programs_.use("wireframe");i.setUniform("u_wireframeColor",I.wireframeColor.rgb),this.drawGeometry(I.wireframeGeometry,I,A,i,g),E!==null&&this.state_.setBlendingMode(E),this.state_.setStencilTest(C)}}drawGeometry(A,I,g,Q,C){const E=Zg(WA(),C.viewMatrix,I.transform.matrix),i=Zg(WA(),Ji,C.projectionMatrix),D=this.currentViewportSize_,a=I.getUniforms(),R={...g.getUniforms(),...a};for(const e of Q.uniformNames)switch(e){case"u_modelView":Q.setUniform(e,E);break;case"u_model":Q.setUniform(e,I.transform.matrix);break;case"u_projection":Q.setUniform(e,i);break;case"u_resolution":Q.setUniform(e,D);break;case"u_hasSceneDepth":Q.setUniform(e,Number(g.requiresSceneDepth&&this.currentViewportHasSceneDepth_));break;case"u_sceneDepth":Q.setUniform(e,this.depthTarget_.textureUnit);break;case"u_mvpInverse":{const K=Zg(WA(),i,E),l=Sg(WA(),K);Q.setUniform(e,l);break}case"u_opacity":Q.setUniform(e,g.opacity*(a.Opacity??1));break;case"u_cameraPositionModel":{const K=Sg(WA(),E),l=Vg(0,0,0,1),V=Rg(xI(),l,K);Q.setUniform(e,wA(V[0],V[1],V[2]));break}default:e in R&&Q.setUniform(e,R[e])}const t=this.glGetPrimitive(A.primitive),J=A.indexData,{instanceCount:n}=A;n!==null?J.length?this.gl_.drawElementsInstanced(t,J.length,this.gl_.UNSIGNED_INT,0,n):this.gl_.drawArraysInstanced(t,0,A.vertexCount,n):J.length?this.gl_.drawElements(t,J.length,this.gl_.UNSIGNED_INT,0):this.gl_.drawArrays(t,0,A.vertexCount)}uploadTexture(A){this.textures_.uploadTexture(A)}disposeTexture(A){this.textures_.dispose(A)}glGetPrimitive(A){switch(A){case"points":return this.gl_.POINTS;case"triangles":return this.gl_.TRIANGLES;case"lines":return this.gl_.LINES;default:{const I=A;throw new Error(`Unknown Primitive type: ${I}`)}}}resize(A,I){const g=new mA(LA(0,0),LA(A,I));this.state_.setViewport(g)}clear(){this.gl_.clearColor(0,0,0,0),this.gl_.clearStencil(0),this.gl_.clear(this.gl_.COLOR_BUFFER_BIT|this.gl_.DEPTH_BUFFER_BIT|this.gl_.STENCIL_BUFFER_BIT)}resetState(){this.state_.setColorMask(!0),this.state_.setDepthMask(!0),this.state_.setDepthTesting(!0),this.state_.setDepthFunc(this.gl_.LEQUAL),this.state_.setPolygonOffset(!1),this.state_.setStencilTest(!1),this.state_.setBlendingMode("none")}}function Ng(B,A){const I=B.priority??Number.MAX_SAFE_INTEGER,g=A.priority??Number.MAX_SAFE_INTEGER;return I===g?(B.orderKey??Number.MAX_SAFE_INTEGER)-(A.orderKey??Number.MAX_SAFE_INTEGER):I-g}class ni{maxConcurrent_;pending_=[];running_=new Map;constructor(A){this.maxConcurrent_=Math.max(1,A)}enqueue(A,I){this.running_.has(A)||this.pending_.some(g=>g.chunk===A)||this.pending_.push({chunk:A,fn:I})}flush(){this.pump()}cancel(A){const I=this.pending_.findIndex(Q=>Q.chunk===A);if(I>=0){this.pending_.splice(I,1),O.debug("ChunkQueue","Cancelled pending request");return}const g=this.running_.get(A);g&&(g.controller.abort(),O.debug("ChunkQueue","Cancelled fetch request"))}get pendingCount(){return this.pending_.length}get runningCount(){return this.running_.size}pump(){if(!(this.running_.size>=this.maxConcurrent_||this.pending_.length===0))for(this.pending_.sort((A,I)=>Ng(A.chunk,I.chunk));this.running_.size<this.maxConcurrent_&&this.pending_.length>0;)this.start(this.pending_.shift())}start(A){const{chunk:I,fn:g}=A;I.state="loading";const Q=new AbortController,C=Promise.resolve().then(()=>g(Q.signal)).then(()=>{I.state==="loading"&&(I.state="loaded")},E=>{I.state==="loading"&&(I.state="unloaded"),E.name!=="AbortError"&&O.error("ChunkQueue",String(E))}).finally(()=>{this.running_.delete(I),this.pump()});this.running_.set(I,{controller:Q,promise:C})}}let vg=0,jg=0;function Yi(B,A){B.data&&(vg-=B.data.byteLength,jg-=1),B.data=A,vg+=A.byteLength,jg+=1}function jQ(B){B.data&&(vg-=B.data.byteLength,jg-=1),B.data=void 0,B.texture?.releaseCpuData()}function Ki(){return{cpuChunkBytes:vg,cpuChunkCount:jg}}function zQ(B,A,I=1e-6){return Math.abs(B-A)<=I}const RA={x:0,y:1,z:2};function bI(B){switch(B){case"XY":return{u:"x",v:"y",w:"z"};case"XZ":return{u:"x",v:"z",w:"y"};case"YZ":return{u:"y",v:"z",w:"x"}}}function PI(B){const A=AA(),I=AA();A[RA[B.u]]=1,I[RA[B.v]]=1;const g=Pg(AA(),A,I),Q=VE(A[0],A[1],A[2],I[0],I[1],I[2],g[0],g[1],g[2]),C=dB(Og(),Q);return Xg(C,C)}const _Q=[Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array];function ei(B){if(_Q.some(I=>B instanceof I))return!0;const A=_Q.map(I=>I.name);return O.debug("Chunk",`Unsupported chunk data type: ${B}. Supported data types: ${A}`),!1}function Mi(B,A){return Math.round((A-B.translation)/B.scale)}function $Q(B,A){const I=AA(),g=AA();for(const C of["x","y","z"]){const E=C===A.w?.5*B.scale[C]:0,i=RA[C];I[i]=1/(B.scale[C]*B.shape[C]),g[i]=E-B.offset[C]}const Q=uQ(WA(),I);return OE(Q,Q,g)}function QI(B,A,I){return Math.max(A,Math.min(I,B))}const zg=Symbol("INTERNAL_POLICY_KEY"),AC=1e-6;class Hi{store_;policy_;policyChanged_=!1;targetLOD_=0;axes_;scale0_;mode_=null;lastViewBounds2D_=null;lastViewProjection_=null;lastSliceCoordW_;lastTCoord_;lastCCoords_;sourceMaxSquareDistance2D_;chunkViewStates_=new Map;isDisposed_=!1;constructor(A,I,g={u:"x",v:"y",w:"z"}){this.store_=A,this.policy_=I,this.axes_=g,O.info("ChunkStoreView","Using image source policy:",this.policy_.profile);const Q=this.store_.dimensions,C=Q[this.axes_.u],E=Q[this.axes_.v];if(C===void 0||E===void 0)throw new Error(`Source is missing dimensions for slice plane axes "${this.axes_.u}" and "${this.axes_.v}"`);const i=C.lods[0],D=E.lods[0];this.scale0_=i.scale,this.sourceMaxSquareDistance2D_=Gi(LA(i.size*i.scale,D.size*D.scale))}get chunkViewStates(){return this.chunkViewStates_}get isDisposed(){return this.isDisposed_}get lodCount(){return this.store_.lodCount}get channelCount(){return this.store_.channelCount}getWholePlaneRect(){const A=this.store_.dimensions,I=A[this.axes_.u].lods[0],g=A[this.axes_.v].lods[0];return new mA(LA(I.translation,g.translation),LA(I.translation+I.size*I.scale,g.translation+g.size*g.scale))}getChunksToRender(){const A=this.mode_==="image"?this.residentChunksForSlice():this.residentChunksMarkedVisible(),I=this.targetLOD_;return A.sort((g,Q)=>Math.abs(g.lod-I)-Math.abs(Q.lod-I)||Q.lod-g.lod)}residentChunksMarkedVisible(){const A=[];for(const[I,g]of this.chunkViewStates_)g.visible&&I.state==="loaded"&&I.texture&&A.push(I);return A}residentChunksForSlice(){const A=this.timeIndex(this.lastTCoord_),I=new Set(this.channelsOfInterest(this.lastCCoords_)),{min:g,max:Q}=this.lodRange(),C=new IC(this.axes_,this.lastSliceCoordW_,this.lastViewBounds2D_,this.store_.dimensions[this.axes_.w]),E=[];for(const i of this.store_.residentChunks)i.lod<g||i.lod>Q||i.chunkIndex.t===A&&I.has(i.chunkIndex.c)&&C.contains(i)&&E.push(i);return E}updateChunksForImage(A,I){const g=I.worldViewRect,C=Math.abs(g.max[0]-g.min[0])/I.bufferWidthPx,E=Math.log2(1/C),i=this.setLOD(E),D=this.getSliceAxisBounds(A);if(!(this.policyChanged_||i||this.viewBounds2DChanged(g)||this.lastSliceCoordW_!==A[this.axes_.w]||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const G=this.timeIndex(A.t);if(!this.store_.hasChunksAtTime(G)){O.warn("ChunkStoreView","updateChunkViewStates called with no chunks initialized"),this.mode_=null,this.chunkViewStates_.forEach(tg);return}const R=VQ();Fi(R,g.min,g.max,.5);const t=this.makeViewBounds3D(g,D);this.chunkViewStates_.forEach(tg);const J=this.channelsOfInterest(A.c),n=this.lodRange().max,e=this.getPaddedBounds(t),K=new IC(this.axes_,A[this.axes_.w],g,this.store_.dimensions[this.axes_.w]),l=this.currentLOD,V=l===n?[l]:[l,n];for(const x of V){const W=x===l,p=x===n;this.iterateChunksInBox(G,x,J,e,T=>{const $=K.contains(T),CA=W&&!$,BA=this.computePriority(p,W,$,CA,!0);BA!==null&&this.chunkViewStates_.set(T,{visible:$,prefetch:CA,priority:BA,orderKey:this.squareDistance2D(T,R)})})}this.markTimeChunksForPrefetchImage(G,A,t,R),this.policyChanged_=!1,this.mode_="image",this.lastViewBounds2D_=g.clone(),this.lastSliceCoordW_=A[this.axes_.w],this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0}updateChunksForVolume(A,I){if(!(this.policyChanged_||this.hasViewProjectionChanged(I)||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const Q=this.timeIndex(A.t);if(!this.store_.hasChunksAtTime(Q)){O.warn("ChunkStoreView","updateChunksForVolume called with no chunks initialized"),this.mode_=null,this.chunkViewStates_.forEach(tg);return}this.targetLOD_=this.policy_.lod.min,this.chunkViewStates_.forEach(tg);const C=this.channelsOfInterest(A.c),E=this.lodRange().max,i=this.currentLOD,D=a=>{const G=a.lod===E,R=a.lod===i,t=this.computePriority(G,R,!0,!1,!0);t!==null&&this.chunkViewStates_.set(a,{visible:!0,prefetch:!1,priority:t,orderKey:0})};this.iterateAllChunksAtLod(Q,i,C,D),i!==E&&this.iterateAllChunksAtLod(Q,E,C,D),this.markTimeChunksForPrefetchVolume(Q,A),this.policyChanged_=!1,this.mode_="volume",this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0,this.lastViewProjection_=I}hasCompleteVisibleLOD(){return this.allVisibleLoadedAt(this.lodRange().max)||this.allVisibleLoadedAt(this.currentLOD)}allVisibleLoadedAt(A){let I=!1;for(const[g,Q]of this.chunkViewStates_)if(!(!Q.visible||g.lod!==A)&&(I=!0,g.texture===void 0))return!1;return I}get currentLOD(){const{min:A,max:I}=this.lodRange();return QI(Math.round(this.targetLOD_),A,I)}maybeForgetChunk(A){const I=this.chunkViewStates_.get(A);I&&(I.visible||I.prefetch||I.priority!==null)||this.chunkViewStates_.delete(A)}dispose(){this.isDisposed_=!0,this.mode_=null,this.chunkViewStates_.forEach(tg)}setImageSourcePolicy(A,I){if(I!==zg)throw new Error("Unauthorized policy mutation");this.policy_!==A&&(this.policy_=A,this.policyChanged_=!0,O.info("ChunkStoreView","Using image source policy:",this.policy_.profile))}setLOD(A){const I=this.policy_.lod.bias,g=-Math.log2(this.scale0_)-A,Q=this.currentLOD;return this.targetLOD_=I-.5+g,this.currentLOD!==Q}markTimeChunksForPrefetchImage(A,I,g,Q){const C=this.store_.dimensions.t?.lods[0].size??1,E=Math.min(this.policy_.prefetch.t,C-1),i=this.policy_.priorityMap.prefetchTime,D=this.channelsOfInterest(I.c);for(let a=1;a<=E;++a){const G=(A+a)%C;this.iterateChunksInBox(G,this.currentLOD,D,g,R=>{const t=this.squareDistance2D(R,Q),J=QI(t/this.sourceMaxSquareDistance2D_,0,1-Number.EPSILON),n=a+J;this.chunkViewStates_.set(R,{visible:!1,prefetch:!0,priority:i,orderKey:n})})}}markTimeChunksForPrefetchVolume(A,I){const g=this.store_.dimensions.t?.lods[0].size??1,Q=Math.min(this.policy_.prefetch.t,g-1),C=this.policy_.priorityMap.prefetchTime,E=this.channelsOfInterest(I.c);for(let i=1;i<=Q;++i){const D=(A+i)%g;this.iterateAllChunksAtLod(D,this.currentLOD,E,a=>{const G=i;this.chunkViewStates_.set(a,{visible:!1,prefetch:!0,priority:C,orderKey:G})})}}computePriority(A,I,g,Q,C){if(!C)return null;const E=this.policy_.priorityMap;return A&&g?E.fallbackVisible:I&&g?E.visibleCurrent:A?E.fallbackBackground:I&&Q?E.prefetchSpace:null}channelsOfInterest(A){return A??Array.from({length:this.store_.channelCount},(I,g)=>g)}chunkIndexRange(A,I){const g=this.store_.dimensions,Q=g.x.lods[I],C=g.y.lods[I],E=g.z?.lods[I],i=Math.ceil(Q.size/Q.chunkSize),D=Math.ceil(C.size/C.chunkSize),a=E?Math.ceil(E.size/E.chunkSize):1,G=Q.chunkSize*Q.scale,R=C.chunkSize*C.scale,t=E?E.chunkSize*E.scale:1,J=Q.translation,n=C.translation,e=E?.translation??0,K=Math.max(0,WB((A.min[0]-J)/G)),l=Math.min(i,mB((A.max[0]-J)/G)),V=Math.max(0,WB((A.min[1]-n)/R)),x=Math.min(D,mB((A.max[1]-n)/R)),W=E?Math.max(0,WB((A.min[2]-e)/t)):0,p=E?Math.min(a,mB((A.max[2]-e)/t)):1;return K>=l||V>=x||W>=p?null:{xMin:K,xMax:l,yMin:V,yMax:x,zMin:W,zMax:p}}iterateChunksInBox(A,I,g,Q,C){const E=this.chunkIndexRange(Q,I);if(E)for(const i of g){const D=this.store_.getChunkGrid(I,A,i);if(D)for(let a=E.zMin;a<E.zMax;++a){const G=D[a];for(let R=E.yMin;R<E.yMax;++R){const t=G[R];for(let J=E.xMin;J<E.xMax;++J){const n=t[J];C(n)}}}}}iterateAllChunksAtLod(A,I,g,Q){for(const C of g){const E=this.store_.getChunkGrid(I,A,C);if(E)for(const i of E)for(const D of i)for(const a of D)Q(a)}}lodRange(){const A=this.store_.getLowestResLOD(),I=Math.max(0,Math.min(A,this.policy_.lod.min)),g=Math.max(I,Math.min(A,this.policy_.lod.max));return{min:I,max:g}}timeIndex(A){const I=this.store_.dimensions.t;return A===void 0||I===void 0?0:Mi(I.lods[0],A)}getSliceAxisBounds(A){const I=this.store_.dimensions[this.axes_.w];if(I===void 0)return[0,1];const g=I.lods[this.currentLOD],Q=A[this.axes_.w];if(Q===void 0)return[g.translation,g.translation+g.size*g.scale];const C=g.size,E=g.scale,i=g.translation,D=Math.floor((Q-i)/E),a=g.chunkSize,G=Math.max(0,Math.min(Math.floor(D/a),Math.ceil(C/a)-1));return[i+G*a*E,i+(G+1)*a*E]}makeViewBounds3D(A,I){const g=AA(),Q=AA();return g[RA[this.axes_.u]]=A.min[0],Q[RA[this.axes_.u]]=A.max[0],g[RA[this.axes_.v]]=A.min[1],Q[RA[this.axes_.v]]=A.max[1],g[RA[this.axes_.w]]=I[0],Q[RA[this.axes_.w]]=I[1],new ZI(g,Q)}viewBounds2DChanged(A){return this.lastViewBounds2D_===null||!vQ(this.lastViewBounds2D_.min,A.min)||!vQ(this.lastViewBounds2D_.max,A.max)}hasViewProjectionChanged(A){return this.lastViewProjection_===null||!Ai(this.lastViewProjection_,A)}cCoordsChanged(A){return!this.lastCCoords_&&!A?!1:!this.lastCCoords_||!A||this.lastCCoords_.length!==A.length?!0:!this.lastCCoords_.every((I,g)=>I===A[g])}getPaddedBounds(A){const{u:I,v:g,w:Q}=this.axes_,C=this.store_.dimensions,E=C[I].lods[this.currentLOD],i=C[g].lods[this.currentLOD],D=C[Q]?.lods[this.currentLOD],a=AA();return a[RA[I]]=E.chunkSize*E.scale*this.policy_.prefetch.x,a[RA[g]]=i.chunkSize*i.scale*this.policy_.prefetch.y,D&&(a[RA[Q]]=D.chunkSize*D.scale*this.policy_.prefetch.z),new ZI(nB(AA(),A.min,a),ug(AA(),A.max,a))}squareDistance2D(A,I){function g(D){return A.offset[D]+.5*A.shape[D]*A.scale[D]}const{u:Q,v:C}=this.axes_,E=g(Q)-I[0],i=g(C)-I[1];return E*E+i*i}}class IC{axes_;viewRect_;chunkRect_=new mA;sliceCoordByLod_;constructor(A,I,g,Q){this.axes_=A,this.viewRect_=g,I!==void 0&&Q!==void 0&&(this.sliceCoordByLod_=Q.lods.map(C=>QI(I,C.translation,C.translation+(C.size-1)*C.scale)))}contains(A){const{u:I,v:g,w:Q}=this.axes_,C=this.sliceCoordByLod_?.[A.lod];return C!==void 0&&(C<A.offset[Q]||C>=TB(A,Q))?!1:(this.chunkRect_.min[0]=A.offset[I],this.chunkRect_.min[1]=A.offset[g],this.chunkRect_.max[0]=TB(A,I),this.chunkRect_.max[1]=TB(A,g),mA.intersects(this.chunkRect_,this.viewRect_))}}function WB(B){return Math.floor(B+AC)}function mB(B){return Math.ceil(B-AC)}function TB(B,A){return B.offset[A]+B.shape[A]*B.scale[A]}function tg(B){B.visible=!1,B.prefetch=!1,B.priority=null,B.orderKey=null}class qi{chunks_;lowestResLOD_;dimensions_;views_=[];hasHadViews_=!1;resident_=new Set;constructor(A){this.dimensions_=A,this.lowestResLOD_=this.dimensions_.numLods-1,this.validateXYScaleRatios();const{size:I}=this.getAndValidateTimeDimension(),{size:g}=this.getAndValidateChannelDimension(),Q=this.dimensions_.numLods;this.chunks_=new Array(Q);for(let C=0;C<Q;++C){const E=this.dimensions_.x.lods[C],i=this.dimensions_.y.lods[C],D=this.dimensions_.z?.lods[C],a=E.chunkSize,G=i.chunkSize,R=D?.chunkSize??1,t=Math.ceil(E.size/a),J=Math.ceil(i.size/G),n=D?Math.ceil(D.size/R):1,e=new Array(I);this.chunks_[C]=e;for(let K=0;K<I;++K){const l=new Array(g);e[K]=l;for(let V=0;V<g;++V){const x=new Array(n);l[V]=x;for(let W=0;W<n;++W){const p=D!==void 0?D.translation+W*R*D.scale:0,T=new Array(J);x[W]=T;for(let $=0;$<J;++$){const CA=i.translation+$*G*i.scale,BA=new Array(t);T[$]=BA;for(let iA=0;iA<t;++iA){const sA=E.translation+iA*a*E.scale;BA[iA]={state:"unloaded",lod:C,visible:!1,prefetch:!1,priority:null,orderKey:null,shape:{x:Math.min(a,E.size-iA*a),y:Math.min(G,i.size-$*G),z:Math.min(R,(D?.size??1)-W*R),c:1},rowAlignmentBytes:1,chunkIndex:{x:iA,y:$,z:W,c:V,t:K},scale:{x:E.scale,y:i.scale,z:D?.scale??1},offset:{x:sA,y:CA,z:p}}}}}}}}}getChunkGrid(A,I,g){return this.chunks_[A]?.[I]?.[g]}hasChunksAtTime(A){return this.chunks_[0]?.[A]!==void 0}get lodCount(){return this.lowestResLOD_+1}get channelCount(){return this.dimensions_.c?.lods[0].size??1}get dimensions(){return this.dimensions_}getLowestResLOD(){return this.lowestResLOD_}addView(A,I){const g=new Hi(this,A,I);return this.views_.push(g),this.hasHadViews_=!0,g}get views(){return this.views_}get residentChunks(){return this.resident_}setChunkTexture(A,I){A.texture=I,this.resident_.add(A)}clearChunkTexture(A){const I=A.texture;return A.texture=void 0,this.resident_.delete(A),I}canDispose(){return this.hasHadViews_&&this.views_.length===0}updateAndCollectChunkChanges(){const A=new Set;for(const I of this.views_)for(const[g,Q]of I.chunkViewStates)A.add(g);for(const I of A)this.aggregateChunkViewStates(I);return this.removeDisposedViews(),A}removeDisposedViews(){for(let A=this.views_.length-1;A>=0;A--)this.views_[A].isDisposed&&this.views_.splice(A,1)}aggregateChunkViewStates(A){let I=!1,g=!1,Q=null,C=null;for(const D of this.views_){const a=D.chunkViewStates.get(A);a&&(a.visible&&(I=!0),a.prefetch&&(g=!0),a.priority!==null&&(Q===null||a.priority<Q)&&(Q=a.priority,C=a.orderKey),!a.visible&&!a.prefetch&&a.priority===null&&D.maybeForgetChunk(A))}if(A.visible=I,A.prefetch=g,A.priority=Q,A.orderKey=C,A.priority!==null&&A.state==="unloaded"){A.state="queued";return}A.priority===null&&A.state==="queued"&&(A.state="unloaded")}validateXYScaleRatios(){const A=this.dimensions_.x,I=this.dimensions_.y;for(let g=1;g<this.dimensions_.numLods;g++){const Q=A.lods[g].scale/A.lods[g-1].scale,C=I.lods[g].scale/I.lods[g-1].scale;if(!zQ(Q,2,.02)||!zQ(C,2,.02))throw new Error(`Invalid downsampling factor between levels ${g-1} → ${g}: expected (2× in X and Y), but got (${Q.toFixed(2)}×, ${C.toFixed(2)}×) from scale [${A.lods[g-1].scale}, ${I.lods[g-1].scale}] → [${A.lods[g].scale}, ${I.lods[g].scale}]`)}}getAndValidateTimeDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.t?.lods[A];if(!I)continue;const g=this.dimensions_.t?.lods[A-1];if(g&&I.size!==g.size)throw new Error(`ChunkStore does not support downsampling in t. Found ${g.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.t?.lods[0].size??1}}getAndValidateChannelDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.c?.lods[A];if(!I)continue;if(I.scale!==1&&O.warn("ChunkStore",`Idetik does not make use of non-unity scale in c. Found ${I.scale} at LOD ${A}`),I.translation!==0)throw new Error(`ChunkStore does not support translation in c. Found ${I.translation} at LOD ${A}`);const g=this.dimensions_.c?.lods[A-1];if(g&&I.size!==g.size)throw new Error(`ChunkStore does not support downsampling in c. Found ${g.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.c?.lods[0].size??1}}}function di(B,A){const I=A.dimensions.t?.lods[0].size??1,g={requested:new Uint32Array(I),resident:new Uint32Array(I)};let Q=0,C=0;const E=A.views;for(let i=0;i<E.length;i++)for(const[D,a]of E[i].chunkViewStates){if(a.priority===null||fi(D,E,i))continue;const G=D.chunkIndex.t;Q+=1,g.requested[G]+=1,D.texture!==void 0&&(C+=1,g.resident[G]+=1)}return{source:B,requested:Q,resident:C,timepoints:g}}function fi(B,A,I){for(let g=0;g<I;g++){const Q=A[g].chunkViewStates.get(B);if(Q!==void 0&&Q.priority!==null)return!0}return!1}function li(B,A){let I=0,g=0;const Q={requested:0,resident:0};for(const C of A){const E=C.currentLOD;for(const[i,D]of C.chunkViewStates){if(D.priority===null)continue;const a=i.texture!==void 0;I+=1,a&&(g+=1),!(!D.visible||i.lod!==E)&&(Q.requested+=1,a&&(Q.resident+=1))}}return{viewportId:B,requested:I,resident:g,current:Q}}class xB extends pB{width_;height_;depth_;constructor(A,I,g,Q){super(),this.dataFormat="scalar",this.dataType=fB(A),this.data_=A,this.width_=I,this.height_=g,this.depth_=Q}get type(){return"Texture3D"}get width(){return this.width_}get height(){return this.height_}get depth(){return this.depth_}static createWithChunk(A){const I=A.data;if(!I)throw new Error("Unable to create texture, chunk data is not initialized.");const g=new xB(I,A.shape.x,A.shape.y,A.shape.z);return g.unpackAlignment=A.rowAlignmentBytes,g}}const pi=8,Wi=4;class mi{stores_=[];queue_;uploadTexture_;disposeTexture_;getGpuResidentBytes_;memoryLimitBytes_;maxGpuUploadsPerUpdate_;constructor(A,I,g=()=>0,Q=1/0,C=pi,E=Wi){this.uploadTexture_=A,this.disposeTexture_=I,this.getGpuResidentBytes_=g,this.memoryLimitBytes_=Q,this.maxGpuUploadsPerUpdate_=Math.max(1,E),this.queue_=new ni(C)}get memoryLimitBytes(){return this.memoryLimitBytes_}set memoryLimitBytes(A){this.memoryLimitBytes_=A}get queueStats(){return{pending:this.queue_.pendingCount,running:this.queue_.runningCount}}get memoryStats(){return Ki()}get sourceChunkStats(){return this.stores_.map(({source:A,store:I})=>di(A,I))}addView(A,I,g){let Q=this.stores_.find(C=>C.source===A)?.store;return Q||(Q=new qi(A.loader.getSourceDimensionMap()),this.stores_.push({source:A,store:Q})),Q.addView(I,g)}update(){const A=[];for(const{source:I,store:g}of this.stores_){const Q=g.updateAndCollectChunkChanges();for(const C of Q)C.priority===null?this.releaseChunk(C):(C.releasedAt=void 0,C.state==="queued"&&A.push({source:I,chunk:C}));this.uploadLoadedChunks(g,Q)}this.enqueueWithinBudget(A),this.queue_.flush();for(let I=this.stores_.length-1;I>=0;I--){const{store:g}=this.stores_[I];if(g.canDispose()){for(const Q of[...g.residentChunks])this.disposeChunkTexture(g,Q),Q.state="unloaded";this.stores_.splice(I,1)}}}releaseChunk(A){if(this.queue_.cancel(A),A.texture!==void 0){A.releasedAt??=performance.now();return}jQ(A),A.state==="loaded"&&(A.state="unloaded")}enqueueWithinBudget(A){if(A.length===0)return;A.sort((Q,C)=>Ng(Q.chunk,C.chunk));let I=this.getGpuResidentBytes_();const g=this.evictionCandidates();for(const{source:Q,chunk:C}of A){const E=this.chunkBytes(Q,C);E>this.memoryLimitBytes_||(I+E>this.memoryLimitBytes_&&(I=this.evictWorseChunks(I,E,C,g)),!(I+E>this.memoryLimitBytes_)&&(I+=E,this.queue_.enqueue(C,i=>Q.loader.loadChunkData(C,i))))}}evictionCandidates(){const A=[];for(const{store:I}of this.stores_){const g=new Set(I.views.flatMap(Q=>Q.getChunksToRender()));for(const Q of I.residentChunks)Q.visible||A.push({store:I,chunk:Q,drawn:g.has(Q)})}return A.sort((I,g)=>{if(I.drawn!==g.drawn)return I.drawn?1:-1;const Q=-Ng(I.chunk,g.chunk);return Q!==0?Q:(I.chunk.releasedAt??0)-(g.chunk.releasedAt??0)})}evictWorseChunks(A,I,g,Q){for(;A+I>this.memoryLimitBytes_&&Q.length>0&&Ng(Q[0].chunk,g)>0&&(!Q[0].drawn||g.visible);){const C=Q.shift();C.chunk.texture!==void 0&&(A-=lB(C.chunk.texture),this.disposeChunkTexture(C.store,C.chunk),C.chunk.state="unloaded",C.chunk.releasedAt=void 0)}return A}chunkBytes(A,I){const g=A.loader.getBytesPerElement();return I.shape.x*I.shape.y*I.shape.z*g}uploadLoadedChunks(A,I){if(!this.uploadTexture_)return;const g=[];for(const C of I)C.state==="loaded"&&C.texture===void 0&&g.push(C);if(g.length===0)return;g.sort(Ng);const Q=Math.min(g.length,this.maxGpuUploadsPerUpdate_);for(let C=0;C<Q;C++){const E=g[C],i=xB.createWithChunk(E);this.uploadTexture_(i),A.setChunkTexture(E,i),jQ(E)}}disposeChunkTexture(A,I){const g=A.clearChunkTexture(I);g!==void 0&&this.disposeTexture_?.(g)}}class Ug{blendMode;occludes;requiresSceneDepth_=!1;coverageGroups_=new Map;state_="initialized";attached_=!1;callbacks_=[];opacity_;constructor({opacity:A=1,blendMode:I="none",occludes:g}={}){this.opacity_=QI(A,0,1),this.blendMode=I,this.occludes=g??I==="none"}get requiresSceneDepth(){return this.requiresSceneDepth_}get opacity(){return this.opacity_}set opacity(A){(A<0||A>1)&&O.warn("Layer",`Opacity out of bounds: ${A} — clamping to [0.0, 1.0]`),this.opacity_=QI(A,0,1)}onEvent(A){}onAttached(A){if(this.attached_)throw new Error(`${this.type} cannot be attached to multiple viewports simultaneously.`);if(this.occludes&&this.requiresSceneDepth_)throw new Error(`${this.type} cannot both occlude and read scene depth.`);this.attach(A),this.attached_=!0}onDetached(A){this.attached_&&(this.detach(A),this.attached_=!1)}attach(A){}detach(A){}get coverageGroups(){return this.coverageGroups_}get state(){return this.state_}addStateChangeCallback(A){this.callbacks_.push(A)}removeStateChangeCallback(A){const I=this.callbacks_.indexOf(A);if(I===-1)throw new Error(`Callback to remove could not be found: ${A}`);this.callbacks_.splice(I,1)}setState(A){const I=this.state_;this.state_=A,this.callbacks_.forEach(g=>g(A,I))}addObject(A,I=null){const g=this.coverageGroups_.get(I);g?g.push(A):this.coverageGroups_.set(I,[A])}clearObjects(){this.coverageGroups_.clear()}getUniforms(){return{}}}const gC=["fallbackVisible","prefetchTime","visibleCurrent","fallbackBackground","prefetchSpace"];function _g(B={}){return $g(ZB({profile:"exploration",prefetch:{x:1,y:1,z:1,t:0},priorityOrder:["fallbackVisible","visibleCurrent","prefetchSpace","prefetchTime","fallbackBackground"]},B))}function Ti(B={}){return $g(ZB({profile:"playback",prefetch:{x:0,y:0,z:0,t:20},priorityOrder:["fallbackVisible","visibleCurrent","prefetchTime","fallbackBackground","prefetchSpace"]},B))}function xi(B={}){return $g(ZB({profile:"no-prefetch",prefetch:{x:0,y:0,z:0,t:0},priorityOrder:["fallbackVisible","visibleCurrent","fallbackBackground","prefetchSpace","prefetchTime"]},B))}function $g(B){Zi(B);const A={x:B.prefetch.x,y:B.prefetch.y,z:B.prefetch.z??0,t:B.prefetch.t??0},I=Object.freeze(gC.reduce((C,E)=>{const i=B.priorityOrder.indexOf(E);return C[E]=i,C},{})),g={min:B.lod?.min??0,max:B.lod?.max??Number.MAX_SAFE_INTEGER,bias:B.lod?.bias??.5},Q={profile:B.profile??"custom",prefetch:A,priorityOrder:Object.freeze([...B.priorityOrder]),priorityMap:I,lod:g};return Object.freeze(Q)}function Zi(B){for(const[g,Q]of Object.entries(B.prefetch))if(Q!==void 0&&Q<0)throw new Error(`prefetch.${g} must be a non-negative number`);const A=B.lod;if(A?.min!==void 0&&A?.max!==void 0&&A.min>A.max)throw new Error("lod.min must be <= lod.max");const I=B.priorityOrder;if(I.length!==gC.length||new Set(I).size!==I.length)throw new Error("priorityOrder must include all categories exactly once")}function ZB(B,A={}){return{profile:A.profile??B.profile,prefetch:{...B.prefetch,...A.prefetch??{}},lod:{...B.lod,...A.lod??{}},priorityOrder:A.priorityOrder??B.priorityOrder}}class GA{static RED=new GA(1,0,0);static GREEN=new GA(0,1,0);static BLUE=new GA(0,0,1);static YELLOW=new GA(1,1,0);static MAGENTA=new GA(1,0,1);static CYAN=new GA(0,1,1);static BLACK=new GA(0,0,0);static WHITE=new GA(1,1,1);static TRANSPARENT=new GA(0,0,0,0);rgba_;constructor(A,I,g,Q){if(A<0||A>1||I<0||I>1||g<0||g>1)throw new Error("RGB values must be in the range [0, 1]");if(Q!==void 0&&(Q<0||Q>1))throw new Error("Alpha value must be in the range [0, 1]");this.rgba_=[A,I,g,Q??1]}get rgb(){return[this.rgba_[0],this.rgba_[1],this.rgba_[2]]}get rgba(){return this.rgba_}get r(){return this.rgba_[0]}get g(){return this.rgba_[1]}get b(){return this.rgba_[2]}get a(){return this.rgba_[3]}get rgbHex(){return`#${this.toHexComponent(this.r)}${this.toHexComponent(this.g)}${this.toHexComponent(this.b)}`}get packed(){return Math.round(this.r*255)<<24|Math.round(this.g*255)<<16|Math.round(this.b*255)<<8|Math.round(this.a*255)}static from(A){if(A instanceof GA)return A;if(Array.isArray(A))return new GA(A[0],A[1],A[2],A[3]);if(typeof A=="string")return GA.fromRgbHex(A);throw new Error("Unsupported color format")}static fromRgbHex(A){const I=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(A);if(!I)throw new Error("Invalid RGB hex, use form '#RRGGBB'");return new GA(parseInt(I[1],16)/255,parseInt(I[2],16)/255,parseInt(I[3],16)/255,1)}toHexComponent(A){const I=Math.round(A*255).toString(16).padStart(2,"0");return I.length===1?"0"+I:I}}const BC=32;function kg(B,{visible:A,color:I,contrastLimits:g,opacity:Q}){return A??=!0,I=I===void 0?GA.WHITE:GA.from(I),Q=Q===void 0?1:QI(Q,0,1),B!==null?g=ui(g,B):g===void 0&&(O.debug("Channel","No texture provided, defaulting channel contrast limits to [0, 1]."),g=[0,1]),{visible:A,color:I,contrastLimits:g,opacity:Q}}function uB(B,A){if(A.length>BC)throw new Error(`Maximum number of channels is ${BC}`);return A.map(I=>kg(B,I))}function QC(B,A){if(B&&B.length!==A)throw new Error(`channelProps length (${B.length}) must match source channel count (${A}).`)}function ui(B,A){if(B===void 0)return Ui(A);if(B[1]<=B[0])throw new Error(`Contrast limits must be strictly increasing: ${B}.`);return B}class bi extends uI{constructor(A){if(super(),A.primitive!="triangles"){O.warn("WireframeGeometry","Only indexed geometries are supported");return}if(A.indexData.length==0){O.warn("WireframeGeometry","Only triangulated geometries are supported");return}this.primitive_="lines",this.vertexData_=A.vertexData,this.attributes_=A.attributes;const I=new Set,g=[],Q=(E,i)=>{const D=Math.min(E,i),a=Math.max(E,i);I.has({i0:D,i1:a})||(I.add({i0:D,i1:a}),g.push(D,a))},C=A.indexData;for(let E=0;E<C.length;E+=3){const i=C[E],D=C[E+1],a=C[E+2];Q(i,D),Q(D,a),Q(a,i)}this.indexData_=new Uint32Array(g)}}const Pi=wA(0,1,0);class bB{dirty_=!0;matrix_=WA();rotation_=Og();translation_=AA();scale_=wA(1,1,1);addRotation(A){ai(this.rotation_,this.rotation_,A),this.dirty_=!0}setRotation(A){yi(this.rotation_,A),this.dirty_=!0}get rotation(){return si(this.rotation_)}addTranslation(A){ug(this.translation_,this.translation_,A),this.dirty_=!0}setTranslation(A){rB(this.translation_,A),this.dirty_=!0}get translation(){return $A(this.translation_)}addScale(A){Ii(this.scale_,this.scale_,A),this.dirty_=!0}setScale(A){rB(this.scale_,A),this.dirty_=!0}targetTo(A){MB(this.translation_,A)&&(A=$A(A),A[2]+=FA);const I=$E(WA(),this.translation_,A,Pi),g=PE(ZQ(),I);dB(this.rotation_,g),Xg(this.rotation_,this.rotation_),this.dirty_=!0}get scale(){return $A(this.scale_)}get matrix(){return this.dirty_&&(this.computeMatrix(),this.dirty_=!1),this.matrix_}get inverse(){return Sg(WA(),this.matrix)}computeMatrix(){XE(this.matrix_,this.rotation_,this.translation_,this.scale_)}}class VI extends xg{wireframeEnabled=!1;wireframeColor=GA.WHITE;depthTest=!0;textures_=[];staleTextures_=[];transform_=new bB;geometry_=new uI;wireframeGeometry_=null;programName_=null;depthProgramName_=null;cullFaceMode_="none";setTexture(A,I){this.textures_[A]=I}clearTextures(){this.textures_.length=0}markStaleTexture(A){A!==void 0&&this.staleTextures_.push(A)}popStaleTextures(){const A=this.staleTextures_;return this.staleTextures_=[],A}get geometry(){return this.geometry_}get wireframeGeometry(){return this.wireframeGeometry_??=new bi(this.geometry),this.wireframeGeometry_}get textures(){return this.textures_}get transform(){return this.transform_}set geometry(A){this.geometry_=A,this.wireframeGeometry_=null}get programName(){return this.programName_}get depthProgramName(){return this.depthProgramName_}get boundingBox(){const A=this.geometry_.boundingBox.clone();return A.applyTransform(this.transform_.matrix),A}set programName(A){this.programName_=A}set depthProgramName(A){this.depthProgramName_=A}get cullFaceMode(){return this.cullFaceMode_}set cullFaceMode(A){this.cullFaceMode_=A}getUniforms(){return{}}}class CC extends uI{constructor(A,I,g,Q){super();const C=[],E=[],i=g,D=Q,a=i+1,G=D+1,R=A/i,t=I/D;for(let J=0;J<G;++J){const n=J*t;for(let e=0;e<a;++e){const K=e*R,l=e/i,V=J/D,x=[K,n,0],W=[0,0,1],p=[l,V];C.push(...x,...W,...p)}}for(let J=0;J<D;++J)for(let n=0;n<i;++n){const e=n+a*J,K=n+a*(J+1),l=n+1+a*(J+1),V=n+1+a*J;E.push(e,K,V),E.push(K,l,V)}this.vertexData_=new Float32Array(C),this.indexData_=new Uint32Array(E),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}}class EC extends VI{worldToTexCoord=WA();channels_;constructor({width:A,height:I,texture:g,channelProps:Q=[]}){super(),this.geometry=new CC(A,I,1,1),this.setTexture(0,g),this.channels_=uB(g,Q),this.programName=Vi(g),this.depthProgramName="meshDepth"}get type(){return"ImageRenderable"}setChannelProps(A){this.channels_=uB(this.textures[0],A)}setChannelProperty(A,I,g){const Q=kg(this.textures[0],{...this.channels_[A],[I]:g});this.channels_[A]=Q}getUniforms(){const A=this.textures[0];if(!A)throw new Error("No texture set");const{color:I,contrastLimits:g,opacity:Q}=this.channels_[0]??kg(A,{});return{u_imageSampler:0,u_color:I.rgb,u_valueOffset:-g[0],u_valueScale:1/(g[1]-g[0]),Opacity:Q,u_worldToTexCoord:this.worldToTexCoord}}}function Vi(B){switch(B.dataType){case"byte":case"int":case"short":return"intScalarImage";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintScalarImage";case"float":return"floatScalarImage"}}class CI{normal;signedDistance;constructor(A=wA(0,1,0),I=0){this.normal=$A(A),this.signedDistance=I}static fromPointAndNormal(A,I){return new CI(I,-bg(I,A))}set(A,I){this.normal=$A(A),this.signedDistance=I}signedDistanceToPoint(A){return bg(this.normal,A)+this.signedDistance}normalize(){const A=JB(this.normal);if(A>0){const I=1/A;YB(this.normal,this.normal,I),this.signedDistance*=I}}}function iC(B,A,I,g,Q=3){switch(B.type){case"pointerdown":{const C=B.event;return LA(C.clientX,C.clientY)}case"pointerup":{if(!A)return A;const C=B.event,E=LA(C.clientX,C.clientY);if(hi(A,E)<Q){if(!g)return null;const D=B.worldRay;return D&&I(D).then(a=>{a!==null&&g(a)}).catch(a=>{O.error("PointPicking",`Failed to read value: ${a}`)}),null}return A}case"pointercancel":return null;default:return A}}class PB{bins_=new Map;acquire(A){const g=this.bins_.get(A)?.pop();return g&&O.debug("RenderablePool","Renderable object acquired"),g}release(A,I){let g=this.bins_.get(A);g||(g=[],this.bins_.set(A,g)),g.push(I),O.debug("RenderablePool","Renderable object released")}clearAll(A){if(A)for(const I of this.bins_.values())I.forEach(A);this.bins_.clear()}}class AB extends Ug{type="ImageLayer";source_;sliceCoords_;axes_;planeRotation_;orientation_;onPickValue_;visibleChunks_=new Map;orderedChunks_=[];pool_=new PB;initialChannelProps_;channelChangeCallbacks_=[];policy_;channelProps_;chunkStoreView_;context_;pointerDownPos_=null;debugMode_=!1;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;wireframeColors_=[new GA(.6,.3,.3),new GA(.3,.6,.4),new GA(.4,.4,.7),new GA(.6,.5,.3)];constructor({source:A,sliceCoords:I,policy:g,orientation:Q,channelProps:C,onPickValue:E,...i}){super({blendMode:"additive",occludes:!0,...i}),this.setState("initialized"),this.source_=A,this.policy_=g??_g(),this.sliceCoords_=I,this.orientation_=Q??"XY",this.axes_=bI(this.orientation_),this.planeRotation_=PI(this.axes_),this.channelProps_=C,this.initialChannelProps_=C,this.onPickValue_=E}attach(A){this.context_=A,this.chunkStoreView_=A.chunkManager.addView(this.source_,this.policy_,this.axes_),QC(this.channelProps_,this.chunkStoreView_.channelCount)}detach(A){this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.orderedChunks_=[],this.clearObjects(),this.chunkStoreView_?.dispose(),this.chunkStoreView_=void 0,this.context_=void 0}update(A){if(!A||!this.chunkStoreView_)return;const I=A.camera,g=I.type==="OrthographicCamera"?I.getWorldViewRect():this.chunkStoreView_.getWholePlaneRect();this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,{worldViewRect:g,bufferWidthPx:A.getBufferRect().width}),this.updateChunks();for(const[Q,C]of this.visibleChunks_)this.updateSlicePosition(C,Q)}get orientation(){return this.orientation_}setOrientation(A){A!==this.orientation_&&(this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.orderedChunks_=[],this.clearObjects(),this.chunkStoreView_?.dispose(),this.lastPresentationTimeStamp_=void 0,this.lastPresentationTimeCoord_=void 0,this.orientation_=A,this.axes_=bI(A),this.planeRotation_=PI(this.axes_),this.context_&&(this.chunkStoreView_=this.context_.chunkManager.addView(this.source_,this.policy_,this.axes_)))}updateChunks(){if(!this.chunkStoreView_)return;this.state!=="ready"&&this.setState("ready");const A=Array.from(this.visibleChunks_.keys()).every(C=>C.texture!==void 0);if(this.visibleChunks_.size>0&&A&&!this.chunkStoreView_.hasCompleteVisibleLOD()&&!this.isPresentationStale())return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const I=this.chunkStoreView_.getChunksToRender(),g=new Set(I),Q=Array.from(this.visibleChunks_.keys()).filter(C=>!g.has(C));this.releaseAndRemoveChunks(Q);for(const C of I)this.visibleChunks_.set(C,this.getImageForChunk(C,C.texture));this.orderedChunks_=I,this.rebuildRenderGroups()}rebuildRenderGroups(){this.clearObjects();for(const A of this.orderedChunks_){const I=this.visibleChunks_.get(A),g=A.chunkIndex.c;I===void 0||this.channelProps_?.[g]?.visible===!1||this.addObject(I,g)}}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>AB.STALE_PRESENTATION_MS_}onEvent(A){this.pointerDownPos_=iC(A,this.pointerDownPos_,I=>this.pickAtRay(I),this.onPickValue_)}async pickAtRay(A){const I=this.visibleChunks_.values().next();if(I.done)return null;const g=I.value.transform,Q=PQ(AA(),wA(0,0,1),g.rotation),C=CI.fromPointAndNormal(g.translation,Q),E=A.intersectWithPlane(C);if(!E)return null;const i=await this.getValueAtWorld(E);return i===null?null:{world:E,value:i}}get chunkStoreView(){return this.chunkStoreView_}get sliceCoords(){return this.sliceCoords_}get source(){return this.source_}get imageSourcePolicy(){return this.policy_}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,zg))}getImageForChunk(A,I){const g=this.visibleChunks_.get(A);if(g)return g;const Q=this.pool_.acquire(IB(A,this.axes_));return Q?(Q.setTexture(0,I),Q.setChannelProps(this.getChannelPropsForChunk(A)),this.updateImageChunk(Q,A),Q):this.createImage(A,I)}getChannelPropsForChunk(A){return this.channelProps_?[this.channelProps_[A.chunkIndex.c]??{}]:[{}]}createImage(A,I){const g=new EC({width:A.shape[this.axes_.u],height:A.shape[this.axes_.v],texture:I,channelProps:this.getChannelPropsForChunk(A)});return this.updateImageChunk(g,A),g}updateSlicePosition(A,I){const{u:g,v:Q,w:C}=this.axes_,E=AA();E[RA[g]]=I.offset[g],E[RA[Q]]=I.offset[Q],E[RA[C]]=this.sliceCoords_[C]??I.offset[C],A.transform.setTranslation(E)}sliceIndexForChunk(A){const I=this.axes_.w,g=this.sliceCoords_[I];if(g===void 0)return 0;const Q=(g-A.offset[I])/A.scale[I];return QI(Math.round(Q),0,A.shape[I]-1)}updateImageChunk(A,I){this.debugMode_?(A.wireframeEnabled=!0,A.wireframeColor=this.wireframeColors_[I.lod%this.wireframeColors_.length]):A.wireframeEnabled=!1;const{u:g,v:Q}=this.axes_;A.transform.setScale([I.scale[g],I.scale[Q],1]),A.transform.setRotation(this.planeRotation_),this.updateSlicePosition(A,I),A.worldToTexCoord=$Q(I,this.axes_)}async getValueAtWorld(A){const I=this.chunkStoreView_?.currentLOD??0;for(const g of[!0,!1])for(const[Q,C]of this.visibleChunks_){if(Q.lod===I!==g)continue;const E=await this.readValueFromChunk(Q,C,A);if(E!==null)return E}return null}async readValueFromChunk(A,I,g){const Q=eB(AA(),g,I.transform.inverse),{u:C,v:E,w:i}=this.axes_,D=Math.floor(Q[0]),a=Math.floor(Q[1]);if(D<0||D>=A.shape[C]||a<0||a>=A.shape[E])return null;const G={x:0,y:0,z:0};return G[C]=D,G[E]=a,G[i]=this.sliceIndexForChunk(A),await I.textures[0].readTexel?.(G.x,G.y,G.z)??null}get debugMode(){return this.debugMode_}set debugMode(A){this.debugMode_=A,this.visibleChunks_.forEach((I,g)=>{I.wireframeEnabled=this.debugMode_,this.debugMode_&&(I.wireframeColor=this.wireframeColors_[g.lod%this.wireframeColors_.length])})}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.visibleChunks_.forEach((I,g)=>{I.setChannelProps(this.getChannelPropsForChunk(g))}),this.rebuildRenderGroups(),this.channelChangeCallbacks_.forEach(I=>{I()})}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===-1)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}releaseAndRemoveChunks(A){for(const I of A){const g=this.visibleChunks_.get(I);g&&(this.pool_.release(IB(I,this.axes_),g),this.visibleChunks_.delete(I))}}}function IB(B,A){return[`plane${A.u}${A.v}`,`lod${B.lod}`,`shape${B.shape.x}x${B.shape.y}x${B.shape.z}`,`align${B.rowAlignmentBytes}`].join(":")}class oC extends pB{width_;height_;constructor(A,I,g){super(),this.dataFormat="scalar",this.dataType=fB(A),this.data_=A,this.width_=I,this.height_=g}get type(){return"Texture2D"}get width(){return this.width_}get height(){return this.height_}}const Oi=[[1,.5,.5],[.5,1,.5],[.5,.5,1],[.5,1,1],[1,.5,1],[1,1,.5]];function Xi(B){return B=B??new Map,new Map(Array.from(B.entries()).map(([A,I])=>[A,GA.from(I)]))}function vi(B){return B=B??Oi,B.map(GA.from)}function gB(B={}){return{lookupTable:Xi(B.lookupTable),cycle:vi(B.cycle)}}const DC=new Set(["byte","short","int"]),ji=new Set(["unsigned_byte","unsigned_short","unsigned_int"]);function zi(B){if(B.dataFormat!=="scalar")throw new Error(`Image data format must be scalar, instead found: ${B.dataFormat}`);if(!DC.has(B.dataType)&&!ji.has(B.dataType))throw new Error(`Image data type must be an integer, instead found: ${B.dataType}`);return B}function _i(B){return DC.has(B.dataType)?"intLabelImage":"labelImage"}class aC extends VI{worldToTexCoord=WA();outlineSelected_;selectedValue_;constructor(A){super(),this.geometry=new CC(A.width,A.height,1,1),this.setTexture(0,zi(A.imageData));const I=gB(A.colorMap);this.setTexture(1,this.makeColorCycleTexture(I.cycle)),this.setTexture(2,this.makeColorLookupTableTexture(I.lookupTable)),this.outlineSelected_=A.outlineSelected??!1,this.selectedValue_=A.selectedValue??null,this.programName=_i(A.imageData),this.depthProgramName="meshDepth"}get type(){return"LabelImageRenderable"}getUniforms(){return{u_imageSampler:0,u_colorCycleSampler:1,u_colorLookupTableSampler:2,u_outlineSelected:this.outlineSelected_?1:0,u_selectedValue:this.selectedValue_??-1,u_worldToTexCoord:this.worldToTexCoord}}setColorMap(A){const I=gB(A);this.markStaleTexture(this.textures[1]),this.markStaleTexture(this.textures[2]),this.setTexture(1,this.makeColorCycleTexture(I.cycle)),this.setTexture(2,this.makeColorLookupTableTexture(I.lookupTable))}setSelectedValue(A){this.selectedValue_=A}makeColorCycleTexture(A){const I=new Uint8Array(A.flatMap(Q=>Q.rgba).map(Q=>Math.round(Q*255))),g=new oC(I,A.length,1);return g.dataFormat="rgba",g}makeColorLookupTableTexture(A){A===void 0?A=new Map([[0,GA.TRANSPARENT]]):A.has(0)||(A=new Map([[0,GA.TRANSPARENT],...A]));const I=Array.from(A.keys()),g=Array.from(A.values()).map(E=>E.packed),Q=A.size,C=new Uint32Array(Q*2);return C.set(I,0),C.set(g,Q),new oC(C,Q,2)}}class BB extends Ug{type="LabelLayer";source_;sliceCoords_;axes_;planeRotation_;orientation_;onPickValue_;outlineSelected_;visibleChunks_=new Map;pool_=new PB;colorMap_;selectedValue_=null;policy_;chunkStoreView_;context_;pointerDownPos_=null;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;constructor({source:A,sliceCoords:I,policy:g,orientation:Q,colorMap:C={},onPickValue:E,outlineSelected:i=!1,...D}){super(D),this.setState("initialized"),this.source_=A,this.policy_=g??_g(),this.sliceCoords_=I,this.orientation_=Q??"XY",this.axes_=bI(this.orientation_),this.planeRotation_=PI(this.axes_),this.colorMap_=gB(C),this.onPickValue_=E,this.outlineSelected_=i}attach(A){if(this.context_=A,this.chunkStoreView_=A.chunkManager.addView(this.source_,this.policy_,this.axes_),this.chunkStoreView_.channelCount>1)throw new Error(`LabelLayer does not support multi-channel sources (found ${this.chunkStoreView_.channelCount} channels). Label data must be single-channel.`)}detach(A){this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_?.dispose(),this.chunkStoreView_=void 0,this.context_=void 0}update(A){if(!A||!this.chunkStoreView_)return;const I=A.camera,g=I.type==="OrthographicCamera"?I.getWorldViewRect():this.chunkStoreView_.getWholePlaneRect();this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,{worldViewRect:g,bufferWidthPx:A.getBufferRect().width}),this.updateChunks();for(const[Q,C]of this.visibleChunks_)this.updateSlicePosition(C,Q)}get orientation(){return this.orientation_}setOrientation(A){A!==this.orientation_&&(this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_?.dispose(),this.lastPresentationTimeStamp_=void 0,this.lastPresentationTimeCoord_=void 0,this.orientation_=A,this.axes_=bI(A),this.planeRotation_=PI(this.axes_),this.context_&&(this.chunkStoreView_=this.context_.chunkManager.addView(this.source_,this.policy_,this.axes_)))}updateChunks(){if(!this.chunkStoreView_)return;this.state!=="ready"&&this.setState("ready");const A=Array.from(this.visibleChunks_.keys()).every(C=>C.texture!==void 0);if(this.visibleChunks_.size>0&&A&&!this.chunkStoreView_.hasCompleteVisibleLOD()&&!this.isPresentationStale())return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const I=this.chunkStoreView_.getChunksToRender(),g=new Set(I),Q=Array.from(this.visibleChunks_.keys()).filter(C=>!g.has(C));this.releaseAndRemoveChunks(Q),this.clearObjects();for(const C of I){const E=this.getLabelForChunk(C,C.texture);this.visibleChunks_.set(C,E),this.addObject(E,0)}}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>BB.STALE_PRESENTATION_MS_}onEvent(A){this.pointerDownPos_=iC(A,this.pointerDownPos_,I=>this.pickAtRay(I),this.outlineSelected_?I=>{this.setSelectedValue(I.value),this.onPickValue_?.(I)}:this.onPickValue_)}async pickAtRay(A){const I=this.visibleChunks_.values().next();if(I.done)return null;const g=I.value.transform,Q=PQ(AA(),wA(0,0,1),g.rotation),C=CI.fromPointAndNormal(g.translation,Q),E=A.intersectWithPlane(C);if(!E)return null;const i=await this.getValueAtWorld(E);return i===null?null:{world:E,value:i}}get colorMap(){return this.colorMap_}setColorMap(A){this.colorMap_=gB(A),this.visibleChunks_.forEach(I=>{I.setColorMap(this.colorMap_)})}setSelectedValue(A){this.selectedValue_=A,this.visibleChunks_.forEach(I=>{I.setSelectedValue(this.selectedValue_)})}get sliceCoords(){return this.sliceCoords_}get source(){return this.source_}get imageSourcePolicy(){return this.policy_}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,zg))}get chunkStoreView(){return this.chunkStoreView_}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}async getValueAtWorld(A){const I=this.chunkStoreView_?.currentLOD??0;for(const g of[!0,!1])for(const[Q,C]of this.visibleChunks_){if(Q.lod===I!==g)continue;const E=await this.readValueFromChunk(Q,C,A);if(E!==null)return E}return null}async readValueFromChunk(A,I,g){const Q=eB(AA(),g,I.transform.inverse),{u:C,v:E,w:i}=this.axes_,D=Math.floor(Q[0]),a=Math.floor(Q[1]);if(D<0||D>=A.shape[C]||a<0||a>=A.shape[E])return null;const G={x:0,y:0,z:0};return G[C]=D,G[E]=a,G[i]=this.sliceIndexForChunk(A),await I.textures[0].readTexel?.(G.x,G.y,G.z)??null}getLabelForChunk(A,I){const g=this.visibleChunks_.get(A);if(g)return g;const Q=this.pool_.acquire(IB(A,this.axes_));return Q?(Q.setTexture(0,I),Q.setColorMap(this.colorMap_),Q.setSelectedValue(this.selectedValue_),this.updateLabelChunk(Q,A),Q):this.createLabel(A,I)}createLabel(A,I){const g=new aC({width:A.shape[this.axes_.u],height:A.shape[this.axes_.v],imageData:I,colorMap:this.colorMap_,outlineSelected:this.outlineSelected_,selectedValue:this.selectedValue_});return this.updateLabelChunk(g,A),g}updateSlicePosition(A,I){const{u:g,v:Q,w:C}=this.axes_,E=AA();E[RA[g]]=I.offset[g],E[RA[Q]]=I.offset[Q],E[RA[C]]=this.sliceCoords_[C]??I.offset[C],A.transform.setTranslation(E)}sliceIndexForChunk(A){const I=this.axes_.w,g=this.sliceCoords_[I];if(g===void 0)return 0;const Q=(g-A.offset[I])/A.scale[I];return QI(Math.round(Q),0,A.shape[I]-1)}updateLabelChunk(A,I){const{u:g,v:Q}=this.axes_;A.transform.setScale([I.scale[g],I.scale[Q],1]),A.transform.setRotation(this.planeRotation_),this.updateSlicePosition(A,I),A.worldToTexCoord=$Q(I,this.axes_)}releaseAndRemoveChunks(A){for(const I of A){const g=this.visibleChunks_.get(I);g&&(this.pool_.release(IB(I,this.axes_),g),this.visibleChunks_.delete(I))}}}class $i extends uI{constructor(A,I,g,Q,C,E){super();const i=[],D=[],a=Math.floor(Q),G=Math.floor(C),R=Math.floor(E);this.buildFace("z","y","x",-1,-1,g,I,A,R,G,1,i,D),this.buildFace("z","y","x",1,-1,g,I,A,R,G,-1,i,D),this.buildFace("x","z","y",1,1,A,g,I,a,R,1,i,D),this.buildFace("x","z","y",1,-1,A,g,I,a,R,-1,i,D),this.buildFace("x","y","z",1,-1,A,I,g,a,G,1,i,D),this.buildFace("x","y","z",-1,-1,A,I,g,a,G,-1,i,D),this.vertexData_=new Float32Array(i),this.indexData_=new Uint32Array(D),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}buildFace(A,I,g,Q,C,E,i,D,a,G,R,t,J){const n=E/a,e=i/G,K=E/2,l=i/2,V=D/2*R,x=a+1,W=G+1,p=t.length/8;for(let T=0;T<W;T++){const $=-l+T*e;for(let CA=0;CA<x;CA++){const BA=-K+CA*n,iA={x:0,y:0,z:0};iA[A]=BA*Q,iA[I]=$*C,iA[g]=V;const sA={x:0,y:0,z:0};sA[g]=R;const qA=CA/a,kA=1-T/G;t.push(iA.x,iA.y,iA.z,sA.x,sA.y,sA.z,qA,kA)}}for(let T=0;T<G;T++)for(let $=0;$<a;$++){const CA=p+$+x*T,BA=p+$+x*(T+1),iA=p+($+1)+x*(T+1),sA=p+($+1)+x*T;J.push(CA,BA,sA,BA,iA,sA)}}}class sC extends VI{voxelScale=wA(1,1,1);channels_;loadedChannels_=new Set;channelToTextureIndex_=new Map;constructor({channelProps:A=[]}={}){super(),this.geometry=new $i(1,1,1,1,1,1),this.cullFaceMode="front",this.depthTest=!1,this.channels_=[],this.setChannelProps(A)}get type(){return"VolumeRenderable"}updateVolumeWithChunk(A){if(!A.texture)return;const I=A.chunkIndex.c,g=this.channelToTextureIndex_.get(I);g!==void 0?this.updateChannelTexture(g,A.texture):this.addChannelTexture(I,A.texture),this.loadedChannels_.add(I)}addChannelTexture(A,I){const g=this.textures.length;this.setTexture(g,I),this.channelToTextureIndex_.set(A,g);const Q=Ao(I.dataType);if(this.programName&&this.programName!==Q)throw new Error(`Volume renderable does not support multiple channels with different data types. Existing program: ${this.programName}, new channel data type: ${I.dataType} and program: ${Q}`);this.programName=Q}updateChannelTexture(A,I){this.setTexture(A,I)}clearLoadedChannels(){this.loadedChannels_=new Set}reset(){this.clearTextures(),this.channelToTextureIndex_.clear(),this.clearLoadedChannels()}getUniforms(){const A=[0,0,0,0],I=[1,1,1,1,1,1,1,1,1,1,1,1],g=[0,0,0,0],Q=[1,1,1,1],C=[1,1,1,1],E=[],i=Math.max(this.channels_.length,this.channelToTextureIndex_.size);for(let D=0;D<i&&E.length<4;D++){const a=this.channelToTextureIndex_.get(D);if(a===void 0||!this.loadedChannels_.has(D))continue;const G=this.textures[a],R=kg(G,this.channels_[D]||{});if(!R.visible)continue;const t=E.length;I[t*3]=R.color.rgb[0],I[t*3+1]=R.color.rgb[1],I[t*3+2]=R.color.rgb[2],E.push(a),g[t]=-R.contrastLimits[0],Q[t]=1/(R.contrastLimits[1]-R.contrastLimits[0]),A[t]=1,C[t]=R.opacity}return E.reduce((D,a,G)=>(D[`u_channel${G}Sampler`]=a,D),{u_visible:A,"u_color[0]":I,u_valueOffset:g,u_valueScale:Q,u_channelOpacity:C,u_voxelScale:[this.voxelScale[0],this.voxelScale[1],this.voxelScale[2]]})}getAvailableChannelTexture(A){if(A!==void 0){const g=this.channelToTextureIndex_.get(A);if(g!==void 0)return this.textures[g]}const I=this.channelToTextureIndex_.values().next().value;return I!==void 0?this.textures[I]:null}setChannelProps(A){this.channels_=uB(this.getAvailableChannelTexture(),A)}setChannelProperty(A,I,g){const Q=kg(this.getAvailableChannelTexture(A),{...this.channels_[A],[I]:g});this.channels_[A]=Q}}function Ao(B){switch(B){case"byte":case"int":case"short":return"intVolume";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintVolume";case"float":return"floatVolume"}}const Io=2;class yC extends Ug{type="VolumeLayer";debugShowDegenerateRays=!1;relativeStepSize=1;opacityMultiplier=1;earlyTerminationAlpha=.99;requiresSceneDepth_=!0;source_;sliceCoords_;currentVolumes_=new Map;volumeToPoolKey_=new Map;pool_=new PB;initialChannelProps_;channelChangeCallbacks_=[];policy_;chunkStoreView_;channelProps_;lastLoadedTime_=void 0;lastNumRenderedChannelChunks_=void 0;interactiveStepSizeScale_=1;debugShowWireframes_=!1;get debugShowWireframes(){return this.debugShowWireframes_}set debugShowWireframes(A){if(this.debugShowWireframes_!==A){for(const I of this.currentVolumes_.values())I.wireframeEnabled=A;this.debugShowWireframes_=A}}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,zg))}setChannelProps(A){this.channelProps_=A;for(const I of this.currentVolumes_.values())I.setChannelProps(A);this.channelChangeCallbacks_.forEach(I=>{I()})}get channelProps(){return this.channelProps_}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===-1)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}constructor({source:A,sliceCoords:I,policy:g,channelProps:Q}){super({blendMode:"premultipliedOver"}),this.source_=A,this.sliceCoords_=I,this.policy_=g??_g(),this.initialChannelProps_=Q,this.channelProps_=Q,this.setState("initialized")}getOrCreateVolume(A,I){const g=this.currentVolumes_.get(A);if(g){for(const E of I)g.updateVolumeWithChunk(E);return g}const Q=Qo(I[0]),C=this.pool_.acquire(Q)??new sC;C.setChannelProps(this.channelProps_??[]),this.volumeToPoolKey_.set(C,Q);for(const E of I)C.updateVolumeWithChunk(E);return this.updateVolumeTransform(C,I[0]),C}attach(A){this.chunkStoreView_=A.chunkManager.addView(this.source_,this.policy_),QC(this.channelProps_,this.chunkStoreView_.channelCount)}detach(A){for(const I of this.currentVolumes_.values())this.releaseAndRemoveVolume(I);this.currentVolumes_.clear(),this.clearObjects(),this.chunkStoreView_?.dispose(),this.chunkStoreView_=void 0}updateChunks(){if(!this.chunkStoreView_)return;this.state!=="ready"&&this.setState("ready");const A=this.chunkStoreView_.getChunksToRender(),I=this.sliceCoords_.t??-1,g=Bo(A);if(this.lastLoadedTime_!==I||g.size!==this.currentVolumes_.size||this.lastNumRenderedChannelChunks_!==A.length){for(const[C,E]of this.currentVolumes_)g.has(C)||(this.releaseAndRemoveVolume(E),this.currentVolumes_.delete(C));for(const[C,E]of g){const i=this.getOrCreateVolume(C,E);i.wireframeEnabled=this.debugShowWireframes,this.currentVolumes_.set(C,i)}this.lastLoadedTime_=I,this.lastNumRenderedChannelChunks_=A.length}}updateVolumeTransform(A,I){const g={x:I.shape.x*I.scale.x,y:I.shape.y*I.scale.y,z:I.shape.z*I.scale.z};A.transform.setScale([g.x,g.y,g.z]),LI(A.voxelScale,I.scale.x,I.scale.y,I.scale.z);const Q={x:I.shape.x*I.scale.x/2,y:I.shape.y*I.scale.y/2,z:I.shape.z*I.scale.z/2};A.transform.setTranslation([I.offset.x+Q.x,I.offset.y+Q.y,I.offset.z+Q.z])}releaseAndRemoveVolume(A){A.reset(),this.pool_.release(this.volumeToPoolKey_.get(A),A),this.volumeToPoolKey_.delete(A)}update(A){if(!A||!this.chunkStoreView_)return;this.chunkStoreView_.updateChunksForVolume(this.sliceCoords_,A.camera.getViewProjection());const I=A.cameraControls?.isMoving??!1;this.interactiveStepSizeScale_=I?Io:1,this.updateChunks(),this.rebuildObjects(A.camera)}rebuildObjects(A){const I=Array.from(this.currentVolumes_.values());Co(I,A),this.clearObjects();for(const g of I)this.addObject(g)}get chunkStoreView(){return this.chunkStoreView_}getUniforms(){return{u_debugShowDegenerateRays:Number(this.debugShowDegenerateRays),u_relativeStepSize:this.relativeStepSize*this.interactiveStepSizeScale_,u_opacityMultiplier:this.opacityMultiplier,u_earlyTerminationAlpha:this.earlyTerminationAlpha}}}function go(B){const{x:A,y:I,z:g,t:Q}=B.chunkIndex;return`${A}:${I}:${g}:${Q}`}function Bo(B){const A=new Map;for(const I of B){const g=go(I);let Q=A.get(g);Q||(Q=[],A.set(g,Q)),Q.push(I)}return A}function Qo(B){return[`lod${B.lod}`,`shape${B.shape.x}x${B.shape.y}x${B.shape.z}`,`align${B.rowAlignmentBytes}`].join(":")}function Co(B,A){const I=A.position,g=new Map;for(const Q of B){const C=Q.transform.translation;g.set(Q,gi(I,C))}B.sort((Q,C)=>g.get(C)-g.get(Q))}var cg=function(B=1){var A=0,I=document.createElement("div");I.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",I.addEventListener("click",function(R){R.preventDefault(),Q(++A%I.children.length)},!1);function g(R){return I.appendChild(R.dom),R}function Q(R){for(var t=0;t<I.children.length;t++)I.children[t].style.display=t===R?"block":"none";A=R}var C=(performance||Date).now(),E=C,i=0,D=g(new cg.Panel("FPS","#0ff","#002",B)),a=g(new cg.Panel("MS","#0f0","#020",B));if(self.performance&&self.performance.memory)var G=g(new cg.Panel("MB","#f08","#201",B));return Q(0),{REVISION:16,dom:I,addPanel:g,showPanel:Q,begin:function(){C=(performance||Date).now()},end:function(){i++;var R=(performance||Date).now();if(a.update(R-C,200),R>=E+1e3&&(D.update(i*1e3/(R-E),100),E=R,i=0,G)){var t=performance.memory;G.update(t.usedJSHeapSize/1048576,t.jsHeapSizeLimit/1048576)}return R},update:function(){C=this.end()},domElement:I,setMode:Q}};cg.Panel=function(B,A,I,g){var Q=1/0,C=0,E=Math.round,i=E(window.devicePixelRatio||1),D=E(80*i*g),a=E(48*i*g),G=E(3*i*g),R=E(2*i*g),t=E(3*i*g),J=E(15*i*g),n=E(74*i*g),e=E(30*i*g),K=document.createElement("canvas");K.width=D,K.height=a,K.style.cssText=`width:${E(g*80)}px;height:${E(g*48)}px`;var l=K.getContext("2d");return l.font="bold "+E(9*i*g)+"px Helvetica,Arial,sans-serif",l.textBaseline="top",l.fillStyle=I,l.fillRect(0,0,D,a),l.fillStyle=A,l.fillText(B,G,R),l.fillRect(t,J,n,e),l.fillStyle=I,l.globalAlpha=.9,l.fillRect(t,J,n,e),{dom:K,update:function(V,x){Q=Math.min(Q,V),C=Math.max(C,V),l.fillStyle=I,l.globalAlpha=1,l.fillRect(0,0,D,J),l.fillStyle=A,l.fillText(E(V)+" "+B+" ("+E(Q)+"-"+E(C)+")",G,R),l.drawImage(K,t+i,J,n-i,e,t,J,n-i,e),l.fillRect(t+n-i,J,i,e),l.fillStyle=I,l.globalAlpha=.9,l.fillRect(t+n-i,J,i,E((1-V/x)*e))}}};function Eo({scale:B}={scale:1.5}){const A=new cg(B);return A.showPanel(0),document.body.appendChild(A.dom),A}const VB=["pointerdown","pointermove","pointerup","pointercancel","wheel"];function io(B){return VB.includes(B)}class oo{propagationStopped_=!1;type;event;worldPos;worldRay;clipPos;constructor(A,I){this.type=A,this.event=I}get propagationStopped(){return this.propagationStopped_}stopPropagation(){this.propagationStopped_=!0}}class Do{listeners_=[];element_;isConnected_=!1;constructor(A){this.element_=A}addEventListener(A){this.listeners_.push(A)}removeEventListener(A){const I=this.listeners_.indexOf(A);if(I===-1)throw new Error(`Listener to remove could not be found: ${A}`);this.listeners_.splice(I,1)}connect(){if(this.isConnected_){O.warn("EventDispatcher","Attempted to connect already connected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!0,VB.forEach(A=>{this.element_.addEventListener(A,this.handleEvent,{passive:!1})})}disconnect(){if(!this.isConnected_){O.debug("EventDispatcher","Attempted to disconnect already disconnected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!1,VB.forEach(A=>{this.element_.removeEventListener(A,this.handleEvent)})}handleEvent=A=>{if(!io(A.type)){O.error("EventDispatcher",`Unsupported event type ${A.type}`);return}const I=new oo(A.type,A);for(const g of this.listeners_)if(g(I),I.propagationStopped)break}}const ao=1e-12;class so{origin;direction;constructor(A,I){this.origin=$A(A),this.direction=bQ(AA(),I)}intersectWithPlane(A){const I=bg(this.direction,A.normal);if(Math.abs(I)<ao)return null;const g=-A.signedDistanceToPoint(this.origin)/I;return KB(AA(),this.origin,this.direction,g)}}class hC{id;element;camera;events;cameraControls;context_;layers_=[];constructor(A){this.id=A.id,this.element=A.element,this.camera=A.camera,this.context_=A.context,this.cameraControls=A.cameraControls,this.updateAspectRatio(),this.events=new Do(this.element),this.events.addEventListener(I=>{if(I.event instanceof PointerEvent||I.event instanceof WheelEvent){const{clientX:g,clientY:Q}=I.event,C=LA(g,Q);I.clipPos=this.clientToClip(C,0),I.worldPos=this.camera.clipToWorld(I.clipPos);const E=this.camera.clipToWorld(this.clientToClip(C,-1)),i=this.camera.clipToWorld(this.clientToClip(C,1));I.worldRay=new so(E,nB(AA(),i,E))}for(const g of this.layers_)if(g.onEvent(I),I.propagationStopped)return;this.cameraControls?.onEvent(I)});for(const I of A.layers??[])this.addLayer(I)}get layers(){return this.layers_}addLayer(A){A.onAttached(this.context_),this.layers_.push(A)}removeLayer(A){const I=this.layers_.indexOf(A);if(I===-1)throw new Error(`Layer to remove not found: ${A}`);this.layers_.splice(I,1),A.onDetached(this.context_)}removeAllLayers(){for(const A of this.layers_)A.onDetached(this.context_);this.layers_=[]}updateSize(){this.updateAspectRatio()}getBoxRelativeTo(A){const I=this.getBox().toRect(),g=A.getBoundingClientRect(),Q=window.devicePixelRatio||1,C=g.left*Q,E=g.top*Q,i=g.height*Q,D=I.x-C,a=I.y-E,G=Math.floor(D),R=Math.floor(i-a-I.height),t=Math.floor(I.width),J=Math.floor(I.height);return new mA(LA(G,R),LA(G+t,R+J))}getBufferRect(){return this.getBoxRelativeTo(this.element).toRect()}clientToClip(A,I=0){const[g,Q]=A,C=this.element.getBoundingClientRect();return wA(2*(g-C.x)/C.width-1,2*(Q-C.y)/C.height-1,I)}clientToWorld(A,I=0){const g=this.clientToClip(A,I);return this.camera.clipToWorld(g)}getBox(){const A=this.element.getBoundingClientRect(),I=window.devicePixelRatio||1,g=A.left*I,Q=A.top*I,C=A.width*I,E=A.height*I;return new mA(LA(g,Q),LA(g+C,Q+E))}updateAspectRatio(){const{width:A,height:I}=this.getBox().toRect();if(A<=0||I<=0){O.debug("Viewport",`Skipping aspect ratio update for viewport ${this.id}: invalid dimensions ${A}x${I}`);return}const g=A/I;this.camera.setAspectRatio(g)}}function GC(B,A){for(const I of A){if(I.id===B.id)throw new Error(`Duplicate viewport ID "${B.id}". Each viewport must have a unique ID.`);if(I.element===B.element){const g=B.element.tagName.toLowerCase()+(B.element.id?`#${B.element.id}`:"[element has no id]");throw new Error(`Multiple viewports cannot share the same HTML element: viewports "${I.id}" and "${B.id}" both use ${g}`)}}}function yo(B){for(let A=0;A<B.length;A++)GC(B[A],B.slice(0,A))}function FC(B,A,I){const g=B.map(Q=>{const C=Q.element??A;return{...Q,element:C,id:Q.id??C.id??xQ("viewport"),context:I}});return yo(g),g.map(Q=>new hC(Q))}class ho{elements_;resizeObserver_;mediaQuery_;onMediaQueryChange_;onChange_;constructor(A=[],I){this.elements_=[...A],this.onChange_=I}connect(){if(this.resizeObserver_){O.warn("PixelSizeObserver","Attempted to connect already connected observer");return}this.resizeObserver_=new ResizeObserver(()=>{this.onChange_()});for(const A of this.elements_)this.resizeObserver_.observe(A);this.startDevicePixelRatioObserver()}startDevicePixelRatioObserver(){this.mediaQuery_=matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this.onMediaQueryChange_=()=>{this.onChange_(),this.startDevicePixelRatioObserver()},this.mediaQuery_.addEventListener("change",this.onMediaQueryChange_,{once:!0})}disconnect(){if(!this.resizeObserver_){O.warn("PixelSizeObserver","Attempted to disconnect already disconnected observer");return}this.resizeObserver_?.disconnect(),this.mediaQuery_&&this.onMediaQueryChange_&&this.mediaQuery_.removeEventListener("change",this.onMediaQueryChange_)}observe(A){if(this.elements_.includes(A)){O.warn("PixelSizeObserver","Element already being observed");return}this.elements_.push(A),this.resizeObserver_&&this.resizeObserver_.observe(A)}unobserve(A){const I=this.elements_.indexOf(A);if(I===-1){O.warn("PixelSizeObserver","Element not being observed");return}this.elements_.splice(I,1),this.resizeObserver_&&this.resizeObserver_.unobserve(A)}}const Go=2048;class Fo{canvas;overlays;chunkManager_;context_;renderer_;viewports_;stats_;sizeObserver_;lastAnimationId_;lastTimestamp_=0;constructor(A){this.canvas=A.canvas,this.renderer_=new ri(this.canvas);const g=(A.memoryLimitMB??Go)*1024*1024;this.chunkManager_=new mi(C=>this.renderer_.uploadTexture(C),C=>this.renderer_.disposeTexture(C),()=>this.renderer_.gpuTextureBytes,g,A.maxConcurrentRequests,A.maxGpuUploadsPerUpdate),this.context_={chunkManager:this.chunkManager_},this.viewports_=FC(A.viewports??[],this.canvas,this.context_),this.overlays=[...A.overlays??[]],A.showStats&&(this.stats_=Eo());const Q=[this.canvas];for(const C of this.viewports_)C.element!==this.canvas&&Q.push(C.element);this.sizeObserver_=new ho(Q,()=>{this.renderer_.updateSize(),this.renderer_.beginFrame();for(const C of this.viewports_)C.updateSize(),this.renderer_.render(C)})}get chunkQueueStats(){return this.chunkManager_.queueStats}get chunkStats(){const A=[];for(const I of this.viewports_){const g=[];for(const Q of I.layers)!(Q instanceof AB)&&!(Q instanceof BB)&&!(Q instanceof yC)||Q.chunkStoreView&&g.push(Q.chunkStoreView);g.length!==0&&A.push(li(I.id,g))}return{sources:this.chunkManager_.sourceChunkStats,viewports:A}}get memoryStats(){const A=performance.memory;return{...this.chunkManager_.memoryStats,gpuTextureBytes:this.renderer_.gpuTextureBytes,gpuTextureCount:this.renderer_.gpuTextureCount,jsHeapUsedBytes:A?.usedJSHeapSize,jsHeapLimitBytes:A?.jsHeapSizeLimit}}get renderedObjects(){return this.renderer_.renderedObjects}get width(){return this.renderer_.width}get height(){return this.renderer_.height}get viewports(){return this.viewports_}get running(){return this.lastAnimationId_!==void 0}getViewport(A){return this.viewports_.find(I=>I.id===A)}addViewport(A){const[I]=FC([A],this.canvas,this.context_);return GC(I,this.viewports_),this.viewports_.push(I),this.running&&(I.events.connect(),I.element!==this.canvas&&this.sizeObserver_.observe(I.element)),O.info("Idetik",`Added viewport "${I.id}"`),I}removeViewport(A){const I=this.viewports_.indexOf(A);return I===-1?(O.warn("Idetik",`Viewport "${A.id}" not found, nothing to remove`),!1):(this.running&&(A.events.disconnect(),A.element!==this.canvas&&this.sizeObserver_.unobserve(A.element)),this.viewports_.splice(I,1),O.info("Idetik",`Removed viewport "${A.id}"`),!0)}addOverlay(A){this.overlays.push(A)}removeOverlay(A){const I=this.overlays.indexOf(A);return I===-1?(O.warn("Idetik","Overlay not found, nothing to remove"),!1):(this.overlays.splice(I,1),!0)}setMemoryLimitMB(A){this.chunkManager_.memoryLimitBytes=A*1024*1024}start(){if(O.info("Idetik","Idetik runtime starting"),this.running)O.warn("Idetik","Idetik runtime already started");else{for(const A of this.viewports_)A.events.connect();this.sizeObserver_.connect(),this.lastAnimationId_=requestAnimationFrame(A=>{this.lastTimestamp_=A,this.animate(A)})}return this}animate(A){this.stats_&&this.stats_.begin();const I=Math.min(A-this.lastTimestamp_,100)/1e3;this.lastTimestamp_=A,this.renderer_.beginFrame();for(const g of this.viewports_)g.cameraControls?.onUpdate(I),this.renderer_.render(g);this.chunkManager_.update();for(const g of this.overlays)g.update(this);this.stats_&&this.stats_.end(),this.lastAnimationId_=requestAnimationFrame(g=>this.animate(g))}stop(){if(O.info("Idetik","Idetik runtime stopping"),!this.running)O.warn("Idetik","Idetik runtime not started");else{this.sizeObserver_.disconnect();for(const A of this.viewports_)A.events.disconnect();cancelAnimationFrame(this.lastAnimationId_),this.lastAnimationId_=void 0}}}function wo(B,A){return{...B,...A,headers:{...B.headers,...A.headers}}}function wC(B,A){const I=typeof B=="string"?new URL(B):B;I.pathname.endsWith("/")||(I.pathname+="/");const g=new URL(A.slice(1),I);return g.search=I.search,g}async function SC(B){if(B.status!==404){if(B.status===200||B.status===206)return new Uint8Array(await B.arrayBuffer());throw new Error(`Unexpected response status ${B.status} ${B.statusText}`)}}class Lg{url;#A;#I;#g;constructor(A,I={}){this.url=A,this.#A=I.fetch??(g=>fetch(g)),this.#I=I.overrides??{},this.#g=I.useSuffixRequest??!1}#B(A,I){return new Request(A,wo(this.#I,I))}async get(A,I={}){let g=wC(this.url,A).href,Q=this.#B(g,I),C=await this.#A(Q);return SC(C)}async getRange(A,I,g={}){let Q=wC(this.url,A),C;if("suffixLength"in I)C=await this.#Q(Q,I.suffixLength,g);else{let E={...g,headers:{...g.headers,Range:`bytes=${I.offset}-${I.offset+I.length-1}`}},i=this.#B(Q,E);C=await this.#A(i)}return SC(C)}async#Q(A,I,g){if(this.#g){let G={...g,headers:{...g.headers,Range:`bytes=-${I}`}};return this.#A(this.#B(A,G))}let Q=this.#B(A,{...g,method:"HEAD"}),C=await this.#A(Q);if(!C.ok)return C;let E=C.headers.get("Content-Length"),i=Number(E),D=i-I,a={...g,headers:{...g.headers,Range:`bytes=${D}-${i-1}`}};return this.#A(this.#B(A,a))}}class Jg extends Error{}class OI extends Jg{_tag="NotFoundError";name="NotFoundError";path;found;constructor(A,I={}){super(`Not found: ${A}`,{cause:I.cause}),this.path=I.path,this.found=I.found}}class JA extends Jg{_tag="InvalidMetadataError";name="InvalidMetadataError";path;constructor(A,I={}){super(A,{cause:I.cause}),this.path=I.path}}class So extends Jg{_tag="UnknownCodecError";name="UnknownCodecError";codec;constructor(A){super(`Unknown codec: ${A}`),this.codec=A}}class Ro extends Jg{_tag="CodecPipelineError";name="CodecPipelineError";direction;codec;chunkPath;constructor(A){const I=[`Failed to ${A.direction} chunk`,A.codec&&`via codec "${A.codec}"`,A.chunkPath&&`at ${A.chunkPath}`].filter(Boolean);super(I.join(" "),{cause:A.cause}),this.direction=A.direction,this.codec=A.codec,this.chunkPath=A.chunkPath}}class OB extends Jg{_tag="UnsupportedError";name="UnsupportedError";feature;constructor(A){super(`Unsupported: ${A}`),this.feature=A}}function JI(B){return()=>{throw new OB(`${B} encode`)}}class QB{kind="array_to_array";constructor(A,I){if(A.keepbits<0)throw new JA("keepbits must be zero or positive")}static fromConfig(A,I){return new QB(A,I)}encode=JI("bitround");decode(A){return A}}function XB(B){return B instanceof ArrayBuffer||B instanceof SharedArrayBuffer}class RC{#A;constructor(A,I,g){typeof A=="number"?this.#A=new Uint8Array(A):XB(A)?this.#A=new Uint8Array(A,I,g):this.#A=new Uint8Array(Array.from(A,Q=>Q?1:0))}get BYTES_PER_ELEMENT(){return 1}get byteOffset(){return this.#A.byteOffset}get byteLength(){return this.#A.byteLength}get buffer(){return this.#A.buffer}get length(){return this.#A.length}get(A){let I=this.#A[A];return typeof I=="number"?I!==0:I}set(A,I){this.#A[A]=I?1:0}fill(A){this.#A.fill(A?1:0)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class vB{_data;chars;#A;constructor(A,I,g,Q){if(this.chars=A,this.#A=new TextEncoder,typeof I=="number")this._data=new Uint8Array(I*A);else if(XB(I))Q&&(Q=Q*A),this._data=new Uint8Array(I,g,Q);else{let C=Array.from(I);this._data=new Uint8Array(C.length*A);for(let E=0;E<C.length;E++)this.set(E,C[E])}}get BYTES_PER_ELEMENT(){return this.chars}get byteOffset(){return this._data.byteOffset}get byteLength(){return this._data.byteLength}get buffer(){return this._data.buffer}get length(){return this.byteLength/this.BYTES_PER_ELEMENT}get(A){const I=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);return new TextDecoder().decode(I).replace(/\x00/g,"")}set(A,I){const g=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);g.fill(0),g.set(this.#A.encode(I))}fill(A){const I=this.#A.encode(A);for(let g=0;g<this.length;g++)this._data.set(I,g*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class rg{#A;chars;constructor(A,I,g,Q){if(this.chars=A,typeof I=="number")this.#A=new Int32Array(I*A);else if(XB(I))Q&&(Q*=A),this.#A=new Int32Array(I,g,Q);else{const C=I,E=new rg(A,1);this.#A=new Int32Array((function*(){for(let i of C)E.set(0,i),yield*E.#A})())}}get BYTES_PER_ELEMENT(){return this.#A.BYTES_PER_ELEMENT*this.chars}get byteLength(){return this.#A.byteLength}get byteOffset(){return this.#A.byteOffset}get buffer(){return this.#A.buffer}get length(){return this.#A.length/this.chars}get(A){const I=this.chars*A;let g="";for(let Q=0;Q<this.chars;Q++)g+=String.fromCodePoint(this.#A[I+Q]);return g.replace(/\u0000/g,"")}set(A,I){const g=this.chars*A,Q=this.#A.subarray(g,g+this.chars);Q.fill(0);for(let C=0;C<this.chars;C++)Q[C]=I.codePointAt(C)??0}fill(A){this.set(0,A);let I=this.#A.subarray(0,this.chars);for(let g=1;g<this.length;g++)this.#A.set(I,g*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}function No(){if(typeof SharedArrayBuffer>"u")throw new Error("SharedArrayBuffer is not available. In browsers, this requires Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers to be set.")}function to(B,A){return new SharedArrayBuffer(B)}function ng(B){const A=new TextDecoder().decode(B);try{return JSON.parse(A)}catch(I){throw new JA("Failed to decode JSON",{cause:I})}}function NC(B,A){const I=A/2,g=A-1;let Q=0;for(let C=0;C<B.length;C+=A)for(let E=0;E<I;E+=1)Q=B[C+E],B[C+E]=B[C+g-E],B[C+g-E]=Q}function XI(B){if(B==="v2:object")return globalThis.Array;let A=B.match(/v2:([US])(\d+)/);if(A){let[,g,Q]=A;return(g==="U"?rg:vB).bind(null,Number(Q))}if(B==="string")return globalThis.Array;let I={int8:Int8Array,int16:Int16Array,int32:Int32Array,int64:globalThis.BigInt64Array,uint8:Uint8Array,uint16:Uint16Array,uint32:Uint32Array,uint64:globalThis.BigUint64Array,float16:globalThis.Float16Array,float32:Float32Array,float64:Float64Array,bool:RC}[B];if(!I)throw new JA(`Unknown or unsupported dataType: ${B}`);return I}function rI(B,A){const I=B.length;typeof A=="string"&&(A=A==="C"?Array.from({length:I},(C,E)=>E):Array.from({length:I},(C,E)=>I-1-E)),VA(I===A.length,"Order length must match the number of dimensions.");let g=1,Q=new Array(I);for(let C=A.length-1;C>=0;C--)Q[A[C]]=g,g*=B[A[C]];return Q}function Uo({name:B,configuration:A}){if(B==="default"){const I=A?.separator??"/";return g=>["c",...g].join(I)}if(B==="v2"){const I=A?.separator??".";return g=>g.join(I)||"0"}throw new JA(`Unknown chunk key encoding: ${B}`)}function tC(B){if(B==="|O")return{dataType:"v2:object"};let A=B.match(/^([<|>])(.*)$/);if(!A)throw new JA(`Invalid dtype: ${B}`);let[,I,g]=A,Q={b1:"bool",i1:"int8",u1:"uint8",i2:"int16",u2:"uint16",i4:"int32",u4:"uint32",i8:"int64",u8:"uint64",f2:"float16",f4:"float32",f8:"float64"}[g]??(g.startsWith("S")||g.startsWith("U")?`v2:${g}`:void 0);if(!Q)throw new JA(`Unsupported or unknown dtype: ${B}`);return I==="|"?{dataType:Q}:{dataType:Q,endian:I==="<"?"little":"big"}}function ko(B){return(B.id==="fixedscaleoffset"||B.id==="numcodecs.fixedscaleoffset")&&typeof B.scale=="number"&&typeof B.offset=="number"&&(B.astype===void 0||typeof B.astype=="string")&&(B.dtype===void 0||typeof B.dtype=="string")}function co(B,A={}){let I=[],g=tC(B.dtype);B.order==="F"&&I.push({name:"transpose",configuration:{order:"F"}});for(let C of B.filters??[]){if(C.id==="fixedscaleoffset"||C.id==="numcodecs.fixedscaleoffset"){if(!ko(C))throw new JA(`Invalid fixedscaleoffset filter: ${JSON.stringify(C)}`);I.push({name:"scale_offset",configuration:{scale:C.scale,offset:C.offset}});let D=C.astype??C.dtype;if(D!==void 0&&D!==B.dtype){let a=tC(D).dataType;if(!jB(a,"number")&&!jB(a,"bigint"))throw new JA(`fixedscaleoffset astype must be a numeric data type, got ${D}`);I.push({name:"cast_value",configuration:{data_type:a,rounding:"nearest-even",out_of_range:"wrap"}})}continue}let{id:E,...i}=C;I.push({name:`numcodecs.${E}`,configuration:i})}if("endian"in g&&g.endian==="big"&&I.push({name:"bytes",configuration:{endian:"big"}}),B.compressor){let{id:C,...E}=B.compressor;I.push({name:`numcodecs.${C}`,configuration:E})}let Q;return globalThis.Array.isArray(A._ARRAY_DIMENSIONS)&&(Q=A._ARRAY_DIMENSIONS),{zarr_format:3,node_type:"array",shape:B.shape,data_type:g.dataType,chunk_grid:{name:"regular",configuration:{chunk_shape:B.chunks}},chunk_key_encoding:{name:"v2",configuration:{separator:B.dimension_separator??"."}},codecs:I,fill_value:B.fill_value,dimension_names:Q,attributes:A}}function Lo(B,A={}){return{zarr_format:3,node_type:"group",attributes:A}}function jB(B,A){if(A!=="number"&&A!=="bigint"&&A!=="boolean"&&A!=="object"&&A!=="string")return B===A;let I=B==="bool";if(A==="boolean")return I;let g=B.startsWith("v2:U")||B.startsWith("v2:S")||B==="string";if(A==="string")return g;let Q=B==="int64"||B==="uint64";if(A==="bigint")return Q;let C=B==="v2:object";return A==="object"?C:!g&&!Q&&!I&&!C}function Jo(B){return B?.name==="sharding_indexed"}function UC(B){if((B.data_type==="uint64"||B.data_type==="int64")&&B.fill_value!=null)return BigInt(B.fill_value);let A=B.data_type==="float16"||B.data_type==="float32"||B.data_type==="float64";if(typeof B.fill_value=="string"&&A){let I={NaN:NaN,Infinity:1/0,"-Infinity":-1/0};if(B.fill_value in I)return I[B.fill_value]}return B.fill_value}function kC(B,...A){if(!A.some(I=>B instanceof I))throw B}function VA(B,A=""){if(!B)throw new Error(A)}async function cC(B,{format:A,signal:I}){let g;if(B instanceof ArrayBuffer)g=new Response(B);else{let Q=new Uint8Array(B.buffer,B.byteOffset,B.byteLength);g=new Response(Q.slice().buffer)}VA(g.body,"Response does not contain body.");try{return await new Response(g.body.pipeThrough(new DecompressionStream(A),{signal:I})).arrayBuffer()}catch{throw I?.throwIfAborted(),new Error(`Failed to decode ${A}`)}}const LC=ro();function ro(){const B=new Uint32Array([305419896]);return new Uint8Array(B.buffer,B.byteOffset,B.byteLength)[0]!==18}function JC(B){return"BYTES_PER_ELEMENT"in B?B.BYTES_PER_ELEMENT:4}class CB{kind="array_to_bytes";#A;#I;#g;#B;#Q;constructor(A,I){this.#Q=A?.endian,this.#I=XI(I.dataType),this.#B=I.shape,this.#A=rI(I.shape,"C");const g=new this.#I(0);this.#g=g.BYTES_PER_ELEMENT}static fromConfig(A,I){return new CB(A,I)}encode(A){let I=new Uint8Array(A.data.buffer);return LC&&this.#Q==="big"&&NC(I,JC(this.#I)),I}computeEncodedSize(A){return A}decode(A){return LC&&this.#Q==="big"&&NC(A,JC(this.#I)),{data:new this.#I(A.buffer,A.byteOffset,A.byteLength/this.#g),shape:this.#B,stride:this.#A}}}const rC={NaN:NaN,Infinity:1/0,"-Infinity":-1/0},nC={float16:2,float32:4,float64:8};function EB(B){return B in nC}function zB(B){return B==="int64"||B==="uint64"}function no(B,A){const I=BigInt(B),g=new ArrayBuffer(A),Q=new DataView(g);if(A===2){if(typeof Q.getFloat16!="function")throw new OB("float16 hex-encoded scalar decoding (requires DataView.prototype.getFloat16)");return Q.setUint16(0,Number(I)),Q.getFloat16(0)}return A===4?(Q.setUint32(0,Number(I)),Q.getFloat32(0)):(Q.setBigUint64(0,I),Q.getFloat64(0))}function iB(B,A){if(zB(B)){if(typeof A!="number"||!Number.isInteger(A))throw new JA(`Expected an integer value for data type "${B}", got ${JSON.stringify(A)}`);return BigInt(A)}if(typeof A=="number"){if(!EB(B)&&!Number.isInteger(A))throw new JA(`Expected an integer value for data type "${B}", got ${A}`);return A}if(!EB(B))throw new JA(`String-encoded scalar "${A}" is not valid for non-float data type "${B}"`);return A in rC?rC[A]:no(A,nC[B])}const YC=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]),_B={int8:[-128,2**7-1],uint8:[0,2**8-1],int16:[-32768,2**15-1],uint16:[0,2**16-1],int32:[-2147483648,2**31-1],uint32:[0,2**32-1]},$B={int64:[-(2n**63n),2n**63n-1n],uint64:[0n,2n**64n-1n]};function KC(B,A,I){return B.map(([g,Q])=>({src:iB(A,g),tgt:iB(I,Q)}))}function Yo(B,A){for(const I of A)if(typeof I.src=="number"&&Number.isNaN(I.src)){if(typeof B=="number"&&Number.isNaN(B))return I.tgt}else if(B===I.src)return I.tgt}function Ko(B){if(!Number.isFinite(B))return B;if(Math.abs(B-Math.trunc(B))===.5){const A=Math.floor(B),I=Math.ceil(B);return A%2===0?A:I}return Math.round(B)}function eo(B){return Math.sign(B)*Math.floor(Math.abs(B)+.5)}function eC(B){switch(B){case"nearest-even":return Ko;case"towards-zero":return Math.trunc;case"towards-positive":return Math.ceil;case"towards-negative":return Math.floor;case"nearest-away":return eo}}function AQ(B,A,I){const g=A-B+1;switch(I){case"clamp":return Q=>Q<B?B:Q>A?A:Q;case"wrap":return Q=>Q>=B&&Q<=A?Q:((Q-B)%g+g)%g+B;default:return Q=>{if(Q>=B&&Q<=A)return Q;throw new Error(`Value ${Q} out of range [${B}, ${A}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}function IQ(B,A,I){const g=A-B+1n;switch(I){case"clamp":return Q=>Q<B?B:Q>A?A:Q;case"wrap":return Q=>Q>=B&&Q<=A?Q:((Q-B)%g+g)%g+B;default:return Q=>{if(Q>=B&&Q<=A)return Q;throw new Error(`Value ${Q} out of range [${B}, ${A}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}class gQ{kind="array_to_array";#A;#I;#g;#B;constructor(A,I,g,Q,C,E){this.#A=I,this.#I=XI(A),this.#g=MC(I,A,g,Q,C),this.#B=MC(A,I,g,Q,E)}getEncodedMeta(A){let I=A.fillValue;return I!=null&&(I=this.#B(I)),{...A,dataType:this.#A,fillValue:I}}static fromConfig(A,I){const g=I.dataType,Q=A.data_type;if(!YC.has(g))throw new JA(`cast_value codec does not support array data type: ${g}`);if(!YC.has(Q))throw new JA(`cast_value codec does not support encoded data type: ${Q}`);const C=A.rounding??"nearest-even",E=A.scalar_map?.decode?KC(A.scalar_map.decode,Q,g):[],i=A.scalar_map?.encode?KC(A.scalar_map.encode,g,Q):[];return new gQ(g,Q,C,A.out_of_range,E,i)}encode=JI("cast_value");decode(A){const I=A.data,g=new this.#I(I.length);for(let Q=0;Q<I.length;Q++)g[Q]=this.#g(I[Q]);return{data:g,shape:A.shape,stride:A.stride}}}function MC(B,A,I,g,Q){const C=EB(B),E=zB(B),i=EB(A),D=zB(A);let a;if(C&&i){if(I!=="nearest-even")throw new JA(`cast_value float -> float only supports "nearest-even" rounding, got "${I}"`);a=R=>R}else if(C&&!i&&!D){const R=eC(I),t=AQ(..._B[A],g);a=J=>{if(!Number.isFinite(J))throw new Error(`Cannot cast ${J} to integer type without scalar_map`);return t(R(J))}}else if(C&&D){const R=eC(I),t=IQ(...$B[A],g);a=J=>{if(!Number.isFinite(J))throw new Error(`Cannot cast ${J} to integer type without scalar_map`);return t(BigInt(R(J)))}}else if(!C&&!E&&i)a=R=>R;else if(E&&i)a=R=>Number(R);else if(!C&&!E&&!i&&!D)a=AQ(..._B[A],g);else if(!C&&!E&&D){const R=IQ(...$B[A],g);a=t=>R(BigInt(t))}else if(E&&!i&&!D){const R=AQ(..._B[A],g);a=t=>R(Number(t))}else if(E&&D)a=IQ(...$B[A],g);else throw new Error(`Unhandled type combination: ${B} -> ${A}`);return Q.length===0?a:R=>{const t=Yo(R,Q);return t!==void 0?t:a(R)}}class BQ{kind="bytes_to_bytes";static fromConfig(){return new BQ}encode=JI("crc32c");decode(A){return new Uint8Array(A.buffer,A.byteOffset,A.byteLength-4)}computeEncodedSize(A){return A+4}}const Mo=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);function HC(B,A){const I=B.length;let g=I===0||A[I-1]===1;for(let C=I-2;C>=0&&g;C--)g=A[C]===A[C+1]*B[C+1];if(g)return;let Q=I===0||A[0]===1;for(let C=1;C<I&&Q;C++)Q=A[C]===A[C-1]*B[C-1];if(!Q)throw new Error(`DeltaCodec requires C- or Fortran-contiguous strides, got shape=${JSON.stringify(B)} stride=${JSON.stringify(A)}`)}class QQ{kind="array_to_array";#A;constructor(A){this.#A=A}static fromConfig(A,I){if(!Mo.has(I.dataType))throw new JA(`Delta codec does not support data type: ${I.dataType}`);return new QQ(XI(I.dataType))}encode(A){HC(A.shape,A.stride);const I=A.data,g=new this.#A(I.length);g[0]=I[0];for(let Q=1;Q<I.length;Q++)g[Q]=I[Q]-I[Q-1];return{data:g,shape:A.shape,stride:A.stride}}decode(A){HC(A.shape,A.stride);const I=A.data,g=new this.#A(I.length);g[0]=I[0];for(let Q=1;Q<I.length;Q++)g[Q]=g[Q-1]+I[Q];return{data:g,shape:A.shape,stride:A.stride}}}class CQ{kind="bytes_to_bytes";static fromConfig(A){return new CQ}encode=JI("gzip");async decode(A){const I=await cC(A,{format:"gzip"});return new Uint8Array(I)}}function Ho(B,A){return VA(!Number.isNaN(A),"JsonCodec allow_nan is false but NaN was encountered during encoding."),VA(A!==Number.POSITIVE_INFINITY,"JsonCodec allow_nan is false but Infinity was encountered during encoding."),VA(A!==Number.NEGATIVE_INFINITY,"JsonCodec allow_nan is false but -Infinity was encountered during encoding."),A}function qo(B,A){return A instanceof Object&&!Array.isArray(A)?Object.keys(A).sort().reduce((I,g)=>(I[g]=A[g],I),{}):A}class oB{configuration;kind="array_to_bytes";#A;#I;constructor(A={}){this.configuration=A;const{encoding:I="utf-8",skipkeys:g=!1,ensure_ascii:Q=!0,check_circular:C=!0,allow_nan:E=!0,sort_keys:i=!0,indent:D,strict:a=!0}=A;let G=A.separators;G||(D?G=[", ",": "]:G=[",",":"]),this.#A={encoding:I,skipkeys:g,ensure_ascii:Q,check_circular:C,allow_nan:E,indent:D,separators:G,sort_keys:i},this.#I={strict:a}}static fromConfig(A){return new oB(A)}encode(A){const{indent:I,encoding:g,ensure_ascii:Q,check_circular:C,allow_nan:E,sort_keys:i}=this.#A;VA(g==="utf-8","JsonCodec does not yet support non-utf-8 encoding.");const D=[];VA(C,"JsonCodec does not yet support skipping the check for circular references during encoding."),E||D.push(Ho),i&&D.push(qo);const a=Array.from(A.data);a.push("|O"),a.push(A.shape);let G;D.length&&(G=(t,J)=>{let n=J;for(let e of D)n=e(t,n);return n});let R=JSON.stringify(a,G,I);return Q&&(R=R.replace(/[\u007F-\uFFFF]/g,t=>{const J=`0000${t.charCodeAt(0).toString(16)}`;return`\\u${J.substring(J.length-4)}`})),new TextEncoder().encode(R)}decode(A){const{strict:I}=this.#I;VA(I,"JsonCodec does not yet support non-strict decoding.");const g=ng(A),Q=g.pop();g.pop(),VA(Q,"0D not implemented for JsonCodec.");const C=rI(Q,"C");return{data:g,shape:Q,stride:C}}}const fo=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);class EQ{kind="array_to_array";#A;#I;#g;constructor(A,I,g){this.#I=A,this.#g=I,this.#A=g}static fromConfig(A,I){if(!fo.has(I.dataType))throw new JA(`scale_offset codec does not support data type: ${I.dataType}`);return new EQ(iB(I.dataType,A.scale??1),iB(I.dataType,A.offset??0),XI(I.dataType))}encode=JI("scale_offset");decode(A){const I=A.data,g=new this.#A(I.length);for(let Q=0;Q<I.length;Q++)g[Q]=I[Q]/this.#I+this.#g;return{data:g,shape:A.shape,stride:A.stride}}}class iQ{kind="bytes_to_bytes";#A;constructor(A,I){if(I){let g=new(XI(I.dataType))(0);VA("BYTES_PER_ELEMENT"in g,`Shuffle codec requires a fixed-size dtype, got "${I.dataType}"`),this.#A=g.BYTES_PER_ELEMENT}else this.#A=A.elementsize??4}static fromConfig(A,I){return new iQ(A,I)}encode(A){return lo(A,this.#A)}decode(A){return po(A,this.#A)}}function lo(B,A){let I=B.length,g=Math.floor(I/A),Q=new Uint8Array(I);for(let C=0;C<A;C++)for(let E=0;E<g;E++)Q[C*g+E]=B[E*A+C];return Q}function po(B,A){let I=B.length,g=Math.floor(I/A),Q=new Uint8Array(I);for(let C=0;C<A;C++)for(let E=0;E<g;E++)Q[E*A+C]=B[C*g+E];return Q}function qC(B){return B instanceof RC||B instanceof vB||B instanceof rg?new Proxy(B,{get(I,g){return I.get(Number(g))},set(I,g,Q){return I.set(Number(g),Q),!0}}):B}function Wo(B,A){let I;return B.data instanceof vB||B.data instanceof rg?I=new B.constructor(B.data.length,B.data.chars):I=new B.constructor(B.data.length),{data:I,shape:B.shape,stride:rI(B.shape,A)}}function mo(B,A){let I=Wo(B,A),g=B.shape.length,Q=B.data.length,C=Array(g).fill(0),E=qC(B.data),i=qC(I.data);for(let D=0;D<Q;D++){let a=0;for(let G=0;G<g;G++)a+=C[G]*I.stride[G];i[a]=E[D],C[0]+=1;for(let G=0;G<g;G++)if(C[G]===B.shape[G]){if(G+1===g)break;C[G]=0,C[G+1]+=1}}return I}function To(B){let A=B.shape.length;return VA(A===B.stride.length,"Shape and stride must have the same length."),B.stride.map((I,g)=>({stride:I,index:g})).sort((I,g)=>g.stride-I.stride).map(I=>I.index)}function xo(B,A){let I=To(B);return VA(I.length===A.length,"Orders must match"),I.every((g,Q)=>g===A[Q])}class oQ{kind="array_to_array";#A;#I;constructor(A,I){let g=A.order??"C",Q=I.shape.length,C=new Array(Q),E=new Array(Q);if(g==="C")for(let i=0;i<Q;++i)C[i]=i,E[i]=i;else if(g==="F")for(let i=0;i<Q;++i)C[i]=Q-i-1,E[i]=Q-i-1;else C=g,C.forEach((i,D)=>{VA(E[i]===void 0,`Invalid permutation: ${JSON.stringify(g)}`),E[i]=D});this.#A=C,this.#I=E}static fromConfig(A,I){return new oQ(A,I)}encode(A){return xo(A,this.#I)?A:mo(A,this.#I)}decode(A){return{data:A.data,shape:A.shape,stride:rI(A.shape,this.#A)}}}class DB{kind="array_to_bytes";#A;#I;constructor(A){this.#A=A,this.#I=rI(A,"C")}static fromConfig(A,I){return new DB(I.shape)}encode=JI("vlen-utf8");decode(A){let I=new TextDecoder,g=new DataView(A.buffer),Q=Array(g.getUint32(0,!0)),C=4;for(let E=0;E<Q.length;E++){let i=g.getUint32(C,!0);C+=4,Q[E]=I.decode(A.buffer.slice(C,C+i)),C+=i}return{data:Q,shape:this.#A,stride:this.#I}}}class DQ{kind="bytes_to_bytes";static fromConfig(A){return new DQ}encode=JI("zlib");async decode(A){const I=await cC(A,{format:"deflate"});return new Uint8Array(I)}}function Zo(){let B=()=>Promise.resolve().then(()=>la).then(C=>C.default),A=()=>Promise.resolve().then(()=>Za).then(C=>C.default),I=()=>Promise.resolve().then(()=>Xa).then(C=>C.default),g=()=>CQ,Q=()=>DQ;return new Map().set("blosc",B).set("lz4",A).set("zstd",I).set("gzip",g).set("zlib",Q).set("transpose",()=>oQ).set("bytes",()=>CB).set("crc32c",()=>BQ).set("vlen-utf8",()=>DB).set("json2",()=>oB).set("bitround",()=>QB).set("cast_value",()=>gQ).set("scale_offset",()=>EQ).set("numcodecs.blosc",B).set("numcodecs.lz4",A).set("numcodecs.zstd",I).set("numcodecs.gzip",g).set("numcodecs.zlib",Q).set("numcodecs.vlen-utf8",()=>DB).set("numcodecs.shuffle",()=>iQ).set("numcodecs.delta",()=>QQ).set("numcodecs.bitround",()=>QB).set("numcodecs.json2",()=>oB)}const uo=Zo();function aQ(B){let A;function I(){return A||(A=bo(B)),A}async function g(Q,C,E){try{return await E()}catch(i){throw new Ro({direction:Q,codec:C,cause:i})}}return{async encode(Q){let C=await I();for(const{name:i,codec:D}of C.arrayToArray)Q=await g("encode",i,()=>D.encode(Q));let E=await g("encode",C.arrayToBytes.name,()=>C.arrayToBytes.codec.encode(Q));for(const{name:i,codec:D}of C.bytesToBytes)E=await g("encode",i,()=>D.encode(E));return E},async decode(Q){let C=await I();for(let i=C.bytesToBytes.length-1;i>=0;i--){const{name:D,codec:a}=C.bytesToBytes[i];Q=await g("decode",D,()=>a.decode(Q))}let E=await g("decode",C.arrayToBytes.name,()=>C.arrayToBytes.codec.decode(Q));for(let i=C.arrayToArray.length-1;i>=0;i--){const{name:D,codec:a}=C.arrayToArray[i];E=await g("decode",D,()=>a.decode(E))}return E},async computeEncodedSize(Q){let C=await I(),E=dC(C.arrayToBytes.name,C.arrayToBytes.codec,Q);for(const{name:i,codec:D}of C.bytesToBytes)E=dC(i,D,E);return E}}}function dC(B,A,I){if(!A.computeEncodedSize)throw new JA(`Codec "${B}" cannot compute its encoded size; it is not a fixed-size codec and cannot be used in a sharding index pipeline`);return A.computeEncodedSize(I)}async function bo(B){let A=B.codecs.map(async E=>{let i=await uo.get(E.name)?.();if(!i)throw new So(E.name);return{Codec:i,meta:E}}),I=[],g,Q=[],C={...B};for await(let{Codec:E,meta:i}of A){let D=E.fromConfig(i.configuration,C);switch(D.kind){case"array_to_array":I.push({name:i.name,codec:D}),D.getEncodedMeta&&(C=D.getEncodedMeta(C));break;case"array_to_bytes":g={name:i.name,codec:D};break;default:Q.push({name:i.name,codec:D})}}if(!g){if(!Po(C))throw new JA(`Cannot encode ${C.dataType} to bytes without a codec`);g={name:"bytes",codec:CB.fromConfig({endian:"little"},C)}}return{arrayToArray:I,arrayToBytes:g,bytesToBytes:Q}}function Po(B){return B.dataType!=="v2:object"&&B.dataType!=="string"}const fC=18446744073709551615n;function Vo(B,A,I,g){if(!B.store.getRange)throw new OB("sharding requires a store with getRange");let Q=B.store.getRange.bind(B.store),C=A.map((a,G)=>a/g.chunk_shape[G]),E=aQ({dataType:"uint64",shape:[...C,2],codecs:g.index_codecs,fillValue:null}),i=16*C.reduce((a,G)=>a*G,1),D={};return async(a,G)=>{let R=a.map((W,p)=>Math.floor(W/C[p])),t=B.resolve(I(R)).path;t in D||(D[t]=(async()=>{let W=await E.computeEncodedSize(i),p=await Q(t,{suffixLength:W},G);return p?await E.decode(p):null})().catch(W=>{throw delete D[t],W}));let J=await D[t];if(J===null)return;let{data:n,shape:e,stride:K}=J,l=a.map((W,p)=>W%e[p]).reduce((W,p,T)=>W+p*K[T],0),V=n[l],x=n[l+1];if(!(V===fC&&x===fC))return Q(t,{offset:Number(V),length:Number(x)},G)}}class vA{store;path;constructor(A,I="/"){this.store=A,this.path=I}resolve(A){let I=new URL(`file://${this.path.endsWith("/")?this.path:`${this.path}/`}`);return new vA(this.store,decodeURIComponent(new URL(A,I).pathname))}}class sQ extends vA{kind="group";#A;constructor(A,I,g){super(A,I),this.#A=g}get attrs(){return this.#A.attributes}}function lC(B){return B.find(I=>I.name==="transpose")?.configuration?.order??"C"}const aB=Symbol("zarrita.context");function Oo(B,A){let{configuration:I}=A.codecs.find(Jo)??{},g={encodeChunkKey:Uo(A.chunk_key_encoding),TypedArray:XI(A.data_type),fillValue:A.fill_value};if(I){let C=lC(I.codecs);return{...g,kind:"sharded",chunkShape:I.chunk_shape,codec:aQ({dataType:A.data_type,shape:I.chunk_shape,codecs:I.codecs,fillValue:A.fill_value}),getStrides(E){return rI(E,C)},getChunkBytes:Vo(B,A.chunk_grid.configuration.chunk_shape,g.encodeChunkKey,I)}}let Q=lC(A.codecs);return{...g,kind:"regular",chunkShape:A.chunk_grid.configuration.chunk_shape,codec:aQ({dataType:A.data_type,shape:A.chunk_grid.configuration.chunk_shape,codecs:A.codecs,fillValue:A.fill_value}),getStrides(C){return rI(C,Q)},async getChunkBytes(C,E){let i=g.encodeChunkKey(C),D=B.resolve(i).path;return B.store.get(D,E)}}}let sB=class extends vA{kind="array";#A;[aB];constructor(A,I,g){super(A,I),this.#A={...g,fill_value:UC(g)},this[aB]=Oo(this,this.#A)}get attrs(){return this.#A.attributes}get dimensionNames(){return this.#A.dimension_names}get fillValue(){return this.#A.fill_value}get shape(){return this.#A.shape}get chunks(){return this[aB].chunkShape}get dtype(){return this.#A.data_type}async getChunk(A,I,g){g?.useSharedArrayBuffer&&No();let Q=this[aB],C=await Q.getChunkBytes(A,I);if(!C){let E=Q.chunkShape.reduce((D,a)=>D*a,1),i;if(g?.useSharedArrayBuffer){let D=new Q.TypedArray(0);if(!("BYTES_PER_ELEMENT"in D))console.warn("zarrita: useSharedArrayBuffer is not supported for non-buffer-backed data types."),i=new Q.TypedArray(E);else{let a=to(E*D.BYTES_PER_ELEMENT);i=new Q.TypedArray(a,0,E)}}else i=new Q.TypedArray(E);return i.fill(Q.fillValue),{data:i,shape:Q.chunkShape,stride:Q.getStrides(Q.chunkShape)}}return Q.codec.decode(C)}is(A){return jB(this.dtype,A)}};function Xo(B,A){let I=B;for(let g of A)I instanceof Promise?I=I.then(Q=>g(Q)):I=g(I);return I}function vo(B,...A){return Xo(B,A)}async function pC(B){let A=B.store.arrayExtensions;return A?.length?await vo(B,...A):B}let yB=jo();function jo(){let B=new WeakMap;function A(I){let g=B.get(I)??{v2:0,v3:0};return B.set(I,g),g}return{increment(I,g){A(I)[g]+=1},versionMax(I){let g=A(I);return g.v3>g.v2?"v3":"v2"}}}async function zo(B,A){let I=await B.store.get(B.resolve(".zattrs").path,{signal:A});return I?ng(I):{}}async function _o(B,A={}){let I="store"in B?B:new vA(B),{signal:g}=A,Q={};return(A.attrs??!0)&&(Q=await zo(I,g)),g?.throwIfAborted(),A.kind==="array"?WC(I,Q,g):A.kind==="group"?mC(I,Q,g):WC(I,Q,g).catch(C=>(kC(C,OI,JA),mC(I,Q,g)))}async function WC(B,A,I){let{path:g}=B.resolve(".zarray"),Q=await B.store.get(g,{signal:I});if(!Q)throw new OI("v2 array",{path:g});return yB.increment(B.store,"v2"),pC(new sB(B.store,B.path,co(ng(Q),A)))}async function mC(B,A,I){let{path:g}=B.resolve(".zgroup"),Q=await B.store.get(g,{signal:I});if(!Q)throw new OI("v2 group",{path:g});return yB.increment(B.store,"v2"),new sQ(B.store,B.path,Lo(ng(Q),A))}async function $o(B,A){let{store:I,path:g}=B.resolve("zarr.json"),Q=await B.store.get(g,{signal:A});if(!Q)throw new OI("v3 array or group",{path:g});let C=ng(Q);return C.node_type==="array"&&(C.fill_value=UC(C)),C.node_type==="array"?pC(new sB(I,B.path,C)):new sQ(I,B.path,C)}async function AD(B,A={}){let I="store"in B?B:new vA(B),g=await $o(I,A.signal);if(yB.increment(I.store,"v3"),A.kind===void 0||A.kind==="array"&&g instanceof sB||A.kind==="group"&&g instanceof sQ)return g;let Q=g instanceof sB?"array":"group";throw new OI(`${A.kind} at ${I.path}`,{path:I.path,found:Q})}async function jA(B,A={}){let I="store"in B?B.store:B,g=yB.versionMax(I),Q=g==="v2"?jA.v2:jA.v3,C=g==="v2"?jA.v3:jA.v2;return Q(B,A).catch(E=>(kC(E,OI,JA),C(B,A)))}jA.v2=_o,jA.v3=AD;async function ID(B,A){const I=A.split("/"),g=I.pop();if(!g)throw new Error("Invalid path");for(const Q of I)B=await B.getDirectoryHandle(Q);return B.getFileHandle(g)}class yQ{#A;constructor(A){this.#A=A}get directoryHandle(){return this.#A}async get(A){const I=await ID(this.#A,A.slice(1)).catch(()=>{});if(!I)return;const Q=await(await I.getFile()).arrayBuffer();return new Uint8Array(Q)}}async function Yg(B,A){if(A==="v2")try{return jA.v2(B,{kind:"group",attrs:!0})}catch{throw new Error(`Failed to open Zarr v2 group at ${B}`)}if(A==="v3")try{return jA.v3(B,{kind:"group"})}catch{throw new Error(`Failed to open Zarr v3 group at ${B}`)}try{return jA(B,{kind:"group"})}catch{throw new Error(`Failed to open Zarr group at ${B}`)}}async function gD(B,A){if(A==="v2")try{return jA.v2(B,{kind:"array",attrs:!1})}catch{throw new Error(`Failed to open Zarr v2 array at ${B}`)}if(A==="v3")try{return jA.v3(B,{kind:"array"})}catch{throw new Error(`Failed to open Zarr v3 array at ${B}`)}try{return jA(B,{kind:"array"})}catch{throw new Error(`Failed to open Zarr array at ${B}`)}}async function BD(B){let A;switch(B.type){case"fetch":{const g=new Lg(B.url);A=new vA(g);break}case"filesystem":{A=new vA(new yQ(B.directoryHandle),B.path);break}default:{const g=B;throw new Error(`Unsupported store type: ${g}`)}}const I=B.arrayPath?A.resolve(B.arrayPath):A;return gD(I,B.zarrVersion)}function QD(B,A,I){if(B.store instanceof Lg)return{type:"fetch",arrayPath:A,zarrVersion:I,url:B.store.url.toString()};if(B.store instanceof yQ)return{type:"filesystem",arrayPath:A,zarrVersion:I,directoryHandle:B.store.directoryHandle,path:B.path};throw new Error(`Unsupported store type: ${B.store.constructor.name}`)}function CD(B,A,I,g){return ED(B,A,I,g)}function ED(B,A,I,g){const{targetShape:Q,chunkIndex:C,dimIndices:E}=g;let i=1;for(let p=A.length-1;p>=0;p--){if(I[p]!==i)throw new Error(`Chunk data is not tightly packed, stride=${JSON.stringify(I)}, shape=${JSON.stringify(A)}`);i*=A[p]}const D={x:A[E.x],y:A[E.y],z:E.z!==void 0?A[E.z]:Q.z};if(D.x<Q.x||D.y<Q.y||D.z<Q.z)throw new Error(`Received chunk too small: expected ${JSON.stringify(Q)}, got ${JSON.stringify(D)}`);const a=g.cChunkSize?C.c%g.cChunkSize:0,G=g.tChunkSize?C.t%g.tChunkSize:0,R=Q.x*Q.y*Q.z,t=E.c!==void 0?I[E.c]:0,J=E.t!==void 0?I[E.t]:0,n=G*J+a*t,e=D.x===Q.x&&D.y===Q.y&&D.z===Q.z;if(n===0&&B.length===R&&e)return B;const l=new B.constructor(R),V=E.z!==void 0?I[E.z]:0,x=I[E.y];let W=0;for(let p=0;p<Q.z;p++){const T=n+p*V;for(let $=0;$<Q.y;$++){const CA=T+$*x,BA=CA+Q.x;l.set(B.subarray(CA,BA),W),W+=Q.x}}return l}const TC=`function xg(B, A) {
466
466
  return {
467
467
  ...B,
468
468
  ...A,