@idetik/core 0.15.1 → 0.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -457,7 +457,7 @@ void main() {
457
457
  fragColor = vec4(color.rgb, alpha);
458
458
  }`;const GE={projectedLine:{vertex:iE,fragment:oE},points:{vertex:DE,fragment:aE},wireframe:{vertex:sE,fragment:yE},floatScalarImage:{vertex:JI,fragment:rB},floatScalarImageArray:{vertex:JI,fragment:YB},intScalarImage:{vertex:JI,fragment:rB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},intScalarImageArray:{vertex:JI,fragment:YB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},uintScalarImage:{vertex:JI,fragment:rB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])},uintScalarImageArray:{vertex:JI,fragment:YB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])},labelImage:{vertex:JI,fragment:hE},floatVolume:{vertex:nB,fragment:KB},intVolume:{vertex:nB,fragment:KB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},uintVolume:{vertex:nB,fragment:KB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])}},eQ={debug:10,info:20,warn:30,error:40},FE={debug:"\x1B[90m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m"};function wE(){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 V{static logLevel_=wE()==="production"?"warn":"debug";static setLogLevel(A){V.logLevel_=A}static debug(A,I,...B){V.log("debug",A,I,...B)}static info(A,I,...B){V.log("info",A,I,...B)}static warn(A,I,...B){V.log("warn",A,I,...B)}static error(A,I,...B){V.log("error",A,I,...B)}static log(A,I,B,...Q){if(eQ[A]<eQ[V.logLevel_])return;const C=new Date().toISOString(),E=FE[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 SE{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(!NE.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]),V.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 RE=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]:[],NE=new Set(RE),MB="#pragma inject_defines";class UE{gl_;programs_=new Map;constructor(A){this.gl_=A}use(A){let I=this.programs_.get(A);if(I===void 0){const B=GE[A],Q=HQ(B.vertex,B.vertexDefines),C=HQ(B.fragment,B.fragmentDefines);I=new SE(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 HQ(g,A){if(A===void 0||A.size==0)return g;if(!g.includes(MB))throw new Error(`Shader source does not contain "${MB}" directive`);const I=Array(A.entries()).map(([E,i])=>`#define ${E} ${i}`).join(`
459
459
  `),Q=`#line __LINE__ + ${1-A.size}`,C=`${I}
