@idetik/core 0.36.2 → 0.37.0

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.
@@ -167,10 +167,10 @@ precision mediump float;
167
167
  layout (location = 0) out vec4 fragColor;
168
168
 
169
169
  uniform float u_opacity;
170
- uniform vec3 u_color;
170
+ uniform vec3 u_wireframeColor;
171
171
 
172
172
  void main() {
173
- fragColor = vec4(u_color, u_opacity);
173
+ fragColor = vec4(u_wireframeColor, u_opacity);
174
174
  }`,NB=`#version 300 es
175
175
 
176
176
  precision highp float;
@@ -426,7 +426,7 @@ void main() {
426
426
  fragColor = vec4(color.rgb, alpha);
427
427
  }`;const nE={projectedLine:{vertex:tE,fragment:kE},points:{vertex:cE,fragment:LE},wireframe:{vertex:JE,fragment:rE},floatScalarImage:{vertex:wg,fragment:RB},intScalarImage:{vertex:wg,fragment:RB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},uintScalarImage:{vertex:wg,fragment:RB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])},labelImage:{vertex:wg,fragment:eQ},intLabelImage:{vertex:wg,fragment:eQ,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},floatVolume:{vertex:NB,fragment:UB},intVolume:{vertex:NB,fragment:UB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},uintVolume:{vertex:NB,fragment:UB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])}},HQ={debug:10,info:20,warn:30,error:40},YE={debug:"\x1B[90m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m"};function KE(){const g=typeof process<"u"&&typeof process.env?.NODE_ENV=="string"?process.env.NODE_ENV:void 0;if(g==="production"||g==="development"||g==="test")return g;if(typeof window<"u"){const{NODE_ENV:A}=window;if(A==="production"||A==="development"||A==="test")return A}return"development"}class O{static logLevel_=KE()==="production"?"warn":"debug";static setLogLevel(A){O.logLevel_=A}static debug(A,I,...B){O.log("debug",A,I,...B)}static info(A,I,...B){O.log("info",A,I,...B)}static warn(A,I,...B){O.log("warn",A,I,...B)}static error(A,I,...B){O.log("error",A,I,...B)}static log(A,I,B,...Q){if(HQ[A]<HQ[O.logLevel_])return;const C=new Date().toISOString(),E=YE[A],i=`[${C}][${A.toUpperCase()}][${I}]`,D=[`${E}${i}`,B,...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,B){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(B,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[B,Q]=this.uniformInfo_.get(A)??[];if(!B||!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(B,I):this.gl_.uniform1fv(B,I);break;case this.gl_.INT:typeof I=="number"?this.gl_.uniform1i(B,I):this.gl_.uniform1iv(B,I);break;case this.gl_.FLOAT_VEC2:this.gl_.uniform2fv(B,I);break;case this.gl_.FLOAT_VEC3:this.gl_.uniform3fv(B,I);break;case this.gl_.FLOAT_VEC4:this.gl_.uniform4fv(B,I);break;case this.gl_.FLOAT_MAT4:this.gl_.uniformMatrix4fv(B,!1,I);break;case this.gl_.UNSIGNED_INT:this.gl_.uniform1ui(B,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(B,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 B=this.gl_.getActiveUniform(this.program_,I);if(B){if(!HE.has(B.type))throw new Error(`Unsupported uniform type "${B.type}" (GLenum) found in shader program for uniform "${B.name}"`);const Q=this.gl_.getUniformLocation(this.program_,B.name);Q&&(this.uniformInfo_.set(B.name,[Q,B]),O.debug("WebGLShaderProgram","Uniform found:",B.name,B.type,B.size))}}}addShader(A,I){const B=this.gl_.createShader(I);if(!B)throw new Error(`Failed to create a new shader of type ${I}`);if(this.gl_.shaderSource(B,A),this.gl_.compileShader(B),!this.gl_.getShaderParameter(B,this.gl_.COMPILE_STATUS)){const Q=this.gl_.getShaderInfoLog(B);throw this.gl_.deleteShader(B),new Error(`Error compiling shader: ${Q}`)}return this.gl_.attachShader(this.program_,B),B}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 eE=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]:[],HE=new Set(eE),tB="#pragma inject_defines";class qE{gl_;programs_=new Map;constructor(A){this.gl_=A}use(A){let I=this.programs_.get(A);if(I===void 0){const B=nE[A],Q=qQ(B.vertex,B.vertexDefines),C=qQ(B.fragment,B.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 qQ(g,A){if(A===void 0||A.size==0)return g;if(!g.includes(tB))throw new Error(`Shader source does not contain "${tB}" directive`);const I=Array.from(A.entries()).map(([E,i])=>`#define ${E} ${i}`).join(`
428
428
  `),Q=`#line __LINE__ + ${1-A.size}`,C=`${I}