460
- ${Q}`;return g.replace(MB,C)}const dA=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];function qQ(){const g=Math.random()*4294967295|0,A=Math.random()*4294967295|0,I=Math.random()*4294967295|0,B=Math.random()*4294967295|0;return(dA[g&255]+dA[g>>8&255]+dA[g>>16&255]+dA[g>>24&255]+"-"+dA[A&255]+dA[A>>8&255]+"-"+dA[A>>16&15|64]+dA[A>>24&255]+"-"+dA[I&63|128]+dA[I>>8&255]+"-"+dA[I>>16&255]+dA[I>>24&255]+dA[B&255]+dA[B>>8&255]+dA[B>>16&255]+dA[B>>24&255]).toLowerCase()}class eB{uuid=qQ()}var hA=1e-6,YA=typeof Float32Array<"u"?Float32Array:Array,tE=Math.PI/180;function kE(g){return g*tE}Math.hypot||(Math.hypot=function(){for(var g=0,A=arguments.length;A--;)g+=arguments[A]*arguments[A];return Math.sqrt(g)});function dQ(){var g=new YA(9);return YA!=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 cE(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 bA(){var g=new YA(16);return YA!=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 gB(g,A){var I=A[0],B=A[1],Q=A[2],C=A[3],E=A[4],i=A[5],D=A[6],s=A[7],h=A[8],k=A[9],c=A[10],r=A[11],n=A[12],H=A[13],M=A[14],q=A[15],x=I*i-B*E,T=I*D-Q*E,X=I*s-C*E,u=B*D-Q*i,Z=B*s-C*i,EA=Q*s-C*D,iA=h*H-k*n,BA=h*M-c*n,sA=h*q-r*n,yA=k*M-c*H,KA=k*q-r*H,NA=c*q-r*M,DA=x*NA-T*KA+X*yA+u*sA-Z*BA+EA*iA;return DA?(DA=1/DA,g[0]=(i*NA-D*KA+s*yA)*DA,g[1]=(Q*KA-B*NA-C*yA)*DA,g[2]=(H*EA-M*Z+q*u)*DA,g[3]=(c*Z-k*EA-r*u)*DA,g[4]=(D*sA-E*NA-s*BA)*DA,g[5]=(I*NA-Q*sA+C*BA)*DA,g[6]=(M*X-n*EA-q*T)*DA,g[7]=(h*EA-c*X+r*T)*DA,g[8]=(E*KA-i*sA+s*iA)*DA,g[9]=(B*sA-I*KA-C*iA)*DA,g[10]=(n*Z-H*X+q*x)*DA,g[11]=(k*X-h*Z-r*x)*DA,g[12]=(i*BA-E*yA-D*iA)*DA,g[13]=(I*yA-B*BA+Q*iA)*DA,g[14]=(H*T-n*u-M*x)*DA,g[15]=(h*u-k*T+c*x)*DA,g):null}function tg(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=A[4],D=A[5],s=A[6],h=A[7],k=A[8],c=A[9],r=A[10],n=A[11],H=A[12],M=A[13],q=A[14],x=A[15],T=I[0],X=I[1],u=I[2],Z=I[3];return g[0]=T*B+X*i+u*k+Z*H,g[1]=T*Q+X*D+u*c+Z*M,g[2]=T*C+X*s+u*r+Z*q,g[3]=T*E+X*h+u*n+Z*x,T=I[4],X=I[5],u=I[6],Z=I[7],g[4]=T*B+X*i+u*k+Z*H,g[5]=T*Q+X*D+u*c+Z*M,g[6]=T*C+X*s+u*r+Z*q,g[7]=T*E+X*h+u*n+Z*x,T=I[8],X=I[9],u=I[10],Z=I[11],g[8]=T*B+X*i+u*k+Z*H,g[9]=T*Q+X*D+u*c+Z*M,g[10]=T*C+X*s+u*r+Z*q,g[11]=T*E+X*h+u*n+Z*x,T=I[12],X=I[13],u=I[14],Z=I[15],g[12]=T*B+X*i+u*k+Z*H,g[13]=T*Q+X*D+u*c+Z*M,g[14]=T*C+X*s+u*r+Z*q,g[15]=T*E+X*h+u*n+Z*x,g}function LE(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 JE(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=A[3],D=Q+Q,s=C+C,h=E+E,k=Q*D,c=Q*s,r=Q*h,n=C*s,H=C*h,M=E*h,q=i*D,x=i*s,T=i*h,X=B[0],u=B[1],Z=B[2];return g[0]=(1-(n+M))*X,g[1]=(c+T)*X,g[2]=(r-x)*X,g[3]=0,g[4]=(c-T)*u,g[5]=(1-(k+M))*u,g[6]=(H+q)*u,g[7]=0,g[8]=(r+x)*Z,g[9]=(H-q)*Z,g[10]=(1-(k+n))*Z,g[11]=0,g[12]=I[0],g[13]=I[1],g[14]=I[2],g[15]=1,g}function rE(g,A,I,B,Q){var C=1/Math.tan(A/2),E;return 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?(E=1/(B-Q),g[10]=(Q+B)*E,g[14]=2*Q*B*E):(g[10]=-1,g[14]=-2*B),g}var YE=rE;function nE(g,A,I,B,Q,C,E){var i=1/(A-I),D=1/(B-Q),s=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*s,g[11]=0,g[12]=(A+I)*i,g[13]=(Q+B)*D,g[14]=(E+C)*s,g[15]=1,g}var KE=nE;function ME(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=B[0],D=B[1],s=B[2],h=Q-I[0],k=C-I[1],c=E-I[2],r=h*h+k*k+c*c;r>0&&(r=1/Math.sqrt(r),h*=r,k*=r,c*=r);var n=D*c-s*k,H=s*h-i*c,M=i*k-D*h;return r=n*n+H*H+M*M,r>0&&(r=1/Math.sqrt(r),n*=r,H*=r,M*=r),g[0]=n,g[1]=H,g[2]=M,g[3]=0,g[4]=k*M-c*H,g[5]=c*n-h*M,g[6]=h*H-k*n,g[7]=0,g[8]=h,g[9]=k,g[10]=c,g[11]=0,g[12]=Q,g[13]=C,g[14]=E,g[15]=1,g}function eE(g,A){var I=g[0],B=g[1],Q=g[2],C=g[3],E=g[4],i=g[5],D=g[6],s=g[7],h=g[8],k=g[9],c=g[10],r=g[11],n=g[12],H=g[13],M=g[14],q=g[15],x=A[0],T=A[1],X=A[2],u=A[3],Z=A[4],EA=A[5],iA=A[6],BA=A[7],sA=A[8],yA=A[9],KA=A[10],NA=A[11],DA=A[12],aI=A[13],AI=A[14],sI=A[15];return Math.abs(I-x)<=hA*Math.max(1,Math.abs(I),Math.abs(x))&&Math.abs(B-T)<=hA*Math.max(1,Math.abs(B),Math.abs(T))&&Math.abs(Q-X)<=hA*Math.max(1,Math.abs(Q),Math.abs(X))&&Math.abs(C-u)<=hA*Math.max(1,Math.abs(C),Math.abs(u))&&Math.abs(E-Z)<=hA*Math.max(1,Math.abs(E),Math.abs(Z))&&Math.abs(i-EA)<=hA*Math.max(1,Math.abs(i),Math.abs(EA))&&Math.abs(D-iA)<=hA*Math.max(1,Math.abs(D),Math.abs(iA))&&Math.abs(s-BA)<=hA*Math.max(1,Math.abs(s),Math.abs(BA))&&Math.abs(h-sA)<=hA*Math.max(1,Math.abs(h),Math.abs(sA))&&Math.abs(k-yA)<=hA*Math.max(1,Math.abs(k),Math.abs(yA))&&Math.abs(c-KA)<=hA*Math.max(1,Math.abs(c),Math.abs(KA))&&Math.abs(r-NA)<=hA*Math.max(1,Math.abs(r),Math.abs(NA))&&Math.abs(n-DA)<=hA*Math.max(1,Math.abs(n),Math.abs(DA))&&Math.abs(H-aI)<=hA*Math.max(1,Math.abs(H),Math.abs(aI))&&Math.abs(M-AI)<=hA*Math.max(1,Math.abs(M),Math.abs(AI))&&Math.abs(q-sI)<=hA*Math.max(1,Math.abs(q),Math.abs(sI))}function aA(){var g=new YA(3);return YA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g}function vA(g){var A=new YA(3);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A}function HB(g){var A=g[0],I=g[1],B=g[2];return Math.hypot(A,I,B)}function oA(g,A,I){var B=new YA(3);return B[0]=g,B[1]=A,B[2]=I,B}function OI(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g}function rI(g,A,I,B){return g[0]=A,g[1]=I,g[2]=B,g}function VI(g,A,I){return g[0]=A[0]+I[0],g[1]=A[1]+I[1],g[2]=A[2]+I[2],g}function HE(g,A,I){return g[0]=A[0]-I[0],g[1]=A[1]-I[1],g[2]=A[2]-I[2],g}function qE(g,A,I){return g[0]=A[0]*I[0],g[1]=A[1]*I[1],g[2]=A[2]*I[2],g}function XI(g,A,I){return g[0]=A[0]*I,g[1]=A[1]*I,g[2]=A[2]*I,g}function BB(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 fQ(g,A){var I=A[0]-g[0],B=A[1]-g[1],Q=A[2]-g[2];return Math.hypot(I,B,Q)}function lQ(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 dE(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 pQ(g,A){return g[0]*A[0]+g[1]*A[1]+g[2]*A[2]}function qB(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 fE(g,A,I,B,Q,C){var E=1-C,i=E*E,D=C*C,s=i*E,h=3*C*i,k=3*D*E,c=D*C;return g[0]=A[0]*s+I[0]*h+B[0]*k+Q[0]*c,g[1]=A[1]*s+I[1]*h+B[1]*k+Q[1]*c,g[2]=A[2]*s+I[2]*h+B[2]*k+Q[2]*c,g}function QB(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 lE(g){return g[0]=0,g[1]=0,g[2]=0,g}function WQ(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)<=hA*Math.max(1,Math.abs(I),Math.abs(C))&&Math.abs(B-E)<=hA*Math.max(1,Math.abs(B),Math.abs(E))&&Math.abs(Q-i)<=hA*Math.max(1,Math.abs(Q),Math.abs(i))}var CB=HE,pE=HB;(function(){var g=aA();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 vI(){var g=new YA(4);return YA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0,g[3]=0),g}function WE(g){var A=new YA(4);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A[3]=g[3],A}function EB(g,A,I,B){var Q=new YA(4);return Q[0]=g,Q[1]=A,Q[2]=I,Q[3]=B,Q}function mE(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g[3]=A[3],g}function TE(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 xE(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 kg(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=vI();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 dB(){var g=new YA(4);return YA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g[3]=1,g}function ZE(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 bE(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=I[0],D=I[1],s=I[2],h=I[3];return g[0]=B*h+E*i+Q*s-C*D,g[1]=Q*h+E*D+C*i-B*s,g[2]=C*h+E*s+B*D-Q*i,g[3]=E*h-B*i-Q*D-C*s,g}function fB(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=A[3],D=I[0],s=I[1],h=I[2],k=I[3],c,r,n,H,M;return r=Q*D+C*s+E*h+i*k,r<0&&(r=-r,D=-D,s=-s,h=-h,k=-k),1-r>hA?(c=Math.acos(r),n=Math.sin(c),H=Math.sin((1-B)*c)/n,M=Math.sin(B*c)/n):(H=1-B,M=B),g[0]=H*Q+M*D,g[1]=H*C+M*s,g[2]=H*E+M*h,g[3]=H*i+M*k,g}function mQ(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 uE=WE,PE=mE,lB=xE;(function(){var g=aA(),A=oA(1,0,0),I=oA(0,1,0);return function(B,Q,C){var E=pQ(Q,C);return E<-.999999?(qB(g,A,Q),pE(g)<1e-6&&qB(g,I,Q),dE(g,g),ZE(B,g,Math.PI),B):E>.999999?(B[0]=0,B[1]=0,B[2]=0,B[3]=1,B):(qB(g,Q,C),B[0]=g[0],B[1]=g[1],B[2]=g[2],B[3]=1+E,lB(B,B))}})(),function(){var g=dB(),A=dB();return function(I,B,Q,C,E,i){return fB(g,B,E,i),fB(A,Q,C,i),fB(I,g,A,2*i*(1-i)),I}}(),function(){var g=dQ();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],lB(A,mQ(A,g))}}();function TQ(){var g=new YA(2);return YA!=Float32Array&&(g[0]=0,g[1]=0),g}function xQ(g){var A=new YA(2);return A[0]=g[0],A[1]=g[1],A}function nA(g,A){var I=new YA(2);return I[0]=g,I[1]=A,I}function OE(g,A){var I=A[0]-g[0],B=A[1]-g[1];return Math.hypot(I,B)}function VE(g){var A=g[0],I=g[1];return A*A+I*I}function XE(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 pB(g,A){var I=g[0],B=g[1],Q=A[0],C=A[1];return Math.abs(I-Q)<=hA*Math.max(1,Math.abs(I),Math.abs(Q))&&Math.abs(B-C)<=hA*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 hI{min;max;constructor(A,I){this.min=A?vA(A):oA(1/0,1/0,1/0),this.max=I?vA(I):oA(-1/0,-1/0,-1/0)}clone(){return new hI(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=[oA(I[0],I[1],I[2]),oA(I[0],I[1],B[2]),oA(I[0],B[1],I[2]),oA(I[0],B[1],B[2]),oA(B[0],I[1],I[2]),oA(B[0],I[1],B[2]),oA(B[0],B[1],I[2]),oA(B[0],B[1],B[2])];this.min=oA(1/0,1/0,1/0),this.max=oA(-1/0,-1/0,-1/0);const C=aA();for(const E of Q)QB(C,E,A),this.expandWithPoint(C)}}const vE={position:0,normal:1,uv:2,next_position:3,previous_position:4,direction:5,path_proportion:6,color:7,size:8,marker:9};class jI extends eB{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 hI,Q=aA();for(let C=0;C<this.vertexData_.length;C+=this.stride)Q[0]=this.vertexData_[C+I+0],Q[1]=this.vertexData_[C+I+1],Q[2]=this.vertexData_[C+I+2],B.expandWithPoint(Q);this.boundingBox_=B}return this.boundingBox_}get type(){return"Geometry"}getAttribute(A){return this.attributes_.find(I=>I.type===A)}}class jE{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(h=>{const k=vE[h.type];this.gl_.vertexAttribPointer(k,h.itemSize,this.gl_.FLOAT,!1,i,h.offset),this.gl_.enableVertexAttribArray(k)});const D={vao:I,vbo:C},{indexData:s}=A;if(s.length){const h=this.gl_.ELEMENT_ARRAY_BUFFER,k=this.gl_.createBuffer();if(!k)throw new Error("Failed to create index buffer (EBO)");this.gl_.bindBuffer(h,k),this.gl_.bufferData(h,s,this.gl_.STATIC_DRAW),D.ebo=k}this.buffers_.set(A,D),this.gl_.bindVertexArray(null)}}class zE{gl_;textures_=new Map;currentTexture_=null;maxTextureUnits_;gpuTextureBytes_=0;textureCount_=0;constructor(A){this.gl_=A,this.maxTextureUnits_=A.getParameter(A.MAX_TEXTURE_IMAGE_UNITS)}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}]`);this.gl_.activeTexture(this.gl_.TEXTURE0+I);const B=this.getTextureType(A),Q=this.getDataFormatInfo(A.dataFormat,A.dataType);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),A.needsUpdate&&A.data!==null&&(this.configureTextureParameters(A,B),this.uploadTextureData(A,Q,B),A.needsUpdate=!1),this.currentTexture_=A}disposeTexture(A){const I=this.textures_.get(A);if(I){this.gl_.deleteTexture(I),this.textures_.delete(A),this.currentTexture_===A&&(this.currentTexture_=null);const B=this.getDataFormatInfo(A.dataFormat,A.dataType),Q=this.computeStorageBytes(A,B);this.gpuTextureBytes_=Math.max(0,this.gpuTextureBytes_-Q),this.textureCount_=Math.max(0,this.textureCount_-1)}}disposeAll(){for(const A of Array.from(this.textures_.keys()))this.disposeTexture(A);this.gpuTextureBytes_=0,this.textureCount_=0}get textureInfo(){return{textures:this.textureCount_,totalBytes:this.gpuTextureBytes_}}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_+=this.computeStorageBytes(A,I),this.textureCount_+=1,this.textures_.set(A,Q),this.gl_.bindTexture(B,null)}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 V.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}`)}computeStorageBytes(A,I){const B=this.bytesPerTexel(I),Q=Math.max(1,A.mipmapLevels),C=this.isTextureStorage3D(A)?Math.max(1,A.depth):1;let E=Math.max(1,A.width),i=Math.max(1,A.height),D=0;for(let s=0;s<Q;s++)D+=E*i*C*B,E=Math.max(1,E>>1),i=Math.max(1,i>>1);return D}bytesPerTexel(A){const I=this.gl_;if(A.format===I.RGB&&A.type===I.UNSIGNED_BYTE)return 3;if(A.format===I.RGBA&&A.type===I.UNSIGNED_BYTE)return 4;if(A.format===I.RED_INTEGER)switch(A.type){case I.BYTE:case I.UNSIGNED_BYTE:return 1;case I.SHORT:case I.UNSIGNED_SHORT:return 2;case I.INT:case I.UNSIGNED_INT:return 4}if(A.format===I.RED&&A.type===I.FLOAT)return 4;throw new Error("bytesPerTexel: unsupported format/type")}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 uA{min;max;constructor(A,I){this.min=A?xQ(A):nA(1/0,1/0),this.max=I?xQ(I):nA(-1/0,-1/0)}clone(){return new uA(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 uA(nA(Math.floor(this.min[0]),Math.floor(this.min[1])),nA(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 _E{gl_;enabledCapabilities_=new Map;depthMaskEnabled_=null;blendSrcFactor_=null;blendDstFactor_=null;currentBlendingMode_=null;currentViewport_=null;currentScissor_=null;currentCullingMode_=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_&&uA.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_&&uA.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)}}const $E=LE(bA(),[1,-1,1]);class bQ extends EE{gl_;programs_;bindings_;textures_;state_;renderedObjectsPerFrame_=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,V.info("WebGLRenderer",`WebGL version ${I.getParameter(I.VERSION)}`),this.programs_=new UE(I),this.bindings_=new jE(I),this.textures_=new zE(I),this.state_=new _E(I),this.initStencil(),this.resize(this.canvas.width,this.canvas.height)}render(A){let I=getComputedStyle(A.element).visibility!=="hidden";const B=A.getBoxRelativeTo(this.canvas),Q=new uA(nA(0,0),nA(this.width,this.height));uA.equals(B.floor(),Q.floor())?this.state_.setScissorTest(!1):uA.intersects(B,Q)?(this.state_.setScissor(B),this.state_.setScissorTest(!0)):(V.warn("WebGLRenderer",`Viewport ${A.id} is entirely outside canvas bounds, skipping render`),I=!1),this.state_.setViewport(B),this.renderedObjectsPerFrame_=0,I&&this.clear();const{opaque:C,transparent:E}=A.layerManager.partitionLayers();this.state_.setDepthMask(!0);const i=A.camera.frustum,D={viewport:A};for(const s of C)s.update(D),s.state==="ready"&&I&&this.renderLayer(s,A.camera,i);this.state_.setDepthMask(!1);for(const s of E)s.update(D),s.state==="ready"&&I&&this.renderLayer(s,A.camera,i);this.state_.setDepthMask(!0),this.renderedObjects_=this.renderedObjectsPerFrame_}get textureInfo(){return this.textures_.textureInfo}initStencil(){this.gl_.clearStencil(0),this.gl_.stencilMask(255),this.gl_.stencilFunc(this.gl_.EQUAL,0,255),this.gl_.stencilOp(this.gl_.KEEP,this.gl_.KEEP,this.gl_.INCR)}renderLayer(A,I,B){if(A.objects.length===0)return;this.state_.setBlendingMode(A.transparent?A.blendMode:"none");const Q=A.hasMultipleLODs();this.state_.setStencilTest(Q),Q&&this.gl_.clear(this.gl_.STENCIL_BUFFER_BIT),A.objects.forEach((C,E)=>{B.intersectsWithBox3(C.boundingBox)&&(this.renderObject(A,E,I),this.renderedObjectsPerFrame_+=1)})}renderObject(A,I,B){const Q=A.objects[I];if(Q.popStaleTextures().forEach(E=>{this.textures_.disposeTexture(E)}),!Q.programName)return;this.state_.setCullFaceMode(Q.cullFaceMode),this.state_.setDepthTesting(Q.depthTest),this.state_.setDepthMask(Q.depthTest),this.bindings_.bindGeometry(Q.geometry),Q.textures.forEach((E,i)=>{this.textures_.bindTexture(E,i)});const C=this.programs_.use(Q.programName);if(this.drawGeometry(Q.geometry,Q,A,C,B),Q.wireframeEnabled){this.bindings_.bindGeometry(Q.wireframeGeometry);const E=this.programs_.use("wireframe");E.setUniform("u_color",Q.wireframeColor.rgb),this.drawGeometry(Q.wireframeGeometry,Q,A,E,B)}}drawGeometry(A,I,B,Q,C){const E=tg(bA(),C.viewMatrix,I.transform.matrix),i=tg(bA(),$E,C.projectionMatrix),D=[this.canvas.width,this.canvas.height],s=I.getUniforms(),k={...B.getUniforms(),...s};for(const n of Q.uniformNames)switch(n){case"ModelView":Q.setUniform(n,E);break;case"Projection":Q.setUniform(n,i);break;case"Resolution":Q.setUniform(n,D);break;case"u_opacity":Q.setUniform(n,B.opacity);break;case"CameraPositionModel":{const H=gB(bA(),E),M=EB(0,0,0,1),q=kg(vI(),M,H);Q.setUniform(n,oA(q[0],q[1],q[2]));break}default:n in k&&Q.setUniform(n,k[n])}const c=this.glGetPrimitive(A.primitive),r=A.indexData;r.length?this.gl_.drawElements(c,r.length,this.gl_.UNSIGNED_INT,0):this.gl_.drawArrays(c,0,A.vertexCount)}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 uA(nA(0,0),nA(A,I));this.state_.setViewport(B)}clear(){this.gl_.clearColor(...this.backgroundColor.rgba),this.gl_.clear(this.gl_.COLOR_BUFFER_BIT|this.gl_.DEPTH_BUFFER_BIT),this.state_.setDepthTesting(!0),this.gl_.depthFunc(this.gl_.LEQUAL)}}const Ai=8;class Ii{maxConcurrent_;pending_=[];running_=new Map;constructor(A=Ai){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),V.debug("ChunkQueue","Cancelled pending request");return}const B=this.running_.get(A);B&&(B.controller.abort(),V.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)=>{const B=A.chunk.priority??Number.MAX_SAFE_INTEGER,Q=I.chunk.priority??Number.MAX_SAFE_INTEGER;return B===Q?(A.chunk.orderKey??Number.MAX_SAFE_INTEGER)-(I.chunk.orderKey??Number.MAX_SAFE_INTEGER):B-Q});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"&&V.error("ChunkQueue",String(E))}).finally(()=>{this.running_.delete(I),this.pump()});this.running_.set(I,{controller:Q,promise:C})}}const uQ=[Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array];function PQ(g){if(uQ.some(I=>g instanceof I))return!0;const A=uQ.map(I=>I.name);return V.debug("Chunk",`Unsupported chunk data type: ${g}. Supported data types: ${A}`),!1}function gi(g,A){return Math.round((A-g.translation)/g.scale)}function WB(g,A,I=1e-6){return Math.abs(g-A)<=I}function YI(g,A,I){return Math.max(A,Math.min(I,g))}const mB=Symbol("INTERNAL_POLICY_KEY");class Bi{store_;policy_;policyChanged_=!1;currentLOD_=0;lastViewBounds2D_=null;lastViewProjection_=null;lastZBounds_;lastTCoord_;sourceMaxSquareDistance2D_;chunkViewStates_=new Map;isDisposed_=!1;constructor(A,I){this.store_=A,this.policy_=I,V.info("ChunkStoreView","Using image source policy:",this.policy_.profile);const B=this.store_.dimensions,Q=B.x.lods[0],C=B.y.lods[0];this.sourceMaxSquareDistance2D_=VE(nA(Q.size*Q.scale,C.size*C.scale))}get chunkViewStates(){return this.chunkViewStates_}get isDisposed(){return this.isDisposed_}getChunksAtTime(A){return this.store_.getChunksAtTime(A)}getTimeIndex(A){return this.store_.getTimeIndex(A)}get lodCount(){return this.store_.lodCount}getChunksToRender(A){const I=this.store_.getTimeIndex(A),B=this.store_.getChunksAtTime(I),Q=B.filter(i=>i.lod===this.currentLOD_&&this.chunkViewStates_.get(i)?.visible===!0&&i.state==="loaded"),C=this.fallbackLOD();if(this.currentLOD_===C)return Q;const E=B.filter(i=>i.lod===C&&this.chunkViewStates_.get(i)?.visible===!0&&i.state==="loaded");return[...Q,...E]}updateChunksForImage(A,I){const B=I.camera;if(B.type!=="OrthographicCamera")throw new Error("ChunkStoreView currently supports only orthographic cameras. Update the implementation before using a perspective camera.");const C=B.getWorldViewRect(),E=Math.abs(C.max[0]-C.min[0]),i=I.element,D=I.getBoxRelativeTo(i).toRect().width,s=E/D,h=Math.log2(1/s);this.setLOD(h);const k=this.getZBounds(A);if(!(this.policyChanged_||this.viewBounds2DChanged(C)||this.zBoundsChanged(k)||this.lastTCoord_!==A.t))return;const r=this.store_.getTimeIndex(A);if(this.store_.getChunksAtTime(r).length===0){V.warn("ChunkStoreView","updateChunkViewStates called with no chunks initialized"),this.chunkViewStates_.clear();return}const H=TQ();XE(H,C.min,C.max,.5);const[M,q]=this.getZBounds(A),x=new hI(oA(C.min[0],C.min[1],M),oA(C.max[0],C.max[1],q));this.chunkViewStates_.forEach(TB),this.updateChunksAtTimeIndex(r,A,x,H),A.t!==void 0&&this.markTimeChunksForPrefetchImage(r,A,x,H),this.policyChanged_=!1,this.lastViewBounds2D_=C.clone(),this.lastZBounds_=k,this.lastTCoord_=A.t}updateChunksForVolume(A,I){const B=tg(bA(),I.camera.projectionMatrix,I.camera.viewMatrix);if(!(this.policyChanged_||this.hasViewProjectionChanged(B)||this.lastTCoord_!==A.t))return;const C=this.store_.getTimeIndex(A),E=this.store_.getChunksAtTime(C);if(E.length===0){V.warn("ChunkStoreView","updateChunksForVolume called with no chunks initialized"),this.chunkViewStates_.clear();return}this.currentLOD_=this.policy_.lod.min,this.chunkViewStates_.forEach(TB);const i=this.fallbackLOD();for(const D of E){const s=D.lod===this.currentLOD_,h=D.lod===i;if(!s&&!h||!this.isChunkChannelInSlice(D,A))continue;const k=this.computePriority(h,s,!0,!1,!0);this.chunkViewStates_.set(D,{visible:!0,prefetch:!1,priority:k,orderKey:0})}A.t!==void 0&&this.markTimeChunksForPrefetchVolume(C,A),this.policyChanged_=!1,this.lastTCoord_=A.t,this.lastViewProjection_=B}allVisibleFallbackLODLoaded(A){const I=this.store_.getTimeIndex(A),B=this.fallbackLOD(),Q=this.store_.getChunksAtTime(I).filter(C=>C.visible&&C.lod===B);return Q.length>0&&Q.every(C=>C.state==="loaded")}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(TB)}setImageSourcePolicy(A,I){if(I!==mB)throw new Error("Unauthorized policy mutation");this.policy_!==A&&(this.policy_=A,this.policyChanged_=!0,V.info("ChunkStoreView","Using image source policy:",this.policy_.profile))}setLOD(A){const B=this.store_.dimensions.x.lods[0].scale,C=this.policy_.lod.bias-Math.log2(B)-A,E=Math.floor(C),i=this.store_.getLowestResLOD(),D=Math.max(0,Math.min(i,this.policy_.lod.min)),s=Math.max(D,Math.min(i,this.policy_.lod.max)),h=YI(E,D,s);h!==this.currentLOD_&&(this.currentLOD_=h)}isChunkChannelInSlice(A,I){return I.c===void 0||I.c===A.chunkIndex.c}updateChunksAtTimeIndex(A,I,B,Q){const C=this.getPaddedBounds(B),E=this.store_.getChunksAtTime(A),i=this.fallbackLOD();for(const D of E){const s=D.lod===this.currentLOD_,h=D.lod===i;if(!s&&!h)continue;const k=this.isChunkChannelInSlice(D,I);if(!k)continue;const c=this.isChunkWithinBounds(D,B),r=!c&&k&&s&&this.isChunkWithinBounds(D,C),n=c&&k,H=this.computePriority(h,s,c,r,k);if(H!==null){const M=this.squareDistance2D(D,Q);this.chunkViewStates_.set(D,{visible:n,prefetch:r,priority:H,orderKey:M})}}}markTimeChunksForPrefetchImage(A,I,B,Q){const C=this.store_.dimensions.t?.lods[0].size??1,E=Math.min(C-1,A+this.policy_.prefetch.t),i=this.fallbackLOD(),D=this.policy_.priorityMap.prefetchTime;for(let s=A+1;s<=E;++s)for(const h of this.store_.getChunksAtTime(s)){if(h.lod!==i||!this.isChunkChannelInSlice(h,I)||!this.isChunkWithinBounds(h,B))continue;const k=this.squareDistance2D(h,Q),c=YI(k/this.sourceMaxSquareDistance2D_,0,1-Number.EPSILON),r=s-A+c;this.chunkViewStates_.set(h,{visible:!1,prefetch:!0,priority:D,orderKey:r})}}markTimeChunksForPrefetchVolume(A,I){const B=this.store_.dimensions.t?.lods[0].size??1,Q=Math.min(B-1,A+this.policy_.prefetch.t),C=this.fallbackLOD(),E=this.policy_.priorityMap.prefetchTime;for(let i=A+1;i<=Q;++i)for(const D of this.store_.getChunksAtTime(i)){if(D.lod!==C||!this.isChunkChannelInSlice(D,I))continue;const s=i-A;this.chunkViewStates_.set(D,{visible:!1,prefetch:!0,priority:E,orderKey:s})}}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}isChunkWithinBounds(A,I){const B=new hI(oA(A.offset.x,A.offset.y,A.offset.z),oA(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));return hI.intersects(B,I)}fallbackLOD(){return Math.min(this.policy_.lod.max,this.store_.getLowestResLOD())}getZBounds(A){const I=this.store_.dimensions.z;if(I===void 0)return[0,1];if(A.z===void 0){const h=I.lods[this.currentLOD_];return[h.translation,h.translation+h.size*h.scale]}const B=I.lods[this.currentLOD_],Q=B.size,C=B.scale,E=B.translation,i=Math.floor((A.z-E)/C),D=B.chunkSize,s=Math.max(0,Math.min(Math.floor(i/D),Math.ceil(Q/D)-1));return[E+s*D*C,E+(s+1)*D*C]}viewBounds2DChanged(A){return this.lastViewBounds2D_===null||!pB(this.lastViewBounds2D_.min,A.min)||!pB(this.lastViewBounds2D_.max,A.max)}hasViewProjectionChanged(A){return this.lastViewProjection_===null||!eE(this.lastViewProjection_,A)}zBoundsChanged(A){return!this.lastZBounds_||!pB(this.lastZBounds_,A)}getPaddedBounds(A){const I=this.store_.dimensions,B=I.x.lods[this.currentLOD_],Q=I.y.lods[this.currentLOD_],C=I.z?.lods[this.currentLOD_],E=B.chunkSize*B.scale*this.policy_.prefetch.x,i=Q.chunkSize*Q.scale*this.policy_.prefetch.y;let D=0;return C&&(D=C.chunkSize*C.scale*this.policy_.prefetch.z),new hI(oA(A.min[0]-E,A.min[1]-i,A.min[2]-D),oA(A.max[0]+E,A.max[1]+i,A.max[2]+D))}squareDistance2D(A,I){const B={x:A.offset.x+.5*A.shape.x*A.scale.x,y:A.offset.y+.5*A.shape.y*A.scale.y},Q=B.x-I[0],C=B.y-I[1];return Q*Q+C*C}}function TB(g){g.visible=!1,g.prefetch=!1,g.priority=null,g.orderKey=null}class Qi{chunks_;loader_;lowestResLOD_;dimensions_;views_=[];hasHadViews_=!1;constructor(A){this.loader_=A,this.dimensions_=this.loader_.getSourceDimensionMap(),this.lowestResLOD_=this.dimensions_.numLods-1,this.validateXYScaleRatios();const{size:I}=this.getAndValidateTimeDimension(),{size:B}=this.getAndValidateChannelDimension();this.chunks_=Array.from({length:I},()=>[]);for(let Q=0;Q<I;++Q){const C=this.chunks_[Q];for(let E=0;E<this.dimensions_.numLods;++E){const i=this.dimensions_.x.lods[E],D=this.dimensions_.y.lods[E],s=this.dimensions_.z?.lods[E],h=i.chunkSize,k=D.chunkSize,c=s?.chunkSize??1,r=Math.ceil(i.size/h),n=Math.ceil(D.size/k),H=Math.ceil((s?.size??1)/c);for(let M=0;M<B;++M)for(let q=0;q<r;++q){const x=i.translation+q*i.chunkSize*i.scale;for(let T=0;T<n;++T){const X=D.translation+T*D.chunkSize*D.scale;for(let u=0;u<H;++u){const Z=s!==void 0?s.translation+u*c*s.scale:0;C.push({state:"unloaded",lod:E,visible:!1,prefetch:!1,priority:null,orderKey:null,shape:{x:Math.min(h,i.size-q*h),y:Math.min(k,D.size-T*k),z:Math.min(c,(s?.size??1)-u*c),c:1},rowAlignmentBytes:1,chunkIndex:{x:q,y:T,z:u,c:M,t:Q},scale:{x:i.scale,y:D.scale,z:s?.scale??1},offset:{x,y:X,z:Z}})}}}}}}getChunksAtTime(A){return this.chunks_[A]}getTimeIndex(A){return A.t===void 0||this.dimensions_.t===void 0?0:gi(this.dimensions_.t.lods[0],A.t)}get lodCount(){return this.lowestResLOD_+1}get dimensions(){return this.dimensions_}getLowestResLOD(){return this.lowestResLOD_}loadChunkData(A,I){return this.loader_.loadChunkData(A,I)}createView(A){const I=new Bi(this,A);return this.views_.push(I),this.hasHadViews_=!0,I}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 s of this.views_){const h=s.chunkViewStates.get(A);h&&(h.visible&&(I=!0),h.prefetch&&(B=!0),h.priority!==null&&(Q===null||h.priority<Q)&&(Q=h.priority,C=h.orderKey),!h.visible&&!h.prefetch&&h.priority===null&&s.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}if(A.priority===null&&A.state==="queued"){A.state="unloaded";return}if(A.state==="loaded"&&A.priority===null){if(A.visible||A.prefetch)throw new Error(`Chunk state inconsistency detected: priority is null but visible=${A.visible} or prefetch=${A.prefetch} for chunk ${JSON.stringify(A.chunkIndex)} in LOD ${A.lod}`);A.data=void 0,A.state="unloaded",A.orderKey=null,V.debug("ChunkStore",`Disposing chunk ${JSON.stringify(A.chunkIndex)} in LOD ${A.lod}`)}}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(!WB(Q,2,.02)||!WB(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)throw new Error(`ChunkStore does not support scale in c. Found ${I.scale} at LOD ${A}`);if(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 Ci{stores_=new Map;pendingStores_=new Map;queue_=new Ii;async addView(A,I){return(await this.getOrCreateStore(A)).createView(I)}async getOrCreateStore(A){const I=this.stores_.get(A);if(I)return I;const B=this.pendingStores_.get(A);if(B)return B;const C=(async()=>{const i=await A.open();return new Qi(i)})();this.pendingStores_.set(A,C);const E=await C;return this.stores_.set(A,E),this.pendingStores_.delete(A),E}update(){for(const[A,I]of this.stores_){const B=I.updateAndCollectChunkChanges();for(const Q of B)Q.priority===null?this.queue_.cancel(Q):Q.state==="queued"&&this.queue_.enqueue(Q,C=>I.loadChunkData(Q,C))}this.queue_.flush();for(const[A,I]of this.stores_)I.canDispose()&&this.stores_.delete(A)}}var cg=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(k){k.preventDefault(),Q(++A%I.children.length)},!1);function B(k){return I.appendChild(k.dom),k}function Q(k){for(var c=0;c<I.children.length;c++)I.children[c].style.display=c===k?"block":"none";A=k}var C=(performance||Date).now(),E=C,i=0,D=B(new cg.Panel("FPS","#0ff","#002",g)),s=B(new cg.Panel("MS","#0f0","#020",g));if(self.performance&&self.performance.memory)var h=B(new cg.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 k=(performance||Date).now();if(s.update(k-C,200),k>=E+1e3&&(D.update(i*1e3/(k-E),100),E=k,i=0,h)){var c=performance.memory;h.update(c.usedJSHeapSize/1048576,c.jsHeapSizeLimit/1048576)}return k},update:function(){C=this.end()},domElement:I,setMode:Q}};cg.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),s=E(48*i*B),h=E(3*i*B),k=E(2*i*B),c=E(3*i*B),r=E(15*i*B),n=E(74*i*B),H=E(30*i*B),M=document.createElement("canvas");M.width=D,M.height=s,M.style.cssText=`width:${E(B*80)}px;height:${E(B*48)}px`;var q=M.getContext("2d");return q.font="bold "+E(9*i*B)+"px Helvetica,Arial,sans-serif",q.textBaseline="top",q.fillStyle=I,q.fillRect(0,0,D,s),q.fillStyle=A,q.fillText(g,h,k),q.fillRect(c,r,n,H),q.fillStyle=I,q.globalAlpha=.9,q.fillRect(c,r,n,H),{dom:M,update:function(x,T){Q=Math.min(Q,x),C=Math.max(C,x),q.fillStyle=I,q.globalAlpha=1,q.fillRect(0,0,D,r),q.fillStyle=A,q.fillText(E(x)+" "+g+" ("+E(Q)+"-"+E(C)+")",h,k),q.drawImage(M,c+i,r,n-i,H,c,r,n-i,H),q.fillRect(c+n-i,r,i,H),q.fillStyle=I,q.globalAlpha=.9,q.fillRect(c+n-i,r,i,E((1-x/T)*H))}}};function Ei({scale:g}={scale:1.5}){const A=new cg(g);return A.showPanel(0),document.body.appendChild(A.dom),A}class OQ{layers_=[];callbacks_=[];context_;constructor(A){this.context_=A}partitionLayers(){const A=[],I=[];for(const B of this.layers)B.transparent?I.push(B):A.push(B);return{opaque:A,transparent:I}}add(A){this.layers_=[...this.layers_,A],A.onAttached(this.context_),this.notifyLayersChanged()}remove(A){const I=this.layers_.indexOf(A);if(I===-1)throw new Error(`Layer to remove not found: ${A}`);this.removeByIndex(I)}removeByIndex(A){const I=this.layers_[A];I&&I.onDetached(this.context_),this.layers_=this.layers_.filter((B,Q)=>Q!==A),this.notifyLayersChanged()}removeAll(){for(const A of this.layers_)A.onDetached(this.context_);this.layers_=[],this.notifyLayersChanged()}get layers(){return this.layers_}notifyLayersChanged(){for(const A of this.callbacks_)A()}addLayersChangeCallback(A){return this.callbacks_.push(A),()=>{this.removeLayersChangeCallback(A)}}removeLayersChangeCallback(A){const I=this.callbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove not found: ${A}`);this.callbacks_.splice(I,1)}}const xB=["pointerdown","pointermove","pointerup","pointercancel","wheel"];function ii(g){return xB.includes(g)}class oi{propagationStopped_=!1;type;event;worldPos;clipPos;constructor(A,I){this.type=A,this.event=I}get propagationStopped(){return this.propagationStopped_}stopPropagation(){this.propagationStopped_=!0}}class Di{listeners_=[];element_;isConnected_=!1;constructor(A){this.element_=A}addEventListener(A){this.listeners_.push(A)}connect(){if(this.isConnected_){V.warn("EventDispatcher","Attempted to connect already connected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!0,xB.forEach(A=>{this.element_.addEventListener(A,this.handleEvent,{passive:!1})})}disconnect(){if(!this.isConnected_){V.debug("EventDispatcher","Attempted to disconnect already disconnected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!1,xB.forEach(A=>{this.element_.removeEventListener(A,this.handleEvent)})}handleEvent=A=>{if(!ii(A.type)){V.error("EventDispatcher",`Unsupported event type ${A.type}`);return}const I=new oi(A.type,A);for(const B of this.listeners_)if(B(I),I.propagationStopped)break}}class VQ{id;element;camera;layerManager;events;cameraControls;constructor(A){this.id=A.id,this.element=A.element,this.camera=A.camera,this.layerManager=A.layerManager,this.cameraControls=A.cameraControls,this.updateAspectRatio(),this.events=new Di(this.element),this.events.addEventListener(I=>{if(I.event instanceof PointerEvent||I.event instanceof WheelEvent){const{clientX:B,clientY:Q}=I.event,C=nA(B,Q);I.clipPos=this.clientToClip(C,0),I.worldPos=this.camera.clipToWorld(I.clipPos)}for(const B of this.layerManager.layers)if(B.onEvent(I),I.propagationStopped)return;this.cameraControls?.onEvent(I)});for(const I of A.layers??[])this.layerManager.add(I)}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,s=I.y-E,h=Math.floor(D),k=Math.floor(i-s-I.height),c=Math.floor(I.width),r=Math.floor(I.height);return new uA(nA(h,k),nA(h+c,k+r))}clientToClip(A,I=0){const[B,Q]=A,C=this.element.getBoundingClientRect();return oA(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 uA(nA(B,Q),nA(B+C,Q+E))}updateAspectRatio(){const{width:A,height:I}=this.getBox().toRect();if(A<=0||I<=0){V.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 ZB(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 ai(g){for(let A=0;A<g.length;A++)ZB(g[A],g.slice(0,A))}function bB(g,A,I){const B=g.map(Q=>{const C=Q.element??A;return{...Q,element:C,id:Q.id??C.id??qQ(),layerManager:new OQ(I)}});return ai(B),B.map(Q=>new VQ(Q))}class si{elements_;resizeObserver_;mediaQuery_;onMediaQueryChange_;onChange_;constructor(A=[],I){this.elements_=[...A],this.onChange_=I}connect(){if(this.resizeObserver_){V.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_){V.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)){V.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){V.warn("PixelSizeObserver","Element not being observed");return}this.elements_.splice(I,1),this.resizeObserver_&&this.resizeObserver_.unobserve(A)}}class yi{chunkManager_;context_;renderer_;viewports_;canvas;overlays;stats_;sizeObserver_;lastAnimationId_;lastTimestamp_=0;constructor(A){this.canvas=A.canvas,this.renderer_=new bQ(this.canvas),this.chunkManager_=new Ci,this.context_={chunkManager:this.chunkManager_},this.viewports_=bB(A.viewports??[],this.canvas,this.context_),this.overlays=A.overlays??[],A.showStats&&(this.stats_=Ei());const I=[this.canvas];for(const B of this.viewports_)B.element!==this.canvas&&I.push(B.element);this.sizeObserver_=new si(I,()=>{this.renderer_.updateSize();for(const B of this.viewports_)B.updateSize(),this.renderer_.render(B)})}get renderedObjects(){return this.renderer_.renderedObjects}get width(){return this.renderer_.width}get height(){return this.renderer_.height}get textureInfo(){return this.renderer_.textureInfo}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]=bB([A],this.canvas,this.context_);return ZB(I,this.viewports_),this.viewports_.push(I),this.running&&(I.events.connect(),I.element!==this.canvas&&this.sizeObserver_.observe(I.element)),V.info("Idetik",`Added viewport "${I.id}"`),I}removeViewport(A){const I=this.viewports_.indexOf(A);return I===-1?(V.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),V.info("Idetik",`Removed viewport "${A.id}"`),!0)}start(){if(V.info("Idetik","Idetik runtime starting"),this.running)V.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;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(V.info("Idetik","Idetik runtime stopping"),!this.running)V.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}}}class hi extends jI{constructor(A){if(super(),A.primitive!="triangles"){V.warn("WireframeGeometry","Only indexed geometries are supported");return}if(A.indexData.length==0){V.warn("WireframeGeometry","Only triangulated geometries are supported");return}this.primitive_="lines",this.vertexData_=A.vertexData,this.attributes_=A.attributes;const I=new Set,B=[],Q=(E,i)=>{const D=Math.min(E,i),s=Math.max(E,i);I.has({i0:D,i1:s})||(I.add({i0:D,i1:s}),B.push(D,s))},C=A.indexData;for(let E=0;E<C.length;E+=3){const i=C[E],D=C[E+1],s=C[E+2];Q(i,D),Q(D,s),Q(s,i)}this.indexData_=new Uint32Array(B)}}const Gi=oA(0,1,0);class Fi{dirty_=!0;matrix_=bA();rotation_=dB();translation_=aA();scale_=oA(1,1,1);addRotation(A){bE(this.rotation_,this.rotation_,A),this.dirty_=!0}setRotation(A){PE(this.rotation_,A),this.dirty_=!0}get rotation(){return uE(this.rotation_)}addTranslation(A){VI(this.translation_,this.translation_,A),this.dirty_=!0}setTranslation(A){OI(this.translation_,A),this.dirty_=!0}get translation(){return vA(this.translation_)}addScale(A){qE(this.scale_,this.scale_,A),this.dirty_=!0}setScale(A){OI(this.scale_,A),this.dirty_=!0}targetTo(A){WQ(this.translation_,A)&&(A=vA(A),A[2]+=hA);const I=ME(bA(),this.translation_,A,Gi),B=cE(dQ(),I);mQ(this.rotation_,B),lB(this.rotation_,this.rotation_),this.dirty_=!0}get scale(){return vA(this.scale_)}get matrix(){return this.dirty_&&(this.computeMatrix(),this.dirty_=!1),this.matrix_}get inverse(){return gB(bA(),this.matrix)}computeMatrix(){JE(this.matrix_,this.rotation_,this.translation_,this.scale_)}}class zI extends eB{wireframeEnabled=!1;wireframeColor=QA.WHITE;depthTest=!0;textures_=[];staleTextures_=[];transform_=new Fi;geometry_=new jI;wireframeGeometry_=null;programName_=null;cullFaceMode_="none";setTexture(A,I){const B=this.textures_[A];B!==void 0&&this.staleTextures_.push(B),this.textures_[A]=I}popStaleTextures(){const A=this.staleTextures_;return this.staleTextures_=[],A}get geometry(){return this.geometry_}get wireframeGeometry(){return this.wireframeGeometry_??=new hi(this.geometry),this.wireframeGeometry_}get textures(){return this.textures_}get transform(){return this.transform_}set geometry(A){this.geometry_=A,this.wireframeGeometry_=null}get programName(){return this.programName_}get boundingBox(){const A=this.geometry_.boundingBox.clone();return A.applyTransform(this.transform_.matrix),A}set programName(A){this.programName_=A}get cullFaceMode(){return this.cullFaceMode_}set cullFaceMode(A){this.cullFaceMode_=A}getUniforms(){return{}}}class nI{normal;signedDistance;constructor(A=oA(0,1,0),I=0){this.normal=vA(A),this.signedDistance=I}set(A,I){this.normal=vA(A),this.signedDistance=I}signedDistanceToPoint(A){return pQ(this.normal,A)+this.signedDistance}normalize(){const A=HB(this.normal);if(A>0){const I=1/A;XI(this.normal,this.normal,I),this.signedDistance*=I}}}class XQ{planes_;constructor(A){this.planes_=[new nI(aA(),0),new nI(aA(),0),new nI(aA(),0),new nI(aA(),0),new nI(aA(),0),new nI(aA(),0)],this.setWithViewProjection(A)}setWithViewProjection(A){const I=aA();this.planes_[0].set(rI(I,A[3]+A[0],A[7]+A[4],A[11]+A[8]),A[15]+A[12]),this.planes_[1].set(rI(I,A[3]-A[0],A[7]-A[4],A[11]-A[8]),A[15]-A[12]),this.planes_[2].set(rI(I,A[3]-A[1],A[7]-A[5],A[11]-A[9]),A[15]-A[13]),this.planes_[3].set(rI(I,A[3]+A[1],A[7]+A[5],A[11]+A[9]),A[15]+A[13]),this.planes_[4].set(rI(I,A[3]+A[2],A[7]+A[6],A[11]+A[10]),A[15]+A[14]),this.planes_[5].set(rI(I,A[3]-A[2],A[7]-A[6],A[11]-A[10]),A[15]-A[14]);for(const B of this.planes_)B.normalize()}intersectsWithBox3(A){const I=aA();for(const B of this.planes_){const Q=B.normal;if(I[0]=Q[0]>0?A.max[0]:A.min[0],I[1]=Q[1]>0?A.max[1]:A.min[1],I[2]=Q[2]>0?A.max[2]:A.min[2],B.signedDistanceToPoint(I)<0)return!1}return!0}}class vQ extends zI{projectionMatrix_=bA();near_=0;far_=0;update(){this.updateProjectionMatrix()}get projectionMatrix(){return this.projectionMatrix_}get viewMatrix(){return this.transform.inverse}get right(){const A=this.transform.matrix;return oA(A[0],A[1],A[2])}get up(){const A=this.transform.matrix;return oA(A[4],A[5],A[6])}get frustum(){return new XQ(tg(bA(),this.projectionMatrix,this.viewMatrix))}pan(A){this.transform.addTranslation(A)}get position(){return this.transform.translation}clipToWorld(A){const I=EB(A[0],A[1],A[2],1),B=gB(bA(),this.projectionMatrix_),Q=kg(vI(),I,B);TE(Q,Q,1/Q[3]);const C=kg(vI(),Q,this.transform.matrix);return oA(C[0],C[1],C[2])}}const jQ=1.77,zQ=128,_Q=128/jQ;class wi extends vQ{width_=zQ;height_=_Q;viewportAspectRatio_=jQ;viewportSize_=[zQ,_Q];constructor(A,I,B,Q,C=0,E=100){super(),this.near_=C,this.far_=E,this.setFrame(A,I,Q,B),this.updateProjectionMatrix()}get viewportSize(){return this.viewportSize_}setAspectRatio(A){this.viewportAspectRatio_=A,this.updateProjectionMatrix()}setFrame(A,I,B,Q){this.width_=Math.abs(I-A),this.height_=Math.abs(Q-B),this.updateProjectionMatrix();const C=.5*(A+I),E=.5*(B+Q);this.transform.setTranslation([C,E,0]),this.transform.setScale([1,1,1]),this.transform.setRotation([0,0,0,1])}get type(){return"OrthographicCamera"}zoom(A){if(A<=0)throw new Error(`Invalid zoom factor: ${A}`);const I=1/A;this.transform.addScale([I,I,1])}getWorldViewRect(){let A=EB(-1,-1,0,1),I=EB(1,1,0,1);const B=tg(bA(),this.projectionMatrix,this.viewMatrix),Q=gB(bA(),B);return A=kg(vI(),A,Q),I=kg(vI(),I,Q),new uA(nA(A[0],A[1]),nA(I[0],I[1]))}updateProjectionMatrix(){const A=this.width_,I=this.height_,B=A/I;let Q=.5*A,C=.5*I;this.viewportAspectRatio_>B?Q*=this.viewportAspectRatio_/B:C*=B/this.viewportAspectRatio_,this.viewportSize_=[2*Q,2*C],KE(this.projectionMatrix_,-Q,Q,-C,C,this.near_,this.far_)}}const Si=60,Ri=1.77,iB=.1,uB=180-iB;class Ni extends vQ{fov_;aspectRatio_;constructor(A={}){const{fov:I=Si,aspectRatio:B=Ri,near:Q=.1,far:C=1e4,position:E=oA(0,0,0)}=A;if(I<iB||I>uB)throw new Error(`Invalid field of view: ${I}, must be in [${iB}, ${uB}] degrees`);super(),this.fov_=I,this.aspectRatio_=B,this.near_=Q,this.far_=C,this.transform.setTranslation(E),this.updateProjectionMatrix()}setAspectRatio(A){this.aspectRatio_=A,this.updateProjectionMatrix()}get type(){return"PerspectiveCamera"}get fov(){return this.fov_}zoom(A){if(A<=0)throw new Error(`Invalid zoom factor: ${A}`);this.fov_=Math.max(iB,Math.min(uB,this.fov_/A)),this.updateProjectionMatrix()}updateProjectionMatrix(){YE(this.projectionMatrix_,kE(this.fov),this.aspectRatio_,this.near_,this.far_)}}const $Q=0;class Ui{camera_;dragActive_=!1;dragStart_=aA();constructor(A){this.camera_=A}get isMoving(){return this.dragActive_}onEvent(A){switch(A.type){case"wheel":this.onWheel(A);break;case"pointerdown":this.onPointerDown(A);break;case"pointermove":this.onPointerMove(A);break;case"pointerup":case"pointercancel":this.onPointerEnd(A);break}}onUpdate(A){}onWheel(A){if(!A.worldPos||!A.clipPos)return;const I=A.event;I.preventDefault();const B=vA(A.worldPos),Q=I.deltaY<0?1.05:.95;this.camera_.zoom(Q);const C=this.camera_.clipToWorld(A.clipPos),E=CB(aA(),B,C);this.camera_.pan(E)}onPointerDown(A){const I=A.event;!A.worldPos||I.button!==$Q||(this.dragStart_=vA(A.worldPos),this.dragActive_=!0,I.target?.setPointerCapture?.(I.pointerId))}onPointerMove(A){if(!this.dragActive_||!A.worldPos)return;const I=CB(aA(),this.dragStart_,A.worldPos);this.camera_.pan(I)}onPointerEnd(A){const I=A.event;!this.dragActive_||I.button!==$Q||(this.dragActive_=!1,I.target?.releasePointerCapture?.(I.pointerId))}}class PB{radius;phi;theta;constructor(A,I,B){this.radius=A,this.phi=I,this.theta=B}toVec3(){const A=Math.cos(this.theta);return oA(this.radius*Math.sin(this.phi)*A,-this.radius*Math.sin(this.theta),this.radius*Math.cos(this.phi)*A)}}const OB=-1,AC=0,ti=1,IC=.009,ki=.001,ci=9e-4,Li=.5,Ji=60;class ri{camera_;orbitVelocity_=new PB(0,0,0);panVelocity_=aA();currPos_;currCenter_=aA();dampingFactor_;currMouseButton_=OB;constructor(A,I){this.camera_=A,this.currPos_=new PB(I?.radius??1,I?.yaw??0,I?.pitch??0),I?.target&&OI(this.currCenter_,I.target),this.dampingFactor_=YI(I?.dampingFactor??Li,0,1),this.updateCamera()}get isMoving(){return this.orbitVelocity_.phi!==0||this.orbitVelocity_.theta!==0||this.orbitVelocity_.radius!==0||this.panVelocity_[0]!==0||this.panVelocity_[1]!==0||this.panVelocity_[2]!==0}onEvent(A){switch(A.type){case"pointerdown":this.onPointerDown(A);break;case"pointermove":this.onPointerMove(A);break;case"wheel":this.onWheel(A);break;case"pointerup":case"pointercancel":this.onPointerEnd(A);break}}onUpdate(A){if(this.orbitVelocity_.phi===0&&this.orbitVelocity_.theta===0&&this.orbitVelocity_.radius===0&&WQ(this.panVelocity_,oA(0,0,0)))return;this.currPos_.phi+=this.orbitVelocity_.phi,this.currPos_.theta+=this.orbitVelocity_.theta,this.currPos_.radius+=this.orbitVelocity_.radius*this.currPos_.radius,VI(this.currCenter_,this.currCenter_,this.panVelocity_);const I=Math.PI/2-hA;this.currPos_.theta=YI(this.currPos_.theta,-I,I),this.currPos_.radius=Math.max(.01,this.currPos_.radius),this.updateCamera();const B=Math.pow(1-this.dampingFactor_,A*Ji);this.orbitVelocity_.phi*=B,this.orbitVelocity_.theta*=B,this.orbitVelocity_.radius*=B,XI(this.panVelocity_,this.panVelocity_,B),this.cutoffLowVelocity()}onPointerDown(A){const I=A.event;this.currMouseButton_=I.button,I.target?.setPointerCapture?.(I.pointerId)}onPointerMove(A){if(this.currMouseButton_==OB)return;const I=A.event,B=I.movementX??0,Q=I.movementY??0,C=this.currMouseButton_===AC&&!I.shiftKey,E=this.currMouseButton_===AC&&I.shiftKey||this.currMouseButton_===ti;C&&this.orbit(B,Q),E&&this.pan(B,Q)}onWheel(A){const I=A.event;I.preventDefault();const B=I.deltaY??0;this.zoom(B)}onPointerEnd(A){this.currMouseButton_=OB;const I=A.event;I.target?.releasePointerCapture?.(I.pointerId)}orbit(A,I){this.orbitVelocity_.phi-=A*IC,this.orbitVelocity_.theta+=I*IC}pan(A,I){const B=this.currPos_.radius*ki,Q=aA();BB(Q,Q,this.camera_.right,A),BB(Q,Q,this.camera_.up,I),XI(Q,Q,B),CB(this.panVelocity_,this.panVelocity_,Q)}zoom(A){this.orbitVelocity_.radius+=A*ci}updateCamera(){const A=VI(aA(),this.currCenter_,this.currPos_.toVec3());this.camera_.transform.setTranslation(A),this.camera_.transform.targetTo(this.currCenter_)}cutoffLowVelocity(){Math.abs(this.orbitVelocity_.phi)<hA&&(this.orbitVelocity_.phi=0),Math.abs(this.orbitVelocity_.theta)<hA&&(this.orbitVelocity_.theta=0),Math.abs(this.orbitVelocity_.radius)<hA&&(this.orbitVelocity_.radius=0),HB(this.panVelocity_)<hA&&lE(this.panVelocity_)}}class EI{objects_=[];state_="initialized";callbacks_=[];transparent;opacity_;blendMode;constructor({transparent:A=!1,opacity:I=1,blendMode:B="normal"}={}){(I<0||I>1)&&V.warn("Layer",`Layer opacity out of bounds: ${I} — clamping to [0.0, 1.0]`),this.transparent=A,this.opacity_=YI(I,0,1),this.blendMode=B}get opacity(){return this.opacity_}set opacity(A){(A<0||A>1)&&V.warn("Layer",`Opacity out of bounds: ${A} — clamping to [0.0, 1.0]`),this.opacity_=YI(A,0,1)}onEvent(A){}async onAttached(A){}onDetached(A){}get objects(){return this.objects_}get state(){return this.state_}addStateChangeCallback(A){this.callbacks_.push(A)}removeStateChangeCallback(A){const I=this.callbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.callbacks_.splice(I,1)}hasMultipleLODs(){return!1}setState(A){const I=this.state_;this.state_=A,this.callbacks_.forEach(B=>B(A,I))}addObject(A){this.objects_.push(A)}removeObject(A){const I=this.objects_.indexOf(A);I!==-1&&this.objects_.splice(I,1)}clearObjects(){this.objects_=[]}getUniforms(){return{}}}class oB extends jI{constructor(A){super(),this.vertexData_=this.createVertices(A),this.indexData_=this.createIndex(A.length),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"previous_position",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"next_position",itemSize:3,offset:6*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"direction",itemSize:1,offset:9*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"path_proportion",itemSize:1,offset:10*Float32Array.BYTES_PER_ELEMENT})}createVertices(A){const I=new Float32Array(2*A.length*11);let B=0,Q=0;const C=A.reduce((E,i,D)=>E+fQ(i,A[D+1]??i),0);for(const E of[...Array(A.length).keys()]){for(const i of[-1,1]){const D=A[E];I[B++]=D[0],I[B++]=D[1],I[B++]=D[2];const s=A[E-1]??A[E];I[B++]=s[0],I[B++]=s[1],I[B++]=s[2];const h=A[E+1]??A[E];I[B++]=h[0],I[B++]=h[1],I[B++]=h[2],I[B++]=i,I[B++]=Q}Q+=fQ(A[E],A[E+1]??A[E])/C}return I}createIndex(A){const I=new Uint32Array((A-1)*6);let B=0;for(let Q=0;Q<2*A;Q+=2)I[B++]=Q+0,I[B++]=Q+1,I[B++]=Q+2,I[B++]=Q+2,I[B++]=Q+1,I[B++]=Q+3;return I}}class VB extends zI{color_;width_;taperOffset_=.5;taperPower_=0;constructor({geometry:A,color:I,width:B,taperOffset:Q,taperPower:C}){super(),this.geometry=A,this.color_=QA.from(I),this.width_=B,this.taperOffset_=Q??this.taperOffset_,this.taperPower_=C??this.taperPower_,this.programName="projectedLine"}get type(){return"ProjectedLine"}get color(){return this.color_}set color(A){this.color_=QA.from(A)}get width(){return this.width_}set width(A){this.width_=A}get taperOffset(){return this.taperOffset_}set taperOffset(A){this.taperOffset_=A}get taperPower(){return this.taperPower_}set taperPower(A){this.taperPower_=A}getUniforms(){return{LineColor:this.color.rgb,LineWidth:this.width,TaperOffset:this.taperOffset,TaperPower:this.taperPower}}}class Yi extends EI{type="AxesLayer";constructor(A){super();const{length:I,width:B}=A;this.addObject(XB({end:[I,0,0],width:B,color:[1,0,0]})),this.addObject(XB({end:[0,I,0],width:B,color:[0,1,0]})),this.addObject(XB({end:[0,0,I],width:B,color:[0,0,1]})),this.setState("ready")}update(){}}function XB(g){const{end:A,width:I,color:B}=g,Q=new oB([[0,0,0],A]);return new VB({geometry:Q,color:B,width:I})}class ni extends EI{type="ProjectedLineLayer";paths_=[];constructor(A=[]){super(),A.forEach(I=>this.addLine(I)),this.setState("ready")}addLine(A){const{path:I,color:B,width:Q}=A;this.paths_.push(I);const C=new oB(I);this.addObject(new VB({geometry:C,color:B,width:Q}))}update(){}get extent(){return Ki(this.paths_.flat())}}function Ki(g){function A(D){const s=g.map(h=>h[D]);return[Math.min(...s),Math.max(...s)]}const[I,B]=A(0),[Q,C]=A(1),[E,i]=A(2);return{xMin:I,xMax:B,yMin:Q,yMax:C,zMin:E,zMax:i}}class Mi extends EI{type="TracksLayer";tracks_=[];constructor(A=[]){super(),A.forEach(I=>this.addLine(I)),this.setState("ready")}addLine(A){this.tracks_.push(A);let I;if(A.interpolation){const i=Hi({path:A.path,pointsPerSegment:A.interpolation.pointsPerSegment,tangentFactor:A.interpolation.tangentFactor});I=new oB(i)}else I=new oB(A.path);const{color:B,width:Q}=A,C=.5,E=1.5;this.addObject(new VB({geometry:I,color:B,width:Q,taperOffset:C,taperPower:E}))}setTimeIndex(A){for(const[I,B]of this.tracks_.entries()){if(!B.time)continue;let Q=.5;A<B.time[0]?Q=-1.5:A>B.time[B.time.length-1]&&(Q=1.5);const C=B.time.findIndex(i=>i===A);B.time&&C!==-1&&(Q=C/(B.time.length-1));const E=this.objects[I];E.taperOffset=Q}}update(){}get extent(){const A=this.tracks_.map(I=>I.path);return ei(A.flat())}}function ei(g){function A(D){const s=g.map(h=>h[D]);return[Math.min(...s),Math.max(...s)]}const[I,B]=A(0),[Q,C]=A(1),[E,i]=A(2);return{xMin:I,xMax:B,yMin:Q,yMax:C,zMin:E,zMax:i}}function Hi({path:g,pointsPerSegment:A,tangentFactor:I=1/3}){const B=qi(g),Q=Array((g.length-1)*A);for(let C=0;C<g.length-1;C++){const E=g[C],i=g[C+1],D=vA(B[C]);BB(D,E,D,I);const s=vA(B[C+1]);BB(s,i,s,-I);for(let h=0;h<A;h++){const k=h/A,c=Q[C*A+h]=aA();fE(c,E,D,s,i,k)}}return Q}function qi(g){if(g.length<2)throw new Error("Path must contain at least 2 points");const A=Array(g.length),I=aA(),B=aA();for(let Q=0;Q<g.length;Q++){const C=g[Q],E=g[Q+1]??g[Q];A[Q]=aA(),Q!==0&&OI(I,B),Q!==g.length-1&&CB(B,E,C),Q===0?OI(A[Q],B):Q==g.length-1?OI(A[Q],I):(VI(A[Q],I,B),XI(A[Q],A[Q],.5))}return A}class gC extends jI{constructor(A,I,B,Q){super();const C=[],E=[],i=B,D=Q,s=i+1,h=D+1,k=A/i,c=I/D;for(let r=0;r<h;++r){const n=r*c;for(let H=0;H<s;++H){const M=H*k,q=H/i,x=r/D,T=[M,n,0],X=[0,0,1],u=[q,x];C.push(...T,...X,...u)}}for(let r=0;r<D;++r)for(let n=0;n<i;++n){const H=n+s*r,M=n+s*(r+1),q=n+1+s*(r+1),x=n+1+s*r;E.push(H,M,x),E.push(M,q,x)}this.vertexData_=new Float32Array(C),this.indexData_=new Uint32Array(E),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}}function BC(g){return g===1||g===2||g===4||g===8}function _I(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){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 vB extends eB{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;get type(){return"Texture"}}const QC=32;function Lg(g,{visible:A,color:I,contrastLimits:B}){return A===void 0&&(A=!0),I===void 0?I=QA.WHITE:I=QA.from(I),g!==null?B=fi(B,g):B===void 0&&(V.debug("Channel","No texture provided, defaulting channel contrast limits to [0, 1]."),B=[0,1]),{visible:A,color:I,contrastLimits:B}}function jB(g,A){if(A.length>QC)throw new Error(`Maximum number of channels is ${QC}`);if(g?.type==="Texture2DArray"){const I=g.depth;if(A.length!==I)throw new Error(`Number of channels (${A.length}) must match depth of texture (${I}).`)}return A.map(I=>Lg(g,I))}function fi(g,A){if(g===void 0)return di(A);if(g[1]<=g[0])throw new Error(`Contrast limits must be strictly increasing: ${g}.`);return g}class zB extends zI{channels_;constructor(A,I,B,Q=[]){super(),this.geometry=new gC(A,I,1,1),this.setTexture(0,B),this.channels_=jB(B,Q),this.programName=li(B)}get type(){return"ImageRenderable"}setChannelProps(A){this.channels_=jB(this.textures[0],A)}setChannelProperty(A,I,B){const Q=Lg(this.textures[0],{...this.channels_[A],[I]:B});this.channels_[A]=Q}getUniforms(){const A=this.textures[0];if(!A)throw new Error("No texture set");if(A.type==="Texture2D"){const{color:I,contrastLimits:B}=this.channels_[0]??Lg(A,{});return{ImageSampler:0,Color:I.rgb,ValueOffset:-B[0],ValueScale:1/(B[1]-B[0]),ChannelCount:1}}else{const I=[],B=[],Q=[],C=[];return this.channels_.forEach(E=>{I.push(E.visible),B.push(...E.color.rgb),Q.push(-E.contrastLimits[0]),C.push(1/(E.contrastLimits[1]-E.contrastLimits[0]))}),{ImageSampler:0,"Visible[0]":I,"Color[0]":B,"ValueOffset[0]":Q,"ValueScale[0]":C,ChannelCount:this.channels_.length}}}}function li(g){if(g.type==="Texture2D")return pi(g.dataType);if(g.type==="Texture2DArray")return Wi(g.dataType);throw new Error(`Unsupported image texture type: ${g.type}`)}function pi(g){switch(g){case"byte":case"int":case"short":return"intScalarImage";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintScalarImage";case"float":return"floatScalarImage"}}function Wi(g){switch(g){case"byte":case"int":case"short":return"intScalarImageArray";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintScalarImageArray";case"float":return"floatScalarImageArray"}}class $I extends vB{data_;width_;height_;depth_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=_I(A),this.data_=A,this.width_=I,this.height_=B,this.depth_=A.length/(I*B)}get type(){return"Texture2DArray"}set data(A){this.data_=A,this.needsUpdate=!0}get data(){return this.data_}get width(){return this.width_}get height(){return this.height_}get depth(){return this.depth_}updateWithChunk(A,I){const B=I??A.data;if(!B)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data===B)return;const Q=A.shape.x,C=A.shape.y,E=B.length/(Q*C);if(this.width!=Q||this.height!=C||this.depth_!=E||this.dataType!=_I(B))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=B}static createWithChunk(A,I){const B=I??A.data;if(!B)throw new Error("Unable to create texture, chunk data is not initialized.");const Q=new $I(B,A.shape.x,A.shape.y);return Q.unpackAlignment=A.rowAlignmentBytes,Q}}function _B(g,A,I,B,Q=3){switch(g.type){case"pointerdown":{const C=g.event;return nA(C.clientX,C.clientY)}case"pointerup":{if(!A)return A;const C=g.event,E=nA(C.clientX,C.clientY);if(OE(A,E)<Q){if(!B)return null;const D=g.worldPos;if(D){const s=I(D);s!==null&&B({world:D,value:s})}return null}return A}case"pointercancel":return null;default:return A}}class CC{bins_=new Map;acquire(A){const B=this.bins_.get(A)?.pop();return B&&V.debug("RenderablePool","Renderable object acquired"),B}release(A,I){let B=this.bins_.get(A);B||(B=[],this.bins_.set(A,B)),B.push(I),V.debug("RenderablePool","Renderable object released")}clearAll(A){if(A)for(const I of this.bins_.values())I.forEach(A);this.bins_.clear()}}class $B extends EI{type="ChunkedImageLayer";source_;sliceCoords_;onPickValue_;visibleChunks_=new Map;pool_=new CC;initialChannelProps_;channelChangeCallbacks_=[];policy_;channelProps_;chunkStoreView_;pointerDownPos_=null;zPrevPointWorld_;debugMode_=!1;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;wireframeColors_=[new QA(.6,.3,.3),new QA(.3,.6,.4),new QA(.4,.4,.7),new QA(.6,.5,.3)];constructor({source:A,sliceCoords:I,policy:B,channelProps:Q,onPickValue:C,...E}){super(E),this.setState("initialized"),this.source_=A,this.policy_=B,this.sliceCoords_=I,this.channelProps_=Q,this.initialChannelProps_=Q,this.onPickValue_=C}async onAttached(A){if(this.chunkStoreView_)throw new Error("ChunkedImageLayer cannot be attached to multiple contexts simultaneously.");this.chunkStoreView_=await A.chunkManager.addView(this.source_,this.policy_)}onDetached(A){this.chunkStoreView_&&(this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_.dispose(),this.chunkStoreView_=void 0)}update(A){!A||!this.chunkStoreView_||(this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,A.viewport),this.updateChunks(),this.resliceIfZChanged())}updateChunks(){if(!this.chunkStoreView_||(this.state!=="ready"&&this.setState("ready"),this.visibleChunks_.size>0&&!this.chunkStoreView_.allVisibleFallbackLODLoaded(this.sliceCoords_)&&!this.isPresentationStale()))return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const A=this.chunkStoreView_.getChunksToRender(this.sliceCoords_),I=new Set(A),B=Array.from(this.visibleChunks_.keys()).filter(Q=>!I.has(Q));this.releaseAndRemoveChunks(B),this.clearObjects();for(const Q of A){if(Q.state!=="loaded")continue;const C=this.getImageForChunk(Q);this.visibleChunks_.set(Q,C),this.addObject(C)}}hasMultipleLODs(){return this.chunkStoreView_?this.chunkStoreView_.lodCount>1:!1}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>$B.STALE_PRESENTATION_MS_}resliceIfZChanged(){const A=this.sliceCoords_.z;if(!(A===void 0||this.zPrevPointWorld_===A)){for(const[I,B]of this.visibleChunks_){if(I.state!=="loaded"||!I.data)continue;const Q=this.slicePlane(I,A);Q&&B.textures[0].updateWithChunk(I,Q)}this.zPrevPointWorld_=A}}onEvent(A){this.pointerDownPos_=_B(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.onPickValue_)}get chunkStoreView(){return this.chunkStoreView_}get sliceCoords(){return this.sliceCoords_}get source(){return this.source_}get imageSourcePolicy(){return this.policy_}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,mB))}slicePlane(A,I){if(!A.data)return;const B=(I-A.offset.z)/A.scale.z,Q=Math.round(B),C=YI(Q,0,A.shape.z-1);WB(B,C,1+1e-6)||V.error("ImageLayer","slicePlane zValue outside extent");const E=A.shape.x*A.shape.y,i=E*C;return A.data.slice(i,i+E)}getImageForChunk(A){const I=this.visibleChunks_.get(A);if(I)return I;const B=this.pool_.acquire(EC(A));return B?(B.textures[0].updateWithChunk(A,this.getDataForImage(A)),this.updateImageChunk(B,A),this.channelProps_&&B.setChannelProps(this.channelProps_),B):this.createImage(A)}createImage(A){const I=new zB(A.shape.x,A.shape.y,$I.createWithChunk(A,this.getDataForImage(A)),this.channelProps_??[{}]);return this.updateImageChunk(I,A),I}getDataForImage(A){const I=this.sliceCoords_?.z!==void 0?this.slicePlane(A,this.sliceCoords_.z):A.data;if(!I){V.warn("ChunkedImageLayer","No data for image");return}return I}updateImageChunk(A,I){this.debugMode_?(A.wireframeEnabled=!0,A.wireframeColor=this.wireframeColors_[I.lod%this.wireframeColors_.length]):A.wireframeEnabled=!1,A.transform.setScale([I.scale.x,I.scale.y,1]),A.transform.setTranslation([I.offset.x,I.offset.y,0])}getValueAtWorld(A){const I=this.chunkStoreView_?.currentLOD??0;for(const[B,Q]of this.visibleChunks_){if(B.lod!==I)continue;const C=this.getValueFromChunk(B,Q,A);if(C!==null)return C}for(const[B,Q]of this.visibleChunks_){if(B.lod===I)continue;const C=this.getValueFromChunk(B,Q,A);if(C!==null)return C}return null}getValueFromChunk(A,I,B){if(!A.data)return null;const Q=QB(aA(),B,I.transform.inverse),C=Math.floor(Q[0]),E=Math.floor(Q[1]);if(C>=0&&C<A.shape.x&&E>=0&&E<A.shape.y){const i=this.sliceCoords_.z!==void 0?this.slicePlane(A,this.sliceCoords_.z):A.data,D=E*A.shape.x+C;return i[D]}return null}get debugMode(){return this.debugMode_}set debugMode(A){this.debugMode_=A,this.visibleChunks_.forEach((I,B)=>{I.wireframeEnabled=this.debugMode_,this.debugMode_&&(I.wireframeColor=this.wireframeColors_[B.lod%this.wireframeColors_.length])})}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.visibleChunks_.forEach(I=>{I.setChannelProps(A)}),this.channelChangeCallbacks_.forEach(I=>{I()})}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===-1)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}releaseAndRemoveChunks(A){for(const I of A){const B=this.visibleChunks_.get(I);B&&(this.pool_.release(EC(I),B),this.visibleChunks_.delete(I))}}}function EC(g){return[`lod${g.lod}`,`shape${g.shape.x}x${g.shape.y}`,`align${g.rowAlignmentBytes}`].join(":")}class mi extends jI{constructor(A,I,B,Q,C,E){super();const i=[],D=[],s=Math.floor(Q),h=Math.floor(C),k=Math.floor(E);this.buildFace("z","y","x",-1,-1,B,I,A,k,h,1,i,D),this.buildFace("z","y","x",1,-1,B,I,A,k,h,-1,i,D),this.buildFace("x","z","y",1,1,A,B,I,s,k,1,i,D),this.buildFace("x","z","y",1,-1,A,B,I,s,k,-1,i,D),this.buildFace("x","y","z",1,-1,A,I,B,s,h,1,i,D),this.buildFace("x","y","z",-1,-1,A,I,B,s,h,-1,i,D),this.vertexData_=new Float32Array(i),this.indexData_=new Uint32Array(D),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}buildFace(A,I,B,Q,C,E,i,D,s,h,k,c,r){const n=E/s,H=i/h,M=E/2,q=i/2,x=D/2*k,T=s+1,X=h+1,u=c.length/8;for(let Z=0;Z<X;Z++){const EA=-q+Z*H;for(let iA=0;iA<T;iA++){const BA=-M+iA*n,sA={x:0,y:0,z:0};sA[A]=BA*Q,sA[I]=EA*C,sA[B]=x;const yA={x:0,y:0,z:0};yA[B]=k;const KA=iA/s,NA=1-Z/h;c.push(sA.x,sA.y,sA.z,yA.x,yA.y,yA.z,KA,NA)}}for(let Z=0;Z<h;Z++)for(let EA=0;EA<s;EA++){const iA=u+EA+T*Z,BA=u+EA+T*(Z+1),sA=u+(EA+1)+T*(Z+1),yA=u+(EA+1)+T*Z;r.push(iA,BA,yA,BA,sA,yA)}}}class Ag extends vB{data_;width_;height_;depth_;constructor(A,I,B,Q){super(),this.dataFormat="scalar",this.dataType=_I(A),this.data_=A,this.width_=I,this.height_=B,this.depth_=Q}set data(A){this.data_=A,this.needsUpdate=!0}get type(){return"Texture3D"}get data(){return this.data_}get width(){return this.width_}get height(){return this.height_}get depth(){return this.depth_}updateWithChunk(A){const I=A.data;if(!I)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data!==I){if(this.width!=A.shape.x||this.height!=A.shape.y||this.depth!=A.shape.z||this.dataType!=_I(I))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=I}}static createWithChunk(A){const I=A.data;if(!I)throw new Error("Unable to create texture, chunk data is not initialized.");const B=new Ag(I,A.shape.x,A.shape.y,A.shape.z);return B.unpackAlignment=A.rowAlignmentBytes,B}}class Ti extends zI{voxelScale=oA(1,1,1);channels_;channelToTextureIndex_=new Map;loadedChannels_=new Set;constructor(){super(),this.geometry=new mi(1,1,1,1,1,1),this.cullFaceMode="front",this.depthTest=!1,this.channels_=[]}get type(){return"VolumeRenderable"}updateVolumeWithChunk(A){const I=A.chunkIndex.c,B=this.channelToTextureIndex_.get(I);B!==void 0?this.updateChannelTexture(B,A):this.addChannelTexture(I,A),this.loadedChannels_.add(I)}addChannelTexture(A,I){const B=Ag.createWithChunk(I),Q=this.textures.length;this.setTexture(Q,B),this.channelToTextureIndex_.set(A,Q);const C=xi(B.dataType);if(this.programName&&this.programName!==C)throw new Error(`Volume renderable does not support multiple channels with different data types. Existing program: ${this.programName}, new channel data type: ${B.dataType} and program: ${C}`);this.programName=C}updateChannelTexture(A,I){const B=this.textures[A];if(!(B instanceof Ag)){const Q=Ag.createWithChunk(I);this.setTexture(A,Q);return}B.updateWithChunk(I)}clearLoadedChannels(){this.loadedChannels_=new Set}getUniforms(){const A=[0,0,0,0],I=[1,1,1,1,1,1,1,1,1,1,1,1],B=[0,0,0,0],Q=[1,1,1,1],C=[],E=Math.max(this.channels_.length,this.channelToTextureIndex_.size);for(let i=0;i<E&&C.length<4;i++){const D=this.channelToTextureIndex_.get(i);if(D===void 0||!this.loadedChannels_.has(i))continue;const s=this.textures[D],h=Lg(s,this.channels_[i]||{});if(!h.visible)continue;const k=C.length;I[k*3]=h.color.rgb[0],I[k*3+1]=h.color.rgb[1],I[k*3+2]=h.color.rgb[2],C.push(D),B[k]=-h.contrastLimits[0],Q[k]=1/(h.contrastLimits[1]-h.contrastLimits[0]),A[k]=1}return C.reduce((i,D,s)=>(i[`Channel${s}Sampler`]=D,i),{Visible:A,"Color[0]":I,ValueOffset:B,ValueScale:Q,VoxelScale:[this.voxelScale[0],this.voxelScale[1],this.voxelScale[2]]})}getAvailableChannelTexture(A){if(A!==void 0){const B=this.channelToTextureIndex_.get(A);if(B!==void 0)return this.textures[B]}const I=this.channelToTextureIndex_.values().next().value;return I!==void 0?this.textures[I]:null}setChannelProps(A){this.channels_=jB(this.getAvailableChannelTexture(),A)}setChannelProperty(A,I,B){const Q=Lg(this.getAvailableChannelTexture(A),{...this.channels_[A],[I]:B});this.channels_[A]=Q}}function xi(g){switch(g){case"byte":case"int":case"short":return"intVolume";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintVolume";case"float":return"floatVolume"}}function Zi(g,A){const I=A.position,B=aA(),Q=aA();return g.sort((C,E)=>{VI(B,C.boundingBox.max,C.boundingBox.min),XI(B,B,.5),VI(Q,E.boundingBox.max,E.boundingBox.min),XI(Q,Q,.5);const i=lQ(I,B),D=lQ(I,Q);return i-D}),g}const bi=2;class ui extends EI{type="VolumeLayer";source_;sliceCoords_;currentVolumes_=new Map;volumeToPoolKey_=new Map;pool_=new CC;initialChannelProps_;channelChangeCallbacks_=[];sourcePolicy_;chunkStoreView_;channelProps_;lastLoadedTime_=void 0;lastNumRenderedChannelChunks_=void 0;interactiveStepSizeScale_=1;debugShowWireframes_=!1;debugShowDegenerateRays=!1;relativeStepSize=1;opacityMultiplier=1;earlyTerminationAlpha=.99;get debugShowWireframes(){return this.debugShowWireframes_}set debugShowWireframes(A){if(this.debugShowWireframes_!==A){for(const I of this.currentVolumes_.values())I.wireframeEnabled=A;this.debugShowWireframes_=A}}set sourcePolicy(A){this.sourcePolicy_!==A&&(this.sourcePolicy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,mB))}setChannelProps(A){this.channelProps_=A;for(const I of this.currentVolumes_.values())I.setChannelProps(A);this.channelChangeCallbacks_.forEach(I=>{I()})}get channelProps(){return this.channelProps_}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}constructor({source:A,sliceCoords:I,policy:B,channelProps:Q}){super({transparent:!0,blendMode:"premultiplied"}),this.source_=A,this.sliceCoords_=I,this.sourcePolicy_=B,this.initialChannelProps_=Q,this.channelProps_=Q,this.setState("initialized")}getOrCreateVolume(A,I){const B=this.currentVolumes_.get(A);if(B){for(const E of I)B.updateVolumeWithChunk(E);return B}const Q=Vi(I[0]),C=this.pool_.acquire(Q)??new Ti;C.setChannelProps(this.channelProps_??[]),this.volumeToPoolKey_.set(C,Q);for(const E of I)C.updateVolumeWithChunk(E);return this.updateVolumeTransform(C,I[0]),C}async onAttached(A){this.chunkStoreView_=await A.chunkManager.addView(this.source_,this.sourcePolicy_)}onDetached(A){this.chunkStoreView_&&(this.releaseAndRemoveVolumes(this.currentVolumes_.values()),this.clearObjects(),this.chunkStoreView_.dispose(),this.chunkStoreView_=void 0)}updateChunks(){if(!this.chunkStoreView_)return;const A=this.chunkStoreView_.getChunksToRender(this.sliceCoords_),I=this.sliceCoords_.t??-1,B=Oi(A),Q=this.lastLoadedTime_!==I||B.size!==this.currentVolumes_.size||this.lastNumRenderedChannelChunks_!==A.length;if(this.lastNumRenderedChannelChunks_=A.length,!Q)return;const C=Array.from(this.currentVolumes_.entries()).filter(([E])=>!B.has(E)).map(([,E])=>E);this.releaseAndRemoveVolumes(C),this.currentVolumes_.clear(),this.clearObjects();for(const[E,i]of B){const D=this.getOrCreateVolume(E,i);D.wireframeEnabled=this.debugShowWireframes,this.currentVolumes_.set(E,D),this.addObject(D)}this.lastLoadedTime_=I,this.state!=="ready"&&this.setState("ready")}updateVolumeTransform(A,I){const B={x:I.shape.x*I.scale.x,y:I.shape.y*I.scale.y,z:I.shape.z*I.scale.z};A.transform.setScale([B.x,B.y,B.z]),rI(A.voxelScale,I.scale.x,I.scale.y,I.scale.z);const Q={x:I.shape.x*I.scale.x/2,y:I.shape.y*I.scale.y/2,z:I.shape.z*I.scale.z/2};A.transform.setTranslation([I.offset.x+Q.x,I.offset.y+Q.y,I.offset.z+Q.z])}releaseAndRemoveVolumes(A){for(const I of A)I.clearLoadedChannels(),this.pool_.release(this.volumeToPoolKey_.get(I),I),this.volumeToPoolKey_.delete(I)}update(A){if(!this.chunkStoreView_)return;if(A===void 0)throw new Error("RenderContext is required for the VolumeLayer update as camera information is used to reorder the chunks.");this.chunkStoreView_.updateChunksForVolume(this.sliceCoords_,A.viewport);const I=A.viewport.cameraControls?.isMoving??!1;this.interactiveStepSizeScale_=I?bi:1,this.updateChunks(),Zi(this.objects,A.viewport.camera)}getUniforms(){return{DebugShowDegenerateRays:Number(this.debugShowDegenerateRays),RelativeStepSize:this.relativeStepSize*this.interactiveStepSizeScale_,OpacityMultiplier:this.opacityMultiplier,EarlyTerminationAlpha:this.earlyTerminationAlpha}}}function Pi(g){const{x:A,y:I,z:B,t:Q}=g.chunkIndex;return`${A}:${I}:${B}:${Q}`}function Oi(g){const A=new Map;for(const I of g){const B=Pi(I);let Q=A.get(B);Q||(Q=[],A.set(B,Q)),Q.push(I)}return A}function Vi(g){return[`lod${g.lod}`,`shape${g.shape.x}x${g.shape.y}x${g.shape.z}`,`align${g.rowAlignmentBytes}`].join(":")}class Xi extends EI{type="ImageLayer";source_;region_;lod_;onPickValue_;initialChannelProps_;channelChangeCallbacks_=[];channelProps_;image_;chunk_;extent_;pointerDownPos_=null;constructor({source:A,region:I,channelProps:B,onPickValue:Q,lod:C,...E}){super(E),this.setState("initialized"),this.source_=A,this.region_=I,this.channelProps_=B,this.initialChannelProps_=B,this.onPickValue_=Q,this.lod_=C}update(){switch(this.state){case"initialized":this.load(this.region_);break;case"loading":case"ready":break;default:{const A=this.state;throw new Error(`Unhandled LayerState case: ${A}`)}}}onEvent(A){this.pointerDownPos_=_B(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.onPickValue_)}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.image_?.setChannelProps(A),this.channelChangeCallbacks_.forEach(I=>{I()})}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}async load(A){if(this.state!=="initialized")throw new Error("Trying to load chunks more than once.");this.setState("loading");const I=await this.source_.open(),B=this.lod_??I.getSourceDimensionMap().numLods-1,Q=await I.loadRegion(A,B);this.extent_={x:Q.shape.x*Q.scale.x,y:Q.shape.y*Q.scale.y},this.image_=this.createImage(Q),this.chunk_=Q,this.addObject(this.image_),this.setState("ready")}get extent(){return this.extent_}createImage(A){const I=new zB(A.shape.x,A.shape.y,$I.createWithChunk(A),this.channelProps);return I.transform.setScale([A.scale.x,A.scale.y,1]),I.transform.setTranslation([A.offset.x,A.offset.y,0]),I}getValueAtWorld(A){if(!this.image_||!this.chunk_?.data)return null;const I=QB(aA(),A,this.image_.transform.inverse),B=Math.floor(I[0]),Q=Math.floor(I[1]);if(B>=0&&B<this.chunk_.shape.x&&Q>=0&&Q<this.chunk_.shape.y){const C=Q*this.chunk_.shape.x+B;return this.chunk_.data[C]}return null}}class Jg extends vB{data_;width_;height_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=_I(A),this.data_=A,this.width_=I,this.height_=B}set data(A){this.data_=A,this.needsUpdate=!0}get type(){return"Texture2D"}get data(){return this.data_}get width(){return this.width_}get height(){return this.height_}updateWithChunk(A,I){const B=I??A.data;if(!B)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data!==B){if(this.width!=A.shape.x||this.height!=A.shape.y||this.dataType!=_I(B))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=B}}static createWithChunk(A,I){const B=I??A.data;if(!B)throw new Error("Unable to create texture, chunk data is not initialized.");const Q=new Jg(B,A.shape.x,A.shape.y);return Q.unpackAlignment=A.rowAlignmentBytes,Q}}const vi=[[1,.5,.5],[.5,1,.5],[.5,.5,1],[.5,1,1],[1,.5,1],[1,1,.5]];function ji(g){return g=g??new Map,new Map(Array.from(g.entries()).map(([A,I])=>[A,QA.from(I)]))}function zi(g){return g=g??vi,g.map(QA.from)}class iC{lookupTable;cycle;constructor(A={}){this.lookupTable=ji(A.lookupTable),this.cycle=zi(A.cycle)}}const _i=new Set(["unsigned_byte","unsigned_short","unsigned_int"]);function $i(g){if(g.dataFormat!=="scalar")throw new Error(`Image data format must be scalar, instead found: ${g.dataFormat}`);if(!_i.has(g.dataType))throw new Error(`Image data type must be unsigned, instead found: ${g.dataType}`);return g}class Ao extends zI{outlineSelected_;selectedValue_;constructor(A){super(),this.geometry=new gC(A.width,A.height,1,1),this.setTexture(0,$i(A.imageData));const I=this.makeColorCycleTexture(A.colorMap.cycle);this.setTexture(1,I);const B=this.makeColorLookupTableTexture(A.colorMap.lookupTable);this.setTexture(2,B),this.outlineSelected_=A.outlineSelected??!1,this.selectedValue_=A.selectedValue??null,this.programName="labelImage"}get type(){return"LabelImageRenderable"}getUniforms(){return{ImageSampler:0,ColorCycleSampler:1,ColorLookupTableSampler:2,u_outlineSelected:this.outlineSelected_?1:0,u_selectedValue:this.selectedValue_??-1}}setColorMap(A){this.setTexture(1,this.makeColorCycleTexture(A.cycle)),this.setTexture(2,this.makeColorLookupTableTexture(A.lookupTable))}setSelectedValue(A){this.selectedValue_=A}makeColorCycleTexture(A){const I=new Uint8Array(A.flatMap(Q=>Q.rgba).map(Q=>Math.round(Q*255))),B=new Jg(I,A.length,1);return B.dataFormat="rgba",B}makeColorLookupTableTexture(A){A===void 0?A=new Map([[0,QA.TRANSPARENT]]):A.has(0)||(A=new Map([[0,QA.TRANSPARENT],...A]));const I=Array.from(A.keys()),B=Array.from(A.values()).map(E=>E.packed),Q=A.size,C=new Uint32Array(Q*2);return C.set(I,0),C.set(B,Q),new Jg(C,Q,2)}}class Io extends EI{type="LabelImageLayer";source_;region_;lod_;colorMap_;onPickValue_;outlineSelected_;image_;imageChunk_;pointerDownPos_=null;selectedValue_=null;constructor({source:A,region:I,colorMap:B={},onPickValue:Q,lod:C,outlineSelected:E=!1,...i}){super(i),this.setState("initialized"),this.source_=A,this.region_=I,this.colorMap_=new iC(B),this.onPickValue_=Q,this.lod_=C,this.outlineSelected_=E}update(){switch(this.state){case"initialized":this.load(this.region_);break;case"loading":case"ready":break;default:{const A=this.state;throw new Error(`Unhandled LayerState case: ${A}`)}}}get colorMap(){return this.colorMap_}setColorMap(A){this.colorMap_=new iC(A),this.image_&&this.image_.setColorMap(this.colorMap_)}setSelectedValue(A){this.selectedValue_=A,this.image_&&this.image_.setSelectedValue(this.selectedValue_)}onEvent(A){this.pointerDownPos_=_B(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.outlineSelected_?I=>{this.setSelectedValue(I.value),this.onPickValue_?.(I)}:this.onPickValue_)}async load(A){if(this.state!=="initialized")throw new Error("Trying to load chunks more than once.");this.setState("loading");const I=await this.source_.open(),B=this.lod_??I.getSourceDimensionMap().numLods-1,Q=await I.loadRegion(A,B);this.image_=this.createImage(Q),this.addObject(this.image_),this.setState("ready")}createImage(A){this.imageChunk_=A;const I=new Ao({width:A.shape.x,height:A.shape.y,imageData:Jg.createWithChunk(A),colorMap:this.colorMap_,outlineSelected:this.outlineSelected_,selectedValue:this.selectedValue_});return I.transform.setScale([A.scale.x,A.scale.y,1]),I.transform.setTranslation([A.offset.x,A.offset.y,0]),I}getValueAtWorld(A){if(!this.image_||!this.imageChunk_?.data)return null;const I=QB(aA(),A,this.image_.transform.inverse),B=Math.floor(I[0]),Q=Math.floor(I[1]);if(B<0||B>=this.imageChunk_.shape.x||Q<0||Q>=this.imageChunk_.shape.y)return null;const C=Q*this.imageChunk_.shape.x+B;return this.imageChunk_.data[C]}}class DB extends Error{constructor(A){super(A),this.name="AbortError",Object.setPrototypeOf(this,DB.prototype)}}class go{maxConcurrent_;pending_=[];abortController_=new AbortController;numRunning_=0;constructor(A){if(A<=0)throw Error(`maxConcurrent (${A}) must be positive`);this.maxConcurrent_=A}async submit(A){return this.abortController_.signal.throwIfAborted(),new Promise((I,B)=>{const Q=async()=>{try{this.abortController_.signal.throwIfAborted();const C=await A();I(C)}catch(C){B(C)}finally{this.numRunning_--,this.maybeRunNext()}};this.pending_.push(Q),this.maybeRunNext()})}maybeRunNext(){if(this.numRunning_>=this.maxConcurrent_)return;const A=this.pending_.shift();A!==void 0&&(this.numRunning_++,A())}get abortSignal(){return this.abortController_.signal}shutdown(){this.abortController_.abort(new DB("shutdown"))}get numRunning(){return this.numRunning_}get numPending(){return this.pending_.length}}class Bo{source_;region_;seriesDimensionName_;seriesIndex_;scheduler_=new go(16);lod_;loader_=null;seriesAttributes_;loadingToken_=null;dataChunks_=[];constructor(A){this.source_=A.source,this.region_=A.region,this.lod_=A.lod,this.seriesDimensionName_=A.seriesDimensionName;const I=A.region.find(B=>B.dimension==A.seriesDimensionName);if(I===void 0)throw new Error(`Series dimension '${A.seriesDimensionName}' not in region ${JSON.stringify(A.region)}`);if(I.index.type==="point")throw new Error("Series dimension index in region must be an interval or 'full', not a point value");this.seriesIndex_=I.index}async setPosition(A){const I=await this.loadSeriesAttributes(),B=Math.round((A-I.start)/I.scale);return await this.setIndex(B)}async setIndex(A){const I=this.loadingToken_;if(I){if(I.index===A&&!I.canceled)return V.debug("ImageSeriesLoader","Ignoring duplicate active setIndex request"),{success:!1,reason:"duplicate"};V.debug("ImageSeriesLoader",`Cancelling setIndex request for index ${I.index}, new requested index is ${A}`),I.canceled=!0}let B=this.dataChunks_[A];if(B===void 0){const Q={canceled:!1,index:A};if(this.loadingToken_=Q,B=await this.loadChunkAtIndex(A,Q),Q.canceled)return{success:!1,reason:"canceled"}}return{success:!0,chunk:B}}shutdown(){this.scheduler_.shutdown()}async loadSeriesAttributes(){if(this.seriesAttributes_)return this.seriesAttributes_;const I=(await this.getLoader()).getSourceDimensionMap(),B=this.lod_??I.numLods-1,Q=[I.x,I.y,I.z,I.c,I.t].filter(c=>c!==void 0),C=Q.find(c=>c.name===this.seriesDimensionName_);if(!C){const c=Q.map(r=>r.name).join(", ");throw new Error(`Series dimension "${this.seriesDimensionName_}" not found in loader dimensions: ${c}`)}const E=C.lods[B].scale,i=C.lods[B].size*E,D=this.seriesIndex_.type==="full",s=D?0:this.seriesIndex_.start,h=D?i:this.seriesIndex_.stop,k=Math.round((h-s)/E);return this.dataChunks_=new Array(k),this.seriesAttributes_={start:s,stop:h,scale:E,length:k},this.seriesAttributes_}async loadChunkAtIndex(A,I){const B=await this.loadSeriesAttributes();if(A<0||A>=B.length)throw new Error(`Requested index ${A} is out of bounds [0, ${B.length-1}]`);const Q=B.start+A*B.scale,C=this.region_.filter(s=>s.dimension!==this.seriesDimensionName_);C.push({dimension:this.seriesDimensionName_,index:{type:"point",value:Q}});const E=await this.getLoader(),i=this.lod_??E.getSourceDimensionMap().numLods-1,D=await E.loadRegion(C,i,this.scheduler_);return this.dataChunks_[A]=D,I&&I.canceled&&(this.loadingToken_=null),D}async preloadAllChunks(){const{length:A}=await this.loadSeriesAttributes(),I=[];for(let Q=0;Q<A;Q++)I.push(this.loadChunkAtIndex(Q));const B=await Promise.allSettled(I);for(const Q of B)if(Q.status==="rejected"){if(Q.reason instanceof DB)return Promise.reject(Q.reason);V.error("ImageSeriesLoader",`Error loading slice: ${Q.reason}`)}}async getLoader(){return this.loader_??=await this.source_.open(),this.loader_}}class Qo extends EI{type="ImageSeriesLayer";seriesLoader_;initialChannelProps_;channelChangeCallbacks_=[];channelProps_;texture_=null;image_;extent_;constructor({source:A,region:I,seriesDimensionName:B,channelProps:Q,lod:C,...E}){super(E),this.setState("initialized"),this.channelProps_=Q,this.initialChannelProps_=Q,this.seriesLoader_=new Bo({source:A,region:I,seriesDimensionName:B,lod:C})}update(){this.state==="initialized"&&(this.setState("loading"),this.seriesLoader_.loadSeriesAttributes())}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.image_?.setChannelProps(A),this.channelChangeCallbacks_.forEach(I=>{I()})}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}async setPosition(A){const I=await this.seriesLoader_.setPosition(A);return this.processIndexResult(I)}async setIndex(A){const I=await this.seriesLoader_.setIndex(A);return this.processIndexResult(I)}close(){this.seriesLoader_.shutdown()}async preloadSeries(){return this.seriesLoader_.preloadAllChunks()}get extent(){return this.extent_}processIndexResult(A){return A.chunk&&(this.setData(A.chunk),this.setState("ready")),A}setData(A){!this.texture_||!this.image_?(this.texture_=$I.createWithChunk(A),this.image_=this.createImage(A,this.texture_,this.channelProps_),this.addObject(this.image_),this.extent_={x:A.shape.x*A.scale.x,y:A.shape.y*A.scale.y}):A.data&&this.texture_.updateWithChunk(A)}createImage(A,I,B){const Q=new zB(A.shape.x,A.shape.y,I,B);return Q.transform.setScale([A.scale.x,A.scale.y,1]),Q.transform.setTranslation([A.offset.x,A.offset.y,0]),Q}}function oC(g,A,I,B={}){return A!==void 0&&I!==void 0&&(B={...B,headers:{...B.headers,Range:`bytes=${A}-${A+I-1}`}}),fetch(g,B)}function Co(g,A){return{...g,...A,headers:{...g.headers,...A.headers}}}function DC(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 aC(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}`)}}async function Eo(g,A,I,B){if(B)return fetch(g,{...I,headers:{...I.headers,Range:`bytes=-${A}`}});let Q=await fetch(g,{...I,method:"HEAD"});if(!Q.ok)return Q;let C=Q.headers.get("Content-Length"),E=Number(C);return oC(g,E-A,E,I)}class Ig{url;#A;#I;constructor(A,I={}){this.url=A,this.#A=I.overrides??{},this.#I=I.useSuffixRequest??!1}#g(A){return Co(this.#A,A)}async get(A,I={}){let B=DC(this.url,A).href,Q=await fetch(B,this.#g(I));return aC(Q)}async getRange(A,I,B={}){let Q=DC(this.url,A),C=this.#g(B),E;return"suffixLength"in I?E=await Eo(Q,I.suffixLength,C,this.#I):E=await oC(Q,I.offset,I.length,C),aC(E)}}class sC{#A;constructor(A,I,B){typeof A=="number"?this.#A=new Uint8Array(A):A instanceof ArrayBuffer?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 AQ{_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(I instanceof ArrayBuffer)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 rg{#A;chars;constructor(A,I,B,Q){if(this.chars=A,typeof I=="number")this.#A=new Int32Array(I*A);else if(I instanceof ArrayBuffer)Q&&(Q*=A),this.#A=new Int32Array(I,B,Q);else{const C=I,E=new rg(A,1);this.#A=new Int32Array(function*(){for(let i of C)E.set(0,i),yield*E.#A}())}}get BYTES_PER_ELEMENT(){return this.#A.BYTES_PER_ELEMENT*this.chars}get byteLength(){return this.#A.byteLength}get byteOffset(){return this.#A.byteOffset}get buffer(){return this.#A.buffer}get length(){return this.#A.length/this.chars}get(A){const I=this.chars*A;let 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 Yg(g){const A=new TextDecoder().decode(g);return JSON.parse(A)}function yC(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 hC(g){if(g==="v2:object")return globalThis.Array;let A=g.match(/v2:([US])(\d+)/);if(A){let[,B,Q]=A;return(B==="U"?rg:AQ).bind(null,Number(Q))}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:sC}[g];return LA(I,`Unknown or unsupported data_type: ${g}`),I}function KI(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)),LA(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 io({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 Error(`Unknown chunk key encoding: ${g}`)}function oo(g){if(g==="|O")return{data_type:"v2:object"};let A=g.match(/^([<|>])(.*)$/);LA(A,`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);return LA(Q,`Unsupported or unknown dtype: ${g}`),I==="|"?{data_type:Q}:{data_type:Q,endian:I==="<"?"little":"big"}}function Do(g,A={}){let I=[],B=oo(g.dtype);g.order==="F"&&I.push({name:"transpose",configuration:{order:"F"}}),"endian"in B&&B.endian==="big"&&I.push({name:"bytes",configuration:{endian:"big"}});for(let{id:Q,...C}of g.filters??[])I.push({name:Q,configuration:C});if(g.compressor){let{id:Q,...C}=g.compressor;I.push({name:Q,configuration:C})}return{zarr_format:3,node_type:"array",shape:g.shape,data_type:B.data_type,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,attributes:A}}function ao(g,A={}){return{zarr_format:3,node_type:"group",attributes:A}}function so(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");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 yo(g){return g?.name==="sharding_indexed"}function GC(g){return(g.data_type==="uint64"||g.data_type==="int64")&&g.fill_value!=null?BigInt(g.fill_value):g.fill_value}function FC(g,...A){if(!A.some(I=>g instanceof I))throw g}function LA(g,A=""){if(!g)throw new Error(A)}async function wC(g,{format:A,signal:I}){const B=g instanceof Response?g:new Response(g);LA(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}`)}}class IQ{kind="array_to_array";constructor(A,I){LA(A.keepbits>=0,"keepbits must be zero or positive")}static fromConfig(A,I){return new IQ(A,I)}encode(A){throw new Error("`BitroundCodec.encode` is not implemented. Please open an issue at https://github.com/manzt/zarrita.js/issues.")}decode(A){return A}}const SC=ho();function ho(){const g=new Uint32Array([305419896]);return new Uint8Array(g.buffer,g.byteOffset,g.byteLength)[0]!==18}function RC(g){return"BYTES_PER_ELEMENT"in g?g.BYTES_PER_ELEMENT:4}class aB{kind="array_to_bytes";#A;#I;#g;#Q;#B;constructor(A,I){this.#B=A?.endian,this.#I=hC(I.data_type),this.#Q=I.shape,this.#A=KI(I.shape,"C");const B=new this.#I(0);this.#g=B.BYTES_PER_ELEMENT}static fromConfig(A,I){return new aB(A,I)}encode(A){let I=new Uint8Array(A.data.buffer);return SC&&this.#B==="big"&&yC(I,RC(this.#I)),I}decode(A){return SC&&this.#B==="big"&&yC(A,RC(this.#I)),{data:new this.#I(A.buffer,A.byteOffset,A.byteLength/this.#g),shape:this.#Q,stride:this.#A}}}class gQ{kind="bytes_to_bytes";static fromConfig(){return new gQ}encode(A){throw new Error("Not implemented")}decode(A){return new Uint8Array(A.buffer,A.byteOffset,A.byteLength-4)}}class BQ{kind="bytes_to_bytes";static fromConfig(A){return new BQ}encode(A){throw new Error("Gzip encoding is not enabled by default. Please register a custom codec with `numcodecs/gzip`.")}async decode(A){const I=await wC(A,{format:"gzip"});return new Uint8Array(I)}}function Go(g,A){return LA(!Number.isNaN(A),"JsonCodec allow_nan is false but NaN was encountered during encoding."),LA(A!==Number.POSITIVE_INFINITY,"JsonCodec allow_nan is false but Infinity was encountered during encoding."),LA(A!==Number.NEGATIVE_INFINITY,"JsonCodec allow_nan is false but -Infinity was encountered during encoding."),A}function Fo(g,A){return A instanceof Object&&!Array.isArray(A)?Object.keys(A).sort().reduce((I,B)=>(I[B]=A[B],I),{}):A}class QQ{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:s=!0}=A;let h=A.separators;h||(D?h=[", ",": "]:h=[",",":"]),this.#A={encoding:I,skipkeys:B,ensure_ascii:Q,check_circular:C,allow_nan:E,indent:D,separators:h,sort_keys:i},this.#I={strict:s}}static fromConfig(A){return new QQ(A)}encode(A){const{indent:I,encoding:B,ensure_ascii:Q,check_circular:C,allow_nan:E,sort_keys:i}=this.#A;LA(B==="utf-8","JsonCodec does not yet support non-utf-8 encoding.");const D=[];LA(C,"JsonCodec does not yet support skipping the check for circular references during encoding."),E||D.push(Go),i&&D.push(Fo);const s=Array.from(A.data);s.push("|O"),s.push(A.shape);let h;D.length&&(h=(c,r)=>{let n=r;for(let H of D)n=H(c,n);return n});let k=JSON.stringify(s,h,I);return Q&&(k=k.replace(/[\u007F-\uFFFF]/g,c=>{const r=`0000${c.charCodeAt(0).toString(16)}`;return`\\u${r.substring(r.length-4)}`})),new TextEncoder().encode(k)}decode(A){const{strict:I}=this.#I;LA(I,"JsonCodec does not yet support non-strict decoding.");const B=Yg(A),Q=B.pop();B.pop(),LA(Q,"0D not implemented for JsonCodec.");const C=KI(Q,"C");return{data:B,shape:Q,stride:C}}}function NC(g){return g instanceof sC||g instanceof AQ||g instanceof rg?new Proxy(g,{get(I,B){return I.get(Number(B))},set(I,B,Q){return I.set(Number(B),Q),!0}}):g}function wo(g,A){let I;return g.data instanceof AQ||g.data instanceof rg?I=new g.constructor(g.data.length,g.data.chars):I=new g.constructor(g.data.length),{data:I,shape:g.shape,stride:KI(g.shape,A)}}function So(g,A){let I=wo(g,A),B=g.shape.length,Q=g.data.length,C=Array(B).fill(0),E=NC(g.data),i=NC(I.data);for(let D=0;D<Q;D++){let s=0;for(let h=0;h<B;h++)s+=C[h]*I.stride[h];i[s]=E[D],C[0]+=1;for(let h=0;h<B;h++)if(C[h]===g.shape[h]){if(h+1===B)break;C[h]=0,C[h+1]+=1}}return I}function Ro(g){let A=g.shape.length;return LA(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 No(g,A){let I=Ro(g);return LA(I.length===A.length,"Orders must match"),I.every((B,Q)=>B===A[Q])}class CQ{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)=>{LA(E[i]===void 0,`Invalid permutation: ${JSON.stringify(B)}`),E[i]=D});this.#A=C,this.#I=E}static fromConfig(A,I){return new CQ(A,I)}encode(A){return No(A,this.#I)?A:So(A,this.#I)}decode(A){return{data:A.data,shape:A.shape,stride:KI(A.shape,this.#A)}}}class EQ{kind="array_to_bytes";#A;#I;constructor(A){this.#A=A,this.#I=KI(A,"C")}static fromConfig(A,I){return new EQ(I.shape)}encode(A){throw new Error("Method not implemented.")}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 iQ{kind="bytes_to_bytes";static fromConfig(A){return new iQ}encode(A){throw new Error("Zlib encoding is not enabled by default. Please register a codec with `numcodecs/zlib`.")}async decode(A){const I=await wC(A,{format:"deflate"});return new Uint8Array(I)}}function Uo(){return new Map().set("blosc",()=>Promise.resolve().then(()=>Pa).then(g=>g.default)).set("lz4",()=>Promise.resolve().then(()=>za).then(g=>g.default)).set("zstd",()=>Promise.resolve().then(()=>Bs).then(g=>g.default)).set("gzip",()=>BQ).set("zlib",()=>iQ).set("transpose",()=>CQ).set("bytes",()=>aB).set("crc32c",()=>gQ).set("vlen-utf8",()=>EQ).set("json2",()=>QQ).set("bitround",()=>IQ)}const to=Uo();function oQ(g){let A;return{async encode(I){A||(A=await UC(g));for(const Q of A.array_to_array)I=await Q.encode(I);let B=await A.array_to_bytes.encode(I);for(const Q of A.bytes_to_bytes)B=await Q.encode(B);return B},async decode(I){A||(A=await UC(g));for(let Q=A.bytes_to_bytes.length-1;Q>=0;Q--)I=await A.bytes_to_bytes[Q].decode(I);let B=await A.array_to_bytes.decode(I);for(let Q=A.array_to_array.length-1;Q>=0;Q--)B=await A.array_to_array[Q].decode(B);return B}}}async function UC(g){let A=g.codecs.map(async C=>{let E=await to.get(C.name)?.();return LA(E,`Unknown codec: ${C.name}`),{Codec:E,meta:C}}),I=[],B,Q=[];for await(let{Codec:C,meta:E}of A){let i=C.fromConfig(E.configuration,g);switch(i.kind){case"array_to_array":I.push(i);break;case"array_to_bytes":B=i;break;default:Q.push(i)}}return B||(LA(ko(g),`Cannot encode ${g.data_type} to bytes without a codec`),B=aB.fromConfig({endian:"little"},g)),{array_to_array:I,array_to_bytes:B,bytes_to_bytes:Q}}function ko(g){return g.data_type!=="v2:object"}class ng extends Error{constructor(A,I={}){super(`Node not found: ${A}`,I),this.name="NodeNotFoundError"}}class DQ extends Error{constructor(A){super(`Missing key: ${A}`),this.name="KeyError"}}const tC=18446744073709551615n;function co(g,A,I,B){LA(g.store.getRange,"Store does not support range requests");let Q=g.store.getRange.bind(g.store),C=A.map((D,s)=>D/B.chunk_shape[s]),E=oQ({data_type:"uint64",shape:[...C,2],codecs:B.index_codecs}),i={};return async D=>{let s=D.map((x,T)=>Math.floor(x/C[T])),h=g.resolve(I(s)).path,k;if(h in i)k=i[h];else{let x=4,T=16*C.reduce((u,Z)=>u*Z,1),X=await Q(h,{suffixLength:T+x});k=i[h]=X?await E.decode(X):null}if(k===null)return;let{data:c,shape:r,stride:n}=k,H=D.map((x,T)=>x%r[T]).reduce((x,T,X)=>x+T*n[X],0),M=c[H],q=c[H+1];if(!(M===tC&&q===tC))return Q(h,{offset:Number(M),length:Number(q)})}}class mA{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 mA(this.store,decodeURIComponent(new URL(A,I).pathname))}}class aQ extends mA{kind="group";#A;constructor(A,I,B){super(A,I),this.#A=B}get attrs(){return this.#A.attributes}}function kC(g){return g.find(I=>I.name==="transpose")?.configuration?.order??"C"}const Kg=Symbol("zarrita.context");function Lo(g){return g[Kg]}function Jo(g,A){let{configuration:I}=A.codecs.find(yo)??{},B={encode_chunk_key:io(A.chunk_key_encoding),TypedArray:hC(A.data_type),fill_value:A.fill_value};if(I){let C=kC(I.codecs);return{...B,kind:"sharded",chunk_shape:I.chunk_shape,codec:oQ({data_type:A.data_type,shape:I.chunk_shape,codecs:I.codecs}),get_strides(E){return KI(E,C)},get_chunk_bytes:co(g,A.chunk_grid.configuration.chunk_shape,B.encode_chunk_key,I)}}let Q=kC(A.codecs);return{...B,kind:"regular",chunk_shape:A.chunk_grid.configuration.chunk_shape,codec:oQ({data_type:A.data_type,shape:A.chunk_grid.configuration.chunk_shape,codecs:A.codecs}),get_strides(C){return KI(C,Q)},async get_chunk_bytes(C,E){let i=B.encode_chunk_key(C),D=g.resolve(i).path;return g.store.get(D,E)}}}let sB=class extends mA{kind="array";#A;[Kg];constructor(A,I,B){super(A,I),this.#A={...B,fill_value:GC(B)},this[Kg]=Jo(this,B)}get attrs(){return this.#A.attributes}get shape(){return this.#A.shape}get chunks(){return this[Kg].chunk_shape}get dtype(){return this.#A.data_type}async getChunk(A,I){let B=this[Kg],Q=await B.get_chunk_bytes(A,I);if(!Q){let C=B.chunk_shape.reduce((i,D)=>i*D,1),E=new B.TypedArray(C);return E.fill(B.fill_value),{data:E,shape:B.chunk_shape,stride:B.get_strides(B.chunk_shape)}}return B.codec.decode(Q)}is(A){return so(this.dtype,A)}};function*ro(g,A,I=1){A===void 0&&(A=g,g=0);for(let B=g;B<A;B+=I)yield B}function*Yo(...g){if(g.length===0)return;const A=g.map(B=>B[Symbol.iterator]()),I=A.map(B=>B.next());if(I.some(B=>B.done))throw new Error("Input contains an empty iterator.");for(let B=0;;){if(I[B].done){if(A[B]=g[B][Symbol.iterator](),I[B]=A[B].next(),++B>=A.length)return}else yield I.map(({value:Q})=>Q),B=0;I[B]=A[B].next()}}function no({start:g,stop:A,step:I},B){if(I===0)throw new Error("slice step cannot be zero");I=I??1;const Q=I<0,[C,E]=Q?[-1,B-1]:[0,B];return g===null?g=Q?E:C:g<0?(g+=B,g<C&&(g=C)):g>E&&(g=E),A===null?A=Q?C:E:A<0?(A+=B,A<C&&(A=C)):A>E&&(A=E),[g,A,I]}function yB(g,A,I=null){return A===void 0&&(A=g,g=null),{start:g,stop:A,step:I}}function Ko(){const g=[];return{add:A=>g.push(A()),onIdle:()=>Promise.all(g)}}class sQ extends Error{constructor(A){super(A),this.name="IndexError"}}function Mo(g,A){throw new sQ(`too many indicies for array; expected ${A.length}, got ${g.length}`)}function eo(g){throw new sQ(`index out of bounds for dimension with length ${g}`)}function Ho(){throw new sQ("only slices with step >= 1 are supported")}function qo(g,A){g.length>A.length&&Mo(g,A)}function fo(g,A){return g=Math.trunc(g),g<0&&(g=A+g),(g>=A||g<0)&&eo(A),g}class lo{dim_sel;dim_len;dim_chunk_len;nitems;constructor({dim_sel:A,dim_len:I,dim_chunk_len:B}){A=fo(A,I),this.dim_sel=A,this.dim_len=I,this.dim_chunk_len=B,this.nitems=1}*[Symbol.iterator](){const A=Math.floor(this.dim_sel/this.dim_chunk_len),I=A*this.dim_chunk_len,B=this.dim_sel-I;yield{dim_chunk_ix:A,dim_chunk_sel:B}}}class cC{start;stop;step;dim_len;dim_chunk_len;nitems;nchunks;constructor({dim_sel:A,dim_len:I,dim_chunk_len:B}){const[Q,C,E]=no(A,I);this.start=Q,this.stop=C,this.step=E,this.step<1&&Ho(),this.dim_len=I,this.dim_chunk_len=B,this.nitems=Math.max(0,Math.ceil((this.stop-this.start)/this.step)),this.nchunks=Math.ceil(this.dim_len/this.dim_chunk_len)}*[Symbol.iterator](){const A=Math.floor(this.start/this.dim_chunk_len),I=Math.ceil(this.stop/this.dim_chunk_len);for(const B of ro(A,I)){const Q=B*this.dim_chunk_len,C=Math.min(this.dim_len,(B+1)*this.dim_chunk_len),E=C-Q;let i=0,D=0;if(this.start<Q){const r=(Q-this.start)%this.step;r&&(D+=this.step-r),i=Math.ceil((Q-this.start)/this.step)}else D=this.start-Q;const s=this.stop>C?E:this.stop-Q,h=[D,s,this.step],k=Math.ceil((s-D)/this.step),c=[i,i+k,1];yield{dim_chunk_ix:B,dim_chunk_sel:h,dim_out_sel:c}}}}function po(g,A){let I=[];return g===null?I=A.map(B=>yB(null)):Array.isArray(g)&&(I=g.map(B=>B??yB(null))),qo(I,A),I}class Wo{dim_indexers;shape;constructor({selection:A,shape:I,chunk_shape:B}){this.dim_indexers=po(A,I).map((Q,C)=>new(typeof Q=="number"?lo:cC)({dim_sel:Q,dim_len:I[C],dim_chunk_len:B[C]})),this.shape=this.dim_indexers.filter(Q=>Q instanceof cC).map(Q=>Q.nitems)}*[Symbol.iterator](){for(const A of Yo(...this.dim_indexers)){const I=A.map(Q=>Q.dim_chunk_ix),B=A.map(Q=>"dim_out_sel"in Q?{from:Q.dim_chunk_sel,to:Q.dim_out_sel}:{from:Q.dim_chunk_sel,to:null});yield{chunk_coords:I,mapping:B}}}}function mo(g,A){return"get"in g?g.get(A):g[A]}async function To(g,A,I,B){let Q=Lo(g),C=new Wo({selection:A,shape:g.shape,chunk_shape:g.chunks}),E=B.prepare(new Q.TypedArray(C.shape.reduce((D,s)=>D*s,1)),C.shape,Q.get_strides(C.shape)),i=I.create_queue?.()??Ko();for(const{chunk_coords:D,mapping:s}of C)i.add(async()=>{let{data:h,shape:k,stride:c}=await g.getChunk(D,I.opts),r=B.prepare(h,k,c);B.set_from_chunk(E,r,s)});return await i.onIdle(),C.shape.length===0?mo(E.data,0):E}function yQ(g,A=0,I){let B=I??g.length-A;return{length:B,subarray(Q,C=B){return yQ(g,A+Q,C-Q)},set(Q,C=0){for(let E=0;E<Q.length;E++)g[A+C+E]=Q.get(E)},get(Q){return g[A+Q]}}}function hQ(g){return globalThis.Array.isArray(g.data)?{data:yQ(g.data),stride:g.stride,bytes_per_element:1}:{data:new Uint8Array(g.data.buffer,g.data.byteOffset,g.data.byteLength),stride:g.stride,bytes_per_element:g.data.BYTES_PER_ELEMENT}}function xo(g){return"chars"in g?g.constructor.bind(null,g.chars):g.constructor}function Zo(g,A){if(globalThis.Array.isArray(g.data))return yQ([A]);let I=xo(g.data),B=new I([A]);return new Uint8Array(B.buffer,B.byteOffset,B.byteLength)}const bo={prepare(g,A,I){return{data:g,shape:A,stride:I}},set_scalar(g,A,I){let B=hQ(g);GQ(B,A,Zo(g,I),B.bytes_per_element)},set_from_chunk(g,A,I){let B=hQ(g);hB(B,hQ(A),B.bytes_per_element,I)}};async function uo(g,A=null,I={}){return To(g,A,I,bo)}function LC(g,A,I){return I<0&&A<g?Math.floor((g-A-1)/-I)+1:g<A?Math.floor((A-g-1)/I)+1:0}function GQ(g,A,I,B){if(A.length===0){g.data.set(I,0);return}const[Q,...C]=A,[E,...i]=g.stride;if(typeof Q=="number"){const c=g.data.subarray(E*Q*B);GQ({data:c,stride:i},C,I,B);return}const[D,s,h]=Q,k=LC(D,s,h);if(C.length===0){for(let c=0;c<k;c++)g.data.set(I,E*(D+h*c)*B);return}for(let c=0;c<k;c++){const r=g.data.subarray(E*(D+h*c)*B);GQ({data:r,stride:i},C,I,B)}}function hB(g,A,I,B){const[Q,...C]=B,[E,...i]=g.stride,[D,...s]=A.stride;if(Q.from===null){if(C.length===0){g.data.set(A.data.subarray(0,I),Q.to*I);return}hB({data:g.data.subarray(E*Q.to*I),stride:i},A,I,C);return}if(Q.to===null){if(C.length===0){let q=Q.from*I;g.data.set(A.data.subarray(q,q+I),0);return}hB(g,{data:A.data.subarray(D*Q.from*I),stride:s},I,C);return}const[h,k,c]=Q.to,[r,n,H]=Q.from,M=LC(h,k,c);if(C.length===0){if(c===1&&H===1&&E===1&&D===1){let q=r*I,x=M*I;g.data.set(A.data.subarray(q,q+x),h*I);return}for(let q=0;q<M;q++){let x=D*(r+H*q)*I;g.data.set(A.data.subarray(x,x+I),E*(h+c*q)*I)}return}for(let q=0;q<M;q++)hB({data:g.data.subarray(E*(h+q*c)*I),stride:i},{data:A.data.subarray(D*(r+q*H)*I),stride:s},I,C)}let GB=Po();function Po(){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},version_max(I){let B=A(I);return B.v3>B.v2?"v3":"v2"}}}async function Oo(g){let A=await g.store.get(g.resolve(".zattrs").path);return A?Yg(A):{}}async function Vo(g,A={}){let I="store"in g?g:new mA(g),B={};return(A.attrs??!0)&&(B=await Oo(I)),A.kind==="array"?JC(I,B):A.kind==="group"?rC(I,B):JC(I,B).catch(Q=>(FC(Q,ng),rC(I,B)))}async function JC(g,A){let{path:I}=g.resolve(".zarray"),B=await g.store.get(I);if(!B)throw new ng("v2 array",{cause:new DQ(I)});return GB.increment(g.store,"v2"),new sB(g.store,g.path,Do(Yg(B),A))}async function rC(g,A){let{path:I}=g.resolve(".zgroup"),B=await g.store.get(I);if(!B)throw new ng("v2 group",{cause:new DQ(I)});return GB.increment(g.store,"v2"),new aQ(g.store,g.path,ao(Yg(B),A))}async function Xo(g){let{store:A,path:I}=g.resolve("zarr.json"),B=await g.store.get(I);if(!B)throw new ng("v3 array or group",{cause:new DQ(I)});let Q=Yg(B);return Q.node_type==="array"&&(Q.fill_value=GC(Q)),Q.node_type==="array"?new sB(A,g.path,Q):new aQ(A,g.path,Q)}async function vo(g,A={}){let I="store"in g?g:new mA(g),B=await Xo(I);if(GB.increment(I.store,"v3"),A.kind===void 0||A.kind==="array"&&B instanceof sB||A.kind==="group"&&B instanceof aQ)return B;let Q=B instanceof sB?"array":"group";throw new Error(`Expected node of kind ${A.kind}, found ${Q}.`)}async function VA(g,A={}){let I="store"in g?g.store:g,B=GB.version_max(I),Q=B==="v2"?VA.v2:VA.v3,C=B==="v2"?VA.v3:VA.v2;return Q(g,A).catch(E=>(FC(E,ng),C(g,A)))}VA.v2=Vo,VA.v3=vo;async function jo(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 FQ{#A;constructor(A){this.#A=A}get directoryHandle(){return this.#A}async get(A){const I=await jo(this.#A,A.slice(1)).catch(()=>{});if(!I)return;const Q=await(await I.getFile()).arrayBuffer();return new Uint8Array(Q)}}function zo(){if(typeof window>"u")return;const g=window.location.hostname;if(!(g==="localhost"||g==="127.0.0.1"||g==="0.0.0.0"||g.startsWith("127."))){const I="S3FetchStore is only allowed in local development environments. ";throw new Error(I)}}class wQ extends Ig{credentials;region;signingKeyCache_=new Map;overrides;useSuffixRequest;constructor(A){zo(),super(A.url,{overrides:A.overrides,useSuffixRequest:A.useSuffixRequest}),this.credentials=A.credentials,this.region=A.region,this.overrides=A.overrides,this.useSuffixRequest=A.useSuffixRequest}async get(A,I){if(this.credentials&&this.region){const Q=`${this.url.toString().replace(/\/$/,"")}${A}`,C=await this.generateAuthHeaders(Q,"GET"),E={...I,headers:{...I?.headers,...C}};return super.get(A,E)}return super.get(A,I)}async getRange(A,I,B){if(this.credentials&&this.region){const C=`${this.url.toString().replace(/\/$/,"")}${A}`,E=await this.generateAuthHeaders(C,"HEAD"),i=await this.generateAuthHeaders(C,"GET"),D=globalThis.fetch,s=async(k,c)=>{const n=(c?.method||"GET")==="HEAD"?E:i,H={...c,headers:{...c?.headers,...n}};return D(k,H)},h=globalThis.fetch;globalThis.fetch=s;try{return await super.getRange(A,I,B)}finally{globalThis.fetch=h}}return super.getRange(A,I,B)}async generateAuthHeaders(A,I="GET"){if(!this.credentials||!this.region)return{};const{accessKeyId:B,secretAccessKey:Q,sessionToken:C}=this.credentials,E=this.region,i="s3",D=this.getAmzDate(),s=D.slice(0,8),h=new URL(A),k=h.host,c=h.pathname,r=h.search.slice(1),n=`host:${k}
460
+ ${Q}`;return g.replace(MB,C)}const dA=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];function qQ(){const g=Math.random()*4294967295|0,A=Math.random()*4294967295|0,I=Math.random()*4294967295|0,B=Math.random()*4294967295|0;return(dA[g&255]+dA[g>>8&255]+dA[g>>16&255]+dA[g>>24&255]+"-"+dA[A&255]+dA[A>>8&255]+"-"+dA[A>>16&15|64]+dA[A>>24&255]+"-"+dA[I&63|128]+dA[I>>8&255]+"-"+dA[I>>16&255]+dA[I>>24&255]+dA[B&255]+dA[B>>8&255]+dA[B>>16&255]+dA[B>>24&255]).toLowerCase()}class eB{uuid=qQ()}var hA=1e-6,YA=typeof Float32Array<"u"?Float32Array:Array,tE=Math.PI/180;function kE(g){return g*tE}Math.hypot||(Math.hypot=function(){for(var g=0,A=arguments.length;A--;)g+=arguments[A]*arguments[A];return Math.sqrt(g)});function dQ(){var g=new YA(9);return YA!=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 cE(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 bA(){var g=new YA(16);return YA!=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 gB(g,A){var I=A[0],B=A[1],Q=A[2],C=A[3],E=A[4],i=A[5],D=A[6],s=A[7],h=A[8],k=A[9],c=A[10],r=A[11],n=A[12],H=A[13],M=A[14],q=A[15],x=I*i-B*E,T=I*D-Q*E,X=I*s-C*E,u=B*D-Q*i,Z=B*s-C*i,EA=Q*s-C*D,iA=h*H-k*n,BA=h*M-c*n,sA=h*q-r*n,yA=k*M-c*H,KA=k*q-r*H,NA=c*q-r*M,DA=x*NA-T*KA+X*yA+u*sA-Z*BA+EA*iA;return DA?(DA=1/DA,g[0]=(i*NA-D*KA+s*yA)*DA,g[1]=(Q*KA-B*NA-C*yA)*DA,g[2]=(H*EA-M*Z+q*u)*DA,g[3]=(c*Z-k*EA-r*u)*DA,g[4]=(D*sA-E*NA-s*BA)*DA,g[5]=(I*NA-Q*sA+C*BA)*DA,g[6]=(M*X-n*EA-q*T)*DA,g[7]=(h*EA-c*X+r*T)*DA,g[8]=(E*KA-i*sA+s*iA)*DA,g[9]=(B*sA-I*KA-C*iA)*DA,g[10]=(n*Z-H*X+q*x)*DA,g[11]=(k*X-h*Z-r*x)*DA,g[12]=(i*BA-E*yA-D*iA)*DA,g[13]=(I*yA-B*BA+Q*iA)*DA,g[14]=(H*T-n*u-M*x)*DA,g[15]=(h*u-k*T+c*x)*DA,g):null}function tg(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=A[4],D=A[5],s=A[6],h=A[7],k=A[8],c=A[9],r=A[10],n=A[11],H=A[12],M=A[13],q=A[14],x=A[15],T=I[0],X=I[1],u=I[2],Z=I[3];return g[0]=T*B+X*i+u*k+Z*H,g[1]=T*Q+X*D+u*c+Z*M,g[2]=T*C+X*s+u*r+Z*q,g[3]=T*E+X*h+u*n+Z*x,T=I[4],X=I[5],u=I[6],Z=I[7],g[4]=T*B+X*i+u*k+Z*H,g[5]=T*Q+X*D+u*c+Z*M,g[6]=T*C+X*s+u*r+Z*q,g[7]=T*E+X*h+u*n+Z*x,T=I[8],X=I[9],u=I[10],Z=I[11],g[8]=T*B+X*i+u*k+Z*H,g[9]=T*Q+X*D+u*c+Z*M,g[10]=T*C+X*s+u*r+Z*q,g[11]=T*E+X*h+u*n+Z*x,T=I[12],X=I[13],u=I[14],Z=I[15],g[12]=T*B+X*i+u*k+Z*H,g[13]=T*Q+X*D+u*c+Z*M,g[14]=T*C+X*s+u*r+Z*q,g[15]=T*E+X*h+u*n+Z*x,g}function LE(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 JE(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=A[3],D=Q+Q,s=C+C,h=E+E,k=Q*D,c=Q*s,r=Q*h,n=C*s,H=C*h,M=E*h,q=i*D,x=i*s,T=i*h,X=B[0],u=B[1],Z=B[2];return g[0]=(1-(n+M))*X,g[1]=(c+T)*X,g[2]=(r-x)*X,g[3]=0,g[4]=(c-T)*u,g[5]=(1-(k+M))*u,g[6]=(H+q)*u,g[7]=0,g[8]=(r+x)*Z,g[9]=(H-q)*Z,g[10]=(1-(k+n))*Z,g[11]=0,g[12]=I[0],g[13]=I[1],g[14]=I[2],g[15]=1,g}function rE(g,A,I,B,Q){var C=1/Math.tan(A/2),E;return 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?(E=1/(B-Q),g[10]=(Q+B)*E,g[14]=2*Q*B*E):(g[10]=-1,g[14]=-2*B),g}var YE=rE;function nE(g,A,I,B,Q,C,E){var i=1/(A-I),D=1/(B-Q),s=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*s,g[11]=0,g[12]=(A+I)*i,g[13]=(Q+B)*D,g[14]=(E+C)*s,g[15]=1,g}var KE=nE;function ME(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=B[0],D=B[1],s=B[2],h=Q-I[0],k=C-I[1],c=E-I[2],r=h*h+k*k+c*c;r>0&&(r=1/Math.sqrt(r),h*=r,k*=r,c*=r);var n=D*c-s*k,H=s*h-i*c,M=i*k-D*h;return r=n*n+H*H+M*M,r>0&&(r=1/Math.sqrt(r),n*=r,H*=r,M*=r),g[0]=n,g[1]=H,g[2]=M,g[3]=0,g[4]=k*M-c*H,g[5]=c*n-h*M,g[6]=h*H-k*n,g[7]=0,g[8]=h,g[9]=k,g[10]=c,g[11]=0,g[12]=Q,g[13]=C,g[14]=E,g[15]=1,g}function eE(g,A){var I=g[0],B=g[1],Q=g[2],C=g[3],E=g[4],i=g[5],D=g[6],s=g[7],h=g[8],k=g[9],c=g[10],r=g[11],n=g[12],H=g[13],M=g[14],q=g[15],x=A[0],T=A[1],X=A[2],u=A[3],Z=A[4],EA=A[5],iA=A[6],BA=A[7],sA=A[8],yA=A[9],KA=A[10],NA=A[11],DA=A[12],aI=A[13],AI=A[14],sI=A[15];return Math.abs(I-x)<=hA*Math.max(1,Math.abs(I),Math.abs(x))&&Math.abs(B-T)<=hA*Math.max(1,Math.abs(B),Math.abs(T))&&Math.abs(Q-X)<=hA*Math.max(1,Math.abs(Q),Math.abs(X))&&Math.abs(C-u)<=hA*Math.max(1,Math.abs(C),Math.abs(u))&&Math.abs(E-Z)<=hA*Math.max(1,Math.abs(E),Math.abs(Z))&&Math.abs(i-EA)<=hA*Math.max(1,Math.abs(i),Math.abs(EA))&&Math.abs(D-iA)<=hA*Math.max(1,Math.abs(D),Math.abs(iA))&&Math.abs(s-BA)<=hA*Math.max(1,Math.abs(s),Math.abs(BA))&&Math.abs(h-sA)<=hA*Math.max(1,Math.abs(h),Math.abs(sA))&&Math.abs(k-yA)<=hA*Math.max(1,Math.abs(k),Math.abs(yA))&&Math.abs(c-KA)<=hA*Math.max(1,Math.abs(c),Math.abs(KA))&&Math.abs(r-NA)<=hA*Math.max(1,Math.abs(r),Math.abs(NA))&&Math.abs(n-DA)<=hA*Math.max(1,Math.abs(n),Math.abs(DA))&&Math.abs(H-aI)<=hA*Math.max(1,Math.abs(H),Math.abs(aI))&&Math.abs(M-AI)<=hA*Math.max(1,Math.abs(M),Math.abs(AI))&&Math.abs(q-sI)<=hA*Math.max(1,Math.abs(q),Math.abs(sI))}function aA(){var g=new YA(3);return YA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g}function vA(g){var A=new YA(3);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A}function HB(g){var A=g[0],I=g[1],B=g[2];return Math.hypot(A,I,B)}function oA(g,A,I){var B=new YA(3);return B[0]=g,B[1]=A,B[2]=I,B}function OI(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g}function rI(g,A,I,B){return g[0]=A,g[1]=I,g[2]=B,g}function VI(g,A,I){return g[0]=A[0]+I[0],g[1]=A[1]+I[1],g[2]=A[2]+I[2],g}function HE(g,A,I){return g[0]=A[0]-I[0],g[1]=A[1]-I[1],g[2]=A[2]-I[2],g}function qE(g,A,I){return g[0]=A[0]*I[0],g[1]=A[1]*I[1],g[2]=A[2]*I[2],g}function XI(g,A,I){return g[0]=A[0]*I,g[1]=A[1]*I,g[2]=A[2]*I,g}function BB(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 fQ(g,A){var I=A[0]-g[0],B=A[1]-g[1],Q=A[2]-g[2];return Math.hypot(I,B,Q)}function lQ(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 dE(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 pQ(g,A){return g[0]*A[0]+g[1]*A[1]+g[2]*A[2]}function qB(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 fE(g,A,I,B,Q,C){var E=1-C,i=E*E,D=C*C,s=i*E,h=3*C*i,k=3*D*E,c=D*C;return g[0]=A[0]*s+I[0]*h+B[0]*k+Q[0]*c,g[1]=A[1]*s+I[1]*h+B[1]*k+Q[1]*c,g[2]=A[2]*s+I[2]*h+B[2]*k+Q[2]*c,g}function QB(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 lE(g){return g[0]=0,g[1]=0,g[2]=0,g}function WQ(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)<=hA*Math.max(1,Math.abs(I),Math.abs(C))&&Math.abs(B-E)<=hA*Math.max(1,Math.abs(B),Math.abs(E))&&Math.abs(Q-i)<=hA*Math.max(1,Math.abs(Q),Math.abs(i))}var CB=HE,pE=HB;(function(){var g=aA();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 vI(){var g=new YA(4);return YA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0,g[3]=0),g}function WE(g){var A=new YA(4);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A[3]=g[3],A}function EB(g,A,I,B){var Q=new YA(4);return Q[0]=g,Q[1]=A,Q[2]=I,Q[3]=B,Q}function mE(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g[3]=A[3],g}function TE(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 xE(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 kg(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=vI();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 dB(){var g=new YA(4);return YA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g[3]=1,g}function ZE(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 bE(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=I[0],D=I[1],s=I[2],h=I[3];return g[0]=B*h+E*i+Q*s-C*D,g[1]=Q*h+E*D+C*i-B*s,g[2]=C*h+E*s+B*D-Q*i,g[3]=E*h-B*i-Q*D-C*s,g}function fB(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=A[3],D=I[0],s=I[1],h=I[2],k=I[3],c,r,n,H,M;return r=Q*D+C*s+E*h+i*k,r<0&&(r=-r,D=-D,s=-s,h=-h,k=-k),1-r>hA?(c=Math.acos(r),n=Math.sin(c),H=Math.sin((1-B)*c)/n,M=Math.sin(B*c)/n):(H=1-B,M=B),g[0]=H*Q+M*D,g[1]=H*C+M*s,g[2]=H*E+M*h,g[3]=H*i+M*k,g}function mQ(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 uE=WE,PE=mE,lB=xE;(function(){var g=aA(),A=oA(1,0,0),I=oA(0,1,0);return function(B,Q,C){var E=pQ(Q,C);return E<-.999999?(qB(g,A,Q),pE(g)<1e-6&&qB(g,I,Q),dE(g,g),ZE(B,g,Math.PI),B):E>.999999?(B[0]=0,B[1]=0,B[2]=0,B[3]=1,B):(qB(g,Q,C),B[0]=g[0],B[1]=g[1],B[2]=g[2],B[3]=1+E,lB(B,B))}})(),function(){var g=dB(),A=dB();return function(I,B,Q,C,E,i){return fB(g,B,E,i),fB(A,Q,C,i),fB(I,g,A,2*i*(1-i)),I}}(),function(){var g=dQ();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],lB(A,mQ(A,g))}}();function TQ(){var g=new YA(2);return YA!=Float32Array&&(g[0]=0,g[1]=0),g}function xQ(g){var A=new YA(2);return A[0]=g[0],A[1]=g[1],A}function nA(g,A){var I=new YA(2);return I[0]=g,I[1]=A,I}function OE(g,A){var I=A[0]-g[0],B=A[1]-g[1];return Math.hypot(I,B)}function VE(g){var A=g[0],I=g[1];return A*A+I*I}function XE(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 pB(g,A){var I=g[0],B=g[1],Q=A[0],C=A[1];return Math.abs(I-Q)<=hA*Math.max(1,Math.abs(I),Math.abs(Q))&&Math.abs(B-C)<=hA*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 hI{min;max;constructor(A,I){this.min=A?vA(A):oA(1/0,1/0,1/0),this.max=I?vA(I):oA(-1/0,-1/0,-1/0)}clone(){return new hI(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=[oA(I[0],I[1],I[2]),oA(I[0],I[1],B[2]),oA(I[0],B[1],I[2]),oA(I[0],B[1],B[2]),oA(B[0],I[1],I[2]),oA(B[0],I[1],B[2]),oA(B[0],B[1],I[2]),oA(B[0],B[1],B[2])];this.min=oA(1/0,1/0,1/0),this.max=oA(-1/0,-1/0,-1/0);const C=aA();for(const E of Q)QB(C,E,A),this.expandWithPoint(C)}}const vE={position:0,normal:1,uv:2,next_position:3,previous_position:4,direction:5,path_proportion:6,color:7,size:8,marker:9};class jI extends eB{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 hI,Q=aA();for(let C=0;C<this.vertexData_.length;C+=this.stride)Q[0]=this.vertexData_[C+I+0],Q[1]=this.vertexData_[C+I+1],Q[2]=this.vertexData_[C+I+2],B.expandWithPoint(Q);this.boundingBox_=B}return this.boundingBox_}get type(){return"Geometry"}getAttribute(A){return this.attributes_.find(I=>I.type===A)}}class jE{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(h=>{const k=vE[h.type];this.gl_.vertexAttribPointer(k,h.itemSize,this.gl_.FLOAT,!1,i,h.offset),this.gl_.enableVertexAttribArray(k)});const D={vao:I,vbo:C},{indexData:s}=A;if(s.length){const h=this.gl_.ELEMENT_ARRAY_BUFFER,k=this.gl_.createBuffer();if(!k)throw new Error("Failed to create index buffer (EBO)");this.gl_.bindBuffer(h,k),this.gl_.bufferData(h,s,this.gl_.STATIC_DRAW),D.ebo=k}this.buffers_.set(A,D),this.gl_.bindVertexArray(null)}}class zE{gl_;textures_=new Map;currentTexture_=null;maxTextureUnits_;gpuTextureBytes_=0;textureCount_=0;constructor(A){this.gl_=A,this.maxTextureUnits_=A.getParameter(A.MAX_TEXTURE_IMAGE_UNITS)}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}]`);this.gl_.activeTexture(this.gl_.TEXTURE0+I);const B=this.getTextureType(A),Q=this.getDataFormatInfo(A.dataFormat,A.dataType);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),A.needsUpdate&&A.data!==null&&(this.configureTextureParameters(A,B),this.uploadTextureData(A,Q,B),A.needsUpdate=!1),this.currentTexture_=A}disposeTexture(A){const I=this.textures_.get(A);if(I){this.gl_.deleteTexture(I),this.textures_.delete(A),this.currentTexture_===A&&(this.currentTexture_=null);const B=this.getDataFormatInfo(A.dataFormat,A.dataType),Q=this.computeStorageBytes(A,B);this.gpuTextureBytes_=Math.max(0,this.gpuTextureBytes_-Q),this.textureCount_=Math.max(0,this.textureCount_-1)}}disposeAll(){for(const A of Array.from(this.textures_.keys()))this.disposeTexture(A);this.gpuTextureBytes_=0,this.textureCount_=0}get textureInfo(){return{textures:this.textureCount_,totalBytes:this.gpuTextureBytes_}}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_+=this.computeStorageBytes(A,I),this.textureCount_+=1,this.textures_.set(A,Q),this.gl_.bindTexture(B,null)}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 V.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}`)}computeStorageBytes(A,I){const B=this.bytesPerTexel(I),Q=Math.max(1,A.mipmapLevels),C=this.isTextureStorage3D(A)?Math.max(1,A.depth):1;let E=Math.max(1,A.width),i=Math.max(1,A.height),D=0;for(let s=0;s<Q;s++)D+=E*i*C*B,E=Math.max(1,E>>1),i=Math.max(1,i>>1);return D}bytesPerTexel(A){const I=this.gl_;if(A.format===I.RGB&&A.type===I.UNSIGNED_BYTE)return 3;if(A.format===I.RGBA&&A.type===I.UNSIGNED_BYTE)return 4;if(A.format===I.RED_INTEGER)switch(A.type){case I.BYTE:case I.UNSIGNED_BYTE:return 1;case I.SHORT:case I.UNSIGNED_SHORT:return 2;case I.INT:case I.UNSIGNED_INT:return 4}if(A.format===I.RED&&A.type===I.FLOAT)return 4;throw new Error("bytesPerTexel: unsupported format/type")}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 uA{min;max;constructor(A,I){this.min=A?xQ(A):nA(1/0,1/0),this.max=I?xQ(I):nA(-1/0,-1/0)}clone(){return new uA(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 uA(nA(Math.floor(this.min[0]),Math.floor(this.min[1])),nA(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 _E{gl_;enabledCapabilities_=new Map;depthMaskEnabled_=null;blendSrcFactor_=null;blendDstFactor_=null;currentBlendingMode_=null;currentViewport_=null;currentScissor_=null;currentCullingMode_=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_&&uA.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_&&uA.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)}}const $E=LE(bA(),[1,-1,1]);class bQ extends EE{gl_;programs_;bindings_;textures_;state_;renderedObjectsPerFrame_=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,V.info("WebGLRenderer",`WebGL version ${I.getParameter(I.VERSION)}`),this.programs_=new UE(I),this.bindings_=new jE(I),this.textures_=new zE(I),this.state_=new _E(I),this.initStencil(),this.resize(this.canvas.width,this.canvas.height)}render(A){let I=getComputedStyle(A.element).visibility!=="hidden";const B=A.getBoxRelativeTo(this.canvas),Q=new uA(nA(0,0),nA(this.width,this.height));uA.equals(B.floor(),Q.floor())?this.state_.setScissorTest(!1):uA.intersects(B,Q)?(this.state_.setScissor(B),this.state_.setScissorTest(!0)):(V.warn("WebGLRenderer",`Viewport ${A.id} is entirely outside canvas bounds, skipping render`),I=!1),this.state_.setViewport(B),this.renderedObjectsPerFrame_=0,I&&this.clear();const{opaque:C,transparent:E}=A.layerManager.partitionLayers();this.state_.setDepthMask(!0);const i=A.camera.frustum,D={viewport:A};for(const s of C)s.update(D),s.state==="ready"&&I&&this.renderLayer(s,A.camera,i);this.state_.setDepthMask(!1);for(const s of E)s.update(D),s.state==="ready"&&I&&this.renderLayer(s,A.camera,i);this.state_.setDepthMask(!0),this.renderedObjects_=this.renderedObjectsPerFrame_}get textureInfo(){return this.textures_.textureInfo}initStencil(){this.gl_.clearStencil(0),this.gl_.stencilMask(255),this.gl_.stencilFunc(this.gl_.EQUAL,0,255),this.gl_.stencilOp(this.gl_.KEEP,this.gl_.KEEP,this.gl_.INCR)}renderLayer(A,I,B){if(A.objects.length===0)return;this.state_.setBlendingMode(A.transparent?A.blendMode:"none");const Q=A.hasMultipleLODs();this.state_.setStencilTest(Q),Q&&this.gl_.clear(this.gl_.STENCIL_BUFFER_BIT),A.objects.forEach((C,E)=>{B.intersectsWithBox3(C.boundingBox)&&(this.renderObject(A,E,I),this.renderedObjectsPerFrame_+=1)})}renderObject(A,I,B){const Q=A.objects[I];if(Q.popStaleTextures().forEach(E=>{this.textures_.disposeTexture(E)}),!Q.programName)return;this.state_.setCullFaceMode(Q.cullFaceMode),this.state_.setDepthTesting(Q.depthTest),this.state_.setDepthMask(Q.depthTest),this.bindings_.bindGeometry(Q.geometry),Q.textures.forEach((E,i)=>{this.textures_.bindTexture(E,i)});const C=this.programs_.use(Q.programName);if(this.drawGeometry(Q.geometry,Q,A,C,B),Q.wireframeEnabled){this.bindings_.bindGeometry(Q.wireframeGeometry);const E=this.programs_.use("wireframe");E.setUniform("u_color",Q.wireframeColor.rgb),this.drawGeometry(Q.wireframeGeometry,Q,A,E,B)}}drawGeometry(A,I,B,Q,C){const E=tg(bA(),C.viewMatrix,I.transform.matrix),i=tg(bA(),$E,C.projectionMatrix),D=[this.canvas.width,this.canvas.height],s=I.getUniforms(),k={...B.getUniforms(),...s};for(const n of Q.uniformNames)switch(n){case"ModelView":Q.setUniform(n,E);break;case"Projection":Q.setUniform(n,i);break;case"Resolution":Q.setUniform(n,D);break;case"u_opacity":Q.setUniform(n,B.opacity);break;case"CameraPositionModel":{const H=gB(bA(),E),M=EB(0,0,0,1),q=kg(vI(),M,H);Q.setUniform(n,oA(q[0],q[1],q[2]));break}default:n in k&&Q.setUniform(n,k[n])}const c=this.glGetPrimitive(A.primitive),r=A.indexData;r.length?this.gl_.drawElements(c,r.length,this.gl_.UNSIGNED_INT,0):this.gl_.drawArrays(c,0,A.vertexCount)}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 uA(nA(0,0),nA(A,I));this.state_.setViewport(B)}clear(){this.gl_.clearColor(...this.backgroundColor.rgba),this.gl_.clear(this.gl_.COLOR_BUFFER_BIT|this.gl_.DEPTH_BUFFER_BIT),this.state_.setDepthTesting(!0),this.gl_.depthFunc(this.gl_.LEQUAL)}}const Ai=8;class Ii{maxConcurrent_;pending_=[];running_=new Map;constructor(A=Ai){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),V.debug("ChunkQueue","Cancelled pending request");return}const B=this.running_.get(A);B&&(B.controller.abort(),V.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)=>{const B=A.chunk.priority??Number.MAX_SAFE_INTEGER,Q=I.chunk.priority??Number.MAX_SAFE_INTEGER;return B===Q?(A.chunk.orderKey??Number.MAX_SAFE_INTEGER)-(I.chunk.orderKey??Number.MAX_SAFE_INTEGER):B-Q});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"&&V.error("ChunkQueue",String(E))}).finally(()=>{this.running_.delete(I),this.pump()});this.running_.set(I,{controller:Q,promise:C})}}const uQ=[Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array];function PQ(g){if(uQ.some(I=>g instanceof I))return!0;const A=uQ.map(I=>I.name);return V.debug("Chunk",`Unsupported chunk data type: ${g}. Supported data types: ${A}`),!1}function gi(g,A){return Math.round((A-g.translation)/g.scale)}function WB(g,A,I=1e-6){return Math.abs(g-A)<=I}function YI(g,A,I){return Math.max(A,Math.min(I,g))}const mB=Symbol("INTERNAL_POLICY_KEY");class Bi{store_;policy_;policyChanged_=!1;currentLOD_=0;lastViewBounds2D_=null;lastViewProjection_=null;lastZBounds_;lastTCoord_;sourceMaxSquareDistance2D_;chunkViewStates_=new Map;isDisposed_=!1;constructor(A,I){this.store_=A,this.policy_=I,V.info("ChunkStoreView","Using image source policy:",this.policy_.profile);const B=this.store_.dimensions,Q=B.x.lods[0],C=B.y.lods[0];this.sourceMaxSquareDistance2D_=VE(nA(Q.size*Q.scale,C.size*C.scale))}get chunkViewStates(){return this.chunkViewStates_}get isDisposed(){return this.isDisposed_}getChunksAtTime(A){return this.store_.getChunksAtTime(A)}getTimeIndex(A){return this.store_.getTimeIndex(A)}get lodCount(){return this.store_.lodCount}getChunksToRender(A){const I=this.store_.getTimeIndex(A),B=this.store_.getChunksAtTime(I),Q=B.filter(i=>i.lod===this.currentLOD_&&this.chunkViewStates_.get(i)?.visible===!0&&i.state==="loaded"),C=this.fallbackLOD();if(this.currentLOD_===C)return Q;const E=B.filter(i=>i.lod===C&&this.chunkViewStates_.get(i)?.visible===!0&&i.state==="loaded");return[...Q,...E]}updateChunksForImage(A,I){const B=I.camera;if(B.type!=="OrthographicCamera")throw new Error("ChunkStoreView currently supports only orthographic cameras. Update the implementation before using a perspective camera.");const C=B.getWorldViewRect(),E=Math.abs(C.max[0]-C.min[0]),i=I.element,D=I.getBoxRelativeTo(i).toRect().width,s=E/D,h=Math.log2(1/s);this.setLOD(h);const k=this.getZBounds(A);if(!(this.policyChanged_||this.viewBounds2DChanged(C)||this.zBoundsChanged(k)||this.lastTCoord_!==A.t))return;const r=this.store_.getTimeIndex(A);if(this.store_.getChunksAtTime(r).length===0){V.warn("ChunkStoreView","updateChunkViewStates called with no chunks initialized"),this.chunkViewStates_.clear();return}const H=TQ();XE(H,C.min,C.max,.5);const[M,q]=this.getZBounds(A),x=new hI(oA(C.min[0],C.min[1],M),oA(C.max[0],C.max[1],q));this.chunkViewStates_.forEach(TB),this.updateChunksAtTimeIndex(r,A,x,H),A.t!==void 0&&this.markTimeChunksForPrefetchImage(r,A,x,H),this.policyChanged_=!1,this.lastViewBounds2D_=C.clone(),this.lastZBounds_=k,this.lastTCoord_=A.t}updateChunksForVolume(A,I){const B=tg(bA(),I.camera.projectionMatrix,I.camera.viewMatrix);if(!(this.policyChanged_||this.hasViewProjectionChanged(B)||this.lastTCoord_!==A.t))return;const C=this.store_.getTimeIndex(A),E=this.store_.getChunksAtTime(C);if(E.length===0){V.warn("ChunkStoreView","updateChunksForVolume called with no chunks initialized"),this.chunkViewStates_.clear();return}this.currentLOD_=this.policy_.lod.min,this.chunkViewStates_.forEach(TB);const i=this.fallbackLOD();for(const D of E){const s=D.lod===this.currentLOD_,h=D.lod===i;if(!s&&!h||!this.isChunkChannelInSlice(D,A))continue;const k=this.computePriority(h,s,!0,!1,!0);this.chunkViewStates_.set(D,{visible:!0,prefetch:!1,priority:k,orderKey:0})}A.t!==void 0&&this.markTimeChunksForPrefetchVolume(C,A),this.policyChanged_=!1,this.lastTCoord_=A.t,this.lastViewProjection_=B}allVisibleFallbackLODLoaded(A){const I=this.store_.getTimeIndex(A),B=this.fallbackLOD(),Q=this.store_.getChunksAtTime(I).filter(C=>C.visible&&C.lod===B);return Q.length>0&&Q.every(C=>C.state==="loaded")}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(TB)}setImageSourcePolicy(A,I){if(I!==mB)throw new Error("Unauthorized policy mutation");this.policy_!==A&&(this.policy_=A,this.policyChanged_=!0,V.info("ChunkStoreView","Using image source policy:",this.policy_.profile))}setLOD(A){const B=this.store_.dimensions.x.lods[0].scale,C=this.policy_.lod.bias-Math.log2(B)-A,E=Math.floor(C),i=this.store_.getLowestResLOD(),D=Math.max(0,Math.min(i,this.policy_.lod.min)),s=Math.max(D,Math.min(i,this.policy_.lod.max)),h=YI(E,D,s);h!==this.currentLOD_&&(this.currentLOD_=h)}isChunkChannelInSlice(A,I){return I.c===void 0||I.c===A.chunkIndex.c}updateChunksAtTimeIndex(A,I,B,Q){const C=this.getPaddedBounds(B),E=this.store_.getChunksAtTime(A),i=this.fallbackLOD();for(const D of E){const s=D.lod===this.currentLOD_,h=D.lod===i;if(!s&&!h)continue;const k=this.isChunkChannelInSlice(D,I);if(!k)continue;const c=this.isChunkWithinBounds(D,B),r=!c&&k&&s&&this.isChunkWithinBounds(D,C),n=c&&k,H=this.computePriority(h,s,c,r,k);if(H!==null){const M=this.squareDistance2D(D,Q);this.chunkViewStates_.set(D,{visible:n,prefetch:r,priority:H,orderKey:M})}}}markTimeChunksForPrefetchImage(A,I,B,Q){const C=this.store_.dimensions.t?.lods[0].size??1,E=Math.min(C-1,A+this.policy_.prefetch.t),i=this.fallbackLOD(),D=this.policy_.priorityMap.prefetchTime;for(let s=A+1;s<=E;++s)for(const h of this.store_.getChunksAtTime(s)){if(h.lod!==i||!this.isChunkChannelInSlice(h,I)||!this.isChunkWithinBounds(h,B))continue;const k=this.squareDistance2D(h,Q),c=YI(k/this.sourceMaxSquareDistance2D_,0,1-Number.EPSILON),r=s-A+c;this.chunkViewStates_.set(h,{visible:!1,prefetch:!0,priority:D,orderKey:r})}}markTimeChunksForPrefetchVolume(A,I){const B=this.store_.dimensions.t?.lods[0].size??1,Q=Math.min(B-1,A+this.policy_.prefetch.t),C=this.fallbackLOD(),E=this.policy_.priorityMap.prefetchTime;for(let i=A+1;i<=Q;++i)for(const D of this.store_.getChunksAtTime(i)){if(D.lod!==C||!this.isChunkChannelInSlice(D,I))continue;const s=i-A;this.chunkViewStates_.set(D,{visible:!1,prefetch:!0,priority:E,orderKey:s})}}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}isChunkWithinBounds(A,I){const B=new hI(oA(A.offset.x,A.offset.y,A.offset.z),oA(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));return hI.intersects(B,I)}fallbackLOD(){return Math.min(this.policy_.lod.max,this.store_.getLowestResLOD())}getZBounds(A){const I=this.store_.dimensions.z;if(I===void 0)return[0,1];if(A.z===void 0){const h=I.lods[this.currentLOD_];return[h.translation,h.translation+h.size*h.scale]}const B=I.lods[this.currentLOD_],Q=B.size,C=B.scale,E=B.translation,i=Math.floor((A.z-E)/C),D=B.chunkSize,s=Math.max(0,Math.min(Math.floor(i/D),Math.ceil(Q/D)-1));return[E+s*D*C,E+(s+1)*D*C]}viewBounds2DChanged(A){return this.lastViewBounds2D_===null||!pB(this.lastViewBounds2D_.min,A.min)||!pB(this.lastViewBounds2D_.max,A.max)}hasViewProjectionChanged(A){return this.lastViewProjection_===null||!eE(this.lastViewProjection_,A)}zBoundsChanged(A){return!this.lastZBounds_||!pB(this.lastZBounds_,A)}getPaddedBounds(A){const I=this.store_.dimensions,B=I.x.lods[this.currentLOD_],Q=I.y.lods[this.currentLOD_],C=I.z?.lods[this.currentLOD_],E=B.chunkSize*B.scale*this.policy_.prefetch.x,i=Q.chunkSize*Q.scale*this.policy_.prefetch.y;let D=0;return C&&(D=C.chunkSize*C.scale*this.policy_.prefetch.z),new hI(oA(A.min[0]-E,A.min[1]-i,A.min[2]-D),oA(A.max[0]+E,A.max[1]+i,A.max[2]+D))}squareDistance2D(A,I){const B={x:A.offset.x+.5*A.shape.x*A.scale.x,y:A.offset.y+.5*A.shape.y*A.scale.y},Q=B.x-I[0],C=B.y-I[1];return Q*Q+C*C}}function TB(g){g.visible=!1,g.prefetch=!1,g.priority=null,g.orderKey=null}class Qi{chunks_;loader_;lowestResLOD_;dimensions_;views_=[];hasHadViews_=!1;constructor(A){this.loader_=A,this.dimensions_=this.loader_.getSourceDimensionMap(),this.lowestResLOD_=this.dimensions_.numLods-1,this.validateXYScaleRatios();const{size:I}=this.getAndValidateTimeDimension(),{size:B}=this.getAndValidateChannelDimension();this.chunks_=Array.from({length:I},()=>[]);for(let Q=0;Q<I;++Q){const C=this.chunks_[Q];for(let E=0;E<this.dimensions_.numLods;++E){const i=this.dimensions_.x.lods[E],D=this.dimensions_.y.lods[E],s=this.dimensions_.z?.lods[E],h=i.chunkSize,k=D.chunkSize,c=s?.chunkSize??1,r=Math.ceil(i.size/h),n=Math.ceil(D.size/k),H=Math.ceil((s?.size??1)/c);for(let M=0;M<B;++M)for(let q=0;q<r;++q){const x=i.translation+q*i.chunkSize*i.scale;for(let T=0;T<n;++T){const X=D.translation+T*D.chunkSize*D.scale;for(let u=0;u<H;++u){const Z=s!==void 0?s.translation+u*c*s.scale:0;C.push({state:"unloaded",lod:E,visible:!1,prefetch:!1,priority:null,orderKey:null,shape:{x:Math.min(h,i.size-q*h),y:Math.min(k,D.size-T*k),z:Math.min(c,(s?.size??1)-u*c),c:1},rowAlignmentBytes:1,chunkIndex:{x:q,y:T,z:u,c:M,t:Q},scale:{x:i.scale,y:D.scale,z:s?.scale??1},offset:{x,y:X,z:Z}})}}}}}}getChunksAtTime(A){return this.chunks_[A]}getTimeIndex(A){return A.t===void 0||this.dimensions_.t===void 0?0:gi(this.dimensions_.t.lods[0],A.t)}get lodCount(){return this.lowestResLOD_+1}get dimensions(){return this.dimensions_}getLowestResLOD(){return this.lowestResLOD_}loadChunkData(A,I){return this.loader_.loadChunkData(A,I)}createView(A){const I=new Bi(this,A);return this.views_.push(I),this.hasHadViews_=!0,I}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 s of this.views_){const h=s.chunkViewStates.get(A);h&&(h.visible&&(I=!0),h.prefetch&&(B=!0),h.priority!==null&&(Q===null||h.priority<Q)&&(Q=h.priority,C=h.orderKey),!h.visible&&!h.prefetch&&h.priority===null&&s.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}if(A.priority===null&&A.state==="queued"){A.state="unloaded";return}if(A.state==="loaded"&&A.priority===null){if(A.visible||A.prefetch)throw new Error(`Chunk state inconsistency detected: priority is null but visible=${A.visible} or prefetch=${A.prefetch} for chunk ${JSON.stringify(A.chunkIndex)} in LOD ${A.lod}`);A.data=void 0,A.state="unloaded",A.orderKey=null,V.debug("ChunkStore",`Disposing chunk ${JSON.stringify(A.chunkIndex)} in LOD ${A.lod}`)}}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(!WB(Q,2,.02)||!WB(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&&V.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 Ci{stores_=new Map;pendingStores_=new Map;queue_=new Ii;async addView(A,I){return(await this.getOrCreateStore(A)).createView(I)}async getOrCreateStore(A){const I=this.stores_.get(A);if(I)return I;const B=this.pendingStores_.get(A);if(B)return B;const C=(async()=>{const i=await A.open();return new Qi(i)})();this.pendingStores_.set(A,C);const E=await C;return this.stores_.set(A,E),this.pendingStores_.delete(A),E}update(){for(const[A,I]of this.stores_){const B=I.updateAndCollectChunkChanges();for(const Q of B)Q.priority===null?this.queue_.cancel(Q):Q.state==="queued"&&this.queue_.enqueue(Q,C=>I.loadChunkData(Q,C))}this.queue_.flush();for(const[A,I]of this.stores_)I.canDispose()&&this.stores_.delete(A)}}var cg=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(k){k.preventDefault(),Q(++A%I.children.length)},!1);function B(k){return I.appendChild(k.dom),k}function Q(k){for(var c=0;c<I.children.length;c++)I.children[c].style.display=c===k?"block":"none";A=k}var C=(performance||Date).now(),E=C,i=0,D=B(new cg.Panel("FPS","#0ff","#002",g)),s=B(new cg.Panel("MS","#0f0","#020",g));if(self.performance&&self.performance.memory)var h=B(new cg.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 k=(performance||Date).now();if(s.update(k-C,200),k>=E+1e3&&(D.update(i*1e3/(k-E),100),E=k,i=0,h)){var c=performance.memory;h.update(c.usedJSHeapSize/1048576,c.jsHeapSizeLimit/1048576)}return k},update:function(){C=this.end()},domElement:I,setMode:Q}};cg.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),s=E(48*i*B),h=E(3*i*B),k=E(2*i*B),c=E(3*i*B),r=E(15*i*B),n=E(74*i*B),H=E(30*i*B),M=document.createElement("canvas");M.width=D,M.height=s,M.style.cssText=`width:${E(B*80)}px;height:${E(B*48)}px`;var q=M.getContext("2d");return q.font="bold "+E(9*i*B)+"px Helvetica,Arial,sans-serif",q.textBaseline="top",q.fillStyle=I,q.fillRect(0,0,D,s),q.fillStyle=A,q.fillText(g,h,k),q.fillRect(c,r,n,H),q.fillStyle=I,q.globalAlpha=.9,q.fillRect(c,r,n,H),{dom:M,update:function(x,T){Q=Math.min(Q,x),C=Math.max(C,x),q.fillStyle=I,q.globalAlpha=1,q.fillRect(0,0,D,r),q.fillStyle=A,q.fillText(E(x)+" "+g+" ("+E(Q)+"-"+E(C)+")",h,k),q.drawImage(M,c+i,r,n-i,H,c,r,n-i,H),q.fillRect(c+n-i,r,i,H),q.fillStyle=I,q.globalAlpha=.9,q.fillRect(c+n-i,r,i,E((1-x/T)*H))}}};function Ei({scale:g}={scale:1.5}){const A=new cg(g);return A.showPanel(0),document.body.appendChild(A.dom),A}class OQ{layers_=[];callbacks_=[];context_;constructor(A){this.context_=A}partitionLayers(){const A=[],I=[];for(const B of this.layers)B.transparent?I.push(B):A.push(B);return{opaque:A,transparent:I}}add(A){this.layers_=[...this.layers_,A],A.onAttached(this.context_),this.notifyLayersChanged()}remove(A){const I=this.layers_.indexOf(A);if(I===-1)throw new Error(`Layer to remove not found: ${A}`);this.removeByIndex(I)}removeByIndex(A){const I=this.layers_[A];I&&I.onDetached(this.context_),this.layers_=this.layers_.filter((B,Q)=>Q!==A),this.notifyLayersChanged()}removeAll(){for(const A of this.layers_)A.onDetached(this.context_);this.layers_=[],this.notifyLayersChanged()}get layers(){return this.layers_}notifyLayersChanged(){for(const A of this.callbacks_)A()}addLayersChangeCallback(A){return this.callbacks_.push(A),()=>{this.removeLayersChangeCallback(A)}}removeLayersChangeCallback(A){const I=this.callbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove not found: ${A}`);this.callbacks_.splice(I,1)}}const xB=["pointerdown","pointermove","pointerup","pointercancel","wheel"];function ii(g){return xB.includes(g)}class oi{propagationStopped_=!1;type;event;worldPos;clipPos;constructor(A,I){this.type=A,this.event=I}get propagationStopped(){return this.propagationStopped_}stopPropagation(){this.propagationStopped_=!0}}class Di{listeners_=[];element_;isConnected_=!1;constructor(A){this.element_=A}addEventListener(A){this.listeners_.push(A)}connect(){if(this.isConnected_){V.warn("EventDispatcher","Attempted to connect already connected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!0,xB.forEach(A=>{this.element_.addEventListener(A,this.handleEvent,{passive:!1})})}disconnect(){if(!this.isConnected_){V.debug("EventDispatcher","Attempted to disconnect already disconnected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!1,xB.forEach(A=>{this.element_.removeEventListener(A,this.handleEvent)})}handleEvent=A=>{if(!ii(A.type)){V.error("EventDispatcher",`Unsupported event type ${A.type}`);return}const I=new oi(A.type,A);for(const B of this.listeners_)if(B(I),I.propagationStopped)break}}class VQ{id;element;camera;layerManager;events;cameraControls;constructor(A){this.id=A.id,this.element=A.element,this.camera=A.camera,this.layerManager=A.layerManager,this.cameraControls=A.cameraControls,this.updateAspectRatio(),this.events=new Di(this.element),this.events.addEventListener(I=>{if(I.event instanceof PointerEvent||I.event instanceof WheelEvent){const{clientX:B,clientY:Q}=I.event,C=nA(B,Q);I.clipPos=this.clientToClip(C,0),I.worldPos=this.camera.clipToWorld(I.clipPos)}for(const B of this.layerManager.layers)if(B.onEvent(I),I.propagationStopped)return;this.cameraControls?.onEvent(I)});for(const I of A.layers??[])this.layerManager.add(I)}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,s=I.y-E,h=Math.floor(D),k=Math.floor(i-s-I.height),c=Math.floor(I.width),r=Math.floor(I.height);return new uA(nA(h,k),nA(h+c,k+r))}clientToClip(A,I=0){const[B,Q]=A,C=this.element.getBoundingClientRect();return oA(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 uA(nA(B,Q),nA(B+C,Q+E))}updateAspectRatio(){const{width:A,height:I}=this.getBox().toRect();if(A<=0||I<=0){V.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 ZB(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 ai(g){for(let A=0;A<g.length;A++)ZB(g[A],g.slice(0,A))}function bB(g,A,I){const B=g.map(Q=>{const C=Q.element??A;return{...Q,element:C,id:Q.id??C.id??qQ(),layerManager:new OQ(I)}});return ai(B),B.map(Q=>new VQ(Q))}class si{elements_;resizeObserver_;mediaQuery_;onMediaQueryChange_;onChange_;constructor(A=[],I){this.elements_=[...A],this.onChange_=I}connect(){if(this.resizeObserver_){V.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_){V.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)){V.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){V.warn("PixelSizeObserver","Element not being observed");return}this.elements_.splice(I,1),this.resizeObserver_&&this.resizeObserver_.unobserve(A)}}class yi{chunkManager_;context_;renderer_;viewports_;canvas;overlays;stats_;sizeObserver_;lastAnimationId_;lastTimestamp_=0;constructor(A){this.canvas=A.canvas,this.renderer_=new bQ(this.canvas),this.chunkManager_=new Ci,this.context_={chunkManager:this.chunkManager_},this.viewports_=bB(A.viewports??[],this.canvas,this.context_),this.overlays=A.overlays??[],A.showStats&&(this.stats_=Ei());const I=[this.canvas];for(const B of this.viewports_)B.element!==this.canvas&&I.push(B.element);this.sizeObserver_=new si(I,()=>{this.renderer_.updateSize();for(const B of this.viewports_)B.updateSize(),this.renderer_.render(B)})}get renderedObjects(){return this.renderer_.renderedObjects}get width(){return this.renderer_.width}get height(){return this.renderer_.height}get textureInfo(){return this.renderer_.textureInfo}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]=bB([A],this.canvas,this.context_);return ZB(I,this.viewports_),this.viewports_.push(I),this.running&&(I.events.connect(),I.element!==this.canvas&&this.sizeObserver_.observe(I.element)),V.info("Idetik",`Added viewport "${I.id}"`),I}removeViewport(A){const I=this.viewports_.indexOf(A);return I===-1?(V.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),V.info("Idetik",`Removed viewport "${A.id}"`),!0)}start(){if(V.info("Idetik","Idetik runtime starting"),this.running)V.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;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(V.info("Idetik","Idetik runtime stopping"),!this.running)V.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}}}class hi extends jI{constructor(A){if(super(),A.primitive!="triangles"){V.warn("WireframeGeometry","Only indexed geometries are supported");return}if(A.indexData.length==0){V.warn("WireframeGeometry","Only triangulated geometries are supported");return}this.primitive_="lines",this.vertexData_=A.vertexData,this.attributes_=A.attributes;const I=new Set,B=[],Q=(E,i)=>{const D=Math.min(E,i),s=Math.max(E,i);I.has({i0:D,i1:s})||(I.add({i0:D,i1:s}),B.push(D,s))},C=A.indexData;for(let E=0;E<C.length;E+=3){const i=C[E],D=C[E+1],s=C[E+2];Q(i,D),Q(D,s),Q(s,i)}this.indexData_=new Uint32Array(B)}}const Gi=oA(0,1,0);class Fi{dirty_=!0;matrix_=bA();rotation_=dB();translation_=aA();scale_=oA(1,1,1);addRotation(A){bE(this.rotation_,this.rotation_,A),this.dirty_=!0}setRotation(A){PE(this.rotation_,A),this.dirty_=!0}get rotation(){return uE(this.rotation_)}addTranslation(A){VI(this.translation_,this.translation_,A),this.dirty_=!0}setTranslation(A){OI(this.translation_,A),this.dirty_=!0}get translation(){return vA(this.translation_)}addScale(A){qE(this.scale_,this.scale_,A),this.dirty_=!0}setScale(A){OI(this.scale_,A),this.dirty_=!0}targetTo(A){WQ(this.translation_,A)&&(A=vA(A),A[2]+=hA);const I=ME(bA(),this.translation_,A,Gi),B=cE(dQ(),I);mQ(this.rotation_,B),lB(this.rotation_,this.rotation_),this.dirty_=!0}get scale(){return vA(this.scale_)}get matrix(){return this.dirty_&&(this.computeMatrix(),this.dirty_=!1),this.matrix_}get inverse(){return gB(bA(),this.matrix)}computeMatrix(){JE(this.matrix_,this.rotation_,this.translation_,this.scale_)}}class zI extends eB{wireframeEnabled=!1;wireframeColor=QA.WHITE;depthTest=!0;textures_=[];staleTextures_=[];transform_=new Fi;geometry_=new jI;wireframeGeometry_=null;programName_=null;cullFaceMode_="none";setTexture(A,I){const B=this.textures_[A];B!==void 0&&this.staleTextures_.push(B),this.textures_[A]=I}popStaleTextures(){const A=this.staleTextures_;return this.staleTextures_=[],A}get geometry(){return this.geometry_}get wireframeGeometry(){return this.wireframeGeometry_??=new hi(this.geometry),this.wireframeGeometry_}get textures(){return this.textures_}get transform(){return this.transform_}set geometry(A){this.geometry_=A,this.wireframeGeometry_=null}get programName(){return this.programName_}get boundingBox(){const A=this.geometry_.boundingBox.clone();return A.applyTransform(this.transform_.matrix),A}set programName(A){this.programName_=A}get cullFaceMode(){return this.cullFaceMode_}set cullFaceMode(A){this.cullFaceMode_=A}getUniforms(){return{}}}class nI{normal;signedDistance;constructor(A=oA(0,1,0),I=0){this.normal=vA(A),this.signedDistance=I}set(A,I){this.normal=vA(A),this.signedDistance=I}signedDistanceToPoint(A){return pQ(this.normal,A)+this.signedDistance}normalize(){const A=HB(this.normal);if(A>0){const I=1/A;XI(this.normal,this.normal,I),this.signedDistance*=I}}}class XQ{planes_;constructor(A){this.planes_=[new nI(aA(),0),new nI(aA(),0),new nI(aA(),0),new nI(aA(),0),new nI(aA(),0),new nI(aA(),0)],this.setWithViewProjection(A)}setWithViewProjection(A){const I=aA();this.planes_[0].set(rI(I,A[3]+A[0],A[7]+A[4],A[11]+A[8]),A[15]+A[12]),this.planes_[1].set(rI(I,A[3]-A[0],A[7]-A[4],A[11]-A[8]),A[15]-A[12]),this.planes_[2].set(rI(I,A[3]-A[1],A[7]-A[5],A[11]-A[9]),A[15]-A[13]),this.planes_[3].set(rI(I,A[3]+A[1],A[7]+A[5],A[11]+A[9]),A[15]+A[13]),this.planes_[4].set(rI(I,A[3]+A[2],A[7]+A[6],A[11]+A[10]),A[15]+A[14]),this.planes_[5].set(rI(I,A[3]-A[2],A[7]-A[6],A[11]-A[10]),A[15]-A[14]);for(const B of this.planes_)B.normalize()}intersectsWithBox3(A){const I=aA();for(const B of this.planes_){const Q=B.normal;if(I[0]=Q[0]>0?A.max[0]:A.min[0],I[1]=Q[1]>0?A.max[1]:A.min[1],I[2]=Q[2]>0?A.max[2]:A.min[2],B.signedDistanceToPoint(I)<0)return!1}return!0}}class vQ extends zI{projectionMatrix_=bA();near_=0;far_=0;update(){this.updateProjectionMatrix()}get projectionMatrix(){return this.projectionMatrix_}get viewMatrix(){return this.transform.inverse}get right(){const A=this.transform.matrix;return oA(A[0],A[1],A[2])}get up(){const A=this.transform.matrix;return oA(A[4],A[5],A[6])}get frustum(){return new XQ(tg(bA(),this.projectionMatrix,this.viewMatrix))}pan(A){this.transform.addTranslation(A)}get position(){return this.transform.translation}clipToWorld(A){const I=EB(A[0],A[1],A[2],1),B=gB(bA(),this.projectionMatrix_),Q=kg(vI(),I,B);TE(Q,Q,1/Q[3]);const C=kg(vI(),Q,this.transform.matrix);return oA(C[0],C[1],C[2])}}const jQ=1.77,zQ=128,_Q=128/jQ;class wi extends vQ{width_=zQ;height_=_Q;viewportAspectRatio_=jQ;viewportSize_=[zQ,_Q];constructor(A,I,B,Q,C=0,E=100){super(),this.near_=C,this.far_=E,this.setFrame(A,I,Q,B),this.updateProjectionMatrix()}get viewportSize(){return this.viewportSize_}setAspectRatio(A){this.viewportAspectRatio_=A,this.updateProjectionMatrix()}setFrame(A,I,B,Q){this.width_=Math.abs(I-A),this.height_=Math.abs(Q-B),this.updateProjectionMatrix();const C=.5*(A+I),E=.5*(B+Q);this.transform.setTranslation([C,E,0]),this.transform.setScale([1,1,1]),this.transform.setRotation([0,0,0,1])}get type(){return"OrthographicCamera"}zoom(A){if(A<=0)throw new Error(`Invalid zoom factor: ${A}`);const I=1/A;this.transform.addScale([I,I,1])}getWorldViewRect(){let A=EB(-1,-1,0,1),I=EB(1,1,0,1);const B=tg(bA(),this.projectionMatrix,this.viewMatrix),Q=gB(bA(),B);return A=kg(vI(),A,Q),I=kg(vI(),I,Q),new uA(nA(A[0],A[1]),nA(I[0],I[1]))}updateProjectionMatrix(){const A=this.width_,I=this.height_,B=A/I;let Q=.5*A,C=.5*I;this.viewportAspectRatio_>B?Q*=this.viewportAspectRatio_/B:C*=B/this.viewportAspectRatio_,this.viewportSize_=[2*Q,2*C],KE(this.projectionMatrix_,-Q,Q,-C,C,this.near_,this.far_)}}const Si=60,Ri=1.77,iB=.1,uB=180-iB;class Ni extends vQ{fov_;aspectRatio_;constructor(A={}){const{fov:I=Si,aspectRatio:B=Ri,near:Q=.1,far:C=1e4,position:E=oA(0,0,0)}=A;if(I<iB||I>uB)throw new Error(`Invalid field of view: ${I}, must be in [${iB}, ${uB}] degrees`);super(),this.fov_=I,this.aspectRatio_=B,this.near_=Q,this.far_=C,this.transform.setTranslation(E),this.updateProjectionMatrix()}setAspectRatio(A){this.aspectRatio_=A,this.updateProjectionMatrix()}get type(){return"PerspectiveCamera"}get fov(){return this.fov_}zoom(A){if(A<=0)throw new Error(`Invalid zoom factor: ${A}`);this.fov_=Math.max(iB,Math.min(uB,this.fov_/A)),this.updateProjectionMatrix()}updateProjectionMatrix(){YE(this.projectionMatrix_,kE(this.fov),this.aspectRatio_,this.near_,this.far_)}}const $Q=0;class Ui{camera_;dragActive_=!1;dragStart_=aA();constructor(A){this.camera_=A}get isMoving(){return this.dragActive_}onEvent(A){switch(A.type){case"wheel":this.onWheel(A);break;case"pointerdown":this.onPointerDown(A);break;case"pointermove":this.onPointerMove(A);break;case"pointerup":case"pointercancel":this.onPointerEnd(A);break}}onUpdate(A){}onWheel(A){if(!A.worldPos||!A.clipPos)return;const I=A.event;I.preventDefault();const B=vA(A.worldPos),Q=I.deltaY<0?1.05:.95;this.camera_.zoom(Q);const C=this.camera_.clipToWorld(A.clipPos),E=CB(aA(),B,C);this.camera_.pan(E)}onPointerDown(A){const I=A.event;!A.worldPos||I.button!==$Q||(this.dragStart_=vA(A.worldPos),this.dragActive_=!0,I.target?.setPointerCapture?.(I.pointerId))}onPointerMove(A){if(!this.dragActive_||!A.worldPos)return;const I=CB(aA(),this.dragStart_,A.worldPos);this.camera_.pan(I)}onPointerEnd(A){const I=A.event;!this.dragActive_||I.button!==$Q||(this.dragActive_=!1,I.target?.releasePointerCapture?.(I.pointerId))}}class PB{radius;phi;theta;constructor(A,I,B){this.radius=A,this.phi=I,this.theta=B}toVec3(){const A=Math.cos(this.theta);return oA(this.radius*Math.sin(this.phi)*A,-this.radius*Math.sin(this.theta),this.radius*Math.cos(this.phi)*A)}}const OB=-1,AC=0,ti=1,IC=.009,ki=.001,ci=9e-4,Li=.5,Ji=60;class ri{camera_;orbitVelocity_=new PB(0,0,0);panVelocity_=aA();currPos_;currCenter_=aA();dampingFactor_;currMouseButton_=OB;constructor(A,I){this.camera_=A,this.currPos_=new PB(I?.radius??1,I?.yaw??0,I?.pitch??0),I?.target&&OI(this.currCenter_,I.target),this.dampingFactor_=YI(I?.dampingFactor??Li,0,1),this.updateCamera()}get isMoving(){return this.orbitVelocity_.phi!==0||this.orbitVelocity_.theta!==0||this.orbitVelocity_.radius!==0||this.panVelocity_[0]!==0||this.panVelocity_[1]!==0||this.panVelocity_[2]!==0}onEvent(A){switch(A.type){case"pointerdown":this.onPointerDown(A);break;case"pointermove":this.onPointerMove(A);break;case"wheel":this.onWheel(A);break;case"pointerup":case"pointercancel":this.onPointerEnd(A);break}}onUpdate(A){if(this.orbitVelocity_.phi===0&&this.orbitVelocity_.theta===0&&this.orbitVelocity_.radius===0&&WQ(this.panVelocity_,oA(0,0,0)))return;this.currPos_.phi+=this.orbitVelocity_.phi,this.currPos_.theta+=this.orbitVelocity_.theta,this.currPos_.radius+=this.orbitVelocity_.radius*this.currPos_.radius,VI(this.currCenter_,this.currCenter_,this.panVelocity_);const I=Math.PI/2-hA;this.currPos_.theta=YI(this.currPos_.theta,-I,I),this.currPos_.radius=Math.max(.01,this.currPos_.radius),this.updateCamera();const B=Math.pow(1-this.dampingFactor_,A*Ji);this.orbitVelocity_.phi*=B,this.orbitVelocity_.theta*=B,this.orbitVelocity_.radius*=B,XI(this.panVelocity_,this.panVelocity_,B),this.cutoffLowVelocity()}onPointerDown(A){const I=A.event;this.currMouseButton_=I.button,I.target?.setPointerCapture?.(I.pointerId)}onPointerMove(A){if(this.currMouseButton_==OB)return;const I=A.event,B=I.movementX??0,Q=I.movementY??0,C=this.currMouseButton_===AC&&!I.shiftKey,E=this.currMouseButton_===AC&&I.shiftKey||this.currMouseButton_===ti;C&&this.orbit(B,Q),E&&this.pan(B,Q)}onWheel(A){const I=A.event;I.preventDefault();const B=I.deltaY??0;this.zoom(B)}onPointerEnd(A){this.currMouseButton_=OB;const I=A.event;I.target?.releasePointerCapture?.(I.pointerId)}orbit(A,I){this.orbitVelocity_.phi-=A*IC,this.orbitVelocity_.theta+=I*IC}pan(A,I){const B=this.currPos_.radius*ki,Q=aA();BB(Q,Q,this.camera_.right,A),BB(Q,Q,this.camera_.up,I),XI(Q,Q,B),CB(this.panVelocity_,this.panVelocity_,Q)}zoom(A){this.orbitVelocity_.radius+=A*ci}updateCamera(){const A=VI(aA(),this.currCenter_,this.currPos_.toVec3());this.camera_.transform.setTranslation(A),this.camera_.transform.targetTo(this.currCenter_)}cutoffLowVelocity(){Math.abs(this.orbitVelocity_.phi)<hA&&(this.orbitVelocity_.phi=0),Math.abs(this.orbitVelocity_.theta)<hA&&(this.orbitVelocity_.theta=0),Math.abs(this.orbitVelocity_.radius)<hA&&(this.orbitVelocity_.radius=0),HB(this.panVelocity_)<hA&&lE(this.panVelocity_)}}class EI{objects_=[];state_="initialized";callbacks_=[];transparent;opacity_;blendMode;constructor({transparent:A=!1,opacity:I=1,blendMode:B="normal"}={}){(I<0||I>1)&&V.warn("Layer",`Layer opacity out of bounds: ${I} — clamping to [0.0, 1.0]`),this.transparent=A,this.opacity_=YI(I,0,1),this.blendMode=B}get opacity(){return this.opacity_}set opacity(A){(A<0||A>1)&&V.warn("Layer",`Opacity out of bounds: ${A} — clamping to [0.0, 1.0]`),this.opacity_=YI(A,0,1)}onEvent(A){}async onAttached(A){}onDetached(A){}get objects(){return this.objects_}get state(){return this.state_}addStateChangeCallback(A){this.callbacks_.push(A)}removeStateChangeCallback(A){const I=this.callbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.callbacks_.splice(I,1)}hasMultipleLODs(){return!1}setState(A){const I=this.state_;this.state_=A,this.callbacks_.forEach(B=>B(A,I))}addObject(A){this.objects_.push(A)}removeObject(A){const I=this.objects_.indexOf(A);I!==-1&&this.objects_.splice(I,1)}clearObjects(){this.objects_=[]}getUniforms(){return{}}}class oB extends jI{constructor(A){super(),this.vertexData_=this.createVertices(A),this.indexData_=this.createIndex(A.length),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"previous_position",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"next_position",itemSize:3,offset:6*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"direction",itemSize:1,offset:9*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"path_proportion",itemSize:1,offset:10*Float32Array.BYTES_PER_ELEMENT})}createVertices(A){const I=new Float32Array(2*A.length*11);let B=0,Q=0;const C=A.reduce((E,i,D)=>E+fQ(i,A[D+1]??i),0);for(const E of[...Array(A.length).keys()]){for(const i of[-1,1]){const D=A[E];I[B++]=D[0],I[B++]=D[1],I[B++]=D[2];const s=A[E-1]??A[E];I[B++]=s[0],I[B++]=s[1],I[B++]=s[2];const h=A[E+1]??A[E];I[B++]=h[0],I[B++]=h[1],I[B++]=h[2],I[B++]=i,I[B++]=Q}Q+=fQ(A[E],A[E+1]??A[E])/C}return I}createIndex(A){const I=new Uint32Array((A-1)*6);let B=0;for(let Q=0;Q<2*A;Q+=2)I[B++]=Q+0,I[B++]=Q+1,I[B++]=Q+2,I[B++]=Q+2,I[B++]=Q+1,I[B++]=Q+3;return I}}class VB extends zI{color_;width_;taperOffset_=.5;taperPower_=0;constructor({geometry:A,color:I,width:B,taperOffset:Q,taperPower:C}){super(),this.geometry=A,this.color_=QA.from(I),this.width_=B,this.taperOffset_=Q??this.taperOffset_,this.taperPower_=C??this.taperPower_,this.programName="projectedLine"}get type(){return"ProjectedLine"}get color(){return this.color_}set color(A){this.color_=QA.from(A)}get width(){return this.width_}set width(A){this.width_=A}get taperOffset(){return this.taperOffset_}set taperOffset(A){this.taperOffset_=A}get taperPower(){return this.taperPower_}set taperPower(A){this.taperPower_=A}getUniforms(){return{LineColor:this.color.rgb,LineWidth:this.width,TaperOffset:this.taperOffset,TaperPower:this.taperPower}}}class Yi extends EI{type="AxesLayer";constructor(A){super();const{length:I,width:B}=A;this.addObject(XB({end:[I,0,0],width:B,color:[1,0,0]})),this.addObject(XB({end:[0,I,0],width:B,color:[0,1,0]})),this.addObject(XB({end:[0,0,I],width:B,color:[0,0,1]})),this.setState("ready")}update(){}}function XB(g){const{end:A,width:I,color:B}=g,Q=new oB([[0,0,0],A]);return new VB({geometry:Q,color:B,width:I})}class ni extends EI{type="ProjectedLineLayer";paths_=[];constructor(A=[]){super(),A.forEach(I=>this.addLine(I)),this.setState("ready")}addLine(A){const{path:I,color:B,width:Q}=A;this.paths_.push(I);const C=new oB(I);this.addObject(new VB({geometry:C,color:B,width:Q}))}update(){}get extent(){return Ki(this.paths_.flat())}}function Ki(g){function A(D){const s=g.map(h=>h[D]);return[Math.min(...s),Math.max(...s)]}const[I,B]=A(0),[Q,C]=A(1),[E,i]=A(2);return{xMin:I,xMax:B,yMin:Q,yMax:C,zMin:E,zMax:i}}class Mi extends EI{type="TracksLayer";tracks_=[];constructor(A=[]){super(),A.forEach(I=>this.addLine(I)),this.setState("ready")}addLine(A){this.tracks_.push(A);let I;if(A.interpolation){const i=Hi({path:A.path,pointsPerSegment:A.interpolation.pointsPerSegment,tangentFactor:A.interpolation.tangentFactor});I=new oB(i)}else I=new oB(A.path);const{color:B,width:Q}=A,C=.5,E=1.5;this.addObject(new VB({geometry:I,color:B,width:Q,taperOffset:C,taperPower:E}))}setTimeIndex(A){for(const[I,B]of this.tracks_.entries()){if(!B.time)continue;let Q=.5;A<B.time[0]?Q=-1.5:A>B.time[B.time.length-1]&&(Q=1.5);const C=B.time.findIndex(i=>i===A);B.time&&C!==-1&&(Q=C/(B.time.length-1));const E=this.objects[I];E.taperOffset=Q}}update(){}get extent(){const A=this.tracks_.map(I=>I.path);return ei(A.flat())}}function ei(g){function A(D){const s=g.map(h=>h[D]);return[Math.min(...s),Math.max(...s)]}const[I,B]=A(0),[Q,C]=A(1),[E,i]=A(2);return{xMin:I,xMax:B,yMin:Q,yMax:C,zMin:E,zMax:i}}function Hi({path:g,pointsPerSegment:A,tangentFactor:I=1/3}){const B=qi(g),Q=Array((g.length-1)*A);for(let C=0;C<g.length-1;C++){const E=g[C],i=g[C+1],D=vA(B[C]);BB(D,E,D,I);const s=vA(B[C+1]);BB(s,i,s,-I);for(let h=0;h<A;h++){const k=h/A,c=Q[C*A+h]=aA();fE(c,E,D,s,i,k)}}return Q}function qi(g){if(g.length<2)throw new Error("Path must contain at least 2 points");const A=Array(g.length),I=aA(),B=aA();for(let Q=0;Q<g.length;Q++){const C=g[Q],E=g[Q+1]??g[Q];A[Q]=aA(),Q!==0&&OI(I,B),Q!==g.length-1&&CB(B,E,C),Q===0?OI(A[Q],B):Q==g.length-1?OI(A[Q],I):(VI(A[Q],I,B),XI(A[Q],A[Q],.5))}return A}class gC extends jI{constructor(A,I,B,Q){super();const C=[],E=[],i=B,D=Q,s=i+1,h=D+1,k=A/i,c=I/D;for(let r=0;r<h;++r){const n=r*c;for(let H=0;H<s;++H){const M=H*k,q=H/i,x=r/D,T=[M,n,0],X=[0,0,1],u=[q,x];C.push(...T,...X,...u)}}for(let r=0;r<D;++r)for(let n=0;n<i;++n){const H=n+s*r,M=n+s*(r+1),q=n+1+s*(r+1),x=n+1+s*r;E.push(H,M,x),E.push(M,q,x)}this.vertexData_=new Float32Array(C),this.indexData_=new Uint32Array(E),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}}function BC(g){return g===1||g===2||g===4||g===8}function _I(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){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 vB extends eB{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;get type(){return"Texture"}}const QC=32;function Lg(g,{visible:A,color:I,contrastLimits:B}){return A===void 0&&(A=!0),I===void 0?I=QA.WHITE:I=QA.from(I),g!==null?B=fi(B,g):B===void 0&&(V.debug("Channel","No texture provided, defaulting channel contrast limits to [0, 1]."),B=[0,1]),{visible:A,color:I,contrastLimits:B}}function jB(g,A){if(A.length>QC)throw new Error(`Maximum number of channels is ${QC}`);if(g?.type==="Texture2DArray"){const I=g.depth;if(A.length!==I)throw new Error(`Number of channels (${A.length}) must match depth of texture (${I}).`)}return A.map(I=>Lg(g,I))}function fi(g,A){if(g===void 0)return di(A);if(g[1]<=g[0])throw new Error(`Contrast limits must be strictly increasing: ${g}.`);return g}class zB extends zI{channels_;constructor(A,I,B,Q=[]){super(),this.geometry=new gC(A,I,1,1),this.setTexture(0,B),this.channels_=jB(B,Q),this.programName=li(B)}get type(){return"ImageRenderable"}setChannelProps(A){this.channels_=jB(this.textures[0],A)}setChannelProperty(A,I,B){const Q=Lg(this.textures[0],{...this.channels_[A],[I]:B});this.channels_[A]=Q}getUniforms(){const A=this.textures[0];if(!A)throw new Error("No texture set");if(A.type==="Texture2D"){const{color:I,contrastLimits:B}=this.channels_[0]??Lg(A,{});return{ImageSampler:0,Color:I.rgb,ValueOffset:-B[0],ValueScale:1/(B[1]-B[0]),ChannelCount:1}}else{const I=[],B=[],Q=[],C=[];return this.channels_.forEach(E=>{I.push(E.visible),B.push(...E.color.rgb),Q.push(-E.contrastLimits[0]),C.push(1/(E.contrastLimits[1]-E.contrastLimits[0]))}),{ImageSampler:0,"Visible[0]":I,"Color[0]":B,"ValueOffset[0]":Q,"ValueScale[0]":C,ChannelCount:this.channels_.length}}}}function li(g){if(g.type==="Texture2D")return pi(g.dataType);if(g.type==="Texture2DArray")return Wi(g.dataType);throw new Error(`Unsupported image texture type: ${g.type}`)}function pi(g){switch(g){case"byte":case"int":case"short":return"intScalarImage";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintScalarImage";case"float":return"floatScalarImage"}}function Wi(g){switch(g){case"byte":case"int":case"short":return"intScalarImageArray";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintScalarImageArray";case"float":return"floatScalarImageArray"}}class $I extends vB{data_;width_;height_;depth_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=_I(A),this.data_=A,this.width_=I,this.height_=B,this.depth_=A.length/(I*B)}get type(){return"Texture2DArray"}set data(A){this.data_=A,this.needsUpdate=!0}get data(){return this.data_}get width(){return this.width_}get height(){return this.height_}get depth(){return this.depth_}updateWithChunk(A,I){const B=I??A.data;if(!B)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data===B)return;const Q=A.shape.x,C=A.shape.y,E=B.length/(Q*C);if(this.width!=Q||this.height!=C||this.depth_!=E||this.dataType!=_I(B))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=B}static createWithChunk(A,I){const B=I??A.data;if(!B)throw new Error("Unable to create texture, chunk data is not initialized.");const Q=new $I(B,A.shape.x,A.shape.y);return Q.unpackAlignment=A.rowAlignmentBytes,Q}}function _B(g,A,I,B,Q=3){switch(g.type){case"pointerdown":{const C=g.event;return nA(C.clientX,C.clientY)}case"pointerup":{if(!A)return A;const C=g.event,E=nA(C.clientX,C.clientY);if(OE(A,E)<Q){if(!B)return null;const D=g.worldPos;if(D){const s=I(D);s!==null&&B({world:D,value:s})}return null}return A}case"pointercancel":return null;default:return A}}class CC{bins_=new Map;acquire(A){const B=this.bins_.get(A)?.pop();return B&&V.debug("RenderablePool","Renderable object acquired"),B}release(A,I){let B=this.bins_.get(A);B||(B=[],this.bins_.set(A,B)),B.push(I),V.debug("RenderablePool","Renderable object released")}clearAll(A){if(A)for(const I of this.bins_.values())I.forEach(A);this.bins_.clear()}}class $B extends EI{type="ChunkedImageLayer";source_;sliceCoords_;onPickValue_;visibleChunks_=new Map;pool_=new CC;initialChannelProps_;channelChangeCallbacks_=[];policy_;channelProps_;chunkStoreView_;pointerDownPos_=null;zPrevPointWorld_;debugMode_=!1;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;wireframeColors_=[new QA(.6,.3,.3),new QA(.3,.6,.4),new QA(.4,.4,.7),new QA(.6,.5,.3)];constructor({source:A,sliceCoords:I,policy:B,channelProps:Q,onPickValue:C,...E}){super(E),this.setState("initialized"),this.source_=A,this.policy_=B,this.sliceCoords_=I,this.channelProps_=Q,this.initialChannelProps_=Q,this.onPickValue_=C}async onAttached(A){if(this.chunkStoreView_)throw new Error("ChunkedImageLayer cannot be attached to multiple contexts simultaneously.");this.chunkStoreView_=await A.chunkManager.addView(this.source_,this.policy_)}onDetached(A){this.chunkStoreView_&&(this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_.dispose(),this.chunkStoreView_=void 0)}update(A){!A||!this.chunkStoreView_||(this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,A.viewport),this.updateChunks(),this.resliceIfZChanged())}updateChunks(){if(!this.chunkStoreView_||(this.state!=="ready"&&this.setState("ready"),this.visibleChunks_.size>0&&!this.chunkStoreView_.allVisibleFallbackLODLoaded(this.sliceCoords_)&&!this.isPresentationStale()))return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const A=this.chunkStoreView_.getChunksToRender(this.sliceCoords_),I=new Set(A),B=Array.from(this.visibleChunks_.keys()).filter(Q=>!I.has(Q));this.releaseAndRemoveChunks(B),this.clearObjects();for(const Q of A){if(Q.state!=="loaded")continue;const C=this.getImageForChunk(Q);this.visibleChunks_.set(Q,C),this.addObject(C)}}hasMultipleLODs(){return this.chunkStoreView_?this.chunkStoreView_.lodCount>1:!1}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>$B.STALE_PRESENTATION_MS_}resliceIfZChanged(){const A=this.sliceCoords_.z;if(!(A===void 0||this.zPrevPointWorld_===A)){for(const[I,B]of this.visibleChunks_){if(I.state!=="loaded"||!I.data)continue;const Q=this.slicePlane(I,A);Q&&B.textures[0].updateWithChunk(I,Q)}this.zPrevPointWorld_=A}}onEvent(A){this.pointerDownPos_=_B(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.onPickValue_)}get chunkStoreView(){return this.chunkStoreView_}get sliceCoords(){return this.sliceCoords_}get source(){return this.source_}get imageSourcePolicy(){return this.policy_}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,mB))}slicePlane(A,I){if(!A.data)return;const B=(I-A.offset.z)/A.scale.z,Q=Math.round(B),C=YI(Q,0,A.shape.z-1);WB(B,C,1+1e-6)||V.error("ImageLayer","slicePlane zValue outside extent");const E=A.shape.x*A.shape.y,i=E*C;return A.data.slice(i,i+E)}getImageForChunk(A){const I=this.visibleChunks_.get(A);if(I)return I;const B=this.pool_.acquire(EC(A));return B?(B.textures[0].updateWithChunk(A,this.getDataForImage(A)),this.updateImageChunk(B,A),this.channelProps_&&B.setChannelProps(this.channelProps_),B):this.createImage(A)}createImage(A){const I=new zB(A.shape.x,A.shape.y,$I.createWithChunk(A,this.getDataForImage(A)),this.channelProps_??[{}]);return this.updateImageChunk(I,A),I}getDataForImage(A){const I=this.sliceCoords_?.z!==void 0?this.slicePlane(A,this.sliceCoords_.z):A.data;if(!I){V.warn("ChunkedImageLayer","No data for image");return}return I}updateImageChunk(A,I){this.debugMode_?(A.wireframeEnabled=!0,A.wireframeColor=this.wireframeColors_[I.lod%this.wireframeColors_.length]):A.wireframeEnabled=!1,A.transform.setScale([I.scale.x,I.scale.y,1]),A.transform.setTranslation([I.offset.x,I.offset.y,0])}getValueAtWorld(A){const I=this.chunkStoreView_?.currentLOD??0;for(const[B,Q]of this.visibleChunks_){if(B.lod!==I)continue;const C=this.getValueFromChunk(B,Q,A);if(C!==null)return C}for(const[B,Q]of this.visibleChunks_){if(B.lod===I)continue;const C=this.getValueFromChunk(B,Q,A);if(C!==null)return C}return null}getValueFromChunk(A,I,B){if(!A.data)return null;const Q=QB(aA(),B,I.transform.inverse),C=Math.floor(Q[0]),E=Math.floor(Q[1]);if(C>=0&&C<A.shape.x&&E>=0&&E<A.shape.y){const i=this.sliceCoords_.z!==void 0?this.slicePlane(A,this.sliceCoords_.z):A.data,D=E*A.shape.x+C;return i[D]}return null}get debugMode(){return this.debugMode_}set debugMode(A){this.debugMode_=A,this.visibleChunks_.forEach((I,B)=>{I.wireframeEnabled=this.debugMode_,this.debugMode_&&(I.wireframeColor=this.wireframeColors_[B.lod%this.wireframeColors_.length])})}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.visibleChunks_.forEach(I=>{I.setChannelProps(A)}),this.channelChangeCallbacks_.forEach(I=>{I()})}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===-1)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}releaseAndRemoveChunks(A){for(const I of A){const B=this.visibleChunks_.get(I);B&&(this.pool_.release(EC(I),B),this.visibleChunks_.delete(I))}}}function EC(g){return[`lod${g.lod}`,`shape${g.shape.x}x${g.shape.y}`,`align${g.rowAlignmentBytes}`].join(":")}class mi extends jI{constructor(A,I,B,Q,C,E){super();const i=[],D=[],s=Math.floor(Q),h=Math.floor(C),k=Math.floor(E);this.buildFace("z","y","x",-1,-1,B,I,A,k,h,1,i,D),this.buildFace("z","y","x",1,-1,B,I,A,k,h,-1,i,D),this.buildFace("x","z","y",1,1,A,B,I,s,k,1,i,D),this.buildFace("x","z","y",1,-1,A,B,I,s,k,-1,i,D),this.buildFace("x","y","z",1,-1,A,I,B,s,h,1,i,D),this.buildFace("x","y","z",-1,-1,A,I,B,s,h,-1,i,D),this.vertexData_=new Float32Array(i),this.indexData_=new Uint32Array(D),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}buildFace(A,I,B,Q,C,E,i,D,s,h,k,c,r){const n=E/s,H=i/h,M=E/2,q=i/2,x=D/2*k,T=s+1,X=h+1,u=c.length/8;for(let Z=0;Z<X;Z++){const EA=-q+Z*H;for(let iA=0;iA<T;iA++){const BA=-M+iA*n,sA={x:0,y:0,z:0};sA[A]=BA*Q,sA[I]=EA*C,sA[B]=x;const yA={x:0,y:0,z:0};yA[B]=k;const KA=iA/s,NA=1-Z/h;c.push(sA.x,sA.y,sA.z,yA.x,yA.y,yA.z,KA,NA)}}for(let Z=0;Z<h;Z++)for(let EA=0;EA<s;EA++){const iA=u+EA+T*Z,BA=u+EA+T*(Z+1),sA=u+(EA+1)+T*(Z+1),yA=u+(EA+1)+T*Z;r.push(iA,BA,yA,BA,sA,yA)}}}class Ag extends vB{data_;width_;height_;depth_;constructor(A,I,B,Q){super(),this.dataFormat="scalar",this.dataType=_I(A),this.data_=A,this.width_=I,this.height_=B,this.depth_=Q}set data(A){this.data_=A,this.needsUpdate=!0}get type(){return"Texture3D"}get data(){return this.data_}get width(){return this.width_}get height(){return this.height_}get depth(){return this.depth_}updateWithChunk(A){const I=A.data;if(!I)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data!==I){if(this.width!=A.shape.x||this.height!=A.shape.y||this.depth!=A.shape.z||this.dataType!=_I(I))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=I}}static createWithChunk(A){const I=A.data;if(!I)throw new Error("Unable to create texture, chunk data is not initialized.");const B=new Ag(I,A.shape.x,A.shape.y,A.shape.z);return B.unpackAlignment=A.rowAlignmentBytes,B}}class Ti extends zI{voxelScale=oA(1,1,1);channels_;channelToTextureIndex_=new Map;loadedChannels_=new Set;constructor(){super(),this.geometry=new mi(1,1,1,1,1,1),this.cullFaceMode="front",this.depthTest=!1,this.channels_=[]}get type(){return"VolumeRenderable"}updateVolumeWithChunk(A){const I=A.chunkIndex.c,B=this.channelToTextureIndex_.get(I);B!==void 0?this.updateChannelTexture(B,A):this.addChannelTexture(I,A),this.loadedChannels_.add(I)}addChannelTexture(A,I){const B=Ag.createWithChunk(I),Q=this.textures.length;this.setTexture(Q,B),this.channelToTextureIndex_.set(A,Q);const C=xi(B.dataType);if(this.programName&&this.programName!==C)throw new Error(`Volume renderable does not support multiple channels with different data types. Existing program: ${this.programName}, new channel data type: ${B.dataType} and program: ${C}`);this.programName=C}updateChannelTexture(A,I){const B=this.textures[A];if(!(B instanceof Ag)){const Q=Ag.createWithChunk(I);this.setTexture(A,Q);return}B.updateWithChunk(I)}clearLoadedChannels(){this.loadedChannels_=new Set}getUniforms(){const A=[0,0,0,0],I=[1,1,1,1,1,1,1,1,1,1,1,1],B=[0,0,0,0],Q=[1,1,1,1],C=[],E=Math.max(this.channels_.length,this.channelToTextureIndex_.size);for(let i=0;i<E&&C.length<4;i++){const D=this.channelToTextureIndex_.get(i);if(D===void 0||!this.loadedChannels_.has(i))continue;const s=this.textures[D],h=Lg(s,this.channels_[i]||{});if(!h.visible)continue;const k=C.length;I[k*3]=h.color.rgb[0],I[k*3+1]=h.color.rgb[1],I[k*3+2]=h.color.rgb[2],C.push(D),B[k]=-h.contrastLimits[0],Q[k]=1/(h.contrastLimits[1]-h.contrastLimits[0]),A[k]=1}return C.reduce((i,D,s)=>(i[`Channel${s}Sampler`]=D,i),{Visible:A,"Color[0]":I,ValueOffset:B,ValueScale:Q,VoxelScale:[this.voxelScale[0],this.voxelScale[1],this.voxelScale[2]]})}getAvailableChannelTexture(A){if(A!==void 0){const B=this.channelToTextureIndex_.get(A);if(B!==void 0)return this.textures[B]}const I=this.channelToTextureIndex_.values().next().value;return I!==void 0?this.textures[I]:null}setChannelProps(A){this.channels_=jB(this.getAvailableChannelTexture(),A)}setChannelProperty(A,I,B){const Q=Lg(this.getAvailableChannelTexture(A),{...this.channels_[A],[I]:B});this.channels_[A]=Q}}function xi(g){switch(g){case"byte":case"int":case"short":return"intVolume";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintVolume";case"float":return"floatVolume"}}function Zi(g,A){const I=A.position,B=aA(),Q=aA();return g.sort((C,E)=>{VI(B,C.boundingBox.max,C.boundingBox.min),XI(B,B,.5),VI(Q,E.boundingBox.max,E.boundingBox.min),XI(Q,Q,.5);const i=lQ(I,B),D=lQ(I,Q);return i-D}),g}const bi=2;class ui extends EI{type="VolumeLayer";source_;sliceCoords_;currentVolumes_=new Map;volumeToPoolKey_=new Map;pool_=new CC;initialChannelProps_;channelChangeCallbacks_=[];sourcePolicy_;chunkStoreView_;channelProps_;lastLoadedTime_=void 0;lastNumRenderedChannelChunks_=void 0;interactiveStepSizeScale_=1;debugShowWireframes_=!1;debugShowDegenerateRays=!1;relativeStepSize=1;opacityMultiplier=1;earlyTerminationAlpha=.99;get debugShowWireframes(){return this.debugShowWireframes_}set debugShowWireframes(A){if(this.debugShowWireframes_!==A){for(const I of this.currentVolumes_.values())I.wireframeEnabled=A;this.debugShowWireframes_=A}}set sourcePolicy(A){this.sourcePolicy_!==A&&(this.sourcePolicy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,mB))}setChannelProps(A){this.channelProps_=A;for(const I of this.currentVolumes_.values())I.setChannelProps(A);this.channelChangeCallbacks_.forEach(I=>{I()})}get channelProps(){return this.channelProps_}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}constructor({source:A,sliceCoords:I,policy:B,channelProps:Q}){super({transparent:!0,blendMode:"premultiplied"}),this.source_=A,this.sliceCoords_=I,this.sourcePolicy_=B,this.initialChannelProps_=Q,this.channelProps_=Q,this.setState("initialized")}getOrCreateVolume(A,I){const B=this.currentVolumes_.get(A);if(B){for(const E of I)B.updateVolumeWithChunk(E);return B}const Q=Vi(I[0]),C=this.pool_.acquire(Q)??new Ti;C.setChannelProps(this.channelProps_??[]),this.volumeToPoolKey_.set(C,Q);for(const E of I)C.updateVolumeWithChunk(E);return this.updateVolumeTransform(C,I[0]),C}async onAttached(A){this.chunkStoreView_=await A.chunkManager.addView(this.source_,this.sourcePolicy_)}onDetached(A){this.chunkStoreView_&&(this.releaseAndRemoveVolumes(this.currentVolumes_.values()),this.clearObjects(),this.chunkStoreView_.dispose(),this.chunkStoreView_=void 0)}updateChunks(){if(!this.chunkStoreView_)return;const A=this.chunkStoreView_.getChunksToRender(this.sliceCoords_),I=this.sliceCoords_.t??-1,B=Oi(A),Q=this.lastLoadedTime_!==I||B.size!==this.currentVolumes_.size||this.lastNumRenderedChannelChunks_!==A.length;if(this.lastNumRenderedChannelChunks_=A.length,!Q)return;const C=Array.from(this.currentVolumes_.entries()).filter(([E])=>!B.has(E)).map(([,E])=>E);this.releaseAndRemoveVolumes(C),this.currentVolumes_.clear(),this.clearObjects();for(const[E,i]of B){const D=this.getOrCreateVolume(E,i);D.wireframeEnabled=this.debugShowWireframes,this.currentVolumes_.set(E,D),this.addObject(D)}this.lastLoadedTime_=I,this.state!=="ready"&&this.setState("ready")}updateVolumeTransform(A,I){const B={x:I.shape.x*I.scale.x,y:I.shape.y*I.scale.y,z:I.shape.z*I.scale.z};A.transform.setScale([B.x,B.y,B.z]),rI(A.voxelScale,I.scale.x,I.scale.y,I.scale.z);const Q={x:I.shape.x*I.scale.x/2,y:I.shape.y*I.scale.y/2,z:I.shape.z*I.scale.z/2};A.transform.setTranslation([I.offset.x+Q.x,I.offset.y+Q.y,I.offset.z+Q.z])}releaseAndRemoveVolumes(A){for(const I of A)I.clearLoadedChannels(),this.pool_.release(this.volumeToPoolKey_.get(I),I),this.volumeToPoolKey_.delete(I)}update(A){if(!this.chunkStoreView_)return;if(A===void 0)throw new Error("RenderContext is required for the VolumeLayer update as camera information is used to reorder the chunks.");this.chunkStoreView_.updateChunksForVolume(this.sliceCoords_,A.viewport);const I=A.viewport.cameraControls?.isMoving??!1;this.interactiveStepSizeScale_=I?bi:1,this.updateChunks(),Zi(this.objects,A.viewport.camera)}getUniforms(){return{DebugShowDegenerateRays:Number(this.debugShowDegenerateRays),RelativeStepSize:this.relativeStepSize*this.interactiveStepSizeScale_,OpacityMultiplier:this.opacityMultiplier,EarlyTerminationAlpha:this.earlyTerminationAlpha}}}function Pi(g){const{x:A,y:I,z:B,t:Q}=g.chunkIndex;return`${A}:${I}:${B}:${Q}`}function Oi(g){const A=new Map;for(const I of g){const B=Pi(I);let Q=A.get(B);Q||(Q=[],A.set(B,Q)),Q.push(I)}return A}function Vi(g){return[`lod${g.lod}`,`shape${g.shape.x}x${g.shape.y}x${g.shape.z}`,`align${g.rowAlignmentBytes}`].join(":")}class Xi extends EI{type="ImageLayer";source_;region_;lod_;onPickValue_;initialChannelProps_;channelChangeCallbacks_=[];channelProps_;image_;chunk_;extent_;pointerDownPos_=null;constructor({source:A,region:I,channelProps:B,onPickValue:Q,lod:C,...E}){super(E),this.setState("initialized"),this.source_=A,this.region_=I,this.channelProps_=B,this.initialChannelProps_=B,this.onPickValue_=Q,this.lod_=C}update(){switch(this.state){case"initialized":this.load(this.region_);break;case"loading":case"ready":break;default:{const A=this.state;throw new Error(`Unhandled LayerState case: ${A}`)}}}onEvent(A){this.pointerDownPos_=_B(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.onPickValue_)}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.image_?.setChannelProps(A),this.channelChangeCallbacks_.forEach(I=>{I()})}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}async load(A){if(this.state!=="initialized")throw new Error("Trying to load chunks more than once.");this.setState("loading");const I=await this.source_.open(),B=this.lod_??I.getSourceDimensionMap().numLods-1,Q=await I.loadRegion(A,B);this.extent_={x:Q.shape.x*Q.scale.x,y:Q.shape.y*Q.scale.y},this.image_=this.createImage(Q),this.chunk_=Q,this.addObject(this.image_),this.setState("ready")}get extent(){return this.extent_}createImage(A){const I=new zB(A.shape.x,A.shape.y,$I.createWithChunk(A),this.channelProps);return I.transform.setScale([A.scale.x,A.scale.y,1]),I.transform.setTranslation([A.offset.x,A.offset.y,0]),I}getValueAtWorld(A){if(!this.image_||!this.chunk_?.data)return null;const I=QB(aA(),A,this.image_.transform.inverse),B=Math.floor(I[0]),Q=Math.floor(I[1]);if(B>=0&&B<this.chunk_.shape.x&&Q>=0&&Q<this.chunk_.shape.y){const C=Q*this.chunk_.shape.x+B;return this.chunk_.data[C]}return null}}class Jg extends vB{data_;width_;height_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=_I(A),this.data_=A,this.width_=I,this.height_=B}set data(A){this.data_=A,this.needsUpdate=!0}get type(){return"Texture2D"}get data(){return this.data_}get width(){return this.width_}get height(){return this.height_}updateWithChunk(A,I){const B=I??A.data;if(!B)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data!==B){if(this.width!=A.shape.x||this.height!=A.shape.y||this.dataType!=_I(B))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=B}}static createWithChunk(A,I){const B=I??A.data;if(!B)throw new Error("Unable to create texture, chunk data is not initialized.");const Q=new Jg(B,A.shape.x,A.shape.y);return Q.unpackAlignment=A.rowAlignmentBytes,Q}}const vi=[[1,.5,.5],[.5,1,.5],[.5,.5,1],[.5,1,1],[1,.5,1],[1,1,.5]];function ji(g){return g=g??new Map,new Map(Array.from(g.entries()).map(([A,I])=>[A,QA.from(I)]))}function zi(g){return g=g??vi,g.map(QA.from)}class iC{lookupTable;cycle;constructor(A={}){this.lookupTable=ji(A.lookupTable),this.cycle=zi(A.cycle)}}const _i=new Set(["unsigned_byte","unsigned_short","unsigned_int"]);function $i(g){if(g.dataFormat!=="scalar")throw new Error(`Image data format must be scalar, instead found: ${g.dataFormat}`);if(!_i.has(g.dataType))throw new Error(`Image data type must be unsigned, instead found: ${g.dataType}`);return g}class Ao extends zI{outlineSelected_;selectedValue_;constructor(A){super(),this.geometry=new gC(A.width,A.height,1,1),this.setTexture(0,$i(A.imageData));const I=this.makeColorCycleTexture(A.colorMap.cycle);this.setTexture(1,I);const B=this.makeColorLookupTableTexture(A.colorMap.lookupTable);this.setTexture(2,B),this.outlineSelected_=A.outlineSelected??!1,this.selectedValue_=A.selectedValue??null,this.programName="labelImage"}get type(){return"LabelImageRenderable"}getUniforms(){return{ImageSampler:0,ColorCycleSampler:1,ColorLookupTableSampler:2,u_outlineSelected:this.outlineSelected_?1:0,u_selectedValue:this.selectedValue_??-1}}setColorMap(A){this.setTexture(1,this.makeColorCycleTexture(A.cycle)),this.setTexture(2,this.makeColorLookupTableTexture(A.lookupTable))}setSelectedValue(A){this.selectedValue_=A}makeColorCycleTexture(A){const I=new Uint8Array(A.flatMap(Q=>Q.rgba).map(Q=>Math.round(Q*255))),B=new Jg(I,A.length,1);return B.dataFormat="rgba",B}makeColorLookupTableTexture(A){A===void 0?A=new Map([[0,QA.TRANSPARENT]]):A.has(0)||(A=new Map([[0,QA.TRANSPARENT],...A]));const I=Array.from(A.keys()),B=Array.from(A.values()).map(E=>E.packed),Q=A.size,C=new Uint32Array(Q*2);return C.set(I,0),C.set(B,Q),new Jg(C,Q,2)}}class Io extends EI{type="LabelImageLayer";source_;region_;lod_;colorMap_;onPickValue_;outlineSelected_;image_;imageChunk_;pointerDownPos_=null;selectedValue_=null;constructor({source:A,region:I,colorMap:B={},onPickValue:Q,lod:C,outlineSelected:E=!1,...i}){super(i),this.setState("initialized"),this.source_=A,this.region_=I,this.colorMap_=new iC(B),this.onPickValue_=Q,this.lod_=C,this.outlineSelected_=E}update(){switch(this.state){case"initialized":this.load(this.region_);break;case"loading":case"ready":break;default:{const A=this.state;throw new Error(`Unhandled LayerState case: ${A}`)}}}get colorMap(){return this.colorMap_}setColorMap(A){this.colorMap_=new iC(A),this.image_&&this.image_.setColorMap(this.colorMap_)}setSelectedValue(A){this.selectedValue_=A,this.image_&&this.image_.setSelectedValue(this.selectedValue_)}onEvent(A){this.pointerDownPos_=_B(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.outlineSelected_?I=>{this.setSelectedValue(I.value),this.onPickValue_?.(I)}:this.onPickValue_)}async load(A){if(this.state!=="initialized")throw new Error("Trying to load chunks more than once.");this.setState("loading");const I=await this.source_.open(),B=this.lod_??I.getSourceDimensionMap().numLods-1,Q=await I.loadRegion(A,B);this.image_=this.createImage(Q),this.addObject(this.image_),this.setState("ready")}createImage(A){this.imageChunk_=A;const I=new Ao({width:A.shape.x,height:A.shape.y,imageData:Jg.createWithChunk(A),colorMap:this.colorMap_,outlineSelected:this.outlineSelected_,selectedValue:this.selectedValue_});return I.transform.setScale([A.scale.x,A.scale.y,1]),I.transform.setTranslation([A.offset.x,A.offset.y,0]),I}getValueAtWorld(A){if(!this.image_||!this.imageChunk_?.data)return null;const I=QB(aA(),A,this.image_.transform.inverse),B=Math.floor(I[0]),Q=Math.floor(I[1]);if(B<0||B>=this.imageChunk_.shape.x||Q<0||Q>=this.imageChunk_.shape.y)return null;const C=Q*this.imageChunk_.shape.x+B;return this.imageChunk_.data[C]}}class DB extends Error{constructor(A){super(A),this.name="AbortError",Object.setPrototypeOf(this,DB.prototype)}}class go{maxConcurrent_;pending_=[];abortController_=new AbortController;numRunning_=0;constructor(A){if(A<=0)throw Error(`maxConcurrent (${A}) must be positive`);this.maxConcurrent_=A}async submit(A){return this.abortController_.signal.throwIfAborted(),new Promise((I,B)=>{const Q=async()=>{try{this.abortController_.signal.throwIfAborted();const C=await A();I(C)}catch(C){B(C)}finally{this.numRunning_--,this.maybeRunNext()}};this.pending_.push(Q),this.maybeRunNext()})}maybeRunNext(){if(this.numRunning_>=this.maxConcurrent_)return;const A=this.pending_.shift();A!==void 0&&(this.numRunning_++,A())}get abortSignal(){return this.abortController_.signal}shutdown(){this.abortController_.abort(new DB("shutdown"))}get numRunning(){return this.numRunning_}get numPending(){return this.pending_.length}}class Bo{source_;region_;seriesDimensionName_;seriesIndex_;scheduler_=new go(16);lod_;loader_=null;seriesAttributes_;loadingToken_=null;dataChunks_=[];constructor(A){this.source_=A.source,this.region_=A.region,this.lod_=A.lod,this.seriesDimensionName_=A.seriesDimensionName;const I=A.region.find(B=>B.dimension==A.seriesDimensionName);if(I===void 0)throw new Error(`Series dimension '${A.seriesDimensionName}' not in region ${JSON.stringify(A.region)}`);if(I.index.type==="point")throw new Error("Series dimension index in region must be an interval or 'full', not a point value");this.seriesIndex_=I.index}async setPosition(A){const I=await this.loadSeriesAttributes(),B=Math.round((A-I.start)/I.scale);return await this.setIndex(B)}async setIndex(A){const I=this.loadingToken_;if(I){if(I.index===A&&!I.canceled)return V.debug("ImageSeriesLoader","Ignoring duplicate active setIndex request"),{success:!1,reason:"duplicate"};V.debug("ImageSeriesLoader",`Cancelling setIndex request for index ${I.index}, new requested index is ${A}`),I.canceled=!0}let B=this.dataChunks_[A];if(B===void 0){const Q={canceled:!1,index:A};if(this.loadingToken_=Q,B=await this.loadChunkAtIndex(A,Q),Q.canceled)return{success:!1,reason:"canceled"}}return{success:!0,chunk:B}}shutdown(){this.scheduler_.shutdown()}async loadSeriesAttributes(){if(this.seriesAttributes_)return this.seriesAttributes_;const I=(await this.getLoader()).getSourceDimensionMap(),B=this.lod_??I.numLods-1,Q=[I.x,I.y,I.z,I.c,I.t].filter(c=>c!==void 0),C=Q.find(c=>c.name===this.seriesDimensionName_);if(!C){const c=Q.map(r=>r.name).join(", ");throw new Error(`Series dimension "${this.seriesDimensionName_}" not found in loader dimensions: ${c}`)}const E=C.lods[B].scale,i=C.lods[B].size*E,D=this.seriesIndex_.type==="full",s=D?0:this.seriesIndex_.start,h=D?i:this.seriesIndex_.stop,k=Math.round((h-s)/E);return this.dataChunks_=new Array(k),this.seriesAttributes_={start:s,stop:h,scale:E,length:k},this.seriesAttributes_}async loadChunkAtIndex(A,I){const B=await this.loadSeriesAttributes();if(A<0||A>=B.length)throw new Error(`Requested index ${A} is out of bounds [0, ${B.length-1}]`);const Q=B.start+A*B.scale,C=this.region_.filter(s=>s.dimension!==this.seriesDimensionName_);C.push({dimension:this.seriesDimensionName_,index:{type:"point",value:Q}});const E=await this.getLoader(),i=this.lod_??E.getSourceDimensionMap().numLods-1,D=await E.loadRegion(C,i,this.scheduler_);return this.dataChunks_[A]=D,I&&I.canceled&&(this.loadingToken_=null),D}async preloadAllChunks(){const{length:A}=await this.loadSeriesAttributes(),I=[];for(let Q=0;Q<A;Q++)I.push(this.loadChunkAtIndex(Q));const B=await Promise.allSettled(I);for(const Q of B)if(Q.status==="rejected"){if(Q.reason instanceof DB)return Promise.reject(Q.reason);V.error("ImageSeriesLoader",`Error loading slice: ${Q.reason}`)}}async getLoader(){return this.loader_??=await this.source_.open(),this.loader_}}class Qo extends EI{type="ImageSeriesLayer";seriesLoader_;initialChannelProps_;channelChangeCallbacks_=[];channelProps_;texture_=null;image_;extent_;constructor({source:A,region:I,seriesDimensionName:B,channelProps:Q,lod:C,...E}){super(E),this.setState("initialized"),this.channelProps_=Q,this.initialChannelProps_=Q,this.seriesLoader_=new Bo({source:A,region:I,seriesDimensionName:B,lod:C})}update(){this.state==="initialized"&&(this.setState("loading"),this.seriesLoader_.loadSeriesAttributes())}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.image_?.setChannelProps(A),this.channelChangeCallbacks_.forEach(I=>{I()})}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}async setPosition(A){const I=await this.seriesLoader_.setPosition(A);return this.processIndexResult(I)}async setIndex(A){const I=await this.seriesLoader_.setIndex(A);return this.processIndexResult(I)}close(){this.seriesLoader_.shutdown()}async preloadSeries(){return this.seriesLoader_.preloadAllChunks()}get extent(){return this.extent_}processIndexResult(A){return A.chunk&&(this.setData(A.chunk),this.setState("ready")),A}setData(A){!this.texture_||!this.image_?(this.texture_=$I.createWithChunk(A),this.image_=this.createImage(A,this.texture_,this.channelProps_),this.addObject(this.image_),this.extent_={x:A.shape.x*A.scale.x,y:A.shape.y*A.scale.y}):A.data&&this.texture_.updateWithChunk(A)}createImage(A,I,B){const Q=new zB(A.shape.x,A.shape.y,I,B);return Q.transform.setScale([A.scale.x,A.scale.y,1]),Q.transform.setTranslation([A.offset.x,A.offset.y,0]),Q}}function oC(g,A,I,B={}){return A!==void 0&&I!==void 0&&(B={...B,headers:{...B.headers,Range:`bytes=${A}-${A+I-1}`}}),fetch(g,B)}function Co(g,A){return{...g,...A,headers:{...g.headers,...A.headers}}}function DC(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 aC(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}`)}}async function Eo(g,A,I,B){if(B)return fetch(g,{...I,headers:{...I.headers,Range:`bytes=-${A}`}});let Q=await fetch(g,{...I,method:"HEAD"});if(!Q.ok)return Q;let C=Q.headers.get("Content-Length"),E=Number(C);return oC(g,E-A,E,I)}class Ig{url;#A;#I;constructor(A,I={}){this.url=A,this.#A=I.overrides??{},this.#I=I.useSuffixRequest??!1}#g(A){return Co(this.#A,A)}async get(A,I={}){let B=DC(this.url,A).href,Q=await fetch(B,this.#g(I));return aC(Q)}async getRange(A,I,B={}){let Q=DC(this.url,A),C=this.#g(B),E;return"suffixLength"in I?E=await Eo(Q,I.suffixLength,C,this.#I):E=await oC(Q,I.offset,I.length,C),aC(E)}}class sC{#A;constructor(A,I,B){typeof A=="number"?this.#A=new Uint8Array(A):A instanceof ArrayBuffer?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 AQ{_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(I instanceof ArrayBuffer)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 rg{#A;chars;constructor(A,I,B,Q){if(this.chars=A,typeof I=="number")this.#A=new Int32Array(I*A);else if(I instanceof ArrayBuffer)Q&&(Q*=A),this.#A=new Int32Array(I,B,Q);else{const C=I,E=new rg(A,1);this.#A=new Int32Array(function*(){for(let i of C)E.set(0,i),yield*E.#A}())}}get BYTES_PER_ELEMENT(){return this.#A.BYTES_PER_ELEMENT*this.chars}get byteLength(){return this.#A.byteLength}get byteOffset(){return this.#A.byteOffset}get buffer(){return this.#A.buffer}get length(){return this.#A.length/this.chars}get(A){const I=this.chars*A;let 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 Yg(g){const A=new TextDecoder().decode(g);return JSON.parse(A)}function yC(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 hC(g){if(g==="v2:object")return globalThis.Array;let A=g.match(/v2:([US])(\d+)/);if(A){let[,B,Q]=A;return(B==="U"?rg:AQ).bind(null,Number(Q))}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:sC}[g];return LA(I,`Unknown or unsupported data_type: ${g}`),I}function KI(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)),LA(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 io({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 Error(`Unknown chunk key encoding: ${g}`)}function oo(g){if(g==="|O")return{data_type:"v2:object"};let A=g.match(/^([<|>])(.*)$/);LA(A,`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);return LA(Q,`Unsupported or unknown dtype: ${g}`),I==="|"?{data_type:Q}:{data_type:Q,endian:I==="<"?"little":"big"}}function Do(g,A={}){let I=[],B=oo(g.dtype);g.order==="F"&&I.push({name:"transpose",configuration:{order:"F"}}),"endian"in B&&B.endian==="big"&&I.push({name:"bytes",configuration:{endian:"big"}});for(let{id:Q,...C}of g.filters??[])I.push({name:Q,configuration:C});if(g.compressor){let{id:Q,...C}=g.compressor;I.push({name:Q,configuration:C})}return{zarr_format:3,node_type:"array",shape:g.shape,data_type:B.data_type,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,attributes:A}}function ao(g,A={}){return{zarr_format:3,node_type:"group",attributes:A}}function so(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");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 yo(g){return g?.name==="sharding_indexed"}function GC(g){return(g.data_type==="uint64"||g.data_type==="int64")&&g.fill_value!=null?BigInt(g.fill_value):g.fill_value}function FC(g,...A){if(!A.some(I=>g instanceof I))throw g}function LA(g,A=""){if(!g)throw new Error(A)}async function wC(g,{format:A,signal:I}){const B=g instanceof Response?g:new Response(g);LA(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}`)}}class IQ{kind="array_to_array";constructor(A,I){LA(A.keepbits>=0,"keepbits must be zero or positive")}static fromConfig(A,I){return new IQ(A,I)}encode(A){throw new Error("`BitroundCodec.encode` is not implemented. Please open an issue at https://github.com/manzt/zarrita.js/issues.")}decode(A){return A}}const SC=ho();function ho(){const g=new Uint32Array([305419896]);return new Uint8Array(g.buffer,g.byteOffset,g.byteLength)[0]!==18}function RC(g){return"BYTES_PER_ELEMENT"in g?g.BYTES_PER_ELEMENT:4}class aB{kind="array_to_bytes";#A;#I;#g;#Q;#B;constructor(A,I){this.#B=A?.endian,this.#I=hC(I.data_type),this.#Q=I.shape,this.#A=KI(I.shape,"C");const B=new this.#I(0);this.#g=B.BYTES_PER_ELEMENT}static fromConfig(A,I){return new aB(A,I)}encode(A){let I=new Uint8Array(A.data.buffer);return SC&&this.#B==="big"&&yC(I,RC(this.#I)),I}decode(A){return SC&&this.#B==="big"&&yC(A,RC(this.#I)),{data:new this.#I(A.buffer,A.byteOffset,A.byteLength/this.#g),shape:this.#Q,stride:this.#A}}}class gQ{kind="bytes_to_bytes";static fromConfig(){return new gQ}encode(A){throw new Error("Not implemented")}decode(A){return new Uint8Array(A.buffer,A.byteOffset,A.byteLength-4)}}class BQ{kind="bytes_to_bytes";static fromConfig(A){return new BQ}encode(A){throw new Error("Gzip encoding is not enabled by default. Please register a custom codec with `numcodecs/gzip`.")}async decode(A){const I=await wC(A,{format:"gzip"});return new Uint8Array(I)}}function Go(g,A){return LA(!Number.isNaN(A),"JsonCodec allow_nan is false but NaN was encountered during encoding."),LA(A!==Number.POSITIVE_INFINITY,"JsonCodec allow_nan is false but Infinity was encountered during encoding."),LA(A!==Number.NEGATIVE_INFINITY,"JsonCodec allow_nan is false but -Infinity was encountered during encoding."),A}function Fo(g,A){return A instanceof Object&&!Array.isArray(A)?Object.keys(A).sort().reduce((I,B)=>(I[B]=A[B],I),{}):A}class QQ{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:s=!0}=A;let h=A.separators;h||(D?h=[", ",": "]:h=[",",":"]),this.#A={encoding:I,skipkeys:B,ensure_ascii:Q,check_circular:C,allow_nan:E,indent:D,separators:h,sort_keys:i},this.#I={strict:s}}static fromConfig(A){return new QQ(A)}encode(A){const{indent:I,encoding:B,ensure_ascii:Q,check_circular:C,allow_nan:E,sort_keys:i}=this.#A;LA(B==="utf-8","JsonCodec does not yet support non-utf-8 encoding.");const D=[];LA(C,"JsonCodec does not yet support skipping the check for circular references during encoding."),E||D.push(Go),i&&D.push(Fo);const s=Array.from(A.data);s.push("|O"),s.push(A.shape);let h;D.length&&(h=(c,r)=>{let n=r;for(let H of D)n=H(c,n);return n});let k=JSON.stringify(s,h,I);return Q&&(k=k.replace(/[\u007F-\uFFFF]/g,c=>{const r=`0000${c.charCodeAt(0).toString(16)}`;return`\\u${r.substring(r.length-4)}`})),new TextEncoder().encode(k)}decode(A){const{strict:I}=this.#I;LA(I,"JsonCodec does not yet support non-strict decoding.");const B=Yg(A),Q=B.pop();B.pop(),LA(Q,"0D not implemented for JsonCodec.");const C=KI(Q,"C");return{data:B,shape:Q,stride:C}}}function NC(g){return g instanceof sC||g instanceof AQ||g instanceof rg?new Proxy(g,{get(I,B){return I.get(Number(B))},set(I,B,Q){return I.set(Number(B),Q),!0}}):g}function wo(g,A){let I;return g.data instanceof AQ||g.data instanceof rg?I=new g.constructor(g.data.length,g.data.chars):I=new g.constructor(g.data.length),{data:I,shape:g.shape,stride:KI(g.shape,A)}}function So(g,A){let I=wo(g,A),B=g.shape.length,Q=g.data.length,C=Array(B).fill(0),E=NC(g.data),i=NC(I.data);for(let D=0;D<Q;D++){let s=0;for(let h=0;h<B;h++)s+=C[h]*I.stride[h];i[s]=E[D],C[0]+=1;for(let h=0;h<B;h++)if(C[h]===g.shape[h]){if(h+1===B)break;C[h]=0,C[h+1]+=1}}return I}function Ro(g){let A=g.shape.length;return LA(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 No(g,A){let I=Ro(g);return LA(I.length===A.length,"Orders must match"),I.every((B,Q)=>B===A[Q])}class CQ{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)=>{LA(E[i]===void 0,`Invalid permutation: ${JSON.stringify(B)}`),E[i]=D});this.#A=C,this.#I=E}static fromConfig(A,I){return new CQ(A,I)}encode(A){return No(A,this.#I)?A:So(A,this.#I)}decode(A){return{data:A.data,shape:A.shape,stride:KI(A.shape,this.#A)}}}class EQ{kind="array_to_bytes";#A;#I;constructor(A){this.#A=A,this.#I=KI(A,"C")}static fromConfig(A,I){return new EQ(I.shape)}encode(A){throw new Error("Method not implemented.")}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 iQ{kind="bytes_to_bytes";static fromConfig(A){return new iQ}encode(A){throw new Error("Zlib encoding is not enabled by default. Please register a codec with `numcodecs/zlib`.")}async decode(A){const I=await wC(A,{format:"deflate"});return new Uint8Array(I)}}function Uo(){return new Map().set("blosc",()=>Promise.resolve().then(()=>Pa).then(g=>g.default)).set("lz4",()=>Promise.resolve().then(()=>za).then(g=>g.default)).set("zstd",()=>Promise.resolve().then(()=>Bs).then(g=>g.default)).set("gzip",()=>BQ).set("zlib",()=>iQ).set("transpose",()=>CQ).set("bytes",()=>aB).set("crc32c",()=>gQ).set("vlen-utf8",()=>EQ).set("json2",()=>QQ).set("bitround",()=>IQ)}const to=Uo();function oQ(g){let A;return{async encode(I){A||(A=await UC(g));for(const Q of A.array_to_array)I=await Q.encode(I);let B=await A.array_to_bytes.encode(I);for(const Q of A.bytes_to_bytes)B=await Q.encode(B);return B},async decode(I){A||(A=await UC(g));for(let Q=A.bytes_to_bytes.length-1;Q>=0;Q--)I=await A.bytes_to_bytes[Q].decode(I);let B=await A.array_to_bytes.decode(I);for(let Q=A.array_to_array.length-1;Q>=0;Q--)B=await A.array_to_array[Q].decode(B);return B}}}async function UC(g){let A=g.codecs.map(async C=>{let E=await to.get(C.name)?.();return LA(E,`Unknown codec: ${C.name}`),{Codec:E,meta:C}}),I=[],B,Q=[];for await(let{Codec:C,meta:E}of A){let i=C.fromConfig(E.configuration,g);switch(i.kind){case"array_to_array":I.push(i);break;case"array_to_bytes":B=i;break;default:Q.push(i)}}return B||(LA(ko(g),`Cannot encode ${g.data_type} to bytes without a codec`),B=aB.fromConfig({endian:"little"},g)),{array_to_array:I,array_to_bytes:B,bytes_to_bytes:Q}}function ko(g){return g.data_type!=="v2:object"}class ng extends Error{constructor(A,I={}){super(`Node not found: ${A}`,I),this.name="NodeNotFoundError"}}class DQ extends Error{constructor(A){super(`Missing key: ${A}`),this.name="KeyError"}}const tC=18446744073709551615n;function co(g,A,I,B){LA(g.store.getRange,"Store does not support range requests");let Q=g.store.getRange.bind(g.store),C=A.map((D,s)=>D/B.chunk_shape[s]),E=oQ({data_type:"uint64",shape:[...C,2],codecs:B.index_codecs}),i={};return async D=>{let s=D.map((x,T)=>Math.floor(x/C[T])),h=g.resolve(I(s)).path,k;if(h in i)k=i[h];else{let x=4,T=16*C.reduce((u,Z)=>u*Z,1),X=await Q(h,{suffixLength:T+x});k=i[h]=X?await E.decode(X):null}if(k===null)return;let{data:c,shape:r,stride:n}=k,H=D.map((x,T)=>x%r[T]).reduce((x,T,X)=>x+T*n[X],0),M=c[H],q=c[H+1];if(!(M===tC&&q===tC))return Q(h,{offset:Number(M),length:Number(q)})}}class mA{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 mA(this.store,decodeURIComponent(new URL(A,I).pathname))}}class aQ extends mA{kind="group";#A;constructor(A,I,B){super(A,I),this.#A=B}get attrs(){return this.#A.attributes}}function kC(g){return g.find(I=>I.name==="transpose")?.configuration?.order??"C"}const Kg=Symbol("zarrita.context");function Lo(g){return g[Kg]}function Jo(g,A){let{configuration:I}=A.codecs.find(yo)??{},B={encode_chunk_key:io(A.chunk_key_encoding),TypedArray:hC(A.data_type),fill_value:A.fill_value};if(I){let C=kC(I.codecs);return{...B,kind:"sharded",chunk_shape:I.chunk_shape,codec:oQ({data_type:A.data_type,shape:I.chunk_shape,codecs:I.codecs}),get_strides(E){return KI(E,C)},get_chunk_bytes:co(g,A.chunk_grid.configuration.chunk_shape,B.encode_chunk_key,I)}}let Q=kC(A.codecs);return{...B,kind:"regular",chunk_shape:A.chunk_grid.configuration.chunk_shape,codec:oQ({data_type:A.data_type,shape:A.chunk_grid.configuration.chunk_shape,codecs:A.codecs}),get_strides(C){return KI(C,Q)},async get_chunk_bytes(C,E){let i=B.encode_chunk_key(C),D=g.resolve(i).path;return g.store.get(D,E)}}}let sB=class extends mA{kind="array";#A;[Kg];constructor(A,I,B){super(A,I),this.#A={...B,fill_value:GC(B)},this[Kg]=Jo(this,B)}get attrs(){return this.#A.attributes}get shape(){return this.#A.shape}get chunks(){return this[Kg].chunk_shape}get dtype(){return this.#A.data_type}async getChunk(A,I){let B=this[Kg],Q=await B.get_chunk_bytes(A,I);if(!Q){let C=B.chunk_shape.reduce((i,D)=>i*D,1),E=new B.TypedArray(C);return E.fill(B.fill_value),{data:E,shape:B.chunk_shape,stride:B.get_strides(B.chunk_shape)}}return B.codec.decode(Q)}is(A){return so(this.dtype,A)}};function*ro(g,A,I=1){A===void 0&&(A=g,g=0);for(let B=g;B<A;B+=I)yield B}function*Yo(...g){if(g.length===0)return;const A=g.map(B=>B[Symbol.iterator]()),I=A.map(B=>B.next());if(I.some(B=>B.done))throw new Error("Input contains an empty iterator.");for(let B=0;;){if(I[B].done){if(A[B]=g[B][Symbol.iterator](),I[B]=A[B].next(),++B>=A.length)return}else yield I.map(({value:Q})=>Q),B=0;I[B]=A[B].next()}}function no({start:g,stop:A,step:I},B){if(I===0)throw new Error("slice step cannot be zero");I=I??1;const Q=I<0,[C,E]=Q?[-1,B-1]:[0,B];return g===null?g=Q?E:C:g<0?(g+=B,g<C&&(g=C)):g>E&&(g=E),A===null?A=Q?C:E:A<0?(A+=B,A<C&&(A=C)):A>E&&(A=E),[g,A,I]}function yB(g,A,I=null){return A===void 0&&(A=g,g=null),{start:g,stop:A,step:I}}function Ko(){const g=[];return{add:A=>g.push(A()),onIdle:()=>Promise.all(g)}}class sQ extends Error{constructor(A){super(A),this.name="IndexError"}}function Mo(g,A){throw new sQ(`too many indicies for array; expected ${A.length}, got ${g.length}`)}function eo(g){throw new sQ(`index out of bounds for dimension with length ${g}`)}function Ho(){throw new sQ("only slices with step >= 1 are supported")}function qo(g,A){g.length>A.length&&Mo(g,A)}function fo(g,A){return g=Math.trunc(g),g<0&&(g=A+g),(g>=A||g<0)&&eo(A),g}class lo{dim_sel;dim_len;dim_chunk_len;nitems;constructor({dim_sel:A,dim_len:I,dim_chunk_len:B}){A=fo(A,I),this.dim_sel=A,this.dim_len=I,this.dim_chunk_len=B,this.nitems=1}*[Symbol.iterator](){const A=Math.floor(this.dim_sel/this.dim_chunk_len),I=A*this.dim_chunk_len,B=this.dim_sel-I;yield{dim_chunk_ix:A,dim_chunk_sel:B}}}class cC{start;stop;step;dim_len;dim_chunk_len;nitems;nchunks;constructor({dim_sel:A,dim_len:I,dim_chunk_len:B}){const[Q,C,E]=no(A,I);this.start=Q,this.stop=C,this.step=E,this.step<1&&Ho(),this.dim_len=I,this.dim_chunk_len=B,this.nitems=Math.max(0,Math.ceil((this.stop-this.start)/this.step)),this.nchunks=Math.ceil(this.dim_len/this.dim_chunk_len)}*[Symbol.iterator](){const A=Math.floor(this.start/this.dim_chunk_len),I=Math.ceil(this.stop/this.dim_chunk_len);for(const B of ro(A,I)){const Q=B*this.dim_chunk_len,C=Math.min(this.dim_len,(B+1)*this.dim_chunk_len),E=C-Q;let i=0,D=0;if(this.start<Q){const r=(Q-this.start)%this.step;r&&(D+=this.step-r),i=Math.ceil((Q-this.start)/this.step)}else D=this.start-Q;const s=this.stop>C?E:this.stop-Q,h=[D,s,this.step],k=Math.ceil((s-D)/this.step),c=[i,i+k,1];yield{dim_chunk_ix:B,dim_chunk_sel:h,dim_out_sel:c}}}}function po(g,A){let I=[];return g===null?I=A.map(B=>yB(null)):Array.isArray(g)&&(I=g.map(B=>B??yB(null))),qo(I,A),I}class Wo{dim_indexers;shape;constructor({selection:A,shape:I,chunk_shape:B}){this.dim_indexers=po(A,I).map((Q,C)=>new(typeof Q=="number"?lo:cC)({dim_sel:Q,dim_len:I[C],dim_chunk_len:B[C]})),this.shape=this.dim_indexers.filter(Q=>Q instanceof cC).map(Q=>Q.nitems)}*[Symbol.iterator](){for(const A of Yo(...this.dim_indexers)){const I=A.map(Q=>Q.dim_chunk_ix),B=A.map(Q=>"dim_out_sel"in Q?{from:Q.dim_chunk_sel,to:Q.dim_out_sel}:{from:Q.dim_chunk_sel,to:null});yield{chunk_coords:I,mapping:B}}}}function mo(g,A){return"get"in g?g.get(A):g[A]}async function To(g,A,I,B){let Q=Lo(g),C=new Wo({selection:A,shape:g.shape,chunk_shape:g.chunks}),E=B.prepare(new Q.TypedArray(C.shape.reduce((D,s)=>D*s,1)),C.shape,Q.get_strides(C.shape)),i=I.create_queue?.()??Ko();for(const{chunk_coords:D,mapping:s}of C)i.add(async()=>{let{data:h,shape:k,stride:c}=await g.getChunk(D,I.opts),r=B.prepare(h,k,c);B.set_from_chunk(E,r,s)});return await i.onIdle(),C.shape.length===0?mo(E.data,0):E}function yQ(g,A=0,I){let B=I??g.length-A;return{length:B,subarray(Q,C=B){return yQ(g,A+Q,C-Q)},set(Q,C=0){for(let E=0;E<Q.length;E++)g[A+C+E]=Q.get(E)},get(Q){return g[A+Q]}}}function hQ(g){return globalThis.Array.isArray(g.data)?{data:yQ(g.data),stride:g.stride,bytes_per_element:1}:{data:new Uint8Array(g.data.buffer,g.data.byteOffset,g.data.byteLength),stride:g.stride,bytes_per_element:g.data.BYTES_PER_ELEMENT}}function xo(g){return"chars"in g?g.constructor.bind(null,g.chars):g.constructor}function Zo(g,A){if(globalThis.Array.isArray(g.data))return yQ([A]);let I=xo(g.data),B=new I([A]);return new Uint8Array(B.buffer,B.byteOffset,B.byteLength)}const bo={prepare(g,A,I){return{data:g,shape:A,stride:I}},set_scalar(g,A,I){let B=hQ(g);GQ(B,A,Zo(g,I),B.bytes_per_element)},set_from_chunk(g,A,I){let B=hQ(g);hB(B,hQ(A),B.bytes_per_element,I)}};async function uo(g,A=null,I={}){return To(g,A,I,bo)}function LC(g,A,I){return I<0&&A<g?Math.floor((g-A-1)/-I)+1:g<A?Math.floor((A-g-1)/I)+1:0}function GQ(g,A,I,B){if(A.length===0){g.data.set(I,0);return}const[Q,...C]=A,[E,...i]=g.stride;if(typeof Q=="number"){const c=g.data.subarray(E*Q*B);GQ({data:c,stride:i},C,I,B);return}const[D,s,h]=Q,k=LC(D,s,h);if(C.length===0){for(let c=0;c<k;c++)g.data.set(I,E*(D+h*c)*B);return}for(let c=0;c<k;c++){const r=g.data.subarray(E*(D+h*c)*B);GQ({data:r,stride:i},C,I,B)}}function hB(g,A,I,B){const[Q,...C]=B,[E,...i]=g.stride,[D,...s]=A.stride;if(Q.from===null){if(C.length===0){g.data.set(A.data.subarray(0,I),Q.to*I);return}hB({data:g.data.subarray(E*Q.to*I),stride:i},A,I,C);return}if(Q.to===null){if(C.length===0){let q=Q.from*I;g.data.set(A.data.subarray(q,q+I),0);return}hB(g,{data:A.data.subarray(D*Q.from*I),stride:s},I,C);return}const[h,k,c]=Q.to,[r,n,H]=Q.from,M=LC(h,k,c);if(C.length===0){if(c===1&&H===1&&E===1&&D===1){let q=r*I,x=M*I;g.data.set(A.data.subarray(q,q+x),h*I);return}for(let q=0;q<M;q++){let x=D*(r+H*q)*I;g.data.set(A.data.subarray(x,x+I),E*(h+c*q)*I)}return}for(let q=0;q<M;q++)hB({data:g.data.subarray(E*(h+q*c)*I),stride:i},{data:A.data.subarray(D*(r+q*H)*I),stride:s},I,C)}let GB=Po();function Po(){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},version_max(I){let B=A(I);return B.v3>B.v2?"v3":"v2"}}}async function Oo(g){let A=await g.store.get(g.resolve(".zattrs").path);return A?Yg(A):{}}async function Vo(g,A={}){let I="store"in g?g:new mA(g),B={};return(A.attrs??!0)&&(B=await Oo(I)),A.kind==="array"?JC(I,B):A.kind==="group"?rC(I,B):JC(I,B).catch(Q=>(FC(Q,ng),rC(I,B)))}async function JC(g,A){let{path:I}=g.resolve(".zarray"),B=await g.store.get(I);if(!B)throw new ng("v2 array",{cause:new DQ(I)});return GB.increment(g.store,"v2"),new sB(g.store,g.path,Do(Yg(B),A))}async function rC(g,A){let{path:I}=g.resolve(".zgroup"),B=await g.store.get(I);if(!B)throw new ng("v2 group",{cause:new DQ(I)});return GB.increment(g.store,"v2"),new aQ(g.store,g.path,ao(Yg(B),A))}async function Xo(g){let{store:A,path:I}=g.resolve("zarr.json"),B=await g.store.get(I);if(!B)throw new ng("v3 array or group",{cause:new DQ(I)});let Q=Yg(B);return Q.node_type==="array"&&(Q.fill_value=GC(Q)),Q.node_type==="array"?new sB(A,g.path,Q):new aQ(A,g.path,Q)}async function vo(g,A={}){let I="store"in g?g:new mA(g),B=await Xo(I);if(GB.increment(I.store,"v3"),A.kind===void 0||A.kind==="array"&&B instanceof sB||A.kind==="group"&&B instanceof aQ)return B;let Q=B instanceof sB?"array":"group";throw new Error(`Expected node of kind ${A.kind}, found ${Q}.`)}async function VA(g,A={}){let I="store"in g?g.store:g,B=GB.version_max(I),Q=B==="v2"?VA.v2:VA.v3,C=B==="v2"?VA.v3:VA.v2;return Q(g,A).catch(E=>(FC(E,ng),C(g,A)))}VA.v2=Vo,VA.v3=vo;async function jo(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 FQ{#A;constructor(A){this.#A=A}get directoryHandle(){return this.#A}async get(A){const I=await jo(this.#A,A.slice(1)).catch(()=>{});if(!I)return;const Q=await(await I.getFile()).arrayBuffer();return new Uint8Array(Q)}}function zo(){if(typeof window>"u")return;const g=window.location.hostname;if(!(g==="localhost"||g==="127.0.0.1"||g==="0.0.0.0"||g.startsWith("127."))){const I="S3FetchStore is only allowed in local development environments. ";throw new Error(I)}}class wQ extends Ig{credentials;region;signingKeyCache_=new Map;overrides;useSuffixRequest;constructor(A){zo(),super(A.url,{overrides:A.overrides,useSuffixRequest:A.useSuffixRequest}),this.credentials=A.credentials,this.region=A.region,this.overrides=A.overrides,this.useSuffixRequest=A.useSuffixRequest}async get(A,I){if(this.credentials&&this.region){const Q=`${this.url.toString().replace(/\/$/,"")}${A}`,C=await this.generateAuthHeaders(Q,"GET"),E={...I,headers:{...I?.headers,...C}};return super.get(A,E)}return super.get(A,I)}async getRange(A,I,B){if(this.credentials&&this.region){const C=`${this.url.toString().replace(/\/$/,"")}${A}`,E=await this.generateAuthHeaders(C,"HEAD"),i=await this.generateAuthHeaders(C,"GET"),D=globalThis.fetch,s=async(k,c)=>{const n=(c?.method||"GET")==="HEAD"?E:i,H={...c,headers:{...c?.headers,...n}};return D(k,H)},h=globalThis.fetch;globalThis.fetch=s;try{return await super.getRange(A,I,B)}finally{globalThis.fetch=h}}return super.getRange(A,I,B)}async generateAuthHeaders(A,I="GET"){if(!this.credentials||!this.region)return{};const{accessKeyId:B,secretAccessKey:Q,sessionToken:C}=this.credentials,E=this.region,i="s3",D=this.getAmzDate(),s=D.slice(0,8),h=new URL(A),k=h.host,c=h.pathname,r=h.search.slice(1),n=`host:${k}
461
461
  x-amz-content-sha256:UNSIGNED-PAYLOAD
462
462
  x-amz-date:${D}
463
463
  `+(C?`x-amz-security-token:${C}