429
- ${Q}`;return g.replace(tB,C)}const xg={};function dQ(g){const A=g??"";return xg[A]=(xg[A]??0)+1,g?`${g}-${xg[A]}`:String(xg[A])}class Zg{id=dQ()}var wA=1e-6,MA=typeof Float32Array<"u"?Float32Array:Array,dE=Math.PI/180;function fE(g){return g*dE}function fQ(){var g=new MA(9);return MA!=Float32Array&&(g[1]=0,g[2]=0,g[3]=0,g[5]=0,g[6]=0,g[7]=0),g[0]=1,g[4]=1,g[8]=1,g}function lE(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g[3]=A[4],g[4]=A[5],g[5]=A[6],g[6]=A[8],g[7]=A[9],g[8]=A[10],g}function pE(g,A,I,B,Q,C,E,i,D){var a=new MA(9);return a[0]=g,a[1]=A,a[2]=I,a[3]=B,a[4]=Q,a[5]=C,a[6]=E,a[7]=i,a[8]=D,a}function xA(){var g=new MA(16);return MA!=Float32Array&&(g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[11]=0,g[12]=0,g[13]=0,g[14]=0),g[0]=1,g[5]=1,g[10]=1,g[15]=1,g}function ug(g,A){var I=A[0],B=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],r=A[12],H=A[13],K=A[14],l=A[15],V=I*i-B*E,Z=I*D-Q*E,W=I*a-C*E,p=B*D-Q*i,T=B*a-C*i,AA=Q*a-C*D,BA=G*H-R*r,EA=G*K-t*r,CA=G*l-J*r,sA=R*K-t*H,qA=R*l-J*H,kA=t*l-J*K,DA=V*kA-Z*qA+W*sA+p*CA-T*EA+AA*BA;return DA?(DA=1/DA,g[0]=(i*kA-D*qA+a*sA)*DA,g[1]=(Q*qA-B*kA-C*sA)*DA,g[2]=(H*AA-K*T+l*p)*DA,g[3]=(t*T-R*AA-J*p)*DA,g[4]=(D*CA-E*kA-a*EA)*DA,g[5]=(I*kA-Q*CA+C*EA)*DA,g[6]=(K*W-r*AA-l*Z)*DA,g[7]=(G*AA-t*W+J*Z)*DA,g[8]=(E*qA-i*CA+a*BA)*DA,g[9]=(B*CA-I*qA-C*BA)*DA,g[10]=(r*T-H*W+l*V)*DA,g[11]=(R*W-G*T-J*V)*DA,g[12]=(i*EA-E*sA-D*BA)*DA,g[13]=(I*sA-B*EA+Q*BA)*DA,g[14]=(H*Z-r*p-K*V)*DA,g[15]=(G*p-R*Z+t*V)*DA,g):null}function kB(g,A,I){var B=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],r=A[11],H=A[12],K=A[13],l=A[14],V=A[15],Z=I[0],W=I[1],p=I[2],T=I[3];return g[0]=Z*B+W*i+p*R+T*H,g[1]=Z*Q+W*D+p*t+T*K,g[2]=Z*C+W*a+p*J+T*l,g[3]=Z*E+W*G+p*r+T*V,Z=I[4],W=I[5],p=I[6],T=I[7],g[4]=Z*B+W*i+p*R+T*H,g[5]=Z*Q+W*D+p*t+T*K,g[6]=Z*C+W*a+p*J+T*l,g[7]=Z*E+W*G+p*r+T*V,Z=I[8],W=I[9],p=I[10],T=I[11],g[8]=Z*B+W*i+p*R+T*H,g[9]=Z*Q+W*D+p*t+T*K,g[10]=Z*C+W*a+p*J+T*l,g[11]=Z*E+W*G+p*r+T*V,Z=I[12],W=I[13],p=I[14],T=I[15],g[12]=Z*B+W*i+p*R+T*H,g[13]=Z*Q+W*D+p*t+T*K,g[14]=Z*C+W*a+p*J+T*l,g[15]=Z*E+W*G+p*r+T*V,g}function WE(g,A,I){var B=I[0],Q=I[1],C=I[2],E,i,D,a,G,R,t,J,r,H,K,l;return A===g?(g[12]=A[0]*B+A[4]*Q+A[8]*C+A[12],g[13]=A[1]*B+A[5]*Q+A[9]*C+A[13],g[14]=A[2]*B+A[6]*Q+A[10]*C+A[14],g[15]=A[3]*B+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],r=A[8],H=A[9],K=A[10],l=A[11],g[0]=E,g[1]=i,g[2]=D,g[3]=a,g[4]=G,g[5]=R,g[6]=t,g[7]=J,g[8]=r,g[9]=H,g[10]=K,g[11]=l,g[12]=E*B+G*Q+r*C+A[12],g[13]=i*B+R*Q+H*C+A[13],g[14]=D*B+t*Q+K*C+A[14],g[15]=a*B+J*Q+l*C+A[15]),g}function lQ(g,A){return g[0]=A[0],g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=A[1],g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[10]=A[2],g[11]=0,g[12]=0,g[13]=0,g[14]=0,g[15]=1,g}function mE(g,A,I,B){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,r=C*a,H=C*G,K=E*G,l=i*D,V=i*a,Z=i*G,W=B[0],p=B[1],T=B[2];return g[0]=(1-(r+K))*W,g[1]=(t+Z)*W,g[2]=(J-V)*W,g[3]=0,g[4]=(t-Z)*p,g[5]=(1-(R+K))*p,g[6]=(H+l)*p,g[7]=0,g[8]=(J+V)*T,g[9]=(H-l)*T,g[10]=(1-(R+r))*T,g[11]=0,g[12]=I[0],g[13]=I[1],g[14]=I[2],g[15]=1,g}function TE(g,A,I,B,Q){var C=1/Math.tan(A/2);if(g[0]=C/I,g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=C,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[11]=-1,g[12]=0,g[13]=0,g[15]=0,Q!=null&&Q!==1/0){var E=1/(B-Q);g[10]=(Q+B)*E,g[14]=2*Q*B*E}else g[10]=-1,g[14]=-2*B;return g}var xE=TE;function ZE(g,A,I,B,Q,C,E){var i=1/(A-I),D=1/(B-Q),a=1/(C-E);return g[0]=-2*i,g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=-2*D,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[10]=2*a,g[11]=0,g[12]=(A+I)*i,g[13]=(Q+B)*D,g[14]=(E+C)*a,g[15]=1,g}var uE=ZE;function bE(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=B[0],D=B[1],a=B[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 r=D*t-a*R,H=a*G-i*t,K=i*R-D*G;return J=r*r+H*H+K*K,J>0&&(J=1/Math.sqrt(J),r*=J,H*=J,K*=J),g[0]=r,g[1]=H,g[2]=K,g[3]=0,g[4]=R*K-t*H,g[5]=t*r-G*K,g[6]=G*H-R*r,g[7]=0,g[8]=G,g[9]=R,g[10]=t,g[11]=0,g[12]=Q,g[13]=C,g[14]=E,g[15]=1,g}function PE(g,A){var I=g[0],B=g[1],Q=g[2],C=g[3],E=g[4],i=g[5],D=g[6],a=g[7],G=g[8],R=g[9],t=g[10],J=g[11],r=g[12],H=g[13],K=g[14],l=g[15],V=A[0],Z=A[1],W=A[2],p=A[3],T=A[4],AA=A[5],BA=A[6],EA=A[7],CA=A[8],sA=A[9],qA=A[10],kA=A[11],DA=A[12],oI=A[13],AI=A[14],DI=A[15];return Math.abs(I-V)<=wA*Math.max(1,Math.abs(I),Math.abs(V))&&Math.abs(B-Z)<=wA*Math.max(1,Math.abs(B),Math.abs(Z))&&Math.abs(Q-W)<=wA*Math.max(1,Math.abs(Q),Math.abs(W))&&Math.abs(C-p)<=wA*Math.max(1,Math.abs(C),Math.abs(p))&&Math.abs(E-T)<=wA*Math.max(1,Math.abs(E),Math.abs(T))&&Math.abs(i-AA)<=wA*Math.max(1,Math.abs(i),Math.abs(AA))&&Math.abs(D-BA)<=wA*Math.max(1,Math.abs(D),Math.abs(BA))&&Math.abs(a-EA)<=wA*Math.max(1,Math.abs(a),Math.abs(EA))&&Math.abs(G-CA)<=wA*Math.max(1,Math.abs(G),Math.abs(CA))&&Math.abs(R-sA)<=wA*Math.max(1,Math.abs(R),Math.abs(sA))&&Math.abs(t-qA)<=wA*Math.max(1,Math.abs(t),Math.abs(qA))&&Math.abs(J-kA)<=wA*Math.max(1,Math.abs(J),Math.abs(kA))&&Math.abs(r-DA)<=wA*Math.max(1,Math.abs(r),Math.abs(DA))&&Math.abs(H-oI)<=wA*Math.max(1,Math.abs(H),Math.abs(oI))&&Math.abs(K-AI)<=wA*Math.max(1,Math.abs(K),Math.abs(AI))&&Math.abs(l-DI)<=wA*Math.max(1,Math.abs(l),Math.abs(DI))}function $(){var g=new MA(3);return MA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g}function BI(g){var A=new MA(3);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A}function cB(g){var A=g[0],I=g[1],B=g[2];return Math.sqrt(A*A+I*I+B*B)}function yA(g,A,I){var B=new MA(3);return B[0]=g,B[1]=A,B[2]=I,B}function LB(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g}function LI(g,A,I,B){return g[0]=A,g[1]=I,g[2]=B,g}function xI(g,A,I){return g[0]=A[0]+I[0],g[1]=A[1]+I[1],g[2]=A[2]+I[2],g}function JB(g,A,I){return g[0]=A[0]-I[0],g[1]=A[1]-I[1],g[2]=A[2]-I[2],g}function VE(g,A,I){return g[0]=A[0]*I[0],g[1]=A[1]*I[1],g[2]=A[2]*I[2],g}function Sg(g,A,I){return g[0]=A[0]*I,g[1]=A[1]*I,g[2]=A[2]*I,g}function rB(g,A,I,B){return g[0]=A[0]+I[0]*B,g[1]=A[1]+I[1]*B,g[2]=A[2]+I[2]*B,g}function pQ(g,A){var I=A[0]-g[0],B=A[1]-g[1],Q=A[2]-g[2];return I*I+B*B+Q*Q}function WQ(g,A){var I=A[0],B=A[1],Q=A[2],C=I*I+B*B+Q*Q;return C>0&&(C=1/Math.sqrt(C)),g[0]=A[0]*C,g[1]=A[1]*C,g[2]=A[2]*C,g}function bg(g,A){return g[0]*A[0]+g[1]*A[1]+g[2]*A[2]}function Pg(g,A,I){var B=A[0],Q=A[1],C=A[2],E=I[0],i=I[1],D=I[2];return g[0]=Q*D-C*i,g[1]=C*E-B*D,g[2]=B*i-Q*E,g}function nB(g,A,I){var B=A[0],Q=A[1],C=A[2],E=I[3]*B+I[7]*Q+I[11]*C+I[15];return E=E||1,g[0]=(I[0]*B+I[4]*Q+I[8]*C+I[12])/E,g[1]=(I[1]*B+I[5]*Q+I[9]*C+I[13])/E,g[2]=(I[2]*B+I[6]*Q+I[10]*C+I[14])/E,g}function mQ(g,A,I){var B=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-B*a,t=B*D-Q*i;return G=G+G,R=R+R,t=t+t,g[0]=i+E*G+Q*t-C*R,g[1]=D+E*R+C*G-B*t,g[2]=a+E*t+B*R-Q*G,g}function OE(g){return g[0]=0,g[1]=0,g[2]=0,g}function YB(g,A){var I=g[0],B=g[1],Q=g[2],C=A[0],E=A[1],i=A[2];return Math.abs(I-C)<=wA*Math.max(1,Math.abs(I),Math.abs(C))&&Math.abs(B-E)<=wA*Math.max(1,Math.abs(B),Math.abs(E))&&Math.abs(Q-i)<=wA*Math.max(1,Math.abs(Q),Math.abs(i))}var KB=JB,XE=cB;(function(){var g=$();return function(A,I,B,Q,C,E){var i,D;for(I||(I=3),B||(B=0),Q?D=Math.min(Q*I+B,A.length):D=A.length,i=B;i<D;i+=I)g[0]=A[i],g[1]=A[i+1],g[2]=A[i+2],C(g,g,E),A[i]=g[0],A[i+1]=g[1],A[i+2]=g[2];return A}})();function ZI(){var g=new MA(4);return MA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0,g[3]=0),g}function vE(g){var A=new MA(4);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A[3]=g[3],A}function Vg(g,A,I,B){var Q=new MA(4);return Q[0]=g,Q[1]=A,Q[2]=I,Q[3]=B,Q}function jE(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g[3]=A[3],g}function zE(g,A,I){return g[0]=A[0]*I,g[1]=A[1]*I,g[2]=A[2]*I,g[3]=A[3]*I,g}function _E(g,A){var I=A[0],B=A[1],Q=A[2],C=A[3],E=I*I+B*B+Q*Q+C*C;return E>0&&(E=1/Math.sqrt(E)),g[0]=I*E,g[1]=B*E,g[2]=Q*E,g[3]=C*E,g}function Rg(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3];return g[0]=I[0]*B+I[4]*Q+I[8]*C+I[12]*E,g[1]=I[1]*B+I[5]*Q+I[9]*C+I[13]*E,g[2]=I[2]*B+I[6]*Q+I[10]*C+I[14]*E,g[3]=I[3]*B+I[7]*Q+I[11]*C+I[15]*E,g}(function(){var g=ZI();return function(A,I,B,Q,C,E){var i,D;for(I||(I=4),B||(B=0),Q?D=Math.min(Q*I+B,A.length):D=A.length,i=B;i<D;i+=I)g[0]=A[i],g[1]=A[i+1],g[2]=A[i+2],g[3]=A[i+3],C(g,g,E),A[i]=g[0],A[i+1]=g[1],A[i+2]=g[2],A[i+3]=g[3];return A}})();function Og(){var g=new MA(4);return MA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g[3]=1,g}function $E(g,A,I){I=I*.5;var B=Math.sin(I);return g[0]=B*A[0],g[1]=B*A[1],g[2]=B*A[2],g[3]=Math.cos(I),g}function Ai(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=I[0],D=I[1],a=I[2],G=I[3];return g[0]=B*G+E*i+Q*a-C*D,g[1]=Q*G+E*D+C*i-B*a,g[2]=C*G+E*a+B*D-Q*i,g[3]=E*G-B*i-Q*D-C*a,g}function MB(g,A,I,B){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,r,H,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>wA?(t=Math.acos(J),r=Math.sin(t),H=Math.sin((1-B)*t)/r,K=Math.sin(B*t)/r):(H=1-B,K=B),g[0]=H*Q+K*D,g[1]=H*C+K*a,g[2]=H*E+K*G,g[3]=H*i+K*R,g}function eB(g,A){var I=A[0]+A[4]+A[8],B;if(I>0)B=Math.sqrt(I+1),g[3]=.5*B,B=.5/B,g[0]=(A[5]-A[7])*B,g[1]=(A[6]-A[2])*B,g[2]=(A[1]-A[3])*B;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;B=Math.sqrt(A[Q*3+Q]-A[C*3+C]-A[E*3+E]+1),g[Q]=.5*B,B=.5/B,g[3]=(A[C*3+E]-A[E*3+C])*B,g[C]=(A[C*3+Q]+A[Q*3+C])*B,g[E]=(A[E*3+Q]+A[Q*3+E])*B}return g}var Ii=vE,gi=jE,Xg=_E;(function(){var g=$(),A=yA(1,0,0),I=yA(0,1,0);return function(B,Q,C){var E=bg(Q,C);return E<-.999999?(Pg(g,A,Q),XE(g)<1e-6&&Pg(g,I,Q),WQ(g,g),$E(B,g,Math.PI),B):E>.999999?(B[0]=0,B[1]=0,B[2]=0,B[3]=1,B):(Pg(g,Q,C),B[0]=g[0],B[1]=g[1],B[2]=g[2],B[3]=1+E,Xg(B,B))}})(),(function(){var g=Og(),A=Og();return function(I,B,Q,C,E,i){return MB(g,B,E,i),MB(A,Q,C,i),MB(I,g,A,2*i*(1-i)),I}})(),(function(){var g=fQ();return function(A,I,B,Q){return g[0]=B[0],g[3]=B[1],g[6]=B[2],g[1]=Q[0],g[4]=Q[1],g[7]=Q[2],g[2]=-I[0],g[5]=-I[1],g[8]=-I[2],Xg(A,eB(A,g))}})();function TQ(){var g=new MA(2);return MA!=Float32Array&&(g[0]=0,g[1]=0),g}function xQ(g){var A=new MA(2);return A[0]=g[0],A[1]=g[1],A}function LA(g,A){var I=new MA(2);return I[0]=g,I[1]=A,I}function Bi(g,A){var I=A[0]-g[0],B=A[1]-g[1];return Math.sqrt(I*I+B*B)}function Qi(g){var A=g[0],I=g[1];return A*A+I*I}function Ci(g,A,I,B){var Q=A[0],C=A[1];return g[0]=Q+B*(I[0]-Q),g[1]=C+B*(I[1]-C),g}function ZQ(g,A){return g[0]===A[0]&&g[1]===A[1]}function HB(g,A){var I=g[0],B=g[1],Q=A[0],C=A[1];return Math.abs(I-Q)<=wA*Math.max(1,Math.abs(I),Math.abs(Q))&&Math.abs(B-C)<=wA*Math.max(1,Math.abs(B),Math.abs(C))}(function(){var g=TQ();return function(A,I,B,Q,C,E){var i,D;for(I||(I=2),B||(B=0),Q?D=Math.min(Q*I+B,A.length):D=A.length,i=B;i<D;i+=I)g[0]=A[i],g[1]=A[i+1],C(g,g,E),A[i]=g[0],A[i+1]=g[1];return A}})();class JI{min;max;constructor(A,I){this.min=A?BI(A):yA(1/0,1/0,1/0),this.max=I?BI(I):yA(-1/0,-1/0,-1/0)}clone(){return new JI(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:B}=this,Q=[yA(I[0],I[1],I[2]),yA(I[0],I[1],B[2]),yA(I[0],B[1],I[2]),yA(I[0],B[1],B[2]),yA(B[0],I[1],I[2]),yA(B[0],I[1],B[2]),yA(B[0],B[1],I[2]),yA(B[0],B[1],B[2])];this.min=yA(1/0,1/0,1/0),this.max=yA(-1/0,-1/0,-1/0);const C=$();for(const E of Q)nB(C,E,A),this.expandWithPoint(C)}}const Ei={position:0,normal:1,uv:2,next_position:3,previous_position:4,direction:5,color:6,size:7,marker:8};class uI extends Zg{boundingBox_=null;primitive_;attributes_;vertexData_;indexData_;constructor(A=[],I=[],B="triangles"){super(),this.vertexData_=new Float32Array(A),this.indexData_=new Uint32Array(I),this.primitive_=B,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,B=new JI,Q=$();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],B.expandWithPoint(Q);this.boundingBox_=B}return this.boundingBox_}get type(){return"Geometry"}getAttribute(A){return this.attributes_.find(I=>I.type===A)}}class ii{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:B}=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,B,this.gl_.STATIC_DRAW);const{attributes:E,strideBytes:i}=A;E.forEach(G=>{const R=Ei[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 oi(g){return g===1||g===2||g===4||g===8}function qB(g){if(g instanceof Int8Array)return"byte";if(g instanceof Int16Array)return"short";if(g instanceof Int32Array)return"int";if(g instanceof Uint8Array)return"unsigned_byte";if(g instanceof Uint16Array)return"unsigned_short";if(g instanceof Uint32Array)return"unsigned_int";if(g instanceof Float32Array)return"float";throw new Error("Unsupported buffer type.")}function Di(g){switch(g.dataFormat){case"scalar":return 1;case"rgb":return 3;case"rgba":return 4}}function ai(g){switch(g.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 dB(g){const A=Di(g)*ai(g),I=Math.max(1,g.mipmapLevels);let B=Math.max(1,g.width),Q=Math.max(1,g.height),C=Math.max(1,g.depth),E=0;for(let i=0;i<I;++i)E+=A*C*B*Q,B=Math.max(1,B>>1),Q=Math.max(1,Q>>1),g.type==="Texture3D"&&(C=Math.max(1,C>>1));return E}function si(g){if(g.dataFormat==="rgb"||g.dataFormat==="rgba")return[0,1];switch(g.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 fB extends Zg{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 yi{gl_;textures_=new Map;currentTexture_=null;maxTextureUnits_;gpuTextureBytes_=0;textureCount_=0;readFramebuffer_=null;constructor(A){this.gl_=A,this.maxTextureUnits_=A.getParameter(A.MAX_TEXTURE_IMAGE_UNITS)}get gpuTextureBytes(){return this.gpuTextureBytes_}get textureCount(){return this.textureCount_}bindTexture(A,I){if(this.alreadyActive(A))return;if(I<0||I>=this.maxTextureUnits_)throw new Error(`Texture index ${I} must be in [0, ${this.maxTextureUnits_-1}]`);const B=this.textures_.get(A);B&&!A.needsUpdate?(this.gl_.activeTexture(this.gl_.TEXTURE0+I),this.gl_.bindTexture(this.getTextureType(A),B)):this.uploadTexture(A,I),this.currentTexture_=A}readTexel(A,I,B,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,B,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 B=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,B);const C=this.textures_.get(A);if(!C)throw new Error("Failed to retrieve texture ID");this.gl_.bindTexture(B,C),this.configureTextureParameters(A,B),this.uploadTextureData(A,Q,B),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 B=dB(A);this.gpuTextureBytes_=Math.max(0,this.gpuTextureBytes_-B),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,B){const Q=this.gl_.createTexture();if(!Q)throw new Error("Failed to create texture");if(this.gl_.bindTexture(B,Q),this.isTexture2D(A))this.gl_.texStorage2D(B,A.mipmapLevels,I.internalFormat,A.width,A.height);else if(this.isTextureStorage3D(A))this.gl_.texStorage3D(B,A.mipmapLevels,I.internalFormat,A.width,A.height,A.depth);else throw new Error(`Unknown texture type ${A.type}`);this.gpuTextureBytes_+=dB(A),this.textureCount_+=1,this.textures_.set(A,Q),this.gl_.bindTexture(B,null),A.readTexel=(C,E,i)=>Promise.resolve(this.readTexel(A,C,E,i))}configureTextureParameters(A,I){const B=this.gl_,Q=this.getFilter(A.minFilter,A),C=this.getFilter(A.maxFilter,A);B.pixelStorei(B.UNPACK_ALIGNMENT,A.unpackAlignment),B.texParameteri(I,B.TEXTURE_MIN_FILTER,Q),B.texParameteri(I,B.TEXTURE_MAG_FILTER,C),B.texParameteri(I,B.TEXTURE_WRAP_S,this.getWrapMode(A.wrapS)),B.texParameteri(I,B.TEXTURE_WRAP_T,this.getWrapMode(A.wrapT)),B.texParameteri(I,B.TEXTURE_WRAP_R,this.getWrapMode(A.wrapR))}uploadTextureData(A,I,B){const C={x:0,y:0,z:0};if(this.isTexture2D(A))this.gl_.texSubImage2D(B,0,C.x,C.y,A.width,A.height,I.format,I.type,A.data);else if(this.isTextureStorage3D(A))this.gl_.texSubImage3D(B,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:B,dataType:Q}=I;if(B==="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==="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 PA{min;max;constructor(A,I){this.min=A?xQ(A):LA(1/0,1/0),this.max=I?xQ(I):LA(-1/0,-1/0)}clone(){return new PA(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 ZQ(A.min,I.min)&&ZQ(A.max,I.max)}floor(){return new PA(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],B=this.max[0]-this.min[0],Q=this.max[1]-this.min[1];return{x:A,y:I,width:B,height:Q}}}class hi{gl_;enabledCapabilities_=new Map;depthMaskEnabled_=null;blendSrcFactor_=null;blendDstFactor_=null;currentBlendingMode_=null;currentViewport_=null;currentScissor_=null;currentCullingMode_=null;stencilFunc_=null;stencilRef_=null;stencilFuncMask_=null;constructor(A){this.gl_=A,this.gl_.frontFace(this.gl_.CW)}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)}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"premultiplied":this.setBlendFunc(this.gl_.ONE_MINUS_DST_ALPHA,this.gl_.ONE);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_&&PA.equals(I,this.currentViewport_))return;const{x:B,y:Q,width:C,height:E}=I.toRect();this.gl_.viewport(B,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_&&PA.equals(I,this.currentScissor_))return;const{x:B,y:Q,width:C,height:E}=I.toRect();this.gl_.scissor(B,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,B){(this.stencilFunc_!==A||this.stencilRef_!==I||this.stencilFuncMask_!==B)&&(this.gl_.stencilFunc(A,I,B),this.stencilFunc_=A,this.stencilRef_=I,this.stencilFuncMask_=B)}}const Gi=lQ(xA(),[1,-1,1]);class Fi extends Fg{gl_;programs_;bindings_;textures_;state_;renderedObjectsPerFrame_=0;stencilRef_=0;currentViewportSize_=[0,0];constructor(A){super(A);const I=this.canvas.getContext("webgl2",{depth:!0,antialias:!0,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 qE(I),this.bindings_=new ii(I),this.textures_=new yi(I),this.state_=new hi(I),this.initStencil(),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;const I=[],B=[];for(const G of A.layers)(G.blendMode==="none"?I:B).push(G);for(const G of[...I,...B])G.update(A);if(getComputedStyle(A.element).visibility==="hidden")return;const Q=A.getBoxRelativeTo(this.canvas),C=new PA(LA(0,0),LA(this.width,this.height)),E=PA.equals(Q.floor(),C.floor()),i=PA.intersects(Q,C);if(E)this.state_.setScissorTest(!1);else if(i)this.state_.setScissorTest(!0),this.state_.setScissor(Q);else{O.warn("WebGLRenderer",`Viewport ${A.id} is entirely outside canvas bounds, skipping render`);return}this.state_.setViewport(Q),this.clear();const D=Q.toRect();this.currentViewportSize_=[D.width,D.height];const a=A.camera.frustum;this.state_.setDepthMask(!0);for(const G of I)G.state==="ready"&&this.renderLayer(G,A.camera,a);this.state_.setDepthMask(!1);for(const G of B)G.state==="ready"&&this.renderLayer(G,A.camera,a);this.renderedObjects_=this.renderedObjectsPerFrame_}initStencil(){this.gl_.clearStencil(0),this.gl_.stencilMask(255),this.gl_.stencilOp(this.gl_.KEEP,this.gl_.KEEP,this.gl_.REPLACE)}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,B){this.state_.setBlendingMode(A.blendMode);for(const[Q,C]of A.coverageGroups){this.setCoverageStencil(Q);for(const E of C)B.intersectsWithBox3(E.boundingBox)&&(this.renderObject(A,E,I),this.renderedObjectsPerFrame_+=1)}}renderObject(A,I,B){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,B),I.wireframeEnabled){this.bindings_.bindGeometry(I.wireframeGeometry);const C=this.programs_.use("wireframe");C.setUniform("u_color",I.wireframeColor.rgb),this.drawGeometry(I.wireframeGeometry,I,A,C,B)}}drawGeometry(A,I,B,Q,C){const E=kB(xA(),C.viewMatrix,I.transform.matrix),i=kB(xA(),Gi,C.projectionMatrix),D=this.currentViewportSize_,a=I.getUniforms(),R={...B.getUniforms(),...a};for(const r of Q.uniformNames)switch(r){case"u_modelView":Q.setUniform(r,E);break;case"u_model":Q.setUniform(r,I.transform.matrix);break;case"u_projection":Q.setUniform(r,i);break;case"u_resolution":Q.setUniform(r,D);break;case"u_opacity":Q.setUniform(r,B.opacity*(a.Opacity??1));break;case"u_cameraPositionModel":{const H=ug(xA(),E),K=Vg(0,0,0,1),l=Rg(ZI(),K,H);Q.setUniform(r,yA(l[0],l[1],l[2]));break}default:r in R&&Q.setUniform(r,R[r])}const t=this.glGetPrimitive(A.primitive),J=A.indexData;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 B=new PA(LA(0,0),LA(A,I));this.state_.setViewport(B)}clear(){this.gl_.clearColor(0,0,0,0),this.gl_.clear(this.gl_.COLOR_BUFFER_BIT|this.gl_.DEPTH_BUFFER_BIT|this.gl_.STENCIL_BUFFER_BIT),this.state_.setDepthTesting(!0),this.gl_.depthFunc(this.gl_.LEQUAL)}}function Ng(g,A){const I=g.priority??Number.MAX_SAFE_INTEGER,B=A.priority??Number.MAX_SAFE_INTEGER;return I===B?(g.orderKey??Number.MAX_SAFE_INTEGER)-(A.orderKey??Number.MAX_SAFE_INTEGER):I-B}class wi{maxConcurrent_;pending_=[];running_=new Map;constructor(A){this.maxConcurrent_=Math.max(1,A)}enqueue(A,I){this.running_.has(A)||this.pending_.some(B=>B.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 B=this.running_.get(A);B&&(B.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:B}=A;I.state="loading";const Q=new AbortController,C=Promise.resolve().then(()=>B(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 Si(g,A){g.data&&(vg-=g.data.byteLength,jg-=1),g.data=A,vg+=A.byteLength,jg+=1}function uQ(g){g.data&&(vg-=g.data.byteLength,jg-=1),g.data=void 0,g.texture?.releaseCpuData()}function Ri(){return{cpuChunkBytes:vg,cpuChunkCount:jg}}function bQ(g,A,I=1e-6){return Math.abs(g-A)<=I}const RA={x:0,y:1,z:2};function bI(g){switch(g){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(g){const A=$(),I=$();A[RA[g.u]]=1,I[RA[g.v]]=1;const B=Pg($(),A,I),Q=pE(A[0],A[1],A[2],I[0],I[1],I[2],B[0],B[1],B[2]),C=eB(Og(),Q);return Xg(C,C)}const PQ=[Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array];function Ni(g){if(PQ.some(I=>g instanceof I))return!0;const A=PQ.map(I=>I.name);return O.debug("Chunk",`Unsupported chunk data type: ${g}. Supported data types: ${A}`),!1}function Ui(g,A){return Math.round((A-g.translation)/g.scale)}function VQ(g,A){const I=$(),B=$();for(const C of["x","y","z"]){const E=C===A.w?.5*g.scale[C]:0,i=RA[C];I[i]=1/(g.scale[C]*g.shape[C]),B[i]=E-g.offset[C]}const Q=lQ(xA(),I);return WE(Q,Q,B)}function EI(g,A,I){return Math.max(A,Math.min(I,g))}const zg=Symbol("INTERNAL_POLICY_KEY");class ti{store_;policy_;policyChanged_=!1;currentLOD_=0;axes_;scale0_;lastViewBounds2D_=null;lastViewProjection_=null;lastSliceBounds_;lastTCoord_;lastCCoords_;sourceMaxSquareDistance2D_;chunkViewStates_=new Map;isDisposed_=!1;constructor(A,I,B={u:"x",v:"y",w:"z"}){this.store_=A,this.policy_=I,this.axes_=B,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_=Qi(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],B=A[this.axes_.v].lods[0];return new PA(LA(I.translation,B.translation),LA(I.translation+I.size*I.scale,B.translation+B.size*B.scale))}getChunksToRender(){const A=this.fallbackLOD(),I=this.currentLOD_,B=[],Q=[];for(const[C,E]of this.chunkViewStates_)!E.visible||C.state!=="loaded"||!C.texture||(C.lod===I?B.push(C):C.lod===A&&I!==A&&Q.push(C));return[...B,...Q]}updateChunksForImage(A,I){const B=I.worldViewRect,C=Math.abs(B.max[0]-B.min[0])/I.bufferWidthPx,E=Math.log2(1/C),i=this.setLOD(E),D=this.getSliceAxisBounds(A);if(!(this.policyChanged_||i||this.viewBounds2DChanged(B)||this.sliceBoundsChanged(D)||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const G=this.timeIndex(A);if(!this.store_.hasChunksAtTime(G)){O.warn("ChunkStoreView","updateChunkViewStates called with no chunks initialized"),this.chunkViewStates_.forEach(Ug);return}const R=TQ();Ci(R,B.min,B.max,.5);const t=this.makeViewBounds3D(B,D);this.chunkViewStates_.forEach(Ug);const J=this.channelsOfInterest(A),r=this.fallbackLOD(),H=this.getPaddedBounds(t),K=this.currentLOD_===r?[this.currentLOD_]:[this.currentLOD_,r];for(const l of K){const V=l===this.currentLOD_,Z=l===r;this.iterateChunksInBox(G,l,J,H,(W,p)=>{const T=JI.intersects(p,t),AA=V&&!T,BA=this.computePriority(Z,V,T,AA,!0);BA!==null&&this.chunkViewStates_.set(W,{visible:T,prefetch:AA,priority:BA,orderKey:this.squareDistance2D(W,R)})})}this.markTimeChunksForPrefetchImage(G,A,t,R),this.policyChanged_=!1,this.lastViewBounds2D_=B.clone(),this.lastSliceBounds_=D,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);if(!this.store_.hasChunksAtTime(Q)){O.warn("ChunkStoreView","updateChunksForVolume called with no chunks initialized"),this.chunkViewStates_.forEach(Ug);return}this.currentLOD_=this.policy_.lod.min,this.chunkViewStates_.forEach(Ug);const C=this.channelsOfInterest(A),E=this.fallbackLOD(),i=D=>{const a=D.lod===E,G=D.lod===this.currentLOD_,R=this.computePriority(a,G,!0,!1,!0);R!==null&&this.chunkViewStates_.set(D,{visible:!0,prefetch:!1,priority:R,orderKey:0})};this.iterateAllChunksAtLod(Q,this.currentLOD_,C,i),this.currentLOD_!==E&&this.iterateAllChunksAtLod(Q,E,C,i),this.markTimeChunksForPrefetchVolume(Q,A),this.policyChanged_=!1,this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0,this.lastViewProjection_=I}allVisibleFallbackLODLoaded(){const A=this.fallbackLOD();let I=!1;for(const[B,Q]of this.chunkViewStates_)if(!(!Q.visible||B.lod!==A)&&(I=!0,B.texture===void 0))return!1;return I}get currentLOD(){return this.currentLOD_}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.chunkViewStates_.forEach(Ug)}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 B=this.policy_.lod.bias-Math.log2(this.scale0_)-A,Q=Math.floor(B),C=this.store_.getLowestResLOD(),E=Math.max(0,Math.min(C,this.policy_.lod.min)),i=Math.max(E,Math.min(C,this.policy_.lod.max)),D=EI(Q,E,i);return D===this.currentLOD_?!1:(this.currentLOD_=D,!0)}markTimeChunksForPrefetchImage(A,I,B,Q){const C=this.store_.dimensions.t?.lods[0].size??1,E=Math.min(this.policy_.prefetch.t,C-1),i=this.fallbackLOD(),D=this.policy_.priorityMap.prefetchTime,a=this.channelsOfInterest(I);for(let G=1;G<=E;++G){const R=(A+G)%C;this.iterateChunksInBox(R,i,a,B,t=>{const J=this.squareDistance2D(t,Q),r=EI(J/this.sourceMaxSquareDistance2D_,0,1-Number.EPSILON),H=G+r;this.chunkViewStates_.set(t,{visible:!1,prefetch:!0,priority:D,orderKey:H})})}}markTimeChunksForPrefetchVolume(A,I){const B=this.store_.dimensions.t?.lods[0].size??1,Q=Math.min(this.policy_.prefetch.t,B-1),C=this.fallbackLOD(),E=this.policy_.priorityMap.prefetchTime,i=this.channelsOfInterest(I);for(let D=1;D<=Q;++D){const a=(A+D)%B;this.iterateAllChunksAtLod(a,C,i,G=>{const R=D;this.chunkViewStates_.set(G,{visible:!1,prefetch:!0,priority:E,orderKey:R})})}}computePriority(A,I,B,Q,C){if(!C)return null;const E=this.policy_.priorityMap;return A&&B?E.fallbackVisible:I&&B?E.visibleCurrent:A?E.fallbackBackground:I&&Q?E.prefetchSpace:null}channelsOfInterest(A){return A.c??Array.from({length:this.store_.channelCount},(I,B)=>B)}chunkIndexRange(A,I){const B=this.store_.dimensions,Q=B.x.lods[I],C=B.y.lods[I],E=B.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,r=C.translation,H=E?.translation??0,K=Math.max(0,Math.floor((A.min[0]-J)/G)),l=Math.min(i,Math.ceil((A.max[0]-J)/G)),V=Math.max(0,Math.floor((A.min[1]-r)/R)),Z=Math.min(D,Math.ceil((A.max[1]-r)/R)),W=E?Math.max(0,Math.floor((A.min[2]-H)/t)):0,p=E?Math.min(a,Math.ceil((A.max[2]-H)/t)):1;return K>=l||V>=Z||W>=p?null:{xMin:K,xMax:l,yMin:V,yMax:Z,zMin:W,zMax:p}}iterateChunksInBox(A,I,B,Q,C){const E=this.chunkIndexRange(Q,I);if(E)for(const i of B){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 r=t[J];C(r,this.getChunkAabb(r))}}}}}iterateAllChunksAtLod(A,I,B,Q){for(const C of B){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,this.getChunkAabb(a))}}getChunkAabb(A){return new JI(yA(A.offset.x,A.offset.y,A.offset.z),yA(A.offset.x+A.shape.x*A.scale.x,A.offset.y+A.shape.y*A.scale.y,A.offset.z+A.shape.z*A.scale.z))}fallbackLOD(){return Math.min(this.policy_.lod.max,this.store_.getLowestResLOD())}timeIndex(A){const I=this.store_.dimensions.t;return A.t===void 0||I===void 0?0:Ui(I.lods[0],A.t)}getSliceAxisBounds(A){const I=this.store_.dimensions[this.axes_.w];if(I===void 0)return[0,1];const B=I.lods[this.currentLOD_],Q=A[this.axes_.w];if(Q===void 0)return[B.translation,B.translation+B.size*B.scale];const C=B.size,E=B.scale,i=B.translation,D=Math.floor((Q-i)/E),a=B.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 B=$(),Q=$();return B[RA[this.axes_.u]]=A.min[0],Q[RA[this.axes_.u]]=A.max[0],B[RA[this.axes_.v]]=A.min[1],Q[RA[this.axes_.v]]=A.max[1],B[RA[this.axes_.w]]=I[0],Q[RA[this.axes_.w]]=I[1],new JI(B,Q)}viewBounds2DChanged(A){return this.lastViewBounds2D_===null||!HB(this.lastViewBounds2D_.min,A.min)||!HB(this.lastViewBounds2D_.max,A.max)}hasViewProjectionChanged(A){return this.lastViewProjection_===null||!PE(this.lastViewProjection_,A)}sliceBoundsChanged(A){return!this.lastSliceBounds_||!HB(this.lastSliceBounds_,A)}cCoordsChanged(A){return!this.lastCCoords_&&!A?!1:!this.lastCCoords_||!A||this.lastCCoords_.length!==A.length?!0:!this.lastCCoords_.every((I,B)=>I===A[B])}getPaddedBounds(A){const{u:I,v:B,w:Q}=this.axes_,C=this.store_.dimensions,E=C[I].lods[this.currentLOD_],i=C[B].lods[this.currentLOD_],D=C[Q]?.lods[this.currentLOD_],a=$();return a[RA[I]]=E.chunkSize*E.scale*this.policy_.prefetch.x,a[RA[B]]=i.chunkSize*i.scale*this.policy_.prefetch.y,D&&(a[RA[Q]]=D.chunkSize*D.scale*this.policy_.prefetch.z),new JI(JB($(),A.min,a),xI($(),A.max,a))}squareDistance2D(A,I){function B(D){return A.offset[D]+.5*A.shape[D]*A.scale[D]}const{u:Q,v:C}=this.axes_,E=B(Q)-I[0],i=B(C)-I[1];return E*E+i*i}}function Ug(g){g.visible=!1,g.prefetch=!1,g.priority=null,g.orderKey=null}class ki{chunks_;lowestResLOD_;dimensions_;views_=[];hasHadViews_=!1;constructor(A){this.dimensions_=A,this.lowestResLOD_=this.dimensions_.numLods-1,this.validateXYScaleRatios();const{size:I}=this.getAndValidateTimeDimension(),{size:B}=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),r=D?Math.ceil(D.size/R):1,H=new Array(I);this.chunks_[C]=H;for(let K=0;K<I;++K){const l=new Array(B);H[K]=l;for(let V=0;V<B;++V){const Z=new Array(r);l[V]=Z;for(let W=0;W<r;++W){const p=D!==void 0?D.translation+W*R*D.scale:0,T=new Array(J);Z[W]=T;for(let AA=0;AA<J;++AA){const BA=i.translation+AA*G*i.scale,EA=new Array(t);T[AA]=EA;for(let CA=0;CA<t;++CA){const sA=E.translation+CA*a*E.scale;EA[CA]={state:"unloaded",lod:C,visible:!1,prefetch:!1,priority:null,orderKey:null,shape:{x:Math.min(a,E.size-CA*a),y:Math.min(G,i.size-AA*G),z:Math.min(R,(D?.size??1)-W*R),c:1},rowAlignmentBytes:1,chunkIndex:{x:CA,y:AA,z:W,c:V,t:K},scale:{x:E.scale,y:i.scale,z:D?.scale??1},offset:{x:sA,y:BA,z:p}}}}}}}}}getChunkGrid(A,I,B){return this.chunks_[A]?.[I]?.[B]}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 B=new ti(this,A,I);return this.views_.push(B),this.hasHadViews_=!0,B}get views(){return this.views_}canDispose(){return this.hasHadViews_&&this.views_.length===0}updateAndCollectChunkChanges(){const A=new Set;for(const I of this.views_)for(const[B,Q]of I.chunkViewStates)A.add(B);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,B=!1,Q=null,C=null;for(const D of this.views_){const a=D.chunkViewStates.get(A);a&&(a.visible&&(I=!0),a.prefetch&&(B=!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=B,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 B=1;B<this.dimensions_.numLods;B++){const Q=A.lods[B].scale/A.lods[B-1].scale,C=I.lods[B].scale/I.lods[B-1].scale;if(!bQ(Q,2,.02)||!bQ(C,2,.02))throw new Error(`Invalid downsampling factor between levels ${B-1} → ${B}: expected (2× in X and Y), but got (${Q.toFixed(2)}×, ${C.toFixed(2)}×) from scale [${A.lods[B-1].scale}, ${I.lods[B-1].scale}] → [${A.lods[B].scale}, ${I.lods[B].scale}]`)}}getAndValidateTimeDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.t?.lods[A];if(!I)continue;const B=this.dimensions_.t?.lods[A-1];if(B&&I.size!==B.size)throw new Error(`ChunkStore does not support downsampling in t. Found ${B.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 B=this.dimensions_.c?.lods[A-1];if(B&&I.size!==B.size)throw new Error(`ChunkStore does not support downsampling in c. Found ${B.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.c?.lods[0].size??1}}}class lB extends fB{width_;height_;depth_;constructor(A,I,B,Q){super(),this.dataFormat="scalar",this.dataType=qB(A),this.data_=A,this.width_=I,this.height_=B,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 B=new lB(I,A.shape.x,A.shape.y,A.shape.z);return B.unpackAlignment=A.rowAlignmentBytes,B}}const ci=8,Li=4;class Ji{stores_=[];queue_;uploadTexture_;disposeTexture_;getGpuResidentBytes_;memoryLimitBytes_;maxGpuUploadsPerUpdate_;resident_=new Set;constructor(A,I,B=()=>0,Q=1/0,C=ci,E=Li){this.uploadTexture_=A,this.disposeTexture_=I,this.getGpuResidentBytes_=B,this.memoryLimitBytes_=Q,this.maxGpuUploadsPerUpdate_=Math.max(1,E),this.queue_=new wi(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 Ri()}addView(A,I,B){let Q=this.stores_.find(C=>C.source===A)?.store;return Q||(Q=new ki(A.loader.getSourceDimensionMap()),this.stores_.push({source:A,store:Q})),Q.addView(I,B)}update(){const A=[];for(const{source:I,store:B}of this.stores_){const Q=B.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(Q)}this.enqueueWithinBudget(A),this.queue_.flush();for(let I=this.stores_.length-1;I>=0;I--)this.stores_[I].store.canDispose()&&this.stores_.splice(I,1)}releaseChunk(A){if(this.queue_.cancel(A),A.texture!==void 0){A.releasedAt??=performance.now();return}uQ(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_(),B=null;for(const{source:Q,chunk:C}of A){const E=this.chunkBytes(Q,C);E>this.memoryLimitBytes_||(I+E>this.memoryLimitBytes_&&(B??=this.evictionCandidates(),I=this.evictWorseChunks(I,E,C,B)),!(I+E>this.memoryLimitBytes_)&&(I+=E,this.queue_.enqueue(C,i=>Q.loader.loadChunkData(C,i))))}}evictionCandidates(){const A=[];for(const I of this.resident_)I.visible||A.push(I);return A.sort((I,B)=>{const Q=-Ng(I,B);return Q!==0?Q:(I.releasedAt??0)-(B.releasedAt??0)})}evictWorseChunks(A,I,B,Q){for(;A+I>this.memoryLimitBytes_&&Q.length>0&&Ng(Q[0],B)>0;){const C=Q.shift();C.texture!==void 0&&(A-=dB(C.texture),this.disposeChunkTexture(C),C.state="unloaded",C.releasedAt=void 0)}return A}chunkBytes(A,I){const B=A.loader.getBytesPerElement();return I.shape.x*I.shape.y*I.shape.z*B}uploadLoadedChunks(A){if(!this.uploadTexture_)return;const I=[];for(const Q of A)Q.state==="loaded"&&Q.texture===void 0&&I.push(Q);if(I.length===0)return;I.sort(Ng);const B=Math.min(I.length,this.maxGpuUploadsPerUpdate_);for(let Q=0;Q<B;Q++){const C=I[Q],E=lB.createWithChunk(C);this.uploadTexture_(E),C.texture=E,this.resident_.add(C),uQ(C)}}disposeChunkTexture(A){this.disposeTexture_&&A.texture!==void 0&&(this.disposeTexture_(A.texture),A.texture=void 0,this.resident_.delete(A))}}var tg=function(g=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 B(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=B(new tg.Panel("FPS","#0ff","#002",g)),a=B(new tg.Panel("MS","#0f0","#020",g));if(self.performance&&self.performance.memory)var G=B(new tg.Panel("MB","#f08","#201",g));return Q(0),{REVISION:16,dom:I,addPanel:B,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}};tg.Panel=function(g,A,I,B){var Q=1/0,C=0,E=Math.round,i=E(window.devicePixelRatio||1),D=E(80*i*B),a=E(48*i*B),G=E(3*i*B),R=E(2*i*B),t=E(3*i*B),J=E(15*i*B),r=E(74*i*B),H=E(30*i*B),K=document.createElement("canvas");K.width=D,K.height=a,K.style.cssText=`width:${E(B*80)}px;height:${E(B*48)}px`;var l=K.getContext("2d");return l.font="bold "+E(9*i*B)+"px Helvetica,Arial,sans-serif",l.textBaseline="top",l.fillStyle=I,l.fillRect(0,0,D,a),l.fillStyle=A,l.fillText(g,G,R),l.fillRect(t,J,r,H),l.fillStyle=I,l.globalAlpha=.9,l.fillRect(t,J,r,H),{dom:K,update:function(V,Z){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)+" "+g+" ("+E(Q)+"-"+E(C)+")",G,R),l.drawImage(K,t+i,J,r-i,H,t,J,r-i,H),l.fillRect(t+r-i,J,i,H),l.fillStyle=I,l.globalAlpha=.9,l.fillRect(t+r-i,J,i,E((1-V/Z)*H))}}};function ri({scale:g}={scale:1.5}){const A=new tg(g);return A.showPanel(0),document.body.appendChild(A.dom),A}const pB=["pointerdown","pointermove","pointerup","pointercancel","wheel"];function ni(g){return pB.includes(g)}class Yi{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 Ki{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,pB.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,pB.forEach(A=>{this.element_.removeEventListener(A,this.handleEvent)})}handleEvent=A=>{if(!ni(A.type)){O.error("EventDispatcher",`Unsupported event type ${A.type}`);return}const I=new Yi(A.type,A);for(const B of this.listeners_)if(B(I),I.propagationStopped)break}}const Mi=1e-12;class ei{origin;direction;constructor(A,I){this.origin=BI(A),this.direction=WQ($(),I)}intersectWithPlane(A){const I=bg(this.direction,A.normal);if(Math.abs(I)<Mi)return null;const B=-A.signedDistanceToPoint(this.origin)/I;return rB($(),this.origin,this.direction,B)}}class Hi{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 Ki(this.element),this.events.addEventListener(I=>{if(I.event instanceof PointerEvent||I.event instanceof WheelEvent){const{clientX:B,clientY:Q}=I.event,C=LA(B,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 ei(E,JB($(),i,E))}for(const B of this.layers_)if(B.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(),B=A.getBoundingClientRect(),Q=window.devicePixelRatio||1,C=B.left*Q,E=B.top*Q,i=B.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 PA(LA(G,R),LA(G+t,R+J))}getBufferRect(){return this.getBoxRelativeTo(this.element).toRect()}clientToClip(A,I=0){const[B,Q]=A,C=this.element.getBoundingClientRect();return yA(2*(B-C.x)/C.width-1,2*(Q-C.y)/C.height-1,I)}clientToWorld(A,I=0){const B=this.clientToClip(A,I);return this.camera.clipToWorld(B)}getBox(){const A=this.element.getBoundingClientRect(),I=window.devicePixelRatio||1,B=A.left*I,Q=A.top*I,C=A.width*I,E=A.height*I;return new PA(LA(B,Q),LA(B+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 B=A/I;this.camera.setAspectRatio(B)}}function OQ(g,A){for(const I of A){if(I.id===g.id)throw new Error(`Duplicate viewport ID "${g.id}". Each viewport must have a unique ID.`);if(I.element===g.element){const B=g.element.tagName.toLowerCase()+(g.element.id?`#${g.element.id}`:"[element has no id]");throw new Error(`Multiple viewports cannot share the same HTML element: viewports "${I.id}" and "${g.id}" both use ${B}`)}}}function qi(g){for(let A=0;A<g.length;A++)OQ(g[A],g.slice(0,A))}function XQ(g,A,I){const B=g.map(Q=>{const C=Q.element??A;return{...Q,element:C,id:Q.id??C.id??dQ("viewport"),context:I}});return qi(B),B.map(Q=>new Hi(Q))}class di{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 fi=2048;class li{chunkManager_;context_;renderer_;viewports_;canvas;overlays;stats_;sizeObserver_;lastAnimationId_;lastTimestamp_=0;constructor(A){this.canvas=A.canvas,this.renderer_=new Fi(this.canvas);const B=(A.memoryLimitMB??fi)*1024*1024;this.chunkManager_=new Ji(C=>this.renderer_.uploadTexture(C),C=>this.renderer_.disposeTexture(C),()=>this.renderer_.gpuTextureBytes,B,A.maxConcurrentRequests,A.maxGpuUploadsPerUpdate),this.context_={chunkManager:this.chunkManager_},this.viewports_=XQ(A.viewports??[],this.canvas,this.context_),this.overlays=[...A.overlays??[]],A.showStats&&(this.stats_=ri());const Q=[this.canvas];for(const C of this.viewports_)C.element!==this.canvas&&Q.push(C.element);this.sizeObserver_=new di(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 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]=XQ([A],this.canvas,this.context_);return OQ(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 B of this.viewports_)B.cameraControls?.onUpdate(I),this.renderer_.render(B);this.chunkManager_.update();for(const B of this.overlays)B.update(this);this.stats_&&this.stats_.end(),this.lastAnimationId_=requestAnimationFrame(B=>this.animate(B))}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 pi(g,A){return{...g,...A,headers:{...g.headers,...A.headers}}}function vQ(g,A){const I=typeof g=="string"?new URL(g):g;I.pathname.endsWith("/")||(I.pathname+="/");const B=new URL(A.slice(1),I);return B.search=I.search,B}async function jQ(g){if(g.status!==404){if(g.status===200||g.status===206)return new Uint8Array(await g.arrayBuffer());throw new Error(`Unexpected response status ${g.status} ${g.statusText}`)}}class kg{url;#A;#I;#g;constructor(A,I={}){this.url=A,this.#A=I.fetch??(B=>fetch(B)),this.#I=I.overrides??{},this.#g=I.useSuffixRequest??!1}#B(A,I){return new Request(A,pi(this.#I,I))}async get(A,I={}){let B=vQ(this.url,A).href,Q=this.#B(B,I),C=await this.#A(Q);return jQ(C)}async getRange(A,I,B={}){let Q=vQ(this.url,A),C;if("suffixLength"in I)C=await this.#Q(Q,I.suffixLength,B);else{let E={...B,headers:{...B.headers,Range:`bytes=${I.offset}-${I.offset+I.length-1}`}},i=this.#B(Q,E);C=await this.#A(i)}return jQ(C)}async#Q(A,I,B){if(this.#g){let G={...B,headers:{...B.headers,Range:`bytes=-${I}`}};return this.#A(this.#B(A,G))}let Q=this.#B(A,{...B,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={...B,headers:{...B.headers,Range:`bytes=${D}-${i-1}`}};return this.#A(this.#B(A,a))}}class cg extends Error{}class VI extends cg{_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 cg{_tag="InvalidMetadataError";name="InvalidMetadataError";path;constructor(A,I={}){super(A,{cause:I.cause}),this.path=I.path}}class Wi extends cg{_tag="UnknownCodecError";name="UnknownCodecError";codec;constructor(A){super(`Unknown codec: ${A}`),this.codec=A}}class mi extends cg{_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 WB extends cg{_tag="UnsupportedError";name="UnsupportedError";feature;constructor(A){super(`Unsupported: ${A}`),this.feature=A}}function rI(g){return()=>{throw new WB(`${g} encode`)}}class _g{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 _g(A,I)}encode=rI("bitround");decode(A){return A}}function mB(g){return g instanceof ArrayBuffer||g instanceof SharedArrayBuffer}class zQ{#A;constructor(A,I,B){typeof A=="number"?this.#A=new Uint8Array(A):mB(A)?this.#A=new Uint8Array(A,I,B):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 TB{_data;chars;#A;constructor(A,I,B,Q){if(this.chars=A,this.#A=new TextEncoder,typeof I=="number")this._data=new Uint8Array(I*A);else if(mB(I))Q&&(Q=Q*A),this._data=new Uint8Array(I,B,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 B=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);B.fill(0),B.set(this.#A.encode(I))}fill(A){const I=this.#A.encode(A);for(let B=0;B<this.length;B++)this._data.set(I,B*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class Lg{#A;chars;constructor(A,I,B,Q){if(this.chars=A,typeof I=="number")this.#A=new Int32Array(I*A);else if(mB(I))Q&&(Q*=A),this.#A=new Int32Array(I,B,Q);else{const C=I,E=new Lg(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 B="";for(let Q=0;Q<this.chars;Q++)B+=String.fromCodePoint(this.#A[I+Q]);return B.replace(/\u0000/g,"")}set(A,I){const B=this.chars*A,Q=this.#A.subarray(B,B+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 B=1;B<this.length;B++)this.#A.set(I,B*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}function Ti(){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 xi(g,A){return new SharedArrayBuffer(g)}function Jg(g){const A=new TextDecoder().decode(g);try{return JSON.parse(A)}catch(I){throw new JA("Failed to decode JSON",{cause:I})}}function _Q(g,A){const I=A/2,B=A-1;let Q=0;for(let C=0;C<g.length;C+=A)for(let E=0;E<I;E+=1)Q=g[C+E],g[C+E]=g[C+B-E],g[C+B-E]=Q}function OI(g){if(g==="v2:object")return globalThis.Array;let A=g.match(/v2:([US])(\d+)/);if(A){let[,B,Q]=A;return(B==="U"?Lg:TB).bind(null,Number(Q))}if(g==="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:zQ}[g];if(!I)throw new JA(`Unknown or unsupported dataType: ${g}`);return I}function nI(g,A){const I=g.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 B=1,Q=new Array(I);for(let C=A.length-1;C>=0;C--)Q[A[C]]=B,B*=g[A[C]];return Q}function Zi({name:g,configuration:A}){if(g==="default"){const I=A?.separator??"/";return B=>["c",...B].join(I)}if(g==="v2"){const I=A?.separator??".";return B=>B.join(I)||"0"}throw new JA(`Unknown chunk key encoding: ${g}`)}function $Q(g){if(g==="|O")return{dataType:"v2:object"};let A=g.match(/^([<|>])(.*)$/);if(!A)throw new JA(`Invalid dtype: ${g}`);let[,I,B]=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"}[B]??(B.startsWith("S")||B.startsWith("U")?`v2:${B}`:void 0);if(!Q)throw new JA(`Unsupported or unknown dtype: ${g}`);return I==="|"?{dataType:Q}:{dataType:Q,endian:I==="<"?"little":"big"}}function ui(g){return(g.id==="fixedscaleoffset"||g.id==="numcodecs.fixedscaleoffset")&&typeof g.scale=="number"&&typeof g.offset=="number"&&(g.astype===void 0||typeof g.astype=="string")&&(g.dtype===void 0||typeof g.dtype=="string")}function bi(g,A={}){let I=[],B=$Q(g.dtype);g.order==="F"&&I.push({name:"transpose",configuration:{order:"F"}});for(let C of g.filters??[]){if(C.id==="fixedscaleoffset"||C.id==="numcodecs.fixedscaleoffset"){if(!ui(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!==g.dtype){let a=$Q(D).dataType;if(!xB(a,"number")&&!xB(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 B&&B.endian==="big"&&I.push({name:"bytes",configuration:{endian:"big"}}),g.compressor){let{id:C,...E}=g.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:g.shape,data_type:B.dataType,chunk_grid:{name:"regular",configuration:{chunk_shape:g.chunks}},chunk_key_encoding:{name:"v2",configuration:{separator:g.dimension_separator??"."}},codecs:I,fill_value:g.fill_value,dimension_names:Q,attributes:A}}function Pi(g,A={}){return{zarr_format:3,node_type:"group",attributes:A}}function xB(g,A){if(A!=="number"&&A!=="bigint"&&A!=="boolean"&&A!=="object"&&A!=="string")return g===A;let I=g==="bool";if(A==="boolean")return I;let B=g.startsWith("v2:U")||g.startsWith("v2:S")||g==="string";if(A==="string")return B;let Q=g==="int64"||g==="uint64";if(A==="bigint")return Q;let C=g==="v2:object";return A==="object"?C:!B&&!Q&&!I&&!C}function Vi(g){return g?.name==="sharding_indexed"}function AC(g){if((g.data_type==="uint64"||g.data_type==="int64")&&g.fill_value!=null)return BigInt(g.fill_value);let A=g.data_type==="float16"||g.data_type==="float32"||g.data_type==="float64";if(typeof g.fill_value=="string"&&A){let I={NaN:NaN,Infinity:1/0,"-Infinity":-1/0};if(g.fill_value in I)return I[g.fill_value]}return g.fill_value}function IC(g,...A){if(!A.some(I=>g instanceof I))throw g}function VA(g,A=""){if(!g)throw new Error(A)}async function gC(g,{format:A,signal:I}){let B;if(g instanceof ArrayBuffer)B=new Response(g);else{let Q=new Uint8Array(g.buffer,g.byteOffset,g.byteLength);B=new Response(Q.slice().buffer)}VA(B.body,"Response does not contain body.");try{return await new Response(B.body.pipeThrough(new DecompressionStream(A),{signal:I})).arrayBuffer()}catch{throw I?.throwIfAborted(),new Error(`Failed to decode ${A}`)}}const BC=Oi();function Oi(){const g=new Uint32Array([305419896]);return new Uint8Array(g.buffer,g.byteOffset,g.byteLength)[0]!==18}function QC(g){return"BYTES_PER_ELEMENT"in g?g.BYTES_PER_ELEMENT:4}class $g{kind="array_to_bytes";#A;#I;#g;#B;#Q;constructor(A,I){this.#Q=A?.endian,this.#I=OI(I.dataType),this.#B=I.shape,this.#A=nI(I.shape,"C");const B=new this.#I(0);this.#g=B.BYTES_PER_ELEMENT}static fromConfig(A,I){return new $g(A,I)}encode(A){let I=new Uint8Array(A.data.buffer);return BC&&this.#Q==="big"&&_Q(I,QC(this.#I)),I}computeEncodedSize(A){return A}decode(A){return BC&&this.#Q==="big"&&_Q(A,QC(this.#I)),{data:new this.#I(A.buffer,A.byteOffset,A.byteLength/this.#g),shape:this.#B,stride:this.#A}}}const CC={NaN:NaN,Infinity:1/0,"-Infinity":-1/0},EC={float16:2,float32:4,float64:8};function AB(g){return g in EC}function ZB(g){return g==="int64"||g==="uint64"}function Xi(g,A){const I=BigInt(g),B=new ArrayBuffer(A),Q=new DataView(B);if(A===2){if(typeof Q.getFloat16!="function")throw new WB("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(g,A){if(ZB(g)){if(typeof A!="number"||!Number.isInteger(A))throw new JA(`Expected an integer value for data type "${g}", got ${JSON.stringify(A)}`);return BigInt(A)}if(typeof A=="number"){if(!AB(g)&&!Number.isInteger(A))throw new JA(`Expected an integer value for data type "${g}", got ${A}`);return A}if(!AB(g))throw new JA(`String-encoded scalar "${A}" is not valid for non-float data type "${g}"`);return A in CC?CC[A]:Xi(A,EC[g])}const iC=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]),uB={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]},bB={int64:[-(2n**63n),2n**63n-1n],uint64:[0n,2n**64n-1n]};function oC(g,A,I){return g.map(([B,Q])=>({src:IB(A,B),tgt:IB(I,Q)}))}function vi(g,A){for(const I of A)if(typeof I.src=="number"&&Number.isNaN(I.src)){if(typeof g=="number"&&Number.isNaN(g))return I.tgt}else if(g===I.src)return I.tgt}function ji(g){if(!Number.isFinite(g))return g;if(Math.abs(g-Math.trunc(g))===.5){const A=Math.floor(g),I=Math.ceil(g);return A%2===0?A:I}return Math.round(g)}function zi(g){return Math.sign(g)*Math.floor(Math.abs(g)+.5)}function DC(g){switch(g){case"nearest-even":return ji;case"towards-zero":return Math.trunc;case"towards-positive":return Math.ceil;case"towards-negative":return Math.floor;case"nearest-away":return zi}}function PB(g,A,I){const B=A-g+1;switch(I){case"clamp":return Q=>Q<g?g:Q>A?A:Q;case"wrap":return Q=>Q>=g&&Q<=A?Q:((Q-g)%B+B)%B+g;default:return Q=>{if(Q>=g&&Q<=A)return Q;throw new Error(`Value ${Q} out of range [${g}, ${A}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}function VB(g,A,I){const B=A-g+1n;switch(I){case"clamp":return Q=>Q<g?g:Q>A?A:Q;case"wrap":return Q=>Q>=g&&Q<=A?Q:((Q-g)%B+B)%B+g;default:return Q=>{if(Q>=g&&Q<=A)return Q;throw new Error(`Value ${Q} out of range [${g}, ${A}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}class OB{kind="array_to_array";#A;#I;#g;#B;constructor(A,I,B,Q,C,E){this.#A=I,this.#I=OI(A),this.#g=aC(I,A,B,Q,C),this.#B=aC(A,I,B,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 B=I.dataType,Q=A.data_type;if(!iC.has(B))throw new JA(`cast_value codec does not support array data type: ${B}`);if(!iC.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?oC(A.scalar_map.decode,Q,B):[],i=A.scalar_map?.encode?oC(A.scalar_map.encode,B,Q):[];return new OB(B,Q,C,A.out_of_range,E,i)}encode=rI("cast_value");decode(A){const I=A.data,B=new this.#I(I.length);for(let Q=0;Q<I.length;Q++)B[Q]=this.#g(I[Q]);return{data:B,shape:A.shape,stride:A.stride}}}function aC(g,A,I,B,Q){const C=AB(g),E=ZB(g),i=AB(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=DC(I),t=PB(...uB[A],B);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=DC(I),t=VB(...bB[A],B);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=PB(...uB[A],B);else if(!C&&!E&&D){const R=VB(...bB[A],B);a=t=>R(BigInt(t))}else if(E&&!i&&!D){const R=PB(...uB[A],B);a=t=>R(Number(t))}else if(E&&D)a=VB(...bB[A],B);else throw new Error(`Unhandled type combination: ${g} -> ${A}`);return Q.length===0?a:R=>{const t=vi(R,Q);return t!==void 0?t:a(R)}}class XB{kind="bytes_to_bytes";static fromConfig(){return new XB}encode=rI("crc32c");decode(A){return new Uint8Array(A.buffer,A.byteOffset,A.byteLength-4)}computeEncodedSize(A){return A+4}}const _i=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);function sC(g,A){const I=g.length;let B=I===0||A[I-1]===1;for(let C=I-2;C>=0&&B;C--)B=A[C]===A[C+1]*g[C+1];if(B)return;let Q=I===0||A[0]===1;for(let C=1;C<I&&Q;C++)Q=A[C]===A[C-1]*g[C-1];if(!Q)throw new Error(`DeltaCodec requires C- or Fortran-contiguous strides, got shape=${JSON.stringify(g)} stride=${JSON.stringify(A)}`)}class vB{kind="array_to_array";#A;constructor(A){this.#A=A}static fromConfig(A,I){if(!_i.has(I.dataType))throw new JA(`Delta codec does not support data type: ${I.dataType}`);return new vB(OI(I.dataType))}encode(A){sC(A.shape,A.stride);const I=A.data,B=new this.#A(I.length);B[0]=I[0];for(let Q=1;Q<I.length;Q++)B[Q]=I[Q]-I[Q-1];return{data:B,shape:A.shape,stride:A.stride}}decode(A){sC(A.shape,A.stride);const I=A.data,B=new this.#A(I.length);B[0]=I[0];for(let Q=1;Q<I.length;Q++)B[Q]=B[Q-1]+I[Q];return{data:B,shape:A.shape,stride:A.stride}}}class jB{kind="bytes_to_bytes";static fromConfig(A){return new jB}encode=rI("gzip");async decode(A){const I=await gC(A,{format:"gzip"});return new Uint8Array(I)}}function $i(g,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 Ao(g,A){return A instanceof Object&&!Array.isArray(A)?Object.keys(A).sort().reduce((I,B)=>(I[B]=A[B],I),{}):A}class gB{configuration;kind="array_to_bytes";#A;#I;constructor(A={}){this.configuration=A;const{encoding:I="utf-8",skipkeys:B=!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:B,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 gB(A)}encode(A){const{indent:I,encoding:B,ensure_ascii:Q,check_circular:C,allow_nan:E,sort_keys:i}=this.#A;VA(B==="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($i),i&&D.push(Ao);const a=Array.from(A.data);a.push("|O"),a.push(A.shape);let G;D.length&&(G=(t,J)=>{let r=J;for(let H of D)r=H(t,r);return r});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 B=Jg(A),Q=B.pop();B.pop(),VA(Q,"0D not implemented for JsonCodec.");const C=nI(Q,"C");return{data:B,shape:Q,stride:C}}}const Io=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);class zB{kind="array_to_array";#A;#I;#g;constructor(A,I,B){this.#I=A,this.#g=I,this.#A=B}static fromConfig(A,I){if(!Io.has(I.dataType))throw new JA(`scale_offset codec does not support data type: ${I.dataType}`);return new zB(IB(I.dataType,A.scale??1),IB(I.dataType,A.offset??0),OI(I.dataType))}encode=rI("scale_offset");decode(A){const I=A.data,B=new this.#A(I.length);for(let Q=0;Q<I.length;Q++)B[Q]=I[Q]/this.#I+this.#g;return{data:B,shape:A.shape,stride:A.stride}}}class _B{kind="bytes_to_bytes";#A;constructor(A,I){if(I){let B=new(OI(I.dataType))(0);VA("BYTES_PER_ELEMENT"in B,`Shuffle codec requires a fixed-size dtype, got "${I.dataType}"`),this.#A=B.BYTES_PER_ELEMENT}else this.#A=A.elementsize??4}static fromConfig(A,I){return new _B(A,I)}encode(A){return go(A,this.#A)}decode(A){return Bo(A,this.#A)}}function go(g,A){let I=g.length,B=Math.floor(I/A),Q=new Uint8Array(I);for(let C=0;C<A;C++)for(let E=0;E<B;E++)Q[C*B+E]=g[E*A+C];return Q}function Bo(g,A){let I=g.length,B=Math.floor(I/A),Q=new Uint8Array(I);for(let C=0;C<A;C++)for(let E=0;E<B;E++)Q[E*A+C]=g[C*B+E];return Q}function yC(g){return g instanceof zQ||g instanceof TB||g instanceof Lg?new Proxy(g,{get(I,B){return I.get(Number(B))},set(I,B,Q){return I.set(Number(B),Q),!0}}):g}function Qo(g,A){let I;return g.data instanceof TB||g.data instanceof Lg?I=new g.constructor(g.data.length,g.data.chars):I=new g.constructor(g.data.length),{data:I,shape:g.shape,stride:nI(g.shape,A)}}function Co(g,A){let I=Qo(g,A),B=g.shape.length,Q=g.data.length,C=Array(B).fill(0),E=yC(g.data),i=yC(I.data);for(let D=0;D<Q;D++){let a=0;for(let G=0;G<B;G++)a+=C[G]*I.stride[G];i[a]=E[D],C[0]+=1;for(let G=0;G<B;G++)if(C[G]===g.shape[G]){if(G+1===B)break;C[G]=0,C[G+1]+=1}}return I}function Eo(g){let A=g.shape.length;return VA(A===g.stride.length,"Shape and stride must have the same length."),g.stride.map((I,B)=>({stride:I,index:B})).sort((I,B)=>B.stride-I.stride).map(I=>I.index)}function io(g,A){let I=Eo(g);return VA(I.length===A.length,"Orders must match"),I.every((B,Q)=>B===A[Q])}class $B{kind="array_to_array";#A;#I;constructor(A,I){let B=A.order??"C",Q=I.shape.length,C=new Array(Q),E=new Array(Q);if(B==="C")for(let i=0;i<Q;++i)C[i]=i,E[i]=i;else if(B==="F")for(let i=0;i<Q;++i)C[i]=Q-i-1,E[i]=Q-i-1;else C=B,C.forEach((i,D)=>{VA(E[i]===void 0,`Invalid permutation: ${JSON.stringify(B)}`),E[i]=D});this.#A=C,this.#I=E}static fromConfig(A,I){return new $B(A,I)}encode(A){return io(A,this.#I)?A:Co(A,this.#I)}decode(A){return{data:A.data,shape:A.shape,stride:nI(A.shape,this.#A)}}}class BB{kind="array_to_bytes";#A;#I;constructor(A){this.#A=A,this.#I=nI(A,"C")}static fromConfig(A,I){return new BB(I.shape)}encode=rI("vlen-utf8");decode(A){let I=new TextDecoder,B=new DataView(A.buffer),Q=Array(B.getUint32(0,!0)),C=4;for(let E=0;E<Q.length;E++){let i=B.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 AQ{kind="bytes_to_bytes";static fromConfig(A){return new AQ}encode=rI("zlib");async decode(A){const I=await gC(A,{format:"deflate"});return new Uint8Array(I)}}function oo(){let g=()=>Promise.resolve().then(()=>Ja).then(C=>C.default),A=()=>Promise.resolve().then(()=>ea).then(C=>C.default),I=()=>Promise.resolve().then(()=>pa).then(C=>C.default),B=()=>jB,Q=()=>AQ;return new Map().set("blosc",g).set("lz4",A).set("zstd",I).set("gzip",B).set("zlib",Q).set("transpose",()=>$B).set("bytes",()=>$g).set("crc32c",()=>XB).set("vlen-utf8",()=>BB).set("json2",()=>gB).set("bitround",()=>_g).set("cast_value",()=>OB).set("scale_offset",()=>zB).set("numcodecs.blosc",g).set("numcodecs.lz4",A).set("numcodecs.zstd",I).set("numcodecs.gzip",B).set("numcodecs.zlib",Q).set("numcodecs.vlen-utf8",()=>BB).set("numcodecs.shuffle",()=>_B).set("numcodecs.delta",()=>vB).set("numcodecs.bitround",()=>_g).set("numcodecs.json2",()=>gB)}const Do=oo();function IQ(g){let A;function I(){return A||(A=ao(g)),A}async function B(Q,C,E){try{return await E()}catch(i){throw new mi({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 B("encode",i,()=>D.encode(Q));let E=await B("encode",C.arrayToBytes.name,()=>C.arrayToBytes.codec.encode(Q));for(const{name:i,codec:D}of C.bytesToBytes)E=await B("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 B("decode",D,()=>a.decode(Q))}let E=await B("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 B("decode",D,()=>a.decode(E))}return E},async computeEncodedSize(Q){let C=await I(),E=hC(C.arrayToBytes.name,C.arrayToBytes.codec,Q);for(const{name:i,codec:D}of C.bytesToBytes)E=hC(i,D,E);return E}}}function hC(g,A,I){if(!A.computeEncodedSize)throw new JA(`Codec "${g}" 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 ao(g){let A=g.codecs.map(async E=>{let i=await Do.get(E.name)?.();if(!i)throw new Wi(E.name);return{Codec:i,meta:E}}),I=[],B,Q=[],C={...g};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":B={name:i.name,codec:D};break;default:Q.push({name:i.name,codec:D})}}if(!B){if(!so(C))throw new JA(`Cannot encode ${C.dataType} to bytes without a codec`);B={name:"bytes",codec:$g.fromConfig({endian:"little"},C)}}return{arrayToArray:I,arrayToBytes:B,bytesToBytes:Q}}function so(g){return g.dataType!=="v2:object"&&g.dataType!=="string"}const GC=18446744073709551615n;function yo(g,A,I,B){if(!g.store.getRange)throw new WB("sharding requires a store with getRange");let Q=g.store.getRange.bind(g.store),C=A.map((a,G)=>a/B.chunk_shape[G]),E=IQ({dataType:"uint64",shape:[...C,2],codecs:B.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=g.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:r,shape:H,stride:K}=J,l=a.map((W,p)=>W%H[p]).reduce((W,p,T)=>W+p*K[T],0),V=r[l],Z=r[l+1];if(!(V===GC&&Z===GC))return Q(t,{offset:Number(V),length:Number(Z)},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 gQ extends vA{kind="group";#A;constructor(A,I,B){super(A,I),this.#A=B}get attrs(){return this.#A.attributes}}function FC(g){return g.find(I=>I.name==="transpose")?.configuration?.order??"C"}const QB=Symbol("zarrita.context");function ho(g,A){let{configuration:I}=A.codecs.find(Vi)??{},B={encodeChunkKey:Zi(A.chunk_key_encoding),TypedArray:OI(A.data_type),fillValue:A.fill_value};if(I){let C=FC(I.codecs);return{...B,kind:"sharded",chunkShape:I.chunk_shape,codec:IQ({dataType:A.data_type,shape:I.chunk_shape,codecs:I.codecs,fillValue:A.fill_value}),getStrides(E){return nI(E,C)},getChunkBytes:yo(g,A.chunk_grid.configuration.chunk_shape,B.encodeChunkKey,I)}}let Q=FC(A.codecs);return{...B,kind:"regular",chunkShape:A.chunk_grid.configuration.chunk_shape,codec:IQ({dataType:A.data_type,shape:A.chunk_grid.configuration.chunk_shape,codecs:A.codecs,fillValue:A.fill_value}),getStrides(C){return nI(C,Q)},async getChunkBytes(C,E){let i=B.encodeChunkKey(C),D=g.resolve(i).path;return g.store.get(D,E)}}}let CB=class extends vA{kind="array";#A;[QB];constructor(A,I,B){super(A,I),this.#A={...B,fill_value:AC(B)},this[QB]=ho(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[QB].chunkShape}get dtype(){return this.#A.data_type}async getChunk(A,I,B){B?.useSharedArrayBuffer&&Ti();let Q=this[QB],C=await Q.getChunkBytes(A,I);if(!C){let E=Q.chunkShape.reduce((D,a)=>D*a,1),i;if(B?.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=xi(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 xB(this.dtype,A)}};function Go(g,A){let I=g;for(let B of A)I instanceof Promise?I=I.then(Q=>B(Q)):I=B(I);return I}function Fo(g,...A){return Go(g,A)}async function wC(g){let A=g.store.arrayExtensions;return A?.length?await Fo(g,...A):g}let EB=wo();function wo(){let g=new WeakMap;function A(I){let B=g.get(I)??{v2:0,v3:0};return g.set(I,B),B}return{increment(I,B){A(I)[B]+=1},versionMax(I){let B=A(I);return B.v3>B.v2?"v3":"v2"}}}async function So(g,A){let I=await g.store.get(g.resolve(".zattrs").path,{signal:A});return I?Jg(I):{}}async function Ro(g,A={}){let I="store"in g?g:new vA(g),{signal:B}=A,Q={};return(A.attrs??!0)&&(Q=await So(I,B)),B?.throwIfAborted(),A.kind==="array"?SC(I,Q,B):A.kind==="group"?RC(I,Q,B):SC(I,Q,B).catch(C=>(IC(C,VI,JA),RC(I,Q,B)))}async function SC(g,A,I){let{path:B}=g.resolve(".zarray"),Q=await g.store.get(B,{signal:I});if(!Q)throw new VI("v2 array",{path:B});return EB.increment(g.store,"v2"),wC(new CB(g.store,g.path,bi(Jg(Q),A)))}async function RC(g,A,I){let{path:B}=g.resolve(".zgroup"),Q=await g.store.get(B,{signal:I});if(!Q)throw new VI("v2 group",{path:B});return EB.increment(g.store,"v2"),new gQ(g.store,g.path,Pi(Jg(Q),A))}async function No(g,A){let{store:I,path:B}=g.resolve("zarr.json"),Q=await g.store.get(B,{signal:A});if(!Q)throw new VI("v3 array or group",{path:B});let C=Jg(Q);return C.node_type==="array"&&(C.fill_value=AC(C)),C.node_type==="array"?wC(new CB(I,g.path,C)):new gQ(I,g.path,C)}async function Uo(g,A={}){let I="store"in g?g:new vA(g),B=await No(I,A.signal);if(EB.increment(I.store,"v3"),A.kind===void 0||A.kind==="array"&&B instanceof CB||A.kind==="group"&&B instanceof gQ)return B;let Q=B instanceof CB?"array":"group";throw new VI(`${A.kind} at ${I.path}`,{path:I.path,found:Q})}async function jA(g,A={}){let I="store"in g?g.store:g,B=EB.versionMax(I),Q=B==="v2"?jA.v2:jA.v3,C=B==="v2"?jA.v3:jA.v2;return Q(g,A).catch(E=>(IC(E,VI,JA),C(g,A)))}jA.v2=Ro,jA.v3=Uo;async function to(g,A){const I=A.split("/"),B=I.pop();if(!B)throw new Error("Invalid path");for(const Q of I)g=await g.getDirectoryHandle(Q);return g.getFileHandle(B)}class BQ{#A;constructor(A){this.#A=A}get directoryHandle(){return this.#A}async get(A){const I=await to(this.#A,A.slice(1)).catch(()=>{});if(!I)return;const Q=await(await I.getFile()).arrayBuffer();return new Uint8Array(Q)}}async function rg(g,A){if(A==="v2")try{return jA.v2(g,{kind:"group",attrs:!0})}catch{throw new Error(`Failed to open Zarr v2 group at ${g}`)}if(A==="v3")try{return jA.v3(g,{kind:"group"})}catch{throw new Error(`Failed to open Zarr v3 group at ${g}`)}try{return jA(g,{kind:"group"})}catch{throw new Error(`Failed to open Zarr group at ${g}`)}}async function ko(g,A){if(A==="v2")try{return jA.v2(g,{kind:"array",attrs:!1})}catch{throw new Error(`Failed to open Zarr v2 array at ${g}`)}if(A==="v3")try{return jA.v3(g,{kind:"array"})}catch{throw new Error(`Failed to open Zarr v3 array at ${g}`)}try{return jA(g,{kind:"array"})}catch{throw new Error(`Failed to open Zarr array at ${g}`)}}async function co(g){let A;switch(g.type){case"fetch":{const B=new kg(g.url);A=new vA(B);break}case"filesystem":{A=new vA(new BQ(g.directoryHandle),g.path);break}default:{const B=g;throw new Error(`Unsupported store type: ${B}`)}}const I=g.arrayPath?A.resolve(g.arrayPath):A;return ko(I,g.zarrVersion)}function Lo(g,A,I){if(g.store instanceof kg)return{type:"fetch",arrayPath:A,zarrVersion:I,url:g.store.url.toString()};if(g.store instanceof BQ)return{type:"filesystem",arrayPath:A,zarrVersion:I,directoryHandle:g.store.directoryHandle,path:g.path};throw new Error(`Unsupported store type: ${g.store.constructor.name}`)}function Jo(g,A,I,B){return ro(g,A,I,B)}function ro(g,A,I,B){const{targetShape:Q,chunkIndex:C,dimIndices:E}=B;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=B.cChunkSize?C.c%B.cChunkSize:0,G=B.tChunkSize?C.t%B.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,r=G*J+a*t,H=D.x===Q.x&&D.y===Q.y&&D.z===Q.z;if(r===0&&g.length===R&&H)return g;const l=new g.constructor(R),V=E.z!==void 0?I[E.z]:0,Z=I[E.y];let W=0;for(let p=0;p<Q.z;p++){const T=r+p*V;for(let AA=0;AA<Q.y;AA++){const BA=T+AA*Z,EA=BA+Q.x;l.set(g.subarray(BA,EA),W),W+=Q.x}}return l}const NC=`function xg(B, A) {
429
+ ${Q}`;return g.replace(tB,C)}const xg={};function dQ(g){const A=g??"";return xg[A]=(xg[A]??0)+1,g?`${g}-${xg[A]}`:String(xg[A])}class Zg{id=dQ()}var wA=1e-6,MA=typeof Float32Array<"u"?Float32Array:Array,dE=Math.PI/180;function fE(g){return g*dE}function fQ(){var g=new MA(9);return MA!=Float32Array&&(g[1]=0,g[2]=0,g[3]=0,g[5]=0,g[6]=0,g[7]=0),g[0]=1,g[4]=1,g[8]=1,g}function lE(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g[3]=A[4],g[4]=A[5],g[5]=A[6],g[6]=A[8],g[7]=A[9],g[8]=A[10],g}function pE(g,A,I,B,Q,C,E,i,D){var a=new MA(9);return a[0]=g,a[1]=A,a[2]=I,a[3]=B,a[4]=Q,a[5]=C,a[6]=E,a[7]=i,a[8]=D,a}function xA(){var g=new MA(16);return MA!=Float32Array&&(g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[11]=0,g[12]=0,g[13]=0,g[14]=0),g[0]=1,g[5]=1,g[10]=1,g[15]=1,g}function ug(g,A){var I=A[0],B=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],r=A[12],H=A[13],K=A[14],l=A[15],V=I*i-B*E,Z=I*D-Q*E,W=I*a-C*E,p=B*D-Q*i,T=B*a-C*i,AA=Q*a-C*D,BA=G*H-R*r,EA=G*K-t*r,CA=G*l-J*r,sA=R*K-t*H,qA=R*l-J*H,kA=t*l-J*K,DA=V*kA-Z*qA+W*sA+p*CA-T*EA+AA*BA;return DA?(DA=1/DA,g[0]=(i*kA-D*qA+a*sA)*DA,g[1]=(Q*qA-B*kA-C*sA)*DA,g[2]=(H*AA-K*T+l*p)*DA,g[3]=(t*T-R*AA-J*p)*DA,g[4]=(D*CA-E*kA-a*EA)*DA,g[5]=(I*kA-Q*CA+C*EA)*DA,g[6]=(K*W-r*AA-l*Z)*DA,g[7]=(G*AA-t*W+J*Z)*DA,g[8]=(E*qA-i*CA+a*BA)*DA,g[9]=(B*CA-I*qA-C*BA)*DA,g[10]=(r*T-H*W+l*V)*DA,g[11]=(R*W-G*T-J*V)*DA,g[12]=(i*EA-E*sA-D*BA)*DA,g[13]=(I*sA-B*EA+Q*BA)*DA,g[14]=(H*Z-r*p-K*V)*DA,g[15]=(G*p-R*Z+t*V)*DA,g):null}function kB(g,A,I){var B=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],r=A[11],H=A[12],K=A[13],l=A[14],V=A[15],Z=I[0],W=I[1],p=I[2],T=I[3];return g[0]=Z*B+W*i+p*R+T*H,g[1]=Z*Q+W*D+p*t+T*K,g[2]=Z*C+W*a+p*J+T*l,g[3]=Z*E+W*G+p*r+T*V,Z=I[4],W=I[5],p=I[6],T=I[7],g[4]=Z*B+W*i+p*R+T*H,g[5]=Z*Q+W*D+p*t+T*K,g[6]=Z*C+W*a+p*J+T*l,g[7]=Z*E+W*G+p*r+T*V,Z=I[8],W=I[9],p=I[10],T=I[11],g[8]=Z*B+W*i+p*R+T*H,g[9]=Z*Q+W*D+p*t+T*K,g[10]=Z*C+W*a+p*J+T*l,g[11]=Z*E+W*G+p*r+T*V,Z=I[12],W=I[13],p=I[14],T=I[15],g[12]=Z*B+W*i+p*R+T*H,g[13]=Z*Q+W*D+p*t+T*K,g[14]=Z*C+W*a+p*J+T*l,g[15]=Z*E+W*G+p*r+T*V,g}function WE(g,A,I){var B=I[0],Q=I[1],C=I[2],E,i,D,a,G,R,t,J,r,H,K,l;return A===g?(g[12]=A[0]*B+A[4]*Q+A[8]*C+A[12],g[13]=A[1]*B+A[5]*Q+A[9]*C+A[13],g[14]=A[2]*B+A[6]*Q+A[10]*C+A[14],g[15]=A[3]*B+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],r=A[8],H=A[9],K=A[10],l=A[11],g[0]=E,g[1]=i,g[2]=D,g[3]=a,g[4]=G,g[5]=R,g[6]=t,g[7]=J,g[8]=r,g[9]=H,g[10]=K,g[11]=l,g[12]=E*B+G*Q+r*C+A[12],g[13]=i*B+R*Q+H*C+A[13],g[14]=D*B+t*Q+K*C+A[14],g[15]=a*B+J*Q+l*C+A[15]),g}function lQ(g,A){return g[0]=A[0],g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=A[1],g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[10]=A[2],g[11]=0,g[12]=0,g[13]=0,g[14]=0,g[15]=1,g}function mE(g,A,I,B){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,r=C*a,H=C*G,K=E*G,l=i*D,V=i*a,Z=i*G,W=B[0],p=B[1],T=B[2];return g[0]=(1-(r+K))*W,g[1]=(t+Z)*W,g[2]=(J-V)*W,g[3]=0,g[4]=(t-Z)*p,g[5]=(1-(R+K))*p,g[6]=(H+l)*p,g[7]=0,g[8]=(J+V)*T,g[9]=(H-l)*T,g[10]=(1-(R+r))*T,g[11]=0,g[12]=I[0],g[13]=I[1],g[14]=I[2],g[15]=1,g}function TE(g,A,I,B,Q){var C=1/Math.tan(A/2);if(g[0]=C/I,g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=C,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[11]=-1,g[12]=0,g[13]=0,g[15]=0,Q!=null&&Q!==1/0){var E=1/(B-Q);g[10]=(Q+B)*E,g[14]=2*Q*B*E}else g[10]=-1,g[14]=-2*B;return g}var xE=TE;function ZE(g,A,I,B,Q,C,E){var i=1/(A-I),D=1/(B-Q),a=1/(C-E);return g[0]=-2*i,g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=-2*D,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[10]=2*a,g[11]=0,g[12]=(A+I)*i,g[13]=(Q+B)*D,g[14]=(E+C)*a,g[15]=1,g}var uE=ZE;function bE(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=B[0],D=B[1],a=B[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 r=D*t-a*R,H=a*G-i*t,K=i*R-D*G;return J=r*r+H*H+K*K,J>0&&(J=1/Math.sqrt(J),r*=J,H*=J,K*=J),g[0]=r,g[1]=H,g[2]=K,g[3]=0,g[4]=R*K-t*H,g[5]=t*r-G*K,g[6]=G*H-R*r,g[7]=0,g[8]=G,g[9]=R,g[10]=t,g[11]=0,g[12]=Q,g[13]=C,g[14]=E,g[15]=1,g}function PE(g,A){var I=g[0],B=g[1],Q=g[2],C=g[3],E=g[4],i=g[5],D=g[6],a=g[7],G=g[8],R=g[9],t=g[10],J=g[11],r=g[12],H=g[13],K=g[14],l=g[15],V=A[0],Z=A[1],W=A[2],p=A[3],T=A[4],AA=A[5],BA=A[6],EA=A[7],CA=A[8],sA=A[9],qA=A[10],kA=A[11],DA=A[12],oI=A[13],AI=A[14],DI=A[15];return Math.abs(I-V)<=wA*Math.max(1,Math.abs(I),Math.abs(V))&&Math.abs(B-Z)<=wA*Math.max(1,Math.abs(B),Math.abs(Z))&&Math.abs(Q-W)<=wA*Math.max(1,Math.abs(Q),Math.abs(W))&&Math.abs(C-p)<=wA*Math.max(1,Math.abs(C),Math.abs(p))&&Math.abs(E-T)<=wA*Math.max(1,Math.abs(E),Math.abs(T))&&Math.abs(i-AA)<=wA*Math.max(1,Math.abs(i),Math.abs(AA))&&Math.abs(D-BA)<=wA*Math.max(1,Math.abs(D),Math.abs(BA))&&Math.abs(a-EA)<=wA*Math.max(1,Math.abs(a),Math.abs(EA))&&Math.abs(G-CA)<=wA*Math.max(1,Math.abs(G),Math.abs(CA))&&Math.abs(R-sA)<=wA*Math.max(1,Math.abs(R),Math.abs(sA))&&Math.abs(t-qA)<=wA*Math.max(1,Math.abs(t),Math.abs(qA))&&Math.abs(J-kA)<=wA*Math.max(1,Math.abs(J),Math.abs(kA))&&Math.abs(r-DA)<=wA*Math.max(1,Math.abs(r),Math.abs(DA))&&Math.abs(H-oI)<=wA*Math.max(1,Math.abs(H),Math.abs(oI))&&Math.abs(K-AI)<=wA*Math.max(1,Math.abs(K),Math.abs(AI))&&Math.abs(l-DI)<=wA*Math.max(1,Math.abs(l),Math.abs(DI))}function $(){var g=new MA(3);return MA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g}function BI(g){var A=new MA(3);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A}function cB(g){var A=g[0],I=g[1],B=g[2];return Math.sqrt(A*A+I*I+B*B)}function yA(g,A,I){var B=new MA(3);return B[0]=g,B[1]=A,B[2]=I,B}function LB(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g}function LI(g,A,I,B){return g[0]=A,g[1]=I,g[2]=B,g}function xI(g,A,I){return g[0]=A[0]+I[0],g[1]=A[1]+I[1],g[2]=A[2]+I[2],g}function JB(g,A,I){return g[0]=A[0]-I[0],g[1]=A[1]-I[1],g[2]=A[2]-I[2],g}function VE(g,A,I){return g[0]=A[0]*I[0],g[1]=A[1]*I[1],g[2]=A[2]*I[2],g}function Sg(g,A,I){return g[0]=A[0]*I,g[1]=A[1]*I,g[2]=A[2]*I,g}function rB(g,A,I,B){return g[0]=A[0]+I[0]*B,g[1]=A[1]+I[1]*B,g[2]=A[2]+I[2]*B,g}function pQ(g,A){var I=A[0]-g[0],B=A[1]-g[1],Q=A[2]-g[2];return I*I+B*B+Q*Q}function WQ(g,A){var I=A[0],B=A[1],Q=A[2],C=I*I+B*B+Q*Q;return C>0&&(C=1/Math.sqrt(C)),g[0]=A[0]*C,g[1]=A[1]*C,g[2]=A[2]*C,g}function bg(g,A){return g[0]*A[0]+g[1]*A[1]+g[2]*A[2]}function Pg(g,A,I){var B=A[0],Q=A[1],C=A[2],E=I[0],i=I[1],D=I[2];return g[0]=Q*D-C*i,g[1]=C*E-B*D,g[2]=B*i-Q*E,g}function nB(g,A,I){var B=A[0],Q=A[1],C=A[2],E=I[3]*B+I[7]*Q+I[11]*C+I[15];return E=E||1,g[0]=(I[0]*B+I[4]*Q+I[8]*C+I[12])/E,g[1]=(I[1]*B+I[5]*Q+I[9]*C+I[13])/E,g[2]=(I[2]*B+I[6]*Q+I[10]*C+I[14])/E,g}function mQ(g,A,I){var B=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-B*a,t=B*D-Q*i;return G=G+G,R=R+R,t=t+t,g[0]=i+E*G+Q*t-C*R,g[1]=D+E*R+C*G-B*t,g[2]=a+E*t+B*R-Q*G,g}function OE(g){return g[0]=0,g[1]=0,g[2]=0,g}function YB(g,A){var I=g[0],B=g[1],Q=g[2],C=A[0],E=A[1],i=A[2];return Math.abs(I-C)<=wA*Math.max(1,Math.abs(I),Math.abs(C))&&Math.abs(B-E)<=wA*Math.max(1,Math.abs(B),Math.abs(E))&&Math.abs(Q-i)<=wA*Math.max(1,Math.abs(Q),Math.abs(i))}var KB=JB,XE=cB;(function(){var g=$();return function(A,I,B,Q,C,E){var i,D;for(I||(I=3),B||(B=0),Q?D=Math.min(Q*I+B,A.length):D=A.length,i=B;i<D;i+=I)g[0]=A[i],g[1]=A[i+1],g[2]=A[i+2],C(g,g,E),A[i]=g[0],A[i+1]=g[1],A[i+2]=g[2];return A}})();function ZI(){var g=new MA(4);return MA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0,g[3]=0),g}function vE(g){var A=new MA(4);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A[3]=g[3],A}function Vg(g,A,I,B){var Q=new MA(4);return Q[0]=g,Q[1]=A,Q[2]=I,Q[3]=B,Q}function jE(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g[3]=A[3],g}function zE(g,A,I){return g[0]=A[0]*I,g[1]=A[1]*I,g[2]=A[2]*I,g[3]=A[3]*I,g}function _E(g,A){var I=A[0],B=A[1],Q=A[2],C=A[3],E=I*I+B*B+Q*Q+C*C;return E>0&&(E=1/Math.sqrt(E)),g[0]=I*E,g[1]=B*E,g[2]=Q*E,g[3]=C*E,g}function Rg(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3];return g[0]=I[0]*B+I[4]*Q+I[8]*C+I[12]*E,g[1]=I[1]*B+I[5]*Q+I[9]*C+I[13]*E,g[2]=I[2]*B+I[6]*Q+I[10]*C+I[14]*E,g[3]=I[3]*B+I[7]*Q+I[11]*C+I[15]*E,g}(function(){var g=ZI();return function(A,I,B,Q,C,E){var i,D;for(I||(I=4),B||(B=0),Q?D=Math.min(Q*I+B,A.length):D=A.length,i=B;i<D;i+=I)g[0]=A[i],g[1]=A[i+1],g[2]=A[i+2],g[3]=A[i+3],C(g,g,E),A[i]=g[0],A[i+1]=g[1],A[i+2]=g[2],A[i+3]=g[3];return A}})();function Og(){var g=new MA(4);return MA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g[3]=1,g}function $E(g,A,I){I=I*.5;var B=Math.sin(I);return g[0]=B*A[0],g[1]=B*A[1],g[2]=B*A[2],g[3]=Math.cos(I),g}function Ai(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=I[0],D=I[1],a=I[2],G=I[3];return g[0]=B*G+E*i+Q*a-C*D,g[1]=Q*G+E*D+C*i-B*a,g[2]=C*G+E*a+B*D-Q*i,g[3]=E*G-B*i-Q*D-C*a,g}function MB(g,A,I,B){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,r,H,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>wA?(t=Math.acos(J),r=Math.sin(t),H=Math.sin((1-B)*t)/r,K=Math.sin(B*t)/r):(H=1-B,K=B),g[0]=H*Q+K*D,g[1]=H*C+K*a,g[2]=H*E+K*G,g[3]=H*i+K*R,g}function eB(g,A){var I=A[0]+A[4]+A[8],B;if(I>0)B=Math.sqrt(I+1),g[3]=.5*B,B=.5/B,g[0]=(A[5]-A[7])*B,g[1]=(A[6]-A[2])*B,g[2]=(A[1]-A[3])*B;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;B=Math.sqrt(A[Q*3+Q]-A[C*3+C]-A[E*3+E]+1),g[Q]=.5*B,B=.5/B,g[3]=(A[C*3+E]-A[E*3+C])*B,g[C]=(A[C*3+Q]+A[Q*3+C])*B,g[E]=(A[E*3+Q]+A[Q*3+E])*B}return g}var Ii=vE,gi=jE,Xg=_E;(function(){var g=$(),A=yA(1,0,0),I=yA(0,1,0);return function(B,Q,C){var E=bg(Q,C);return E<-.999999?(Pg(g,A,Q),XE(g)<1e-6&&Pg(g,I,Q),WQ(g,g),$E(B,g,Math.PI),B):E>.999999?(B[0]=0,B[1]=0,B[2]=0,B[3]=1,B):(Pg(g,Q,C),B[0]=g[0],B[1]=g[1],B[2]=g[2],B[3]=1+E,Xg(B,B))}})(),(function(){var g=Og(),A=Og();return function(I,B,Q,C,E,i){return MB(g,B,E,i),MB(A,Q,C,i),MB(I,g,A,2*i*(1-i)),I}})(),(function(){var g=fQ();return function(A,I,B,Q){return g[0]=B[0],g[3]=B[1],g[6]=B[2],g[1]=Q[0],g[4]=Q[1],g[7]=Q[2],g[2]=-I[0],g[5]=-I[1],g[8]=-I[2],Xg(A,eB(A,g))}})();function TQ(){var g=new MA(2);return MA!=Float32Array&&(g[0]=0,g[1]=0),g}function xQ(g){var A=new MA(2);return A[0]=g[0],A[1]=g[1],A}function LA(g,A){var I=new MA(2);return I[0]=g,I[1]=A,I}function Bi(g,A){var I=A[0]-g[0],B=A[1]-g[1];return Math.sqrt(I*I+B*B)}function Qi(g){var A=g[0],I=g[1];return A*A+I*I}function Ci(g,A,I,B){var Q=A[0],C=A[1];return g[0]=Q+B*(I[0]-Q),g[1]=C+B*(I[1]-C),g}function ZQ(g,A){return g[0]===A[0]&&g[1]===A[1]}function HB(g,A){var I=g[0],B=g[1],Q=A[0],C=A[1];return Math.abs(I-Q)<=wA*Math.max(1,Math.abs(I),Math.abs(Q))&&Math.abs(B-C)<=wA*Math.max(1,Math.abs(B),Math.abs(C))}(function(){var g=TQ();return function(A,I,B,Q,C,E){var i,D;for(I||(I=2),B||(B=0),Q?D=Math.min(Q*I+B,A.length):D=A.length,i=B;i<D;i+=I)g[0]=A[i],g[1]=A[i+1],C(g,g,E),A[i]=g[0],A[i+1]=g[1];return A}})();class JI{min;max;constructor(A,I){this.min=A?BI(A):yA(1/0,1/0,1/0),this.max=I?BI(I):yA(-1/0,-1/0,-1/0)}clone(){return new JI(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:B}=this,Q=[yA(I[0],I[1],I[2]),yA(I[0],I[1],B[2]),yA(I[0],B[1],I[2]),yA(I[0],B[1],B[2]),yA(B[0],I[1],I[2]),yA(B[0],I[1],B[2]),yA(B[0],B[1],I[2]),yA(B[0],B[1],B[2])];this.min=yA(1/0,1/0,1/0),this.max=yA(-1/0,-1/0,-1/0);const C=$();for(const E of Q)nB(C,E,A),this.expandWithPoint(C)}}const Ei={position:0,normal:1,uv:2,next_position:3,previous_position:4,direction:5,color:6,size:7,marker:8};class uI extends Zg{boundingBox_=null;primitive_;attributes_;vertexData_;indexData_;constructor(A=[],I=[],B="triangles"){super(),this.vertexData_=new Float32Array(A),this.indexData_=new Uint32Array(I),this.primitive_=B,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,B=new JI,Q=$();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],B.expandWithPoint(Q);this.boundingBox_=B}return this.boundingBox_}get type(){return"Geometry"}getAttribute(A){return this.attributes_.find(I=>I.type===A)}}class ii{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:B}=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,B,this.gl_.STATIC_DRAW);const{attributes:E,strideBytes:i}=A;E.forEach(G=>{const R=Ei[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 oi(g){return g===1||g===2||g===4||g===8}function qB(g){if(g instanceof Int8Array)return"byte";if(g instanceof Int16Array)return"short";if(g instanceof Int32Array)return"int";if(g instanceof Uint8Array)return"unsigned_byte";if(g instanceof Uint16Array)return"unsigned_short";if(g instanceof Uint32Array)return"unsigned_int";if(g instanceof Float32Array)return"float";throw new Error("Unsupported buffer type.")}function Di(g){switch(g.dataFormat){case"scalar":return 1;case"rgb":return 3;case"rgba":return 4}}function ai(g){switch(g.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 dB(g){const A=Di(g)*ai(g),I=Math.max(1,g.mipmapLevels);let B=Math.max(1,g.width),Q=Math.max(1,g.height),C=Math.max(1,g.depth),E=0;for(let i=0;i<I;++i)E+=A*C*B*Q,B=Math.max(1,B>>1),Q=Math.max(1,Q>>1),g.type==="Texture3D"&&(C=Math.max(1,C>>1));return E}function si(g){if(g.dataFormat==="rgb"||g.dataFormat==="rgba")return[0,1];switch(g.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 fB extends Zg{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 yi{gl_;textures_=new Map;currentTexture_=null;maxTextureUnits_;gpuTextureBytes_=0;textureCount_=0;readFramebuffer_=null;constructor(A){this.gl_=A,this.maxTextureUnits_=A.getParameter(A.MAX_TEXTURE_IMAGE_UNITS)}get gpuTextureBytes(){return this.gpuTextureBytes_}get textureCount(){return this.textureCount_}bindTexture(A,I){if(this.alreadyActive(A))return;if(I<0||I>=this.maxTextureUnits_)throw new Error(`Texture index ${I} must be in [0, ${this.maxTextureUnits_-1}]`);const B=this.textures_.get(A);B&&!A.needsUpdate?(this.gl_.activeTexture(this.gl_.TEXTURE0+I),this.gl_.bindTexture(this.getTextureType(A),B)):this.uploadTexture(A,I),this.currentTexture_=A}readTexel(A,I,B,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,B,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 B=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,B);const C=this.textures_.get(A);if(!C)throw new Error("Failed to retrieve texture ID");this.gl_.bindTexture(B,C),this.configureTextureParameters(A,B),this.uploadTextureData(A,Q,B),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 B=dB(A);this.gpuTextureBytes_=Math.max(0,this.gpuTextureBytes_-B),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,B){const Q=this.gl_.createTexture();if(!Q)throw new Error("Failed to create texture");if(this.gl_.bindTexture(B,Q),this.isTexture2D(A))this.gl_.texStorage2D(B,A.mipmapLevels,I.internalFormat,A.width,A.height);else if(this.isTextureStorage3D(A))this.gl_.texStorage3D(B,A.mipmapLevels,I.internalFormat,A.width,A.height,A.depth);else throw new Error(`Unknown texture type ${A.type}`);this.gpuTextureBytes_+=dB(A),this.textureCount_+=1,this.textures_.set(A,Q),this.gl_.bindTexture(B,null),A.readTexel=(C,E,i)=>Promise.resolve(this.readTexel(A,C,E,i))}configureTextureParameters(A,I){const B=this.gl_,Q=this.getFilter(A.minFilter,A),C=this.getFilter(A.maxFilter,A);B.pixelStorei(B.UNPACK_ALIGNMENT,A.unpackAlignment),B.texParameteri(I,B.TEXTURE_MIN_FILTER,Q),B.texParameteri(I,B.TEXTURE_MAG_FILTER,C),B.texParameteri(I,B.TEXTURE_WRAP_S,this.getWrapMode(A.wrapS)),B.texParameteri(I,B.TEXTURE_WRAP_T,this.getWrapMode(A.wrapT)),B.texParameteri(I,B.TEXTURE_WRAP_R,this.getWrapMode(A.wrapR))}uploadTextureData(A,I,B){const C={x:0,y:0,z:0};if(this.isTexture2D(A))this.gl_.texSubImage2D(B,0,C.x,C.y,A.width,A.height,I.format,I.type,A.data);else if(this.isTextureStorage3D(A))this.gl_.texSubImage3D(B,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:B,dataType:Q}=I;if(B==="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==="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 PA{min;max;constructor(A,I){this.min=A?xQ(A):LA(1/0,1/0),this.max=I?xQ(I):LA(-1/0,-1/0)}clone(){return new PA(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 ZQ(A.min,I.min)&&ZQ(A.max,I.max)}floor(){return new PA(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],B=this.max[0]-this.min[0],Q=this.max[1]-this.min[1];return{x:A,y:I,width:B,height:Q}}}class hi{gl_;enabledCapabilities_=new Map;depthMaskEnabled_=null;blendSrcFactor_=null;blendDstFactor_=null;currentBlendingMode_=null;currentViewport_=null;currentScissor_=null;currentCullingMode_=null;stencilFunc_=null;stencilRef_=null;stencilFuncMask_=null;constructor(A){this.gl_=A,this.gl_.frontFace(this.gl_.CW)}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_}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"premultiplied":this.setBlendFunc(this.gl_.ONE_MINUS_DST_ALPHA,this.gl_.ONE);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_&&PA.equals(I,this.currentViewport_))return;const{x:B,y:Q,width:C,height:E}=I.toRect();this.gl_.viewport(B,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_&&PA.equals(I,this.currentScissor_))return;const{x:B,y:Q,width:C,height:E}=I.toRect();this.gl_.scissor(B,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,B){(this.stencilFunc_!==A||this.stencilRef_!==I||this.stencilFuncMask_!==B)&&(this.gl_.stencilFunc(A,I,B),this.stencilFunc_=A,this.stencilRef_=I,this.stencilFuncMask_=B)}}const Gi=lQ(xA(),[1,-1,1]);class Fi extends Fg{gl_;programs_;bindings_;textures_;state_;renderedObjectsPerFrame_=0;stencilRef_=0;currentViewportSize_=[0,0];constructor(A){super(A);const I=this.canvas.getContext("webgl2",{depth:!0,antialias:!0,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 qE(I),this.bindings_=new ii(I),this.textures_=new yi(I),this.state_=new hi(I),this.initStencil(),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;const I=[],B=[];for(const G of A.layers)(G.blendMode==="none"?I:B).push(G);for(const G of[...I,...B])G.update(A);if(getComputedStyle(A.element).visibility==="hidden")return;const Q=A.getBoxRelativeTo(this.canvas),C=new PA(LA(0,0),LA(this.width,this.height)),E=PA.equals(Q.floor(),C.floor()),i=PA.intersects(Q,C);if(E)this.state_.setScissorTest(!1);else if(i)this.state_.setScissorTest(!0),this.state_.setScissor(Q);else{O.warn("WebGLRenderer",`Viewport ${A.id} is entirely outside canvas bounds, skipping render`);return}this.state_.setViewport(Q),this.clear();const D=Q.toRect();this.currentViewportSize_=[D.width,D.height];const a=A.camera.frustum;this.state_.setDepthMask(!0);for(const G of I)G.state==="ready"&&this.renderLayer(G,A.camera,a);this.state_.setDepthMask(!1);for(const G of B)G.state==="ready"&&this.renderLayer(G,A.camera,a);this.renderedObjects_=this.renderedObjectsPerFrame_}initStencil(){this.gl_.clearStencil(0),this.gl_.stencilMask(255),this.gl_.stencilOp(this.gl_.KEEP,this.gl_.KEEP,this.gl_.REPLACE)}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,B){this.state_.setBlendingMode(A.blendMode);for(const[Q,C]of A.coverageGroups){this.setCoverageStencil(Q);for(const E of C)B.intersectsWithBox3(E.boundingBox)&&(this.renderObject(A,E,I),this.renderedObjectsPerFrame_+=1)}}renderObject(A,I,B){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,B),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,B),E!==null&&this.state_.setBlendingMode(E),this.state_.setStencilTest(C)}}drawGeometry(A,I,B,Q,C){const E=kB(xA(),C.viewMatrix,I.transform.matrix),i=kB(xA(),Gi,C.projectionMatrix),D=this.currentViewportSize_,a=I.getUniforms(),R={...B.getUniforms(),...a};for(const r of Q.uniformNames)switch(r){case"u_modelView":Q.setUniform(r,E);break;case"u_model":Q.setUniform(r,I.transform.matrix);break;case"u_projection":Q.setUniform(r,i);break;case"u_resolution":Q.setUniform(r,D);break;case"u_opacity":Q.setUniform(r,B.opacity*(a.Opacity??1));break;case"u_cameraPositionModel":{const H=ug(xA(),E),K=Vg(0,0,0,1),l=Rg(ZI(),K,H);Q.setUniform(r,yA(l[0],l[1],l[2]));break}default:r in R&&Q.setUniform(r,R[r])}const t=this.glGetPrimitive(A.primitive),J=A.indexData;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 B=new PA(LA(0,0),LA(A,I));this.state_.setViewport(B)}clear(){this.gl_.clearColor(0,0,0,0),this.gl_.clear(this.gl_.COLOR_BUFFER_BIT|this.gl_.DEPTH_BUFFER_BIT|this.gl_.STENCIL_BUFFER_BIT),this.state_.setDepthTesting(!0),this.gl_.depthFunc(this.gl_.LEQUAL)}}function Ng(g,A){const I=g.priority??Number.MAX_SAFE_INTEGER,B=A.priority??Number.MAX_SAFE_INTEGER;return I===B?(g.orderKey??Number.MAX_SAFE_INTEGER)-(A.orderKey??Number.MAX_SAFE_INTEGER):I-B}class wi{maxConcurrent_;pending_=[];running_=new Map;constructor(A){this.maxConcurrent_=Math.max(1,A)}enqueue(A,I){this.running_.has(A)||this.pending_.some(B=>B.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 B=this.running_.get(A);B&&(B.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:B}=A;I.state="loading";const Q=new AbortController,C=Promise.resolve().then(()=>B(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 Si(g,A){g.data&&(vg-=g.data.byteLength,jg-=1),g.data=A,vg+=A.byteLength,jg+=1}function uQ(g){g.data&&(vg-=g.data.byteLength,jg-=1),g.data=void 0,g.texture?.releaseCpuData()}function Ri(){return{cpuChunkBytes:vg,cpuChunkCount:jg}}function bQ(g,A,I=1e-6){return Math.abs(g-A)<=I}const RA={x:0,y:1,z:2};function bI(g){switch(g){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(g){const A=$(),I=$();A[RA[g.u]]=1,I[RA[g.v]]=1;const B=Pg($(),A,I),Q=pE(A[0],A[1],A[2],I[0],I[1],I[2],B[0],B[1],B[2]),C=eB(Og(),Q);return Xg(C,C)}const PQ=[Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array];function Ni(g){if(PQ.some(I=>g instanceof I))return!0;const A=PQ.map(I=>I.name);return O.debug("Chunk",`Unsupported chunk data type: ${g}. Supported data types: ${A}`),!1}function Ui(g,A){return Math.round((A-g.translation)/g.scale)}function VQ(g,A){const I=$(),B=$();for(const C of["x","y","z"]){const E=C===A.w?.5*g.scale[C]:0,i=RA[C];I[i]=1/(g.scale[C]*g.shape[C]),B[i]=E-g.offset[C]}const Q=lQ(xA(),I);return WE(Q,Q,B)}function EI(g,A,I){return Math.max(A,Math.min(I,g))}const zg=Symbol("INTERNAL_POLICY_KEY");class ti{store_;policy_;policyChanged_=!1;currentLOD_=0;axes_;scale0_;lastViewBounds2D_=null;lastViewProjection_=null;lastSliceBounds_;lastTCoord_;lastCCoords_;sourceMaxSquareDistance2D_;chunkViewStates_=new Map;isDisposed_=!1;constructor(A,I,B={u:"x",v:"y",w:"z"}){this.store_=A,this.policy_=I,this.axes_=B,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_=Qi(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],B=A[this.axes_.v].lods[0];return new PA(LA(I.translation,B.translation),LA(I.translation+I.size*I.scale,B.translation+B.size*B.scale))}getChunksToRender(){const A=this.fallbackLOD(),I=this.currentLOD_,B=[],Q=[];for(const[C,E]of this.chunkViewStates_)!E.visible||C.state!=="loaded"||!C.texture||(C.lod===I?B.push(C):C.lod===A&&I!==A&&Q.push(C));return[...B,...Q]}updateChunksForImage(A,I){const B=I.worldViewRect,C=Math.abs(B.max[0]-B.min[0])/I.bufferWidthPx,E=Math.log2(1/C),i=this.setLOD(E),D=this.getSliceAxisBounds(A);if(!(this.policyChanged_||i||this.viewBounds2DChanged(B)||this.sliceBoundsChanged(D)||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const G=this.timeIndex(A);if(!this.store_.hasChunksAtTime(G)){O.warn("ChunkStoreView","updateChunkViewStates called with no chunks initialized"),this.chunkViewStates_.forEach(Ug);return}const R=TQ();Ci(R,B.min,B.max,.5);const t=this.makeViewBounds3D(B,D);this.chunkViewStates_.forEach(Ug);const J=this.channelsOfInterest(A),r=this.fallbackLOD(),H=this.getPaddedBounds(t),K=this.currentLOD_===r?[this.currentLOD_]:[this.currentLOD_,r];for(const l of K){const V=l===this.currentLOD_,Z=l===r;this.iterateChunksInBox(G,l,J,H,(W,p)=>{const T=JI.intersects(p,t),AA=V&&!T,BA=this.computePriority(Z,V,T,AA,!0);BA!==null&&this.chunkViewStates_.set(W,{visible:T,prefetch:AA,priority:BA,orderKey:this.squareDistance2D(W,R)})})}this.markTimeChunksForPrefetchImage(G,A,t,R),this.policyChanged_=!1,this.lastViewBounds2D_=B.clone(),this.lastSliceBounds_=D,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);if(!this.store_.hasChunksAtTime(Q)){O.warn("ChunkStoreView","updateChunksForVolume called with no chunks initialized"),this.chunkViewStates_.forEach(Ug);return}this.currentLOD_=this.policy_.lod.min,this.chunkViewStates_.forEach(Ug);const C=this.channelsOfInterest(A),E=this.fallbackLOD(),i=D=>{const a=D.lod===E,G=D.lod===this.currentLOD_,R=this.computePriority(a,G,!0,!1,!0);R!==null&&this.chunkViewStates_.set(D,{visible:!0,prefetch:!1,priority:R,orderKey:0})};this.iterateAllChunksAtLod(Q,this.currentLOD_,C,i),this.currentLOD_!==E&&this.iterateAllChunksAtLod(Q,E,C,i),this.markTimeChunksForPrefetchVolume(Q,A),this.policyChanged_=!1,this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0,this.lastViewProjection_=I}allVisibleFallbackLODLoaded(){const A=this.fallbackLOD();let I=!1;for(const[B,Q]of this.chunkViewStates_)if(!(!Q.visible||B.lod!==A)&&(I=!0,B.texture===void 0))return!1;return I}get currentLOD(){return this.currentLOD_}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.chunkViewStates_.forEach(Ug)}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 B=this.policy_.lod.bias-Math.log2(this.scale0_)-A,Q=Math.floor(B),C=this.store_.getLowestResLOD(),E=Math.max(0,Math.min(C,this.policy_.lod.min)),i=Math.max(E,Math.min(C,this.policy_.lod.max)),D=EI(Q,E,i);return D===this.currentLOD_?!1:(this.currentLOD_=D,!0)}markTimeChunksForPrefetchImage(A,I,B,Q){const C=this.store_.dimensions.t?.lods[0].size??1,E=Math.min(this.policy_.prefetch.t,C-1),i=this.fallbackLOD(),D=this.policy_.priorityMap.prefetchTime,a=this.channelsOfInterest(I);for(let G=1;G<=E;++G){const R=(A+G)%C;this.iterateChunksInBox(R,i,a,B,t=>{const J=this.squareDistance2D(t,Q),r=EI(J/this.sourceMaxSquareDistance2D_,0,1-Number.EPSILON),H=G+r;this.chunkViewStates_.set(t,{visible:!1,prefetch:!0,priority:D,orderKey:H})})}}markTimeChunksForPrefetchVolume(A,I){const B=this.store_.dimensions.t?.lods[0].size??1,Q=Math.min(this.policy_.prefetch.t,B-1),C=this.fallbackLOD(),E=this.policy_.priorityMap.prefetchTime,i=this.channelsOfInterest(I);for(let D=1;D<=Q;++D){const a=(A+D)%B;this.iterateAllChunksAtLod(a,C,i,G=>{const R=D;this.chunkViewStates_.set(G,{visible:!1,prefetch:!0,priority:E,orderKey:R})})}}computePriority(A,I,B,Q,C){if(!C)return null;const E=this.policy_.priorityMap;return A&&B?E.fallbackVisible:I&&B?E.visibleCurrent:A?E.fallbackBackground:I&&Q?E.prefetchSpace:null}channelsOfInterest(A){return A.c??Array.from({length:this.store_.channelCount},(I,B)=>B)}chunkIndexRange(A,I){const B=this.store_.dimensions,Q=B.x.lods[I],C=B.y.lods[I],E=B.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,r=C.translation,H=E?.translation??0,K=Math.max(0,Math.floor((A.min[0]-J)/G)),l=Math.min(i,Math.ceil((A.max[0]-J)/G)),V=Math.max(0,Math.floor((A.min[1]-r)/R)),Z=Math.min(D,Math.ceil((A.max[1]-r)/R)),W=E?Math.max(0,Math.floor((A.min[2]-H)/t)):0,p=E?Math.min(a,Math.ceil((A.max[2]-H)/t)):1;return K>=l||V>=Z||W>=p?null:{xMin:K,xMax:l,yMin:V,yMax:Z,zMin:W,zMax:p}}iterateChunksInBox(A,I,B,Q,C){const E=this.chunkIndexRange(Q,I);if(E)for(const i of B){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 r=t[J];C(r,this.getChunkAabb(r))}}}}}iterateAllChunksAtLod(A,I,B,Q){for(const C of B){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,this.getChunkAabb(a))}}getChunkAabb(A){return new JI(yA(A.offset.x,A.offset.y,A.offset.z),yA(A.offset.x+A.shape.x*A.scale.x,A.offset.y+A.shape.y*A.scale.y,A.offset.z+A.shape.z*A.scale.z))}fallbackLOD(){return Math.min(this.policy_.lod.max,this.store_.getLowestResLOD())}timeIndex(A){const I=this.store_.dimensions.t;return A.t===void 0||I===void 0?0:Ui(I.lods[0],A.t)}getSliceAxisBounds(A){const I=this.store_.dimensions[this.axes_.w];if(I===void 0)return[0,1];const B=I.lods[this.currentLOD_],Q=A[this.axes_.w];if(Q===void 0)return[B.translation,B.translation+B.size*B.scale];const C=B.size,E=B.scale,i=B.translation,D=Math.floor((Q-i)/E),a=B.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 B=$(),Q=$();return B[RA[this.axes_.u]]=A.min[0],Q[RA[this.axes_.u]]=A.max[0],B[RA[this.axes_.v]]=A.min[1],Q[RA[this.axes_.v]]=A.max[1],B[RA[this.axes_.w]]=I[0],Q[RA[this.axes_.w]]=I[1],new JI(B,Q)}viewBounds2DChanged(A){return this.lastViewBounds2D_===null||!HB(this.lastViewBounds2D_.min,A.min)||!HB(this.lastViewBounds2D_.max,A.max)}hasViewProjectionChanged(A){return this.lastViewProjection_===null||!PE(this.lastViewProjection_,A)}sliceBoundsChanged(A){return!this.lastSliceBounds_||!HB(this.lastSliceBounds_,A)}cCoordsChanged(A){return!this.lastCCoords_&&!A?!1:!this.lastCCoords_||!A||this.lastCCoords_.length!==A.length?!0:!this.lastCCoords_.every((I,B)=>I===A[B])}getPaddedBounds(A){const{u:I,v:B,w:Q}=this.axes_,C=this.store_.dimensions,E=C[I].lods[this.currentLOD_],i=C[B].lods[this.currentLOD_],D=C[Q]?.lods[this.currentLOD_],a=$();return a[RA[I]]=E.chunkSize*E.scale*this.policy_.prefetch.x,a[RA[B]]=i.chunkSize*i.scale*this.policy_.prefetch.y,D&&(a[RA[Q]]=D.chunkSize*D.scale*this.policy_.prefetch.z),new JI(JB($(),A.min,a),xI($(),A.max,a))}squareDistance2D(A,I){function B(D){return A.offset[D]+.5*A.shape[D]*A.scale[D]}const{u:Q,v:C}=this.axes_,E=B(Q)-I[0],i=B(C)-I[1];return E*E+i*i}}function Ug(g){g.visible=!1,g.prefetch=!1,g.priority=null,g.orderKey=null}class ki{chunks_;lowestResLOD_;dimensions_;views_=[];hasHadViews_=!1;constructor(A){this.dimensions_=A,this.lowestResLOD_=this.dimensions_.numLods-1,this.validateXYScaleRatios();const{size:I}=this.getAndValidateTimeDimension(),{size:B}=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),r=D?Math.ceil(D.size/R):1,H=new Array(I);this.chunks_[C]=H;for(let K=0;K<I;++K){const l=new Array(B);H[K]=l;for(let V=0;V<B;++V){const Z=new Array(r);l[V]=Z;for(let W=0;W<r;++W){const p=D!==void 0?D.translation+W*R*D.scale:0,T=new Array(J);Z[W]=T;for(let AA=0;AA<J;++AA){const BA=i.translation+AA*G*i.scale,EA=new Array(t);T[AA]=EA;for(let CA=0;CA<t;++CA){const sA=E.translation+CA*a*E.scale;EA[CA]={state:"unloaded",lod:C,visible:!1,prefetch:!1,priority:null,orderKey:null,shape:{x:Math.min(a,E.size-CA*a),y:Math.min(G,i.size-AA*G),z:Math.min(R,(D?.size??1)-W*R),c:1},rowAlignmentBytes:1,chunkIndex:{x:CA,y:AA,z:W,c:V,t:K},scale:{x:E.scale,y:i.scale,z:D?.scale??1},offset:{x:sA,y:BA,z:p}}}}}}}}}getChunkGrid(A,I,B){return this.chunks_[A]?.[I]?.[B]}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 B=new ti(this,A,I);return this.views_.push(B),this.hasHadViews_=!0,B}get views(){return this.views_}canDispose(){return this.hasHadViews_&&this.views_.length===0}updateAndCollectChunkChanges(){const A=new Set;for(const I of this.views_)for(const[B,Q]of I.chunkViewStates)A.add(B);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,B=!1,Q=null,C=null;for(const D of this.views_){const a=D.chunkViewStates.get(A);a&&(a.visible&&(I=!0),a.prefetch&&(B=!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=B,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 B=1;B<this.dimensions_.numLods;B++){const Q=A.lods[B].scale/A.lods[B-1].scale,C=I.lods[B].scale/I.lods[B-1].scale;if(!bQ(Q,2,.02)||!bQ(C,2,.02))throw new Error(`Invalid downsampling factor between levels ${B-1} → ${B}: expected (2× in X and Y), but got (${Q.toFixed(2)}×, ${C.toFixed(2)}×) from scale [${A.lods[B-1].scale}, ${I.lods[B-1].scale}] → [${A.lods[B].scale}, ${I.lods[B].scale}]`)}}getAndValidateTimeDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.t?.lods[A];if(!I)continue;const B=this.dimensions_.t?.lods[A-1];if(B&&I.size!==B.size)throw new Error(`ChunkStore does not support downsampling in t. Found ${B.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 B=this.dimensions_.c?.lods[A-1];if(B&&I.size!==B.size)throw new Error(`ChunkStore does not support downsampling in c. Found ${B.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.c?.lods[0].size??1}}}class lB extends fB{width_;height_;depth_;constructor(A,I,B,Q){super(),this.dataFormat="scalar",this.dataType=qB(A),this.data_=A,this.width_=I,this.height_=B,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 B=new lB(I,A.shape.x,A.shape.y,A.shape.z);return B.unpackAlignment=A.rowAlignmentBytes,B}}const ci=8,Li=4;class Ji{stores_=[];queue_;uploadTexture_;disposeTexture_;getGpuResidentBytes_;memoryLimitBytes_;maxGpuUploadsPerUpdate_;resident_=new Set;constructor(A,I,B=()=>0,Q=1/0,C=ci,E=Li){this.uploadTexture_=A,this.disposeTexture_=I,this.getGpuResidentBytes_=B,this.memoryLimitBytes_=Q,this.maxGpuUploadsPerUpdate_=Math.max(1,E),this.queue_=new wi(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 Ri()}addView(A,I,B){let Q=this.stores_.find(C=>C.source===A)?.store;return Q||(Q=new ki(A.loader.getSourceDimensionMap()),this.stores_.push({source:A,store:Q})),Q.addView(I,B)}update(){const A=[];for(const{source:I,store:B}of this.stores_){const Q=B.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(Q)}this.enqueueWithinBudget(A),this.queue_.flush();for(let I=this.stores_.length-1;I>=0;I--)this.stores_[I].store.canDispose()&&this.stores_.splice(I,1)}releaseChunk(A){if(this.queue_.cancel(A),A.texture!==void 0){A.releasedAt??=performance.now();return}uQ(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_(),B=null;for(const{source:Q,chunk:C}of A){const E=this.chunkBytes(Q,C);E>this.memoryLimitBytes_||(I+E>this.memoryLimitBytes_&&(B??=this.evictionCandidates(),I=this.evictWorseChunks(I,E,C,B)),!(I+E>this.memoryLimitBytes_)&&(I+=E,this.queue_.enqueue(C,i=>Q.loader.loadChunkData(C,i))))}}evictionCandidates(){const A=[];for(const I of this.resident_)I.visible||A.push(I);return A.sort((I,B)=>{const Q=-Ng(I,B);return Q!==0?Q:(I.releasedAt??0)-(B.releasedAt??0)})}evictWorseChunks(A,I,B,Q){for(;A+I>this.memoryLimitBytes_&&Q.length>0&&Ng(Q[0],B)>0;){const C=Q.shift();C.texture!==void 0&&(A-=dB(C.texture),this.disposeChunkTexture(C),C.state="unloaded",C.releasedAt=void 0)}return A}chunkBytes(A,I){const B=A.loader.getBytesPerElement();return I.shape.x*I.shape.y*I.shape.z*B}uploadLoadedChunks(A){if(!this.uploadTexture_)return;const I=[];for(const Q of A)Q.state==="loaded"&&Q.texture===void 0&&I.push(Q);if(I.length===0)return;I.sort(Ng);const B=Math.min(I.length,this.maxGpuUploadsPerUpdate_);for(let Q=0;Q<B;Q++){const C=I[Q],E=lB.createWithChunk(C);this.uploadTexture_(E),C.texture=E,this.resident_.add(C),uQ(C)}}disposeChunkTexture(A){this.disposeTexture_&&A.texture!==void 0&&(this.disposeTexture_(A.texture),A.texture=void 0,this.resident_.delete(A))}}var tg=function(g=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 B(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=B(new tg.Panel("FPS","#0ff","#002",g)),a=B(new tg.Panel("MS","#0f0","#020",g));if(self.performance&&self.performance.memory)var G=B(new tg.Panel("MB","#f08","#201",g));return Q(0),{REVISION:16,dom:I,addPanel:B,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}};tg.Panel=function(g,A,I,B){var Q=1/0,C=0,E=Math.round,i=E(window.devicePixelRatio||1),D=E(80*i*B),a=E(48*i*B),G=E(3*i*B),R=E(2*i*B),t=E(3*i*B),J=E(15*i*B),r=E(74*i*B),H=E(30*i*B),K=document.createElement("canvas");K.width=D,K.height=a,K.style.cssText=`width:${E(B*80)}px;height:${E(B*48)}px`;var l=K.getContext("2d");return l.font="bold "+E(9*i*B)+"px Helvetica,Arial,sans-serif",l.textBaseline="top",l.fillStyle=I,l.fillRect(0,0,D,a),l.fillStyle=A,l.fillText(g,G,R),l.fillRect(t,J,r,H),l.fillStyle=I,l.globalAlpha=.9,l.fillRect(t,J,r,H),{dom:K,update:function(V,Z){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)+" "+g+" ("+E(Q)+"-"+E(C)+")",G,R),l.drawImage(K,t+i,J,r-i,H,t,J,r-i,H),l.fillRect(t+r-i,J,i,H),l.fillStyle=I,l.globalAlpha=.9,l.fillRect(t+r-i,J,i,E((1-V/Z)*H))}}};function ri({scale:g}={scale:1.5}){const A=new tg(g);return A.showPanel(0),document.body.appendChild(A.dom),A}const pB=["pointerdown","pointermove","pointerup","pointercancel","wheel"];function ni(g){return pB.includes(g)}class Yi{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 Ki{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,pB.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,pB.forEach(A=>{this.element_.removeEventListener(A,this.handleEvent)})}handleEvent=A=>{if(!ni(A.type)){O.error("EventDispatcher",`Unsupported event type ${A.type}`);return}const I=new Yi(A.type,A);for(const B of this.listeners_)if(B(I),I.propagationStopped)break}}const Mi=1e-12;class ei{origin;direction;constructor(A,I){this.origin=BI(A),this.direction=WQ($(),I)}intersectWithPlane(A){const I=bg(this.direction,A.normal);if(Math.abs(I)<Mi)return null;const B=-A.signedDistanceToPoint(this.origin)/I;return rB($(),this.origin,this.direction,B)}}class Hi{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 Ki(this.element),this.events.addEventListener(I=>{if(I.event instanceof PointerEvent||I.event instanceof WheelEvent){const{clientX:B,clientY:Q}=I.event,C=LA(B,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 ei(E,JB($(),i,E))}for(const B of this.layers_)if(B.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(),B=A.getBoundingClientRect(),Q=window.devicePixelRatio||1,C=B.left*Q,E=B.top*Q,i=B.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 PA(LA(G,R),LA(G+t,R+J))}getBufferRect(){return this.getBoxRelativeTo(this.element).toRect()}clientToClip(A,I=0){const[B,Q]=A,C=this.element.getBoundingClientRect();return yA(2*(B-C.x)/C.width-1,2*(Q-C.y)/C.height-1,I)}clientToWorld(A,I=0){const B=this.clientToClip(A,I);return this.camera.clipToWorld(B)}getBox(){const A=this.element.getBoundingClientRect(),I=window.devicePixelRatio||1,B=A.left*I,Q=A.top*I,C=A.width*I,E=A.height*I;return new PA(LA(B,Q),LA(B+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 B=A/I;this.camera.setAspectRatio(B)}}function OQ(g,A){for(const I of A){if(I.id===g.id)throw new Error(`Duplicate viewport ID "${g.id}". Each viewport must have a unique ID.`);if(I.element===g.element){const B=g.element.tagName.toLowerCase()+(g.element.id?`#${g.element.id}`:"[element has no id]");throw new Error(`Multiple viewports cannot share the same HTML element: viewports "${I.id}" and "${g.id}" both use ${B}`)}}}function qi(g){for(let A=0;A<g.length;A++)OQ(g[A],g.slice(0,A))}function XQ(g,A,I){const B=g.map(Q=>{const C=Q.element??A;return{...Q,element:C,id:Q.id??C.id??dQ("viewport"),context:I}});return qi(B),B.map(Q=>new Hi(Q))}class di{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 fi=2048;class li{chunkManager_;context_;renderer_;viewports_;canvas;overlays;stats_;sizeObserver_;lastAnimationId_;lastTimestamp_=0;constructor(A){this.canvas=A.canvas,this.renderer_=new Fi(this.canvas);const B=(A.memoryLimitMB??fi)*1024*1024;this.chunkManager_=new Ji(C=>this.renderer_.uploadTexture(C),C=>this.renderer_.disposeTexture(C),()=>this.renderer_.gpuTextureBytes,B,A.maxConcurrentRequests,A.maxGpuUploadsPerUpdate),this.context_={chunkManager:this.chunkManager_},this.viewports_=XQ(A.viewports??[],this.canvas,this.context_),this.overlays=[...A.overlays??[]],A.showStats&&(this.stats_=ri());const Q=[this.canvas];for(const C of this.viewports_)C.element!==this.canvas&&Q.push(C.element);this.sizeObserver_=new di(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 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]=XQ([A],this.canvas,this.context_);return OQ(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 B of this.viewports_)B.cameraControls?.onUpdate(I),this.renderer_.render(B);this.chunkManager_.update();for(const B of this.overlays)B.update(this);this.stats_&&this.stats_.end(),this.lastAnimationId_=requestAnimationFrame(B=>this.animate(B))}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 pi(g,A){return{...g,...A,headers:{...g.headers,...A.headers}}}function vQ(g,A){const I=typeof g=="string"?new URL(g):g;I.pathname.endsWith("/")||(I.pathname+="/");const B=new URL(A.slice(1),I);return B.search=I.search,B}async function jQ(g){if(g.status!==404){if(g.status===200||g.status===206)return new Uint8Array(await g.arrayBuffer());throw new Error(`Unexpected response status ${g.status} ${g.statusText}`)}}class kg{url;#A;#I;#g;constructor(A,I={}){this.url=A,this.#A=I.fetch??(B=>fetch(B)),this.#I=I.overrides??{},this.#g=I.useSuffixRequest??!1}#B(A,I){return new Request(A,pi(this.#I,I))}async get(A,I={}){let B=vQ(this.url,A).href,Q=this.#B(B,I),C=await this.#A(Q);return jQ(C)}async getRange(A,I,B={}){let Q=vQ(this.url,A),C;if("suffixLength"in I)C=await this.#Q(Q,I.suffixLength,B);else{let E={...B,headers:{...B.headers,Range:`bytes=${I.offset}-${I.offset+I.length-1}`}},i=this.#B(Q,E);C=await this.#A(i)}return jQ(C)}async#Q(A,I,B){if(this.#g){let G={...B,headers:{...B.headers,Range:`bytes=-${I}`}};return this.#A(this.#B(A,G))}let Q=this.#B(A,{...B,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={...B,headers:{...B.headers,Range:`bytes=${D}-${i-1}`}};return this.#A(this.#B(A,a))}}class cg extends Error{}class VI extends cg{_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 cg{_tag="InvalidMetadataError";name="InvalidMetadataError";path;constructor(A,I={}){super(A,{cause:I.cause}),this.path=I.path}}class Wi extends cg{_tag="UnknownCodecError";name="UnknownCodecError";codec;constructor(A){super(`Unknown codec: ${A}`),this.codec=A}}class mi extends cg{_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 WB extends cg{_tag="UnsupportedError";name="UnsupportedError";feature;constructor(A){super(`Unsupported: ${A}`),this.feature=A}}function rI(g){return()=>{throw new WB(`${g} encode`)}}class _g{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 _g(A,I)}encode=rI("bitround");decode(A){return A}}function mB(g){return g instanceof ArrayBuffer||g instanceof SharedArrayBuffer}class zQ{#A;constructor(A,I,B){typeof A=="number"?this.#A=new Uint8Array(A):mB(A)?this.#A=new Uint8Array(A,I,B):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 TB{_data;chars;#A;constructor(A,I,B,Q){if(this.chars=A,this.#A=new TextEncoder,typeof I=="number")this._data=new Uint8Array(I*A);else if(mB(I))Q&&(Q=Q*A),this._data=new Uint8Array(I,B,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 B=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);B.fill(0),B.set(this.#A.encode(I))}fill(A){const I=this.#A.encode(A);for(let B=0;B<this.length;B++)this._data.set(I,B*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class Lg{#A;chars;constructor(A,I,B,Q){if(this.chars=A,typeof I=="number")this.#A=new Int32Array(I*A);else if(mB(I))Q&&(Q*=A),this.#A=new Int32Array(I,B,Q);else{const C=I,E=new Lg(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 B="";for(let Q=0;Q<this.chars;Q++)B+=String.fromCodePoint(this.#A[I+Q]);return B.replace(/\u0000/g,"")}set(A,I){const B=this.chars*A,Q=this.#A.subarray(B,B+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 B=1;B<this.length;B++)this.#A.set(I,B*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}function Ti(){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 xi(g,A){return new SharedArrayBuffer(g)}function Jg(g){const A=new TextDecoder().decode(g);try{return JSON.parse(A)}catch(I){throw new JA("Failed to decode JSON",{cause:I})}}function _Q(g,A){const I=A/2,B=A-1;let Q=0;for(let C=0;C<g.length;C+=A)for(let E=0;E<I;E+=1)Q=g[C+E],g[C+E]=g[C+B-E],g[C+B-E]=Q}function OI(g){if(g==="v2:object")return globalThis.Array;let A=g.match(/v2:([US])(\d+)/);if(A){let[,B,Q]=A;return(B==="U"?Lg:TB).bind(null,Number(Q))}if(g==="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:zQ}[g];if(!I)throw new JA(`Unknown or unsupported dataType: ${g}`);return I}function nI(g,A){const I=g.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 B=1,Q=new Array(I);for(let C=A.length-1;C>=0;C--)Q[A[C]]=B,B*=g[A[C]];return Q}function Zi({name:g,configuration:A}){if(g==="default"){const I=A?.separator??"/";return B=>["c",...B].join(I)}if(g==="v2"){const I=A?.separator??".";return B=>B.join(I)||"0"}throw new JA(`Unknown chunk key encoding: ${g}`)}function $Q(g){if(g==="|O")return{dataType:"v2:object"};let A=g.match(/^([<|>])(.*)$/);if(!A)throw new JA(`Invalid dtype: ${g}`);let[,I,B]=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"}[B]??(B.startsWith("S")||B.startsWith("U")?`v2:${B}`:void 0);if(!Q)throw new JA(`Unsupported or unknown dtype: ${g}`);return I==="|"?{dataType:Q}:{dataType:Q,endian:I==="<"?"little":"big"}}function ui(g){return(g.id==="fixedscaleoffset"||g.id==="numcodecs.fixedscaleoffset")&&typeof g.scale=="number"&&typeof g.offset=="number"&&(g.astype===void 0||typeof g.astype=="string")&&(g.dtype===void 0||typeof g.dtype=="string")}function bi(g,A={}){let I=[],B=$Q(g.dtype);g.order==="F"&&I.push({name:"transpose",configuration:{order:"F"}});for(let C of g.filters??[]){if(C.id==="fixedscaleoffset"||C.id==="numcodecs.fixedscaleoffset"){if(!ui(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!==g.dtype){let a=$Q(D).dataType;if(!xB(a,"number")&&!xB(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 B&&B.endian==="big"&&I.push({name:"bytes",configuration:{endian:"big"}}),g.compressor){let{id:C,...E}=g.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:g.shape,data_type:B.dataType,chunk_grid:{name:"regular",configuration:{chunk_shape:g.chunks}},chunk_key_encoding:{name:"v2",configuration:{separator:g.dimension_separator??"."}},codecs:I,fill_value:g.fill_value,dimension_names:Q,attributes:A}}function Pi(g,A={}){return{zarr_format:3,node_type:"group",attributes:A}}function xB(g,A){if(A!=="number"&&A!=="bigint"&&A!=="boolean"&&A!=="object"&&A!=="string")return g===A;let I=g==="bool";if(A==="boolean")return I;let B=g.startsWith("v2:U")||g.startsWith("v2:S")||g==="string";if(A==="string")return B;let Q=g==="int64"||g==="uint64";if(A==="bigint")return Q;let C=g==="v2:object";return A==="object"?C:!B&&!Q&&!I&&!C}function Vi(g){return g?.name==="sharding_indexed"}function AC(g){if((g.data_type==="uint64"||g.data_type==="int64")&&g.fill_value!=null)return BigInt(g.fill_value);let A=g.data_type==="float16"||g.data_type==="float32"||g.data_type==="float64";if(typeof g.fill_value=="string"&&A){let I={NaN:NaN,Infinity:1/0,"-Infinity":-1/0};if(g.fill_value in I)return I[g.fill_value]}return g.fill_value}function IC(g,...A){if(!A.some(I=>g instanceof I))throw g}function VA(g,A=""){if(!g)throw new Error(A)}async function gC(g,{format:A,signal:I}){let B;if(g instanceof ArrayBuffer)B=new Response(g);else{let Q=new Uint8Array(g.buffer,g.byteOffset,g.byteLength);B=new Response(Q.slice().buffer)}VA(B.body,"Response does not contain body.");try{return await new Response(B.body.pipeThrough(new DecompressionStream(A),{signal:I})).arrayBuffer()}catch{throw I?.throwIfAborted(),new Error(`Failed to decode ${A}`)}}const BC=Oi();function Oi(){const g=new Uint32Array([305419896]);return new Uint8Array(g.buffer,g.byteOffset,g.byteLength)[0]!==18}function QC(g){return"BYTES_PER_ELEMENT"in g?g.BYTES_PER_ELEMENT:4}class $g{kind="array_to_bytes";#A;#I;#g;#B;#Q;constructor(A,I){this.#Q=A?.endian,this.#I=OI(I.dataType),this.#B=I.shape,this.#A=nI(I.shape,"C");const B=new this.#I(0);this.#g=B.BYTES_PER_ELEMENT}static fromConfig(A,I){return new $g(A,I)}encode(A){let I=new Uint8Array(A.data.buffer);return BC&&this.#Q==="big"&&_Q(I,QC(this.#I)),I}computeEncodedSize(A){return A}decode(A){return BC&&this.#Q==="big"&&_Q(A,QC(this.#I)),{data:new this.#I(A.buffer,A.byteOffset,A.byteLength/this.#g),shape:this.#B,stride:this.#A}}}const CC={NaN:NaN,Infinity:1/0,"-Infinity":-1/0},EC={float16:2,float32:4,float64:8};function AB(g){return g in EC}function ZB(g){return g==="int64"||g==="uint64"}function Xi(g,A){const I=BigInt(g),B=new ArrayBuffer(A),Q=new DataView(B);if(A===2){if(typeof Q.getFloat16!="function")throw new WB("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(g,A){if(ZB(g)){if(typeof A!="number"||!Number.isInteger(A))throw new JA(`Expected an integer value for data type "${g}", got ${JSON.stringify(A)}`);return BigInt(A)}if(typeof A=="number"){if(!AB(g)&&!Number.isInteger(A))throw new JA(`Expected an integer value for data type "${g}", got ${A}`);return A}if(!AB(g))throw new JA(`String-encoded scalar "${A}" is not valid for non-float data type "${g}"`);return A in CC?CC[A]:Xi(A,EC[g])}const iC=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]),uB={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]},bB={int64:[-(2n**63n),2n**63n-1n],uint64:[0n,2n**64n-1n]};function oC(g,A,I){return g.map(([B,Q])=>({src:IB(A,B),tgt:IB(I,Q)}))}function vi(g,A){for(const I of A)if(typeof I.src=="number"&&Number.isNaN(I.src)){if(typeof g=="number"&&Number.isNaN(g))return I.tgt}else if(g===I.src)return I.tgt}function ji(g){if(!Number.isFinite(g))return g;if(Math.abs(g-Math.trunc(g))===.5){const A=Math.floor(g),I=Math.ceil(g);return A%2===0?A:I}return Math.round(g)}function zi(g){return Math.sign(g)*Math.floor(Math.abs(g)+.5)}function DC(g){switch(g){case"nearest-even":return ji;case"towards-zero":return Math.trunc;case"towards-positive":return Math.ceil;case"towards-negative":return Math.floor;case"nearest-away":return zi}}function PB(g,A,I){const B=A-g+1;switch(I){case"clamp":return Q=>Q<g?g:Q>A?A:Q;case"wrap":return Q=>Q>=g&&Q<=A?Q:((Q-g)%B+B)%B+g;default:return Q=>{if(Q>=g&&Q<=A)return Q;throw new Error(`Value ${Q} out of range [${g}, ${A}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}function VB(g,A,I){const B=A-g+1n;switch(I){case"clamp":return Q=>Q<g?g:Q>A?A:Q;case"wrap":return Q=>Q>=g&&Q<=A?Q:((Q-g)%B+B)%B+g;default:return Q=>{if(Q>=g&&Q<=A)return Q;throw new Error(`Value ${Q} out of range [${g}, ${A}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}class OB{kind="array_to_array";#A;#I;#g;#B;constructor(A,I,B,Q,C,E){this.#A=I,this.#I=OI(A),this.#g=aC(I,A,B,Q,C),this.#B=aC(A,I,B,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 B=I.dataType,Q=A.data_type;if(!iC.has(B))throw new JA(`cast_value codec does not support array data type: ${B}`);if(!iC.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?oC(A.scalar_map.decode,Q,B):[],i=A.scalar_map?.encode?oC(A.scalar_map.encode,B,Q):[];return new OB(B,Q,C,A.out_of_range,E,i)}encode=rI("cast_value");decode(A){const I=A.data,B=new this.#I(I.length);for(let Q=0;Q<I.length;Q++)B[Q]=this.#g(I[Q]);return{data:B,shape:A.shape,stride:A.stride}}}function aC(g,A,I,B,Q){const C=AB(g),E=ZB(g),i=AB(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=DC(I),t=PB(...uB[A],B);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=DC(I),t=VB(...bB[A],B);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=PB(...uB[A],B);else if(!C&&!E&&D){const R=VB(...bB[A],B);a=t=>R(BigInt(t))}else if(E&&!i&&!D){const R=PB(...uB[A],B);a=t=>R(Number(t))}else if(E&&D)a=VB(...bB[A],B);else throw new Error(`Unhandled type combination: ${g} -> ${A}`);return Q.length===0?a:R=>{const t=vi(R,Q);return t!==void 0?t:a(R)}}class XB{kind="bytes_to_bytes";static fromConfig(){return new XB}encode=rI("crc32c");decode(A){return new Uint8Array(A.buffer,A.byteOffset,A.byteLength-4)}computeEncodedSize(A){return A+4}}const _i=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);function sC(g,A){const I=g.length;let B=I===0||A[I-1]===1;for(let C=I-2;C>=0&&B;C--)B=A[C]===A[C+1]*g[C+1];if(B)return;let Q=I===0||A[0]===1;for(let C=1;C<I&&Q;C++)Q=A[C]===A[C-1]*g[C-1];if(!Q)throw new Error(`DeltaCodec requires C- or Fortran-contiguous strides, got shape=${JSON.stringify(g)} stride=${JSON.stringify(A)}`)}class vB{kind="array_to_array";#A;constructor(A){this.#A=A}static fromConfig(A,I){if(!_i.has(I.dataType))throw new JA(`Delta codec does not support data type: ${I.dataType}`);return new vB(OI(I.dataType))}encode(A){sC(A.shape,A.stride);const I=A.data,B=new this.#A(I.length);B[0]=I[0];for(let Q=1;Q<I.length;Q++)B[Q]=I[Q]-I[Q-1];return{data:B,shape:A.shape,stride:A.stride}}decode(A){sC(A.shape,A.stride);const I=A.data,B=new this.#A(I.length);B[0]=I[0];for(let Q=1;Q<I.length;Q++)B[Q]=B[Q-1]+I[Q];return{data:B,shape:A.shape,stride:A.stride}}}class jB{kind="bytes_to_bytes";static fromConfig(A){return new jB}encode=rI("gzip");async decode(A){const I=await gC(A,{format:"gzip"});return new Uint8Array(I)}}function $i(g,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 Ao(g,A){return A instanceof Object&&!Array.isArray(A)?Object.keys(A).sort().reduce((I,B)=>(I[B]=A[B],I),{}):A}class gB{configuration;kind="array_to_bytes";#A;#I;constructor(A={}){this.configuration=A;const{encoding:I="utf-8",skipkeys:B=!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:B,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 gB(A)}encode(A){const{indent:I,encoding:B,ensure_ascii:Q,check_circular:C,allow_nan:E,sort_keys:i}=this.#A;VA(B==="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($i),i&&D.push(Ao);const a=Array.from(A.data);a.push("|O"),a.push(A.shape);let G;D.length&&(G=(t,J)=>{let r=J;for(let H of D)r=H(t,r);return r});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 B=Jg(A),Q=B.pop();B.pop(),VA(Q,"0D not implemented for JsonCodec.");const C=nI(Q,"C");return{data:B,shape:Q,stride:C}}}const Io=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);class zB{kind="array_to_array";#A;#I;#g;constructor(A,I,B){this.#I=A,this.#g=I,this.#A=B}static fromConfig(A,I){if(!Io.has(I.dataType))throw new JA(`scale_offset codec does not support data type: ${I.dataType}`);return new zB(IB(I.dataType,A.scale??1),IB(I.dataType,A.offset??0),OI(I.dataType))}encode=rI("scale_offset");decode(A){const I=A.data,B=new this.#A(I.length);for(let Q=0;Q<I.length;Q++)B[Q]=I[Q]/this.#I+this.#g;return{data:B,shape:A.shape,stride:A.stride}}}class _B{kind="bytes_to_bytes";#A;constructor(A,I){if(I){let B=new(OI(I.dataType))(0);VA("BYTES_PER_ELEMENT"in B,`Shuffle codec requires a fixed-size dtype, got "${I.dataType}"`),this.#A=B.BYTES_PER_ELEMENT}else this.#A=A.elementsize??4}static fromConfig(A,I){return new _B(A,I)}encode(A){return go(A,this.#A)}decode(A){return Bo(A,this.#A)}}function go(g,A){let I=g.length,B=Math.floor(I/A),Q=new Uint8Array(I);for(let C=0;C<A;C++)for(let E=0;E<B;E++)Q[C*B+E]=g[E*A+C];return Q}function Bo(g,A){let I=g.length,B=Math.floor(I/A),Q=new Uint8Array(I);for(let C=0;C<A;C++)for(let E=0;E<B;E++)Q[E*A+C]=g[C*B+E];return Q}function yC(g){return g instanceof zQ||g instanceof TB||g instanceof Lg?new Proxy(g,{get(I,B){return I.get(Number(B))},set(I,B,Q){return I.set(Number(B),Q),!0}}):g}function Qo(g,A){let I;return g.data instanceof TB||g.data instanceof Lg?I=new g.constructor(g.data.length,g.data.chars):I=new g.constructor(g.data.length),{data:I,shape:g.shape,stride:nI(g.shape,A)}}function Co(g,A){let I=Qo(g,A),B=g.shape.length,Q=g.data.length,C=Array(B).fill(0),E=yC(g.data),i=yC(I.data);for(let D=0;D<Q;D++){let a=0;for(let G=0;G<B;G++)a+=C[G]*I.stride[G];i[a]=E[D],C[0]+=1;for(let G=0;G<B;G++)if(C[G]===g.shape[G]){if(G+1===B)break;C[G]=0,C[G+1]+=1}}return I}function Eo(g){let A=g.shape.length;return VA(A===g.stride.length,"Shape and stride must have the same length."),g.stride.map((I,B)=>({stride:I,index:B})).sort((I,B)=>B.stride-I.stride).map(I=>I.index)}function io(g,A){let I=Eo(g);return VA(I.length===A.length,"Orders must match"),I.every((B,Q)=>B===A[Q])}class $B{kind="array_to_array";#A;#I;constructor(A,I){let B=A.order??"C",Q=I.shape.length,C=new Array(Q),E=new Array(Q);if(B==="C")for(let i=0;i<Q;++i)C[i]=i,E[i]=i;else if(B==="F")for(let i=0;i<Q;++i)C[i]=Q-i-1,E[i]=Q-i-1;else C=B,C.forEach((i,D)=>{VA(E[i]===void 0,`Invalid permutation: ${JSON.stringify(B)}`),E[i]=D});this.#A=C,this.#I=E}static fromConfig(A,I){return new $B(A,I)}encode(A){return io(A,this.#I)?A:Co(A,this.#I)}decode(A){return{data:A.data,shape:A.shape,stride:nI(A.shape,this.#A)}}}class BB{kind="array_to_bytes";#A;#I;constructor(A){this.#A=A,this.#I=nI(A,"C")}static fromConfig(A,I){return new BB(I.shape)}encode=rI("vlen-utf8");decode(A){let I=new TextDecoder,B=new DataView(A.buffer),Q=Array(B.getUint32(0,!0)),C=4;for(let E=0;E<Q.length;E++){let i=B.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 AQ{kind="bytes_to_bytes";static fromConfig(A){return new AQ}encode=rI("zlib");async decode(A){const I=await gC(A,{format:"deflate"});return new Uint8Array(I)}}function oo(){let g=()=>Promise.resolve().then(()=>Ja).then(C=>C.default),A=()=>Promise.resolve().then(()=>ea).then(C=>C.default),I=()=>Promise.resolve().then(()=>pa).then(C=>C.default),B=()=>jB,Q=()=>AQ;return new Map().set("blosc",g).set("lz4",A).set("zstd",I).set("gzip",B).set("zlib",Q).set("transpose",()=>$B).set("bytes",()=>$g).set("crc32c",()=>XB).set("vlen-utf8",()=>BB).set("json2",()=>gB).set("bitround",()=>_g).set("cast_value",()=>OB).set("scale_offset",()=>zB).set("numcodecs.blosc",g).set("numcodecs.lz4",A).set("numcodecs.zstd",I).set("numcodecs.gzip",B).set("numcodecs.zlib",Q).set("numcodecs.vlen-utf8",()=>BB).set("numcodecs.shuffle",()=>_B).set("numcodecs.delta",()=>vB).set("numcodecs.bitround",()=>_g).set("numcodecs.json2",()=>gB)}const Do=oo();function IQ(g){let A;function I(){return A||(A=ao(g)),A}async function B(Q,C,E){try{return await E()}catch(i){throw new mi({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 B("encode",i,()=>D.encode(Q));let E=await B("encode",C.arrayToBytes.name,()=>C.arrayToBytes.codec.encode(Q));for(const{name:i,codec:D}of C.bytesToBytes)E=await B("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 B("decode",D,()=>a.decode(Q))}let E=await B("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 B("decode",D,()=>a.decode(E))}return E},async computeEncodedSize(Q){let C=await I(),E=hC(C.arrayToBytes.name,C.arrayToBytes.codec,Q);for(const{name:i,codec:D}of C.bytesToBytes)E=hC(i,D,E);return E}}}function hC(g,A,I){if(!A.computeEncodedSize)throw new JA(`Codec "${g}" 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 ao(g){let A=g.codecs.map(async E=>{let i=await Do.get(E.name)?.();if(!i)throw new Wi(E.name);return{Codec:i,meta:E}}),I=[],B,Q=[],C={...g};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":B={name:i.name,codec:D};break;default:Q.push({name:i.name,codec:D})}}if(!B){if(!so(C))throw new JA(`Cannot encode ${C.dataType} to bytes without a codec`);B={name:"bytes",codec:$g.fromConfig({endian:"little"},C)}}return{arrayToArray:I,arrayToBytes:B,bytesToBytes:Q}}function so(g){return g.dataType!=="v2:object"&&g.dataType!=="string"}const GC=18446744073709551615n;function yo(g,A,I,B){if(!g.store.getRange)throw new WB("sharding requires a store with getRange");let Q=g.store.getRange.bind(g.store),C=A.map((a,G)=>a/B.chunk_shape[G]),E=IQ({dataType:"uint64",shape:[...C,2],codecs:B.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=g.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:r,shape:H,stride:K}=J,l=a.map((W,p)=>W%H[p]).reduce((W,p,T)=>W+p*K[T],0),V=r[l],Z=r[l+1];if(!(V===GC&&Z===GC))return Q(t,{offset:Number(V),length:Number(Z)},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 gQ extends vA{kind="group";#A;constructor(A,I,B){super(A,I),this.#A=B}get attrs(){return this.#A.attributes}}function FC(g){return g.find(I=>I.name==="transpose")?.configuration?.order??"C"}const QB=Symbol("zarrita.context");function ho(g,A){let{configuration:I}=A.codecs.find(Vi)??{},B={encodeChunkKey:Zi(A.chunk_key_encoding),TypedArray:OI(A.data_type),fillValue:A.fill_value};if(I){let C=FC(I.codecs);return{...B,kind:"sharded",chunkShape:I.chunk_shape,codec:IQ({dataType:A.data_type,shape:I.chunk_shape,codecs:I.codecs,fillValue:A.fill_value}),getStrides(E){return nI(E,C)},getChunkBytes:yo(g,A.chunk_grid.configuration.chunk_shape,B.encodeChunkKey,I)}}let Q=FC(A.codecs);return{...B,kind:"regular",chunkShape:A.chunk_grid.configuration.chunk_shape,codec:IQ({dataType:A.data_type,shape:A.chunk_grid.configuration.chunk_shape,codecs:A.codecs,fillValue:A.fill_value}),getStrides(C){return nI(C,Q)},async getChunkBytes(C,E){let i=B.encodeChunkKey(C),D=g.resolve(i).path;return g.store.get(D,E)}}}let CB=class extends vA{kind="array";#A;[QB];constructor(A,I,B){super(A,I),this.#A={...B,fill_value:AC(B)},this[QB]=ho(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[QB].chunkShape}get dtype(){return this.#A.data_type}async getChunk(A,I,B){B?.useSharedArrayBuffer&&Ti();let Q=this[QB],C=await Q.getChunkBytes(A,I);if(!C){let E=Q.chunkShape.reduce((D,a)=>D*a,1),i;if(B?.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=xi(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 xB(this.dtype,A)}};function Go(g,A){let I=g;for(let B of A)I instanceof Promise?I=I.then(Q=>B(Q)):I=B(I);return I}function Fo(g,...A){return Go(g,A)}async function wC(g){let A=g.store.arrayExtensions;return A?.length?await Fo(g,...A):g}let EB=wo();function wo(){let g=new WeakMap;function A(I){let B=g.get(I)??{v2:0,v3:0};return g.set(I,B),B}return{increment(I,B){A(I)[B]+=1},versionMax(I){let B=A(I);return B.v3>B.v2?"v3":"v2"}}}async function So(g,A){let I=await g.store.get(g.resolve(".zattrs").path,{signal:A});return I?Jg(I):{}}async function Ro(g,A={}){let I="store"in g?g:new vA(g),{signal:B}=A,Q={};return(A.attrs??!0)&&(Q=await So(I,B)),B?.throwIfAborted(),A.kind==="array"?SC(I,Q,B):A.kind==="group"?RC(I,Q,B):SC(I,Q,B).catch(C=>(IC(C,VI,JA),RC(I,Q,B)))}async function SC(g,A,I){let{path:B}=g.resolve(".zarray"),Q=await g.store.get(B,{signal:I});if(!Q)throw new VI("v2 array",{path:B});return EB.increment(g.store,"v2"),wC(new CB(g.store,g.path,bi(Jg(Q),A)))}async function RC(g,A,I){let{path:B}=g.resolve(".zgroup"),Q=await g.store.get(B,{signal:I});if(!Q)throw new VI("v2 group",{path:B});return EB.increment(g.store,"v2"),new gQ(g.store,g.path,Pi(Jg(Q),A))}async function No(g,A){let{store:I,path:B}=g.resolve("zarr.json"),Q=await g.store.get(B,{signal:A});if(!Q)throw new VI("v3 array or group",{path:B});let C=Jg(Q);return C.node_type==="array"&&(C.fill_value=AC(C)),C.node_type==="array"?wC(new CB(I,g.path,C)):new gQ(I,g.path,C)}async function Uo(g,A={}){let I="store"in g?g:new vA(g),B=await No(I,A.signal);if(EB.increment(I.store,"v3"),A.kind===void 0||A.kind==="array"&&B instanceof CB||A.kind==="group"&&B instanceof gQ)return B;let Q=B instanceof CB?"array":"group";throw new VI(`${A.kind} at ${I.path}`,{path:I.path,found:Q})}async function jA(g,A={}){let I="store"in g?g.store:g,B=EB.versionMax(I),Q=B==="v2"?jA.v2:jA.v3,C=B==="v2"?jA.v3:jA.v2;return Q(g,A).catch(E=>(IC(E,VI,JA),C(g,A)))}jA.v2=Ro,jA.v3=Uo;async function to(g,A){const I=A.split("/"),B=I.pop();if(!B)throw new Error("Invalid path");for(const Q of I)g=await g.getDirectoryHandle(Q);return g.getFileHandle(B)}class BQ{#A;constructor(A){this.#A=A}get directoryHandle(){return this.#A}async get(A){const I=await to(this.#A,A.slice(1)).catch(()=>{});if(!I)return;const Q=await(await I.getFile()).arrayBuffer();return new Uint8Array(Q)}}async function rg(g,A){if(A==="v2")try{return jA.v2(g,{kind:"group",attrs:!0})}catch{throw new Error(`Failed to open Zarr v2 group at ${g}`)}if(A==="v3")try{return jA.v3(g,{kind:"group"})}catch{throw new Error(`Failed to open Zarr v3 group at ${g}`)}try{return jA(g,{kind:"group"})}catch{throw new Error(`Failed to open Zarr group at ${g}`)}}async function ko(g,A){if(A==="v2")try{return jA.v2(g,{kind:"array",attrs:!1})}catch{throw new Error(`Failed to open Zarr v2 array at ${g}`)}if(A==="v3")try{return jA.v3(g,{kind:"array"})}catch{throw new Error(`Failed to open Zarr v3 array at ${g}`)}try{return jA(g,{kind:"array"})}catch{throw new Error(`Failed to open Zarr array at ${g}`)}}async function co(g){let A;switch(g.type){case"fetch":{const B=new kg(g.url);A=new vA(B);break}case"filesystem":{A=new vA(new BQ(g.directoryHandle),g.path);break}default:{const B=g;throw new Error(`Unsupported store type: ${B}`)}}const I=g.arrayPath?A.resolve(g.arrayPath):A;return ko(I,g.zarrVersion)}function Lo(g,A,I){if(g.store instanceof kg)return{type:"fetch",arrayPath:A,zarrVersion:I,url:g.store.url.toString()};if(g.store instanceof BQ)return{type:"filesystem",arrayPath:A,zarrVersion:I,directoryHandle:g.store.directoryHandle,path:g.path};throw new Error(`Unsupported store type: ${g.store.constructor.name}`)}function Jo(g,A,I,B){return ro(g,A,I,B)}function ro(g,A,I,B){const{targetShape:Q,chunkIndex:C,dimIndices:E}=B;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=B.cChunkSize?C.c%B.cChunkSize:0,G=B.tChunkSize?C.t%B.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,r=G*J+a*t,H=D.x===Q.x&&D.y===Q.y&&D.z===Q.z;if(r===0&&g.length===R&&H)return g;const l=new g.constructor(R),V=E.z!==void 0?I[E.z]:0,Z=I[E.y];let W=0;for(let p=0;p<Q.z;p++){const T=r+p*V;for(let AA=0;AA<Q.y;AA++){const BA=T+AA*Z,EA=BA+Q.x;l.set(g.subarray(BA,EA),W),W+=Q.x}}return l}const NC=`function xg(B, A) {
430
430
  return {
431
431
  ...B,
432
432
  ...A,