@idetik/core 0.4.3 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +5 -3
- package/dist/index.js +28 -21
- package/dist/index.js.map +1 -1
- package/dist/index.umd.cjs +1 -1
- package/dist/index.umd.cjs.map +1 -1
- package/dist/types/src/idetik.d.ts +3 -2
- package/dist/types/src/idetik.d.ts.map +1 -1
- package/dist/types/src/objects/cameras/controls.d.ts +2 -0
- package/dist/types/src/objects/cameras/controls.d.ts.map +1 -1
- package/dist/types/src/objects/cameras/orbit_controls.d.ts +9 -3
- package/dist/types/src/objects/cameras/orbit_controls.d.ts.map +1 -1
- package/dist/types/src/renderers/webgl_renderer.d.ts +0 -1
- package/dist/types/src/renderers/webgl_renderer.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.umd.cjs
CHANGED
|
@@ -344,7 +344,7 @@ void main() {
|
|
|
344
344
|
fragColor = vec4(color.rgb, alpha);
|
|
345
345
|
}`;const mE={projectedLine:{vertex:HE,fragment:qE},points:{vertex:dE,fragment:fE},wireframe:{vertex:lE,fragment:pE},floatScalarImage:{vertex:dI,fragment:qB},floatScalarImageArray:{vertex:dI,fragment:dB},intScalarImage:{vertex:dI,fragment:qB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},intScalarImageArray:{vertex:dI,fragment:dB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},uintScalarImage:{vertex:dI,fragment:qB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])},uintScalarImageArray:{vertex:dI,fragment:dB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])},labelImage:{vertex:dI,fragment:WE},floatVolume:{vertex:fB,fragment:lB},intVolume:{vertex:fB,fragment:lB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},uintVolume:{vertex:fB,fragment:lB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])}},ZQ={debug:10,info:20,warn:30,error:40},TE={debug:"\x1B[90m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m"};function xE(){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 j{static logLevel_=xE()==="production"?"warn":"debug";static setLogLevel(A){j.logLevel_=A}static debug(A,I,...B){j.log("debug",A,I,...B)}static info(A,I,...B){j.log("info",A,I,...B)}static warn(A,I,...B){j.log("warn",A,I,...B)}static error(A,I,...B){j.log("error",A,I,...B)}static log(A,I,B,...Q){if(ZQ[A]<ZQ[j.logLevel_])return;const C=new Date().toISOString(),E=TE[A],i=`[${C}][${A.toUpperCase()}][${I}]`,o=[`${E}${i}`,B,...Q];switch(A){case"debug":console.debug(...o);break;case"info":console.info(...o);break;case"warn":console.warn(...o);break;case"error":console.error(...o);break}}}class ZE{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_.FLOAT_VEC2:this.gl_.uniform2fv(B,I);break;case this.gl_.FLOAT_VEC3:this.gl_.uniform3fv(B,I);break;case this.gl_.FLOAT_MAT4:this.gl_.uniformMatrix4fv(B,!1,I);break;case this.gl_.INT:this.gl_.uniform1i(B,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(!uE.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]),j.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 bE=typeof window<"u"?[WebGL2RenderingContext.BOOL,WebGL2RenderingContext.FLOAT,WebGL2RenderingContext.FLOAT_VEC2,WebGL2RenderingContext.FLOAT_VEC3,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]:[],uE=new Set(bE),pB="#pragma inject_defines";class PE{gl_;programs_=new Map;constructor(A){this.gl_=A}use(A){let I=this.programs_.get(A);if(I===void 0){const B=mE[A],Q=bQ(B.vertex,B.vertexDefines),C=bQ(B.fragment,B.fragmentDefines);I=new ZE(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 bQ(g,A){if(A===void 0||A.size==0)return g;if(!g.includes(pB))throw new Error(`Shader source does not contain "${pB}" directive`);const I=Array(A.entries()).map(([E,i])=>`#define ${E} ${i}`).join(`
|
|
346
346
|
`),Q=`#line __LINE__ + ${1-A.size}`,C=`${I}
|
|
347
|
-
${Q}`;return g.replace(pB,C)}const ZA=["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 uQ(){const g=Math.random()*4294967295|0,A=Math.random()*4294967295|0,I=Math.random()*4294967295|0,B=Math.random()*4294967295|0;return(ZA[g&255]+ZA[g>>8&255]+ZA[g>>16&255]+ZA[g>>24&255]+"-"+ZA[A&255]+ZA[A>>8&255]+"-"+ZA[A>>16&15|64]+ZA[A>>24&255]+"-"+ZA[I&63|128]+ZA[I>>8&255]+"-"+ZA[I>>16&255]+ZA[I>>24&255]+ZA[B&255]+ZA[B>>8&255]+ZA[B>>16&255]+ZA[B>>24&255]).toLowerCase()}class WB{uuid=uQ()}var fI=1e-6,lA=typeof Float32Array<"u"?Float32Array:Array,OE=Math.PI/180;function VE(g){return g*OE}Math.hypot||(Math.hypot=function(){for(var g=0,A=arguments.length;A--;)g+=arguments[A]*arguments[A];return Math.sqrt(g)});function PQ(){var g=new lA(9);return lA!=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 XE(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 QI(){var g=new lA(16);return lA!=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 mB(g,A){var I=A[0],B=A[1],Q=A[2],C=A[3],E=A[4],i=A[5],o=A[6],y=A[7],a=A[8],R=A[9],N=A[10],r=A[11],K=A[12],e=A[13],n=A[14],q=A[15],x=I*i-B*E,W=I*o-Q*E,P=I*y-C*E,b=B*o-Q*i,m=B*y-C*i,IA=Q*y-C*o,X=a*e-R*K,Z=a*n-N*K,gA=a*q-r*K,AA=R*n-N*e,wA=R*q-r*e,tA=N*q-r*n,CA=x*tA-W*wA+P*AA+b*gA-m*Z+IA*X;return CA?(CA=1/CA,g[0]=(i*tA-o*wA+y*AA)*CA,g[1]=(Q*wA-B*tA-C*AA)*CA,g[2]=(e*IA-n*m+q*b)*CA,g[3]=(N*m-R*IA-r*b)*CA,g[4]=(o*gA-E*tA-y*Z)*CA,g[5]=(I*tA-Q*gA+C*Z)*CA,g[6]=(n*P-K*IA-q*W)*CA,g[7]=(a*IA-N*P+r*W)*CA,g[8]=(E*wA-i*gA+y*X)*CA,g[9]=(B*gA-I*wA-C*X)*CA,g[10]=(K*m-e*P+q*x)*CA,g[11]=(R*P-a*m-r*x)*CA,g[12]=(i*Z-E*AA-o*X)*CA,g[13]=(I*AA-B*Z+Q*X)*CA,g[14]=(e*W-K*b-n*x)*CA,g[15]=(a*b-R*W+N*x)*CA,g):null}function DB(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=A[4],o=A[5],y=A[6],a=A[7],R=A[8],N=A[9],r=A[10],K=A[11],e=A[12],n=A[13],q=A[14],x=A[15],W=I[0],P=I[1],b=I[2],m=I[3];return g[0]=W*B+P*i+b*R+m*e,g[1]=W*Q+P*o+b*N+m*n,g[2]=W*C+P*y+b*r+m*q,g[3]=W*E+P*a+b*K+m*x,W=I[4],P=I[5],b=I[6],m=I[7],g[4]=W*B+P*i+b*R+m*e,g[5]=W*Q+P*o+b*N+m*n,g[6]=W*C+P*y+b*r+m*q,g[7]=W*E+P*a+b*K+m*x,W=I[8],P=I[9],b=I[10],m=I[11],g[8]=W*B+P*i+b*R+m*e,g[9]=W*Q+P*o+b*N+m*n,g[10]=W*C+P*y+b*r+m*q,g[11]=W*E+P*a+b*K+m*x,W=I[12],P=I[13],b=I[14],m=I[15],g[12]=W*B+P*i+b*R+m*e,g[13]=W*Q+P*o+b*N+m*n,g[14]=W*C+P*y+b*r+m*q,g[15]=W*E+P*a+b*K+m*x,g}function vE(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],o=Q+Q,y=C+C,a=E+E,R=Q*o,N=Q*y,r=Q*a,K=C*y,e=C*a,n=E*a,q=i*o,x=i*y,W=i*a,P=B[0],b=B[1],m=B[2];return g[0]=(1-(K+n))*P,g[1]=(N+W)*P,g[2]=(r-x)*P,g[3]=0,g[4]=(N-W)*b,g[5]=(1-(R+n))*b,g[6]=(e+q)*b,g[7]=0,g[8]=(r+x)*m,g[9]=(e-q)*m,g[10]=(1-(R+K))*m,g[11]=0,g[12]=I[0],g[13]=I[1],g[14]=I[2],g[15]=1,g}function zE(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 _E=zE;function $E(g,A,I,B,Q,C,E){var i=1/(A-I),o=1/(B-Q),y=1/(C-E);return g[0]=-2*i,g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=-2*o,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[10]=2*y,g[11]=0,g[12]=(A+I)*i,g[13]=(Q+B)*o,g[14]=(E+C)*y,g[15]=1,g}var Ai=$E;function Ii(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=B[0],o=B[1],y=B[2],a=Q-I[0],R=C-I[1],N=E-I[2],r=a*a+R*R+N*N;r>0&&(r=1/Math.sqrt(r),a*=r,R*=r,N*=r);var K=o*N-y*R,e=y*a-i*N,n=i*R-o*a;return r=K*K+e*e+n*n,r>0&&(r=1/Math.sqrt(r),K*=r,e*=r,n*=r),g[0]=K,g[1]=e,g[2]=n,g[3]=0,g[4]=R*n-N*e,g[5]=N*K-a*n,g[6]=a*e-R*K,g[7]=0,g[8]=a,g[9]=R,g[10]=N,g[11]=0,g[12]=Q,g[13]=C,g[14]=E,g[15]=1,g}function rA(){var g=new lA(3);return lA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g}function CI(g){var A=new lA(3);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A}function OQ(g){var A=g[0],I=g[1],B=g[2];return Math.hypot(A,I,B)}function NA(g,A,I){var B=new lA(3);return B[0]=g,B[1]=A,B[2]=I,B}function cg(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g}function _I(g,A,I,B){return g[0]=A,g[1]=I,g[2]=B,g}function VQ(g,A,I){return g[0]=A[0]+I[0],g[1]=A[1]+I[1],g[2]=A[2]+I[2],g}function gi(g,A,I){return g[0]=A[0]-I[0],g[1]=A[1]-I[1],g[2]=A[2]-I[2],g}function Bi(g,A,I){return g[0]=A[0]*I[0],g[1]=A[1]*I[1],g[2]=A[2]*I[2],g}function XQ(g,A,I){return g[0]=A[0]*I,g[1]=A[1]*I,g[2]=A[2]*I,g}function vQ(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 jQ(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 Qi(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 zQ(g,A){return g[0]*A[0]+g[1]*A[1]+g[2]*A[2]}function TB(g,A,I){var B=A[0],Q=A[1],C=A[2],E=I[0],i=I[1],o=I[2];return g[0]=Q*o-C*i,g[1]=C*E-B*o,g[2]=B*i-Q*E,g}function Ci(g,A,I,B,Q,C){var E=1-C,i=E*E,o=C*C,y=i*E,a=3*C*i,R=3*o*E,N=o*C;return g[0]=A[0]*y+I[0]*a+B[0]*R+Q[0]*N,g[1]=A[1]*y+I[1]*a+B[1]*R+Q[1]*N,g[2]=A[2]*y+I[2]*a+B[2]*R+Q[2]*N,g}function oB(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 Ei(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)<=fI*Math.max(1,Math.abs(I),Math.abs(C))&&Math.abs(B-E)<=fI*Math.max(1,Math.abs(B),Math.abs(E))&&Math.abs(Q-i)<=fI*Math.max(1,Math.abs(Q),Math.abs(i))}var xB=gi,ii=OQ;(function(){var g=rA();return function(A,I,B,Q,C,E){var i,o;for(I||(I=3),B||(B=0),Q?o=Math.min(Q*I+B,A.length):o=A.length,i=B;i<o;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 Lg(){var g=new lA(4);return lA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0,g[3]=0),g}function Di(g){var A=new lA(4);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A[3]=g[3],A}function ZB(g,A,I,B){var Q=new lA(4);return Q[0]=g,Q[1]=A,Q[2]=I,Q[3]=B,Q}function oi(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g[3]=A[3],g}function ai(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 si(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 aB(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=Lg();return function(A,I,B,Q,C,E){var i,o;for(I||(I=4),B||(B=0),Q?o=Math.min(Q*I+B,A.length):o=A.length,i=B;i<o;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 bB(){var g=new lA(4);return lA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g[3]=1,g}function yi(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 hi(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=I[0],o=I[1],y=I[2],a=I[3];return g[0]=B*a+E*i+Q*y-C*o,g[1]=Q*a+E*o+C*i-B*y,g[2]=C*a+E*y+B*o-Q*i,g[3]=E*a-B*i-Q*o-C*y,g}function uB(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=A[3],o=I[0],y=I[1],a=I[2],R=I[3],N,r,K,e,n;return r=Q*o+C*y+E*a+i*R,r<0&&(r=-r,o=-o,y=-y,a=-a,R=-R),1-r>fI?(N=Math.acos(r),K=Math.sin(N),e=Math.sin((1-B)*N)/K,n=Math.sin(B*N)/K):(e=1-B,n=B),g[0]=e*Q+n*o,g[1]=e*C+n*y,g[2]=e*E+n*a,g[3]=e*i+n*R,g}function _Q(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 Gi=Di,Fi=oi,PB=si;(function(){var g=rA(),A=NA(1,0,0),I=NA(0,1,0);return function(B,Q,C){var E=zQ(Q,C);return E<-.999999?(TB(g,A,Q),ii(g)<1e-6&&TB(g,I,Q),Qi(g,g),yi(B,g,Math.PI),B):E>.999999?(B[0]=0,B[1]=0,B[2]=0,B[3]=1,B):(TB(g,Q,C),B[0]=g[0],B[1]=g[1],B[2]=g[2],B[3]=1+E,PB(B,B))}})(),function(){var g=bB(),A=bB();return function(I,B,Q,C,E,i){return uB(g,B,E,i),uB(A,Q,C,i),uB(I,g,A,2*i*(1-i)),I}}(),function(){var g=PQ();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],PB(A,_Q(A,g))}}();function $Q(){var g=new lA(2);return lA!=Float32Array&&(g[0]=0,g[1]=0),g}function AC(g){var A=new lA(2);return A[0]=g[0],A[1]=g[1],A}function pA(g,A){var I=new lA(2);return I[0]=g,I[1]=A,I}function wi(g,A){var I=A[0]-g[0],B=A[1]-g[1];return Math.hypot(I,B)}function Si(g){var A=g[0],I=g[1];return A*A+I*I}function Ri(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 IC(g,A){return g[0]===A[0]&&g[1]===A[1]}function OB(g,A){var I=g[0],B=g[1],Q=A[0],C=A[1];return Math.abs(I-Q)<=fI*Math.max(1,Math.abs(I),Math.abs(Q))&&Math.abs(B-C)<=fI*Math.max(1,Math.abs(B),Math.abs(C))}(function(){var g=$Q();return function(A,I,B,Q,C,E){var i,o;for(I||(I=2),B||(B=0),Q?o=Math.min(Q*I+B,A.length):o=A.length,i=B;i<o;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 kI{min;max;constructor(A,I){this.min=A?CI(A):NA(1/0,1/0,1/0),this.max=I?CI(I):NA(-1/0,-1/0,-1/0)}clone(){return new kI(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=[NA(I[0],I[1],I[2]),NA(I[0],I[1],B[2]),NA(I[0],B[1],I[2]),NA(I[0],B[1],B[2]),NA(B[0],I[1],I[2]),NA(B[0],I[1],B[2]),NA(B[0],B[1],I[2]),NA(B[0],B[1],B[2])];this.min=NA(1/0,1/0,1/0),this.max=NA(-1/0,-1/0,-1/0);const C=rA();for(const E of Q)oB(C,E,A),this.expandWithPoint(C)}}const Ni={position:0,normal:1,uv:2,next_position:3,previous_position:4,direction:5,path_proportion:6,color:7,size:8,marker:9};class $I extends WB{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 kI,Q=rA();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 Ui{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(a=>{const R=Ni[a.type];this.gl_.vertexAttribPointer(R,a.itemSize,this.gl_.FLOAT,!1,i,a.offset),this.gl_.enableVertexAttribArray(R)});const o={vao:I,vbo:C},{indexData:y}=A;if(y.length){const a=this.gl_.ELEMENT_ARRAY_BUFFER,R=this.gl_.createBuffer();if(!R)throw new Error("Failed to create index buffer (EBO)");this.gl_.bindBuffer(a,R),this.gl_.bufferData(a,y,this.gl_.STATIC_DRAW),o.ebo=R}this.buffers_.set(A,o),this.gl_.bindVertexArray(null)}}class ti{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 j.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),o=0;for(let y=0;y<Q;y++)o+=E*i*C*B,E=Math.max(1,E>>1),i=Math.max(1,i>>1);return o}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 zA{min;max;constructor(A,I){this.min=A?AC(A):pA(1/0,1/0),this.max=I?AC(I):pA(-1/0,-1/0)}clone(){return new zA(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 IC(A.min,I.min)&&IC(A.max,I.max)}floor(){return new zA(pA(Math.floor(this.min[0]),Math.floor(this.min[1])),pA(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 ki{gl_;enabledCapabilities_=new Map;depthMaskEnabled_=null;blendSrcFactor_=null;blendDstFactor_=null;currentBlendingMode_=null;currentViewport_=null;currentScissor_=null;currentCullingMode_=null;constructor(A){this.gl_=A}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"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_&&zA.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_&&zA.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}}}const ci=vE(QI(),[1,-1,1]);class gC extends eE{gl_=null;programs_;bindings_;textures_;state_;renderedObjectsPerFrame_=0;constructor(A){if(super(A),this.gl_=this.canvas.getContext("webgl2",{depth:!0,antialias:!0}),!this.gl_)throw new Error("Failed to initialize WebGL2 context");j.info("WebGLRenderer",`WebGL version ${this.gl.getParameter(this.gl.VERSION)}`),this.programs_=new PE(this.gl),this.bindings_=new Ui(this.gl),this.textures_=new ti(this.gl),this.state_=new ki(this.gl),this.resize(this.canvas.width,this.canvas.height)}render(A){const I=A.getBoxRelativeTo(this.canvas),B=new zA(pA(0,0),pA(this.width,this.height));if(zA.equals(I.floor(),B.floor()))this.state_.setScissorTest(!1);else if(zA.intersects(I,B))this.state_.setScissor(I),this.state_.setScissorTest(!0);else{j.warn("WebGLRenderer",`Viewport ${A.id} is entirely outside canvas bounds, skipping render`);return}this.state_.setViewport(I),this.renderedObjectsPerFrame_=0,this.clear();const{opaque:Q,transparent:C}=A.layerManager.partitionLayers();this.state_.setDepthMask(!0);const E=A.camera.frustum,i={viewport:A};for(const o of Q)o.update(i),o.state==="ready"&&this.renderLayer(o,A.camera,E);this.state_.setDepthMask(!1);for(const o of C)o.update(i),o.state==="ready"&&this.renderLayer(o,A.camera,E);this.state_.setDepthMask(!0),this.renderedObjects_=this.renderedObjectsPerFrame_}get textureInfo(){return this.textures_.textureInfo}renderLayer(A,I,B){this.state_.setBlendingMode(A.transparent?A.blendMode:"none"),A.objects.forEach((Q,C)=>{B.intersectsWithBox3(Q.boundingBox)&&(this.renderObject(A,C,I),this.renderedObjectsPerFrame_+=1)})}renderObject(A,I,B){const Q=A.objects[I];this.state_.setCullFaceMode(Q.cullFaceMode),this.bindings_.bindGeometry(Q.geometry),Q.popStaleTextures().forEach(E=>{this.textures_.disposeTexture(E)}),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=DB(QI(),C.viewMatrix,I.transform.matrix),i=DB(QI(),ci,C.projectionMatrix),o=[this.canvas.width,this.canvas.height],y=I.getUniforms();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,o);break;case"u_opacity":Q.setUniform(N,B.opacity);break;default:N in y&&Q.setUniform(N,y[N])}const a=this.glGetPrimitive(A.primitive),R=A.indexData;R.length?this.gl.drawElements(a,R.length,this.gl.UNSIGNED_INT,0):this.gl.drawArrays(a,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 zA(pA(0,0),pA(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)}get gl(){return this.gl_}}const Li=8;class Ji{maxConcurrent_;pending_=[];running_=new Map;constructor(A=Li){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),j.debug("ChunkQueue","Cancelled pending request");return}const B=this.running_.get(A);B&&(B.controller.abort(),j.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"&&j.error("ChunkQueue",String(E))}).finally(()=>{this.running_.delete(I),this.pump()});this.running_.set(I,{controller:Q,promise:C})}}const BC=[Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array];function QC(g){if(BC.some(I=>g instanceof I))return!0;const A=BC.map(I=>I.name);return j.debug("Chunk",`Unsupported chunk data type: ${g}. Supported data types: ${A}`),!1}function ri(g,A){return Math.round((A-g.translation)/g.scale)}function VB(g,A,I=1e-6){return Math.abs(g-A)<=I}function Jg(g,A,I){return Math.max(A,Math.min(I,g))}const CC=Symbol("INTERNAL_POLICY_KEY");class Yi{store_;policy_;policyChanged_=!1;currentLOD_=0;lastViewBounds2D_=null;lastZBounds_;lastTCoord_;sourceMaxSquareDistance2D_;chunkViewStates_=new Map;constructor(A,I){this.store_=A,this.policy_=I,j.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_=Si(pA(Q.size*Q.scale,C.size*C.scale))}get chunkViewStates(){return this.chunkViewStates_}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.store_.getLowestResLOD();return this.currentLOD_===C?Q:[...B.filter(i=>i.lod===C&&this.chunkViewStates_.get(i)?.visible===!0&&i.state==="loaded"),...Q]}updateChunkStates(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,o=I.getBoxRelativeTo(i).toRect().width,y=E/o,a=Math.log2(1/y);this.setLOD(a);const R=this.getZBounds(A);(this.policyChanged_||this.viewBounds2DChanged(C)||this.zBoundsChanged(R)||this.lastTCoord_!==A.t)&&(this.updateChunkViewStates(A,C),this.policyChanged_=!1,this.lastViewBounds2D_=C.clone(),this.lastZBounds_=R,this.lastTCoord_=A.t)}allVisibleLowestLODLoaded(A){const I=this.store_.getTimeIndex(A),B=this.store_.getChunksAtTime(I).filter(Q=>Q.visible&&Q.lod===this.store_.getLowestResLOD());return B.length>0&&B.every(Q=>Q.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.store_.removeView(this)}setImageSourcePolicy(A,I){if(I!==CC)throw new Error("Unauthorized policy mutation");this.policy_!==A&&(this.policy_=A,this.policyChanged_=!0,j.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(),o=Math.max(0,Math.min(i,this.policy_.lod.min)),y=Math.max(o,Math.min(i,this.policy_.lod.max)),a=Jg(E,o,y);a!==this.currentLOD_&&(this.currentLOD_=a)}updateChunkViewStates(A,I){const B=this.store_.getTimeIndex(A);if(this.store_.getChunksAtTime(B).length===0){j.warn("ChunkStoreView","updateChunkViewStates called with no chunks initialized"),this.chunkViewStates_.clear();return}const C=$Q();Ri(C,I.min,I.max,.5);const[E,i]=this.getZBounds(A),o=new kI(NA(I.min[0],I.min[1],E),NA(I.max[0],I.max[1],i));this.chunkViewStates_.forEach(ni),this.updateChunksAtTimeIndex(B,A,o,C),A.t!==void 0&&this.markTimeChunksForPrefetch(B,o,C)}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);for(const i of E){const o=this.isChunkWithinBounds(i,B),y=this.isChunkChannelInSlice(i,I),a=i.lod===this.currentLOD_,R=i.lod===this.store_.getLowestResLOD(),N=!o&&y&&a&&this.isChunkWithinBounds(i,C),r=o&&y,K=this.computePriority(R,a,o,N,y);if(K!==null){const e=this.squareDistance2D(i,Q);this.chunkViewStates_.set(i,{visible:r,prefetch:N,priority:K,orderKey:e})}}}markTimeChunksForPrefetch(A,I,B){const Q=this.store_.dimensions.t?.lods[0].size??1,C=Math.min(Q-1,A+this.policy_.prefetch.t);for(let E=A+1;E<=C;++E)for(const i of this.store_.getChunksAtTime(E)){if(i.lod!==this.store_.getLowestResLOD()||!this.isChunkWithinBounds(i,I))continue;const o=this.policy_.priorityMap.prefetchTime,y=this.squareDistance2D(i,B),a=Jg(y/this.sourceMaxSquareDistance2D_,0,1-Number.EPSILON),R=E-A+a;this.chunkViewStates_.set(i,{visible:!1,prefetch:!0,priority:o,orderKey:R})}}computePriority(A,I,B,Q,C){if(!C)return null;const E=this.policy_.priorityMap;return A&&B?E.fallbackVisible:I&&B?E.visibleCurrent:A?E.fallbackBackground:I&&Q?E.prefetchSpace:null}isChunkWithinBounds(A,I){const B=new kI(NA(A.offset.x,A.offset.y,A.offset.z),NA(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 kI.intersects(B,I)}getZBounds(A){const I=this.store_.dimensions.z;if(I===void 0||A.z===void 0)return[0,1];const B=I.lods[this.currentLOD_],Q=B.size,C=B.scale,E=B.translation,i=Math.floor((A.z-E)/C),o=B.chunkSize,y=Math.max(0,Math.min(Math.floor(i/o),Math.ceil(Q/o)-1));return[E+y*o*C,E+(y+1)*o*C]}viewBounds2DChanged(A){return this.lastViewBounds2D_===null||!OB(this.lastViewBounds2D_.min,A.min)||!OB(this.lastViewBounds2D_.max,A.max)}zBoundsChanged(A){return!this.lastZBounds_||!OB(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 o=0;return C&&(o=C.chunkSize*C.scale*this.policy_.prefetch.z),new kI(NA(A.min[0]-E,A.min[1]-i,A.min[2]-o),NA(A.max[0]+E,A.max[1]+i,A.max[2]+o))}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 ni(g){g.visible=!1,g.prefetch=!1,g.priority=null,g.orderKey=null}class Ki{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],o=this.dimensions_.y.lods[E],y=this.dimensions_.z?.lods[E],a=i.chunkSize,R=o.chunkSize,N=y?.chunkSize??1,r=Math.ceil(i.size/a),K=Math.ceil(o.size/R),e=Math.ceil((y?.size??1)/N);for(let n=0;n<B;++n)for(let q=0;q<r;++q){const x=i.translation+q*i.chunkSize*i.scale;for(let W=0;W<K;++W){const P=o.translation+W*o.chunkSize*o.scale;for(let b=0;b<e;++b){const m=y!==void 0?y.translation+b*N*y.scale:0;C.push({state:"unloaded",lod:E,visible:!1,prefetch:!1,priority:null,orderKey:null,shape:{x:Math.min(a,i.size-q*a),y:Math.min(R,o.size-W*R),z:Math.min(N,(y?.size??1)-b*N),c:1},rowAlignmentBytes:1,chunkIndex:{x:q,y:W,z:b,c:n,t:Q},scale:{x:i.scale,y:o.scale,z:y?.scale??1},offset:{x,y:P,z:m}})}}}}}}getChunksAtTime(A){return this.chunks_[A]}getTimeIndex(A){return A.t===void 0||this.dimensions_.t===void 0?0:ri(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 Yi(this,A);return this.views_.push(I),this.hasHadViews_=!0,I}removeView(A){const I=this.views_.indexOf(A);if(I===-1)throw new Error("Cannot remove view: view not found in store's view list");const B=Array.from(A.chunkViewStates.keys());this.views_.splice(I,1);for(const Q of B)this.aggregateChunkViewStates(Q)}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 A}aggregateChunkViewStates(A){let I=!1,B=!1,Q=null,C=null;for(const y of this.views_){const a=y.chunkViewStates.get(A);a&&(a.visible&&(I=!0),a.prefetch&&(B=!0),a.priority!==null&&(Q===null||a.priority<Q)&&(Q=a.priority,C=a.orderKey),!a.visible&&!a.prefetch&&a.priority===null&&y.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,j.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(!VB(Q,2,.02)||!VB(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;if(I.chunkSize!==1)throw new Error(`ChunkStore only supports a chunk size of 1 in t. Found ${I.chunkSize} at LOD ${A}`);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.chunkSize!==1)throw new Error(`ChunkStore only supports a chunk size of 1 in c. Found ${I.chunkSize} at LOD ${A}`);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 Mi{stores_=new Map;pendingStores_=new Map;queue_=new Ji;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 Ki(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 rg=function(g=1){var A=0,I=document.createElement("div");I.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",I.addEventListener("click",function(R){R.preventDefault(),Q(++A%I.children.length)},!1);function B(R){return I.appendChild(R.dom),R}function Q(R){for(var N=0;N<I.children.length;N++)I.children[N].style.display=N===R?"block":"none";A=R}var C=(performance||Date).now(),E=C,i=0,o=B(new rg.Panel("FPS","#0ff","#002",g)),y=B(new rg.Panel("MS","#0f0","#020",g));if(self.performance&&self.performance.memory)var a=B(new rg.Panel("MB","#f08","#201",g));return Q(0),{REVISION:16,dom:I,addPanel:B,showPanel:Q,begin:function(){C=(performance||Date).now()},end:function(){i++;var R=(performance||Date).now();if(y.update(R-C,200),R>=E+1e3&&(o.update(i*1e3/(R-E),100),E=R,i=0,a)){var N=performance.memory;a.update(N.usedJSHeapSize/1048576,N.jsHeapSizeLimit/1048576)}return R},update:function(){C=this.end()},domElement:I,setMode:Q}};rg.Panel=function(g,A,I,B){var Q=1/0,C=0,E=Math.round,i=E(window.devicePixelRatio||1),o=E(80*i*B),y=E(48*i*B),a=E(3*i*B),R=E(2*i*B),N=E(3*i*B),r=E(15*i*B),K=E(74*i*B),e=E(30*i*B),n=document.createElement("canvas");n.width=o,n.height=y,n.style.cssText=`width:${E(B*80)}px;height:${E(B*48)}px`;var q=n.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,o,y),q.fillStyle=A,q.fillText(g,a,R),q.fillRect(N,r,K,e),q.fillStyle=I,q.globalAlpha=.9,q.fillRect(N,r,K,e),{dom:n,update:function(x,W){Q=Math.min(Q,x),C=Math.max(C,x),q.fillStyle=I,q.globalAlpha=1,q.fillRect(0,0,o,r),q.fillStyle=A,q.fillText(E(x)+" "+g+" ("+E(Q)+"-"+E(C)+")",a,R),q.drawImage(n,N+i,r,K-i,e,N,r,K-i,e),q.fillRect(N+K-i,r,i,e),q.fillStyle=I,q.globalAlpha=.9,q.fillRect(N+K-i,r,i,E((1-x/W)*e))}}};function ei({scale:g}={scale:1.5}){const A=new rg(g);return A.showPanel(0),document.body.appendChild(A.dom),A}class EC{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 Hi(g){return XB.includes(g)}class qi{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_){j.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_){j.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(!Hi(A.type)){j.error("EventDispatcher",`Unsupported event type ${A.type}`);return}const I=new qi(A.type,A);for(const B of this.listeners_)if(B(I),I.propagationStopped)break}}class iC{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=pA(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,o=I.x-C,y=I.y-E,a=Math.floor(o),R=Math.floor(i-y-I.height),N=Math.floor(I.width),r=Math.floor(I.height);return new zA(pA(a,R),pA(a+N,R+r))}clientToClip(A,I=0){const[B,Q]=A,C=this.element.getBoundingClientRect();return NA(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 zA(pA(B,Q),pA(B+C,Q+E))}updateAspectRatio(){const{width:A,height:I}=this.getBox().toRect();if(A<=0||I<=0){j.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 fi(g){const A=new Map,I=new Set;for(const B of g){if(I.has(B.id))throw new Error(`Duplicate viewport ID "${B.id}". Each viewport must have a unique ID.`);if(I.add(B.id),A.has(B.element)){const Q=A.get(B.element),C=B.element.tagName.toLowerCase()+(B.element.id?`#${B.element.id}`:"[element has no id]");throw new Error(`Multiple viewports cannot share the same HTML element: viewports "${Q}" and "${B.id}" both use ${C}`)}A.set(B.element,B.id)}}function DC(g,A,I){const B=g.map(Q=>{const C=Q.element??A;return{...Q,element:C,id:Q.id??C.id??uQ(),layerManager:new EC(I)}});return fi(B),B.map(Q=>new iC(Q))}class li{elements_;resizeObserver_;mediaQuery_;onMediaQueryChange_;onChange_;constructor(A=[],I){this.elements_=A,this.onChange_=I}connect(){if(this.resizeObserver_){j.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_){j.warn("PixelSizeObserver","Attempted to disconnect already disconnected observer");return}this.resizeObserver_?.disconnect(),this.mediaQuery_&&this.onMediaQueryChange_&&this.mediaQuery_.removeEventListener("change",this.onMediaQueryChange_)}}class pi{lastAnimationId_;chunkManager_;context_;renderer_;viewports_;canvas;overlays;stats_;sizeObserver_;constructor(A){if(this.canvas=A.canvas,A.viewports.length===0)throw new Error("At least one viewport config must be specified.");this.renderer_=new gC(this.canvas),this.chunkManager_=new Mi,this.context_={chunkManager:this.chunkManager_},this.viewports_=DC(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 li(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_}getViewport(A){return this.viewports_.find(I=>I.id===A)}start(){if(j.info("Idetik","Idetik runtime starting"),this.lastAnimationId_===void 0){for(const A of this.viewports_)A.events.connect();this.sizeObserver_.connect(),this.animate()}else j.warn("Idetik","Idetik runtime already started");return this}animate(A){this.stats_&&this.stats_.begin();for(const I of this.viewports_)this.renderer_.render(I);this.chunkManager_.update();for(const I of this.overlays)I.update(this,A);this.stats_&&this.stats_.end(),this.lastAnimationId_=requestAnimationFrame(I=>this.animate(I))}stop(){if(j.info("Idetik","Idetik runtime stopping"),this.lastAnimationId_===void 0)j.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 Wi extends $I{constructor(A){if(super(),A.primitive!="triangles"){j.warn("WireframeGeometry","Only indexed geometries are supported");return}if(A.indexData.length==0){j.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 o=Math.min(E,i),y=Math.max(E,i);I.has({i0:o,i1:y})||(I.add({i0:o,i1:y}),B.push(o,y))},C=A.indexData;for(let E=0;E<C.length;E+=3){const i=C[E],o=C[E+1],y=C[E+2];Q(i,o),Q(o,y),Q(y,i)}this.indexData_=new Uint32Array(B)}}const mi=NA(0,1,0);class Ti{dirty_=!0;matrix_=QI();rotation_=bB();translation_=rA();scale_=NA(1,1,1);addRotation(A){hi(this.rotation_,this.rotation_,A),this.dirty_=!0}setRotation(A){Fi(this.rotation_,A),this.dirty_=!0}get rotation(){return Gi(this.rotation_)}addTranslation(A){VQ(this.translation_,this.translation_,A),this.dirty_=!0}setTranslation(A){cg(this.translation_,A),this.dirty_=!0}get translation(){return CI(this.translation_)}addScale(A){Bi(this.scale_,this.scale_,A),this.dirty_=!0}setScale(A){cg(this.scale_,A),this.dirty_=!0}targetTo(A){Ei(this.translation_,A)&&(A=CI(A),A[2]+=fI);const I=Ii(QI(),this.translation_,A,mi),B=XE(PQ(),I);_Q(this.rotation_,B),PB(this.rotation_,this.rotation_),this.dirty_=!0}get scale(){return CI(this.scale_)}get matrix(){return this.dirty_&&(this.computeMatrix(),this.dirty_=!1),this.matrix_}get inverse(){return mB(QI(),this.matrix)}computeMatrix(){jE(this.matrix_,this.rotation_,this.translation_,this.scale_)}}class Ag extends WB{wireframeEnabled=!1;wireframeColor=hA.WHITE;textures_=[];staleTextures_=[];transform_=new Ti;geometry_=new $I;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 Wi(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(){if(this.programName_===null)throw new Error("Program name not set");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 lI{normal;signedDistance;constructor(A=NA(0,1,0),I=0){this.normal=CI(A),this.signedDistance=I}set(A,I){this.normal=CI(A),this.signedDistance=I}signedDistanceToPoint(A){return zQ(this.normal,A)+this.signedDistance}normalize(){const A=OQ(this.normal);if(A>0){const I=1/A;XQ(this.normal,this.normal,I),this.signedDistance*=I}}}class oC{planes_;constructor(A){this.planes_=[new lI(rA(),0),new lI(rA(),0),new lI(rA(),0),new lI(rA(),0),new lI(rA(),0),new lI(rA(),0)],this.setWithViewProjection(A)}setWithViewProjection(A){const I=rA();this.planes_[0].set(_I(I,A[3]+A[0],A[7]+A[4],A[11]+A[8]),A[15]+A[12]),this.planes_[1].set(_I(I,A[3]-A[0],A[7]-A[4],A[11]-A[8]),A[15]-A[12]),this.planes_[2].set(_I(I,A[3]-A[1],A[7]-A[5],A[11]-A[9]),A[15]-A[13]),this.planes_[3].set(_I(I,A[3]+A[1],A[7]+A[5],A[11]+A[9]),A[15]+A[13]),this.planes_[4].set(_I(I,A[3]+A[2],A[7]+A[6],A[11]+A[10]),A[15]+A[14]),this.planes_[5].set(_I(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=rA();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 aC extends Ag{projectionMatrix_=QI();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 NA(A[0],A[1],A[2])}get up(){const A=this.transform.matrix;return NA(A[4],A[5],A[6])}get frustum(){return new oC(DB(QI(),this.projectionMatrix,this.viewMatrix))}pan(A){this.transform.addTranslation(A)}get position(){return this.transform.translation}clipToWorld(A){const I=ZB(A[0],A[1],A[2],1),B=mB(QI(),this.projectionMatrix_),Q=aB(Lg(),I,B);ai(Q,Q,1/Q[3]);const C=aB(Lg(),Q,this.transform.matrix);return NA(C[0],C[1],C[2])}}const sC=1.77,yC=128,hC=128/sC;class xi extends aC{width_=yC;height_=hC;viewportAspectRatio_=sC;viewportSize_=[yC,hC];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=ZB(-1,-1,0,1),I=ZB(1,1,0,1);const B=DB(QI(),this.projectionMatrix,this.viewMatrix),Q=mB(QI(),B);return A=aB(Lg(),A,Q),I=aB(Lg(),I,Q),new zA(pA(A[0],A[1]),pA(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],Ai(this.projectionMatrix_,-Q,Q,-C,C,this.near_,this.far_)}}const Zi=60,bi=1.77,sB=.1,vB=180-sB;class ui extends aC{fov_;aspectRatio_;constructor(A={}){const{fov:I=Zi,aspectRatio:B=bi,near:Q=.1,far:C=1e4,position:E=NA(0,0,0)}=A;if(I<sB||I>vB)throw new Error(`Invalid field of view: ${I}, must be in [${sB}, ${vB}] 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(sB,Math.min(vB,this.fov_/A)),this.updateProjectionMatrix()}updateProjectionMatrix(){_E(this.projectionMatrix_,VE(this.fov),this.aspectRatio_,this.near_,this.far_)}}const GC=0;class Pi{camera_;dragActive_=!1;dragStart_=rA();constructor(A){this.camera_=A}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}}onWheel(A){if(!A.worldPos||!A.clipPos)return;const I=A.event;I.preventDefault();const B=CI(A.worldPos),Q=I.deltaY<0?1.05:.95;this.camera_.zoom(Q);const C=this.camera_.clipToWorld(A.clipPos),E=xB(rA(),B,C);this.camera_.pan(E)}onPointerDown(A){const I=A.event;!A.worldPos||I.button!==GC||(this.dragStart_=CI(A.worldPos),this.dragActive_=!0,I.target?.setPointerCapture?.(I.pointerId))}onPointerMove(A){if(!this.dragActive_||!A.worldPos)return;const I=xB(rA(),this.dragStart_,A.worldPos);this.camera_.pan(I)}onPointerEnd(A){const I=A.event;!this.dragActive_||I.button!==GC||(this.dragActive_=!1,I.target?.releasePointerCapture?.(I.pointerId))}}class SI{objects_=[];state_="initialized";callbacks_=[];transparent;opacity_;blendMode;constructor({transparent:A=!1,opacity:I=1,blendMode:B="normal"}={}){(I<0||I>1)&&j.warn("Layer",`Layer opacity out of bounds: ${I} — clamping to [0.0, 1.0]`),this.transparent=A,this.opacity_=Jg(I,0,1),this.blendMode=B}get opacity(){return this.opacity_}set opacity(A){(A<0||A>1)&&j.warn("Layer",`Opacity out of bounds: ${A} — clamping to [0.0, 1.0]`),this.opacity_=Jg(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)}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_=[]}}class yB extends $I{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,o)=>E+jQ(i,A[o+1]??i),0);for(const E of[...Array(A.length).keys()]){for(const i of[-1,1]){const o=A[E];I[B++]=o[0],I[B++]=o[1],I[B++]=o[2];const y=A[E-1]??A[E];I[B++]=y[0],I[B++]=y[1],I[B++]=y[2];const a=A[E+1]??A[E];I[B++]=a[0],I[B++]=a[1],I[B++]=a[2],I[B++]=i,I[B++]=Q}Q+=jQ(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 jB extends Ag{color_;width_;taperOffset_=.5;taperPower_=0;constructor({geometry:A,color:I,width:B,taperOffset:Q,taperPower:C}){super(),this.geometry=A,this.color_=hA.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_=hA.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 Oi extends SI{type="AxesLayer";constructor(A){super();const{length:I,width:B}=A;this.addObject(zB({end:[I,0,0],width:B,color:[1,0,0]})),this.addObject(zB({end:[0,I,0],width:B,color:[0,1,0]})),this.addObject(zB({end:[0,0,I],width:B,color:[0,0,1]})),this.setState("ready")}update(){}}function zB(g){const{end:A,width:I,color:B}=g,Q=new yB([[0,0,0],A]);return new jB({geometry:Q,color:B,width:I})}class Vi extends SI{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 yB(I);this.addObject(new jB({geometry:C,color:B,width:Q}))}update(){}get extent(){return Xi(this.paths_.flat())}}function Xi(g){function A(o){const y=g.map(a=>a[o]);return[Math.min(...y),Math.max(...y)]}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 vi extends SI{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=zi({path:A.path,pointsPerSegment:A.interpolation.pointsPerSegment,tangentFactor:A.interpolation.tangentFactor});I=new yB(i)}else I=new yB(A.path);const{color:B,width:Q}=A,C=.5,E=1.5;this.addObject(new jB({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 ji(A.flat())}}function ji(g){function A(o){const y=g.map(a=>a[o]);return[Math.min(...y),Math.max(...y)]}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 zi({path:g,pointsPerSegment:A,tangentFactor:I=1/3}){const B=_i(g),Q=Array((g.length-1)*A);for(let C=0;C<g.length-1;C++){const E=g[C],i=g[C+1],o=CI(B[C]);vQ(o,E,o,I);const y=CI(B[C+1]);vQ(y,i,y,-I);for(let a=0;a<A;a++){const R=a/A,N=Q[C*A+a]=rA();Ci(N,E,o,y,i,R)}}return Q}function _i(g){if(g.length<2)throw new Error("Path must contain at least 2 points");const A=Array(g.length),I=rA(),B=rA();for(let Q=0;Q<g.length;Q++){const C=g[Q],E=g[Q+1]??g[Q];A[Q]=rA(),Q!==0&&cg(I,B),Q!==g.length-1&&xB(B,E,C),Q===0?cg(A[Q],B):Q==g.length-1?cg(A[Q],I):(VQ(A[Q],I,B),XQ(A[Q],A[Q],.5))}return A}class FC extends $I{constructor(A,I,B,Q){super();const C=[],E=[],i=B,o=Q,y=i+1,a=o+1,R=A/i,N=I/o;for(let r=0;r<a;++r){const K=r*N;for(let e=0;e<y;++e){const n=e*R,q=e/i,x=r/o,W=[n,K,0],P=[0,0,1],b=[q,x];C.push(...W,...P,...b)}}for(let r=0;r<o;++r)for(let K=0;K<i;++K){const e=K+y*r,n=K+y*(r+1),q=K+1+y*(r+1),x=K+1+y*r;E.push(e,n,x),E.push(n,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 wC(g){return g===1||g===2||g===4||g===8}function Ig(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 $i(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 _B extends WB{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 SC=32;function $B(g,{visible:A,color:I,contrastLimits:B}){return A===void 0&&(A=!0),I===void 0?I=hA.WHITE:I=hA.from(I),g!==null?B=AD(B,g):B===void 0&&(j.debug("Channel","No texture provided, defaulting channel contrast limits to [0, 1]."),B=[0,1]),{visible:A,color:I,contrastLimits:B}}function RC(g,A){if(A.length>SC)throw new Error(`Maximum number of channels is ${SC}`);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=>$B(g,I))}function AD(g,A){if(g===void 0)return $i(A);if(g[1]<=g[0])throw new Error(`Contrast limits must be strictly increasing: ${g}.`);return g}class AQ extends Ag{channels_;constructor(A,I,B,Q=[]){super(),this.geometry=new FC(A,I,1,1),this.setTexture(0,B),this.channels_=RC(B,Q),this.programName=ID(B)}get type(){return"ImageRenderable"}setChannelProps(A){this.channels_=RC(this.textures[0],A)}setChannelProperty(A,I,B){const Q=$B(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]??$B(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 ID(g){if(g.type==="Texture2D")return gD(g.dataType);if(g.type==="Texture2DArray")return BD(g.dataType);throw new Error(`Unsupported image texture type: ${g.type}`)}function gD(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 BD(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 gg extends _B{data_;width_;height_;depth_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=Ig(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!=Ig(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 gg(B,A.shape.x,A.shape.y);return Q.unpackAlignment=A.rowAlignmentBytes,Q}}function IQ(g,A,I,B,Q=3){switch(g.type){case"pointerdown":{const C=g.event;return pA(C.clientX,C.clientY)}case"pointerup":{if(!A)return A;const C=g.event,E=pA(C.clientX,C.clientY);if(wi(A,E)<Q){if(!B)return null;const o=g.worldPos;if(o){const y=I(o);y!==null&&B({world:o,value:y})}return null}return A}case"pointercancel":return null;default:return A}}class QD{bins_=new Map;acquire(A){const B=this.bins_.get(A)?.pop();return B&&j.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),j.debug("RenderablePool","Renderable object released")}clearAll(A){if(A)for(const I of this.bins_.values())I.forEach(A);this.bins_.clear()}}class gQ extends SI{type="ChunkedImageLayer";source_;sliceCoords_;onPickValue_;visibleChunks_=new Map;pool_=new QD;initialChannelProps_;channelChangeCallbacks_=[];policy_;channelProps_;chunkStoreView_;pointerDownPos_=null;zPrevPointWorld_;debugMode_=!1;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;wireframeColors_=[new hA(.6,.3,.3),new hA(.3,.6,.4),new hA(.4,.4,.7),new hA(.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.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_&&(this.chunkStoreView_.dispose(),this.chunkStoreView_=void 0)}update(A){!A||!this.chunkStoreView_||(this.chunkStoreView_.updateChunkStates(this.sliceCoords_,A.viewport),this.updateChunks(),this.resliceIfZChanged())}updateChunks(){if(!this.chunkStoreView_||(this.state!=="ready"&&this.setState("ready"),this.visibleChunks_.size>0&&!this.chunkStoreView_.allVisibleLowestLODLoaded(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)}}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>gQ.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_=IQ(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,CC))}slicePlane(A,I){if(!A.data)return;const B=(I-A.offset.z)/A.scale.z,Q=Math.round(B),C=Jg(Q,0,A.shape.z-1);VB(B,C,1+1e-6)||j.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(NC(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 AQ(A.shape.x,A.shape.y,gg.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){j.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=oB(rA(),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,o=E*A.shape.x+C;return i[o]}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(NC(I),B),this.visibleChunks_.delete(I))}}}function NC(g){return[`lod${g.lod}`,`shape${g.shape.x}x${g.shape.y}`,`align${g.rowAlignmentBytes}`].join(":")}class hB extends _B{data_;width_;height_;depth_;constructor(A,I,B,Q){super(),this.dataFormat="scalar",this.dataType=Ig(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!=Ig(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 hB(I,A.shape.x,A.shape.y,A.shape.z);return B.unpackAlignment=A.rowAlignmentBytes,B}}class CD extends $I{constructor(A,I,B,Q,C,E){super();const i=[],o=[],y=Math.floor(Q),a=Math.floor(C),R=Math.floor(E);this.buildFace("z","y","x",-1,-1,B,I,A,R,a,1,i,o),this.buildFace("z","y","x",1,-1,B,I,A,R,a,-1,i,o),this.buildFace("x","z","y",1,1,A,B,I,y,R,1,i,o),this.buildFace("x","z","y",1,-1,A,B,I,y,R,-1,i,o),this.buildFace("x","y","z",1,-1,A,I,B,y,a,1,i,o),this.buildFace("x","y","z",-1,-1,A,I,B,y,a,-1,i,o),this.vertexData_=new Float32Array(i),this.indexData_=new Uint32Array(o),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,o,y,a,R,N,r){const K=E/y,e=i/a,n=E/2,q=i/2,x=o/2*R,W=y+1,P=a+1,b=N.length/8;for(let m=0;m<P;m++){const IA=-q+m*e;for(let X=0;X<W;X++){const Z=-n+X*K,gA={x:0,y:0,z:0};gA[A]=Z*Q,gA[I]=IA*C,gA[B]=x;const AA={x:0,y:0,z:0};AA[B]=R;const wA=X/y,tA=1-m/a;N.push(gA.x,gA.y,gA.z,AA.x,AA.y,AA.z,wA,tA)}}for(let m=0;m<a;m++)for(let IA=0;IA<y;IA++){const X=b+IA+W*m,Z=b+IA+W*(m+1),gA=b+(IA+1)+W*(m+1),AA=b+(IA+1)+W*m;R===1?r.push(X,Z,AA,Z,gA,AA):r.push(X,AA,Z,Z,AA,gA)}}}class ED extends Ag{constructor(A,I,B,Q){super(),this.geometry=new CD(A,I,B,1,1,1),this.cullFaceMode="back",this.setTexture(0,Q),this.programName=iD(Q.dataType)}get type(){return"VolumeRenderable"}}function iD(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"}}class DD extends SI{type="VolumeLayer";constructor(){super();const A=new Int8Array([127,0,0,127,127,0,0,127]),I=new hB(A,2,2,2);I.unpackAlignment=1;const B=new ED(1,1,1,I);B.wireframeEnabled=!0,this.addObject(B),this.setState("ready")}update(){}}class oD extends SI{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_=IQ(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 AQ(A.shape.x,A.shape.y,gg.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=oB(rA(),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 Yg extends _B{data_;width_;height_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=Ig(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!=Ig(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 Yg(B,A.shape.x,A.shape.y);return Q.unpackAlignment=A.rowAlignmentBytes,Q}}const aD=[[1,.5,.5],[.5,1,.5],[.5,.5,1],[.5,1,1],[1,.5,1],[1,1,.5]];function sD(g){return g=g??new Map,new Map(Array.from(g.entries()).map(([A,I])=>[A,hA.from(I)]))}function yD(g){return g=g??aD,g.map(hA.from)}class UC{lookupTable;cycle;constructor(A={}){this.lookupTable=sD(A.lookupTable),this.cycle=yD(A.cycle)}}const hD=new Set(["unsigned_byte","unsigned_short","unsigned_int"]);function GD(g){if(g.dataFormat!=="scalar")throw new Error(`Image data format must be scalar, instead found: ${g.dataFormat}`);if(!hD.has(g.dataType))throw new Error(`Image data type must be unsigned, instead found: ${g.dataType}`);return g}class FD extends Ag{outlineSelected_;selectedValue_;constructor(A){super(),this.geometry=new FC(A.width,A.height,1,1),this.setTexture(0,GD(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 Yg(I,A.length,1);return B.dataFormat="rgba",B}makeColorLookupTableTexture(A){A===void 0?A=new Map([[0,hA.TRANSPARENT]]):A.has(0)||(A=new Map([[0,hA.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 Yg(C,Q,2)}}class wD extends SI{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 UC(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 UC(A),this.image_&&this.image_.setColorMap(this.colorMap_)}setSelectedValue(A){this.selectedValue_=A,this.image_&&this.image_.setSelectedValue(this.selectedValue_)}onEvent(A){this.pointerDownPos_=IQ(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 FD({width:A.shape.x,height:A.shape.y,imageData:Yg.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=oB(rA(),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 GB extends Error{constructor(A){super(A),this.name="AbortError",Object.setPrototypeOf(this,GB.prototype)}}class SD{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 GB("shutdown"))}get numRunning(){return this.numRunning_}get numPending(){return this.pending_.length}}class RD{source_;region_;seriesDimensionName_;seriesIndex_;scheduler_=new SD(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 j.debug("ImageSeriesLoader","Ignoring duplicate active setIndex request"),{success:!1,reason:"duplicate"};j.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(N=>N!==void 0),C=Q.find(N=>N.name===this.seriesDimensionName_);if(!C){const N=Q.map(r=>r.name).join(", ");throw new Error(`Series dimension "${this.seriesDimensionName_}" not found in loader dimensions: ${N}`)}const E=C.lods[B].scale,i=C.lods[B].size*E,o=this.seriesIndex_.type==="full",y=o?0:this.seriesIndex_.start,a=o?i:this.seriesIndex_.stop,R=Math.round((a-y)/E);return this.dataChunks_=new Array(R),this.seriesAttributes_={start:y,stop:a,scale:E,length:R},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(y=>y.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,o=await E.loadRegion(C,i,this.scheduler_);return this.dataChunks_[A]=o,I&&I.canceled&&(this.loadingToken_=null),o}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 GB)return Promise.reject(Q.reason);j.error("ImageSeriesLoader",`Error loading slice: ${Q.reason}`)}}async getLoader(){return this.loader_??=await this.source_.open(),this.loader_}}class ND extends SI{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 RD({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_=gg.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 AQ(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}}class ng extends Error{constructor(A,I={}){super(`Node not found: ${A}`,I),this.name="NodeNotFoundError"}}class BQ extends Error{constructor(A){super(`Missing key: ${A}`),this.name="KeyError"}}class QQ{kind="array_to_array";constructor(A,I){if(A.keepbits<0)throw new Error("keepbits must be zero or positive")}static fromConfig(A,I){return new QQ(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}}class tC{#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 CQ{_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 Kg{#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 Kg(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 Mg(g){const A=new TextDecoder().decode(g);return JSON.parse(A)}function kC(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}const UD={int8:Int8Array,int16:Int16Array,int32:Int32Array,int64:globalThis.BigInt64Array,uint8:Uint8Array,uint16:Uint16Array,uint32:Uint32Array,uint64:globalThis.BigUint64Array,float32:Float32Array,float64:Float64Array,bool:tC},tD=/v2:([US])(\d+)/;function cC(g){if(g==="v2:object")return globalThis.Array;let A=g.match(tD);if(A){let[,B,Q]=A;return(B==="U"?Kg:CQ).bind(null,Number(Q))}let I=UD[g];if(!I)throw new Error(`Unknown or unsupported data_type: ${g}`);return I}function pI(g,A){return(A==="C"?kD:cD)(g)}function kD(g){const A=g.length,I=globalThis.Array(A);for(let B=A-1,Q=1;B>=0;B--)I[B]=Q,Q*=g[B];return I}function cD(g){const A=g.length,I=globalThis.Array(A);for(let B=0,Q=1;B<A;B++)I[B]=Q,Q*=g[B];return I}function LD({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 EQ(g){return g.find(I=>I.name==="transpose")?.configuration?.order==="F"?"F":"C"}const JD=/^([<|>])(.*)$/;function rD(g){if(g==="|O")return{data_type:"v2:object"};let A=g.match(JD);if(!A)throw new Error(`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",f4:"float32",f8:"float64"}[B]??(B.startsWith("S")||B.startsWith("U")?`v2:${B}`:void 0);if(!Q)throw new Error(`Unsupported or unknown dtype: ${g}`);return I==="|"?{data_type:Q}:{data_type:Q,endian:I==="<"?"little":"big"}}function YD(g,A={}){let I=[],B=rD(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 nD(g,A={}){return{zarr_format:3,node_type:"group",attributes:A}}function KD(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 MD(g){return g?.name==="sharding_indexed"}function LC(g){return(g.data_type==="uint64"||g.data_type==="int64")&&g.fill_value!=null?BigInt(g.fill_value):g.fill_value}const JC=eD();function eD(){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 FB{kind="array_to_bytes";#A;#I;#g;#Q;#B;constructor(A,I){this.#B=A?.endian,this.#I=cC(I.data_type),this.#Q=I.shape,this.#A=pI(I.shape,EQ(I.codecs));const B=new this.#I(0);this.#g=B.BYTES_PER_ELEMENT}static fromConfig(A,I){return new FB(A,I)}encode(A){let I=new Uint8Array(A.data.buffer);return JC&&this.#B==="big"&&kC(I,rC(this.#I)),I}decode(A){return JC&&this.#B==="big"&&kC(A,rC(this.#I)),{data:new this.#I(A.buffer,A.byteOffset,A.byteLength/this.#g),shape:this.#Q,stride:this.#A}}}class iQ{kind="bytes_to_bytes";static fromConfig(){return new iQ}encode(A){throw new Error("Not implemented")}decode(A){return new Uint8Array(A.buffer,A.byteOffset,A.byteLength-4)}}function HD(g,A){if(Number.isNaN(A))throw new Error("JsonCodec allow_nan is false but NaN was encountered during encoding.");if(A===Number.POSITIVE_INFINITY)throw new Error("JsonCodec allow_nan is false but Infinity was encountered during encoding.");if(A===Number.NEGATIVE_INFINITY)throw new Error("JsonCodec allow_nan is false but -Infinity was encountered during encoding.");return A}function qD(g,A){return A instanceof Object&&!Array.isArray(A)?Object.keys(A).sort().reduce((I,B)=>(I[B]=A[B],I),{}):A}class DQ{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:o,strict:y=!0}=A;let a=A.separators;a||(o?a=[", ",": "]:a=[",",":"]),this.#A={encoding:I,skipkeys:B,ensure_ascii:Q,check_circular:C,allow_nan:E,indent:o,separators:a,sort_keys:i},this.#I={strict:y}}static fromConfig(A){return new DQ(A)}encode(A){const{indent:I,encoding:B,ensure_ascii:Q,check_circular:C,allow_nan:E,sort_keys:i}=this.#A;if(B!=="utf-8")throw new Error("JsonCodec does not yet support non-utf-8 encoding.");const o=[];if(!C)throw new Error("JsonCodec does not yet support skipping the check for circular references during encoding.");E||o.push(HD),i&&o.push(qD);const y=Array.from(A.data);y.push("|O"),y.push(A.shape);let a;o.length&&(a=(N,r)=>{let K=r;for(let e of o)K=e(N,K);return K});let R=JSON.stringify(y,a,I);return Q&&(R=R.replace(/[\u007F-\uFFFF]/g,N=>{const r=`0000${N.charCodeAt(0).toString(16)}`;return`\\u${r.substring(r.length-4)}`})),new TextEncoder().encode(R)}decode(A){const{strict:I}=this.#I;if(!I)throw new Error("JsonCodec does not yet support non-strict decoding.");const B=Mg(A),Q=B.pop();if(B.pop(),!Q)throw new Error("0D not implemented for JsonCodec.");const C=pI(Q,"C");return{data:B,shape:Q,stride:C}}}function YC(g){return g instanceof tC||g instanceof CQ||g instanceof Kg?new Proxy(g,{get(I,B){return I.get(Number(B))},set(I,B,Q){return I.set(Number(B),Q),!0}}):g}function dD(g,A){let I;return g.data instanceof CQ||g.data instanceof Kg?I=new g.constructor(g.data.length,g.data.chars):I=new g.constructor(g.data.length),{data:I,shape:g.shape,stride:pI(g.shape,A)}}function fD(g,A){let I=dD(g,A),B=g.shape.length,Q=g.data.length,C=Array(B).fill(0),E=YC(g.data),i=YC(I.data);for(let o=0;o<Q;o++){let y=0;for(let a=0;a<B;a++)y+=C[a]*I.stride[a];i[y]=E[o],C[0]+=1;for(let a=0;a<B;a++)if(C[a]===g.shape[a]){if(a+1===B)break;C[a]=0,C[a+1]+=1}}return I}function lD(g){if(!g.stride)return"C";let A=pI(g.shape,"C");return g.stride.every((I,B)=>I===A[B])?"C":"F"}class oQ{configuration;kind="array_to_array";constructor(A){this.configuration=A}static fromConfig(A){return new oQ(A)}encode(A){return lD(A)===this.configuration?.order?A:fD(A,this.configuration?.order??"C")}decode(A){return A}}class aQ{kind="array_to_bytes";#A;#I;constructor(A){this.#A=A,this.#I=pI(A,"C")}static fromConfig(A,I){return new aQ(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}}}function pD(){return new Map().set("blosc",()=>Promise.resolve().then(()=>ss).then(g=>g.default)).set("gzip",()=>Promise.resolve().then(()=>ls).then(g=>g.default)).set("lz4",()=>Promise.resolve().then(()=>Zs).then(g=>g.default)).set("zlib",()=>Promise.resolve().then(()=>Ps).then(g=>g.default)).set("zstd",()=>Promise.resolve().then(()=>zs).then(g=>g.default)).set("transpose",()=>oQ).set("bytes",()=>FB).set("crc32c",()=>iQ).set("vlen-utf8",()=>aQ).set("json2",()=>DQ).set("bitround",()=>QQ)}const WD=pD();function sQ(g){let A;return{async encode(I){A||(A=await nC(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 nC(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 nC(g){let A=g.codecs.map(async C=>{let E=await WD.get(C.name)?.();if(!E)throw new Error(`Unknown codec: ${C.name}`);return{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)}}if(!B){if(!mD(g))throw new Error(`Cannot encode ${g.data_type} to bytes without a codec`);B=FB.fromConfig({endian:"little"},g)}return{array_to_array:I,array_to_bytes:B,bytes_to_bytes:Q}}function mD(g){return g.data_type!=="v2:object"}const KC=18446744073709551615n;function TD(g,A,I,B){if(g.store.getRange===void 0)throw new Error("Store does not support range requests");let Q=g.store.getRange.bind(g.store),C=A.map((o,y)=>o/B.chunk_shape[y]),E=sQ({data_type:"uint64",shape:[...C,2],codecs:B.index_codecs}),i={};return async o=>{let y=o.map((x,W)=>Math.floor(x/C[W])),a=g.resolve(I(y)).path,R;if(a in i)R=i[a];else{let x=4,W=16*C.reduce((b,m)=>b*m,1),P=await Q(a,{suffixLength:W+x});R=i[a]=P?await E.decode(P):null}if(R===null)return;let{data:N,shape:r,stride:K}=R,e=o.map((x,W)=>x%r[W]).reduce((x,W,P)=>x+W*K[P],0),n=N[e],q=N[e+1];if(!(n===KC&&q===KC))return Q(a,{offset:Number(n),length:Number(q)})}}class VA{store;path;constructor(A,I="/"){this.store=A,this.path=I}resolve(A){let I=new URL(`file://${this.path.endsWith("/")?this.path:`${this.path}/`}`);return new VA(this.store,new URL(A,I).pathname)}}class yQ extends VA{kind="group";#A;constructor(A,I,B){super(A,I),this.#A=B}get attrs(){return this.#A.attributes}}const eg=Symbol("zarrita.context");function xD(g){return g[eg]}function ZD(g,A){let{configuration:I}=A.codecs.find(MD)??{},B={encode_chunk_key:LD(A.chunk_key_encoding),TypedArray:cC(A.data_type),fill_value:A.fill_value};if(I){let C=EQ(I.codecs);return{...B,kind:"sharded",chunk_shape:I.chunk_shape,codec:sQ({data_type:A.data_type,shape:I.chunk_shape,codecs:I.codecs}),get_strides(E,i){return pI(E,i??C)},get_chunk_bytes:TD(g,A.chunk_grid.configuration.chunk_shape,B.encode_chunk_key,I)}}let Q=EQ(A.codecs);return{...B,kind:"regular",chunk_shape:A.chunk_grid.configuration.chunk_shape,codec:sQ({data_type:A.data_type,shape:A.chunk_grid.configuration.chunk_shape,codecs:A.codecs}),get_strides(C,E){return pI(C,E??Q)},async get_chunk_bytes(C,E){let i=B.encode_chunk_key(C),o=g.resolve(i).path;return g.store.get(o,E)}}}let wB=class extends VA{kind="array";#A;[eg];constructor(A,I,B){super(A,I),this.#A={...B,fill_value:LC(B)},this[eg]=ZD(this,B)}get attrs(){return this.#A.attributes}get shape(){return this.#A.shape}get chunks(){return this[eg].chunk_shape}get dtype(){return this.#A.data_type}async getChunk(A,I){let B=this[eg],Q=await B.get_chunk_bytes(A,I);if(!Q){let C=B.chunk_shape.reduce((i,o)=>i*o,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 KD(this.dtype,A)}},SB=bD();function bD(){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 uD(g){let A=await g.store.get(g.resolve(".zattrs").path);return A?Mg(A):{}}async function PD(g,A={}){let I="store"in g?g:new VA(g),B={};return(A.attrs??!0)&&(B=await uD(I)),A.kind==="array"?MC(I,B):A.kind==="group"?eC(I,B):MC(I,B).catch(Q=>{if(Q instanceof ng)return eC(I,B);throw Q})}async function MC(g,A){let{path:I}=g.resolve(".zarray"),B=await g.store.get(I);if(!B)throw new ng("v2 array",{cause:new BQ(I)});return SB.increment(g.store,"v2"),new wB(g.store,g.path,YD(Mg(B),A))}async function eC(g,A){let{path:I}=g.resolve(".zgroup"),B=await g.store.get(I);if(!B)throw new ng("v2 group",{cause:new BQ(I)});return SB.increment(g.store,"v2"),new yQ(g.store,g.path,nD(Mg(B),A))}async function OD(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 BQ(I)});let Q=Mg(B);return Q.node_type==="array"&&(Q.fill_value=LC(Q)),Q.node_type==="array"?new wB(A,g.path,Q):new yQ(A,g.path,Q)}async function VD(g,A={}){let I="store"in g?g:new VA(g),B=await OD(I);if(SB.increment(I.store,"v3"),A.kind===void 0||A.kind==="array"&&B instanceof wB||A.kind==="group"&&B instanceof yQ)return B;let Q=B instanceof wB?"array":"group";throw new Error(`Expected node of kind ${A.kind}, found ${Q}.`)}async function gI(g,A={}){let I="store"in g?g.store:g,B=SB.version_max(I),Q=B==="v2"?gI.v2:gI.v3,C=B==="v2"?gI.v3:gI.v2;return Q(g,A).catch(E=>{if(E instanceof ng)return C(g,A);throw E})}gI.v2=PD,gI.v3=VD;function HC(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 XD(g,A){return{...g,...A,headers:{...g.headers,...A.headers}}}function qC(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 dC(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 vD(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 HC(g,E-A,E,I)}class Bg{url;#A;#I;constructor(A,I={}){this.url=A,this.#A=I.overrides??{},this.#I=I.useSuffixRequest??!1}#g(A){return XD(this.#A,A)}async get(A,I={}){let B=qC(this.url,A).href,Q=await fetch(B,this.#g(I));return dC(Q)}async getRange(A,I,B={}){let Q=qC(this.url,A),C=this.#g(B),E;return"suffixLength"in I?E=await vD(Q,I.suffixLength,C,this.#I):E=await HC(Q,I.offset,I.length,C),dC(E)}}function*jD(g,A,I=1){A===void 0&&(A=g,g=0);for(let B=g;B<A;B+=I)yield B}function*zD(...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 _D({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 RB(g,A,I=null){return A===void 0&&(A=g,g=null),{start:g,stop:A,step:I}}function $D(){const g=[];return{add:A=>g.push(A()),onIdle:()=>Promise.all(g)}}class hQ extends Error{constructor(A){super(A),this.name="IndexError"}}function Ao(g,A){throw new hQ(`too many indicies for array; expected ${A.length}, got ${g.length}`)}function Io(g){throw new hQ(`index out of bounds for dimension with length ${g}`)}function go(){throw new hQ("only slices with step >= 1 are supported")}function Bo(g,A){g.length>A.length&&Ao(g,A)}function Qo(g,A){return g=Math.trunc(g),g<0&&(g=A+g),(g>=A||g<0)&&Io(A),g}class Co{dim_sel;dim_len;dim_chunk_len;nitems;constructor({dim_sel:A,dim_len:I,dim_chunk_len:B}){A=Qo(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 fC{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]=_D(A,I);this.start=Q,this.stop=C,this.step=E,this.step<1&&go(),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 jD(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,o=0;if(this.start<Q){const r=(Q-this.start)%this.step;r&&(o+=this.step-r),i=Math.ceil((Q-this.start)/this.step)}else o=this.start-Q;const y=this.stop>C?E:this.stop-Q,a=[o,y,this.step],R=Math.ceil((y-o)/this.step),N=[i,i+R,1];yield{dim_chunk_ix:B,dim_chunk_sel:a,dim_out_sel:N}}}}function Eo(g,A){let I=[];return g===null?I=A.map(B=>RB(null)):Array.isArray(g)&&(I=g.map(B=>B??RB(null))),Bo(I,A),I}class io{dim_indexers;shape;constructor({selection:A,shape:I,chunk_shape:B}){this.dim_indexers=Eo(A,I).map((Q,C)=>new(typeof Q=="number"?Co:fC)({dim_sel:Q,dim_len:I[C],dim_chunk_len:B[C]})),this.shape=this.dim_indexers.filter(Q=>Q instanceof fC).map(Q=>Q.nitems)}*[Symbol.iterator](){for(const A of zD(...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 Do(g,A){return"get"in g?g.get(A):g[A]}async function oo(g,A,I,B){let Q=xD(g),C=new io({selection:A,shape:g.shape,chunk_shape:g.chunks}),E=B.prepare(new Q.TypedArray(C.shape.reduce((o,y)=>o*y,1)),C.shape,Q.get_strides(C.shape,I.order)),i=I.create_queue?.()??$D();for(const{chunk_coords:o,mapping:y}of C)i.add(async()=>{let{data:a,shape:R,stride:N}=await g.getChunk(o,I.opts),r=B.prepare(a,R,N);B.set_from_chunk(E,r,y)});return await i.onIdle(),C.shape.length===0?Do(E.data,0):E}function GQ(g,A=0,I){let B=I??g.length-A;return{length:B,subarray(Q,C=B){return GQ(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 FQ(g){return globalThis.Array.isArray(g.data)?{data:GQ(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 ao(g){return"chars"in g?g.constructor.bind(null,g.chars):g.constructor}function so(g,A){if(globalThis.Array.isArray(g.data))return GQ([A]);let I=ao(g.data),B=new I([A]);return new Uint8Array(B.buffer,B.byteOffset,B.byteLength)}const yo={prepare(g,A,I){return{data:g,shape:A,stride:I}},set_scalar(g,A,I){let B=FQ(g);wQ(B,A,so(g,I),B.bytes_per_element)},set_from_chunk(g,A,I){let B=FQ(g);NB(B,FQ(A),B.bytes_per_element,I)}};async function ho(g,A=null,I={}){return oo(g,A,I,yo)}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 wQ(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 N=g.data.subarray(E*Q*B);wQ({data:N,stride:i},C,I,B);return}const[o,y,a]=Q,R=lC(o,y,a);if(C.length===0){for(let N=0;N<R;N++)g.data.set(I,E*(o+a*N)*B);return}for(let N=0;N<R;N++){const r=g.data.subarray(E*(o+a*N)*B);wQ({data:r,stride:i},C,I,B)}}function NB(g,A,I,B){const[Q,...C]=B,[E,...i]=g.stride,[o,...y]=A.stride;if(Q.from===null){if(C.length===0){g.data.set(A.data.subarray(0,I),Q.to*I);return}NB({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}NB(g,{data:A.data.subarray(o*Q.from*I),stride:y},I,C);return}const[a,R,N]=Q.to,[r,K,e]=Q.from,n=lC(a,R,N);if(C.length===0){if(N===1&&e===1&&E===1&&o===1){let q=r*I,x=n*I;g.data.set(A.data.subarray(q,q+x),a*I);return}for(let q=0;q<n;q++){let x=o*(r+e*q)*I;g.data.set(A.data.subarray(x,x+I),E*(a+N*q)*I)}return}for(let q=0;q<n;q++)NB({data:g.data.subarray(E*(a+q*N)*I),stride:i},{data:A.data.subarray(o*(r+q*e)*I),stride:y},I,C)}async function Go(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 SQ{#A;constructor(A){this.#A=A}get directoryHandle(){return this.#A}async get(A){const I=await Go(this.#A,A.slice(1)).catch(()=>{});if(!I)return;const Q=await(await I.getFile()).arrayBuffer();return new Uint8Array(Q)}}function Fo(){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 RQ extends Bg{credentials;region;signingKeyCache_=new Map;overrides;useSuffixRequest;constructor(A){Fo(),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"),o=globalThis.fetch,y=async(R,N)=>{const K=(N?.method||"GET")==="HEAD"?E:i,e={...N,headers:{...N?.headers,...K}};return o(R,e)},a=globalThis.fetch;globalThis.fetch=y;try{return await super.getRange(A,I,B)}finally{globalThis.fetch=a}}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",o=this.getAmzDate(),y=o.slice(0,8),a=new URL(A),R=a.host,N=a.pathname,r=a.search.slice(1),K=`host:${R}
|
|
347
|
+
${Q}`;return g.replace(pB,C)}const ZA=["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 uQ(){const g=Math.random()*4294967295|0,A=Math.random()*4294967295|0,I=Math.random()*4294967295|0,B=Math.random()*4294967295|0;return(ZA[g&255]+ZA[g>>8&255]+ZA[g>>16&255]+ZA[g>>24&255]+"-"+ZA[A&255]+ZA[A>>8&255]+"-"+ZA[A>>16&15|64]+ZA[A>>24&255]+"-"+ZA[I&63|128]+ZA[I>>8&255]+"-"+ZA[I>>16&255]+ZA[I>>24&255]+ZA[B&255]+ZA[B>>8&255]+ZA[B>>16&255]+ZA[B>>24&255]).toLowerCase()}class WB{uuid=uQ()}var fI=1e-6,lA=typeof Float32Array<"u"?Float32Array:Array,OE=Math.PI/180;function VE(g){return g*OE}Math.hypot||(Math.hypot=function(){for(var g=0,A=arguments.length;A--;)g+=arguments[A]*arguments[A];return Math.sqrt(g)});function PQ(){var g=new lA(9);return lA!=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 XE(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 QI(){var g=new lA(16);return lA!=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 mB(g,A){var I=A[0],B=A[1],Q=A[2],C=A[3],E=A[4],i=A[5],o=A[6],y=A[7],a=A[8],R=A[9],N=A[10],r=A[11],K=A[12],e=A[13],n=A[14],q=A[15],x=I*i-B*E,W=I*o-Q*E,P=I*y-C*E,b=B*o-Q*i,m=B*y-C*i,IA=Q*y-C*o,X=a*e-R*K,Z=a*n-N*K,gA=a*q-r*K,AA=R*n-N*e,wA=R*q-r*e,tA=N*q-r*n,CA=x*tA-W*wA+P*AA+b*gA-m*Z+IA*X;return CA?(CA=1/CA,g[0]=(i*tA-o*wA+y*AA)*CA,g[1]=(Q*wA-B*tA-C*AA)*CA,g[2]=(e*IA-n*m+q*b)*CA,g[3]=(N*m-R*IA-r*b)*CA,g[4]=(o*gA-E*tA-y*Z)*CA,g[5]=(I*tA-Q*gA+C*Z)*CA,g[6]=(n*P-K*IA-q*W)*CA,g[7]=(a*IA-N*P+r*W)*CA,g[8]=(E*wA-i*gA+y*X)*CA,g[9]=(B*gA-I*wA-C*X)*CA,g[10]=(K*m-e*P+q*x)*CA,g[11]=(R*P-a*m-r*x)*CA,g[12]=(i*Z-E*AA-o*X)*CA,g[13]=(I*AA-B*Z+Q*X)*CA,g[14]=(e*W-K*b-n*x)*CA,g[15]=(a*b-R*W+N*x)*CA,g):null}function DB(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=A[4],o=A[5],y=A[6],a=A[7],R=A[8],N=A[9],r=A[10],K=A[11],e=A[12],n=A[13],q=A[14],x=A[15],W=I[0],P=I[1],b=I[2],m=I[3];return g[0]=W*B+P*i+b*R+m*e,g[1]=W*Q+P*o+b*N+m*n,g[2]=W*C+P*y+b*r+m*q,g[3]=W*E+P*a+b*K+m*x,W=I[4],P=I[5],b=I[6],m=I[7],g[4]=W*B+P*i+b*R+m*e,g[5]=W*Q+P*o+b*N+m*n,g[6]=W*C+P*y+b*r+m*q,g[7]=W*E+P*a+b*K+m*x,W=I[8],P=I[9],b=I[10],m=I[11],g[8]=W*B+P*i+b*R+m*e,g[9]=W*Q+P*o+b*N+m*n,g[10]=W*C+P*y+b*r+m*q,g[11]=W*E+P*a+b*K+m*x,W=I[12],P=I[13],b=I[14],m=I[15],g[12]=W*B+P*i+b*R+m*e,g[13]=W*Q+P*o+b*N+m*n,g[14]=W*C+P*y+b*r+m*q,g[15]=W*E+P*a+b*K+m*x,g}function vE(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],o=Q+Q,y=C+C,a=E+E,R=Q*o,N=Q*y,r=Q*a,K=C*y,e=C*a,n=E*a,q=i*o,x=i*y,W=i*a,P=B[0],b=B[1],m=B[2];return g[0]=(1-(K+n))*P,g[1]=(N+W)*P,g[2]=(r-x)*P,g[3]=0,g[4]=(N-W)*b,g[5]=(1-(R+n))*b,g[6]=(e+q)*b,g[7]=0,g[8]=(r+x)*m,g[9]=(e-q)*m,g[10]=(1-(R+K))*m,g[11]=0,g[12]=I[0],g[13]=I[1],g[14]=I[2],g[15]=1,g}function zE(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 _E=zE;function $E(g,A,I,B,Q,C,E){var i=1/(A-I),o=1/(B-Q),y=1/(C-E);return g[0]=-2*i,g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=-2*o,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[10]=2*y,g[11]=0,g[12]=(A+I)*i,g[13]=(Q+B)*o,g[14]=(E+C)*y,g[15]=1,g}var Ai=$E;function Ii(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=B[0],o=B[1],y=B[2],a=Q-I[0],R=C-I[1],N=E-I[2],r=a*a+R*R+N*N;r>0&&(r=1/Math.sqrt(r),a*=r,R*=r,N*=r);var K=o*N-y*R,e=y*a-i*N,n=i*R-o*a;return r=K*K+e*e+n*n,r>0&&(r=1/Math.sqrt(r),K*=r,e*=r,n*=r),g[0]=K,g[1]=e,g[2]=n,g[3]=0,g[4]=R*n-N*e,g[5]=N*K-a*n,g[6]=a*e-R*K,g[7]=0,g[8]=a,g[9]=R,g[10]=N,g[11]=0,g[12]=Q,g[13]=C,g[14]=E,g[15]=1,g}function rA(){var g=new lA(3);return lA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g}function CI(g){var A=new lA(3);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A}function OQ(g){var A=g[0],I=g[1],B=g[2];return Math.hypot(A,I,B)}function NA(g,A,I){var B=new lA(3);return B[0]=g,B[1]=A,B[2]=I,B}function cg(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g}function _I(g,A,I,B){return g[0]=A,g[1]=I,g[2]=B,g}function VQ(g,A,I){return g[0]=A[0]+I[0],g[1]=A[1]+I[1],g[2]=A[2]+I[2],g}function gi(g,A,I){return g[0]=A[0]-I[0],g[1]=A[1]-I[1],g[2]=A[2]-I[2],g}function Bi(g,A,I){return g[0]=A[0]*I[0],g[1]=A[1]*I[1],g[2]=A[2]*I[2],g}function XQ(g,A,I){return g[0]=A[0]*I,g[1]=A[1]*I,g[2]=A[2]*I,g}function vQ(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 jQ(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 Qi(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 zQ(g,A){return g[0]*A[0]+g[1]*A[1]+g[2]*A[2]}function TB(g,A,I){var B=A[0],Q=A[1],C=A[2],E=I[0],i=I[1],o=I[2];return g[0]=Q*o-C*i,g[1]=C*E-B*o,g[2]=B*i-Q*E,g}function Ci(g,A,I,B,Q,C){var E=1-C,i=E*E,o=C*C,y=i*E,a=3*C*i,R=3*o*E,N=o*C;return g[0]=A[0]*y+I[0]*a+B[0]*R+Q[0]*N,g[1]=A[1]*y+I[1]*a+B[1]*R+Q[1]*N,g[2]=A[2]*y+I[2]*a+B[2]*R+Q[2]*N,g}function oB(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 Ei(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)<=fI*Math.max(1,Math.abs(I),Math.abs(C))&&Math.abs(B-E)<=fI*Math.max(1,Math.abs(B),Math.abs(E))&&Math.abs(Q-i)<=fI*Math.max(1,Math.abs(Q),Math.abs(i))}var xB=gi,ii=OQ;(function(){var g=rA();return function(A,I,B,Q,C,E){var i,o;for(I||(I=3),B||(B=0),Q?o=Math.min(Q*I+B,A.length):o=A.length,i=B;i<o;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 Lg(){var g=new lA(4);return lA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0,g[3]=0),g}function Di(g){var A=new lA(4);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A[3]=g[3],A}function ZB(g,A,I,B){var Q=new lA(4);return Q[0]=g,Q[1]=A,Q[2]=I,Q[3]=B,Q}function oi(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g[3]=A[3],g}function ai(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 si(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 aB(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=Lg();return function(A,I,B,Q,C,E){var i,o;for(I||(I=4),B||(B=0),Q?o=Math.min(Q*I+B,A.length):o=A.length,i=B;i<o;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 bB(){var g=new lA(4);return lA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g[3]=1,g}function yi(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 hi(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=I[0],o=I[1],y=I[2],a=I[3];return g[0]=B*a+E*i+Q*y-C*o,g[1]=Q*a+E*o+C*i-B*y,g[2]=C*a+E*y+B*o-Q*i,g[3]=E*a-B*i-Q*o-C*y,g}function uB(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=A[3],o=I[0],y=I[1],a=I[2],R=I[3],N,r,K,e,n;return r=Q*o+C*y+E*a+i*R,r<0&&(r=-r,o=-o,y=-y,a=-a,R=-R),1-r>fI?(N=Math.acos(r),K=Math.sin(N),e=Math.sin((1-B)*N)/K,n=Math.sin(B*N)/K):(e=1-B,n=B),g[0]=e*Q+n*o,g[1]=e*C+n*y,g[2]=e*E+n*a,g[3]=e*i+n*R,g}function _Q(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 Gi=Di,Fi=oi,PB=si;(function(){var g=rA(),A=NA(1,0,0),I=NA(0,1,0);return function(B,Q,C){var E=zQ(Q,C);return E<-.999999?(TB(g,A,Q),ii(g)<1e-6&&TB(g,I,Q),Qi(g,g),yi(B,g,Math.PI),B):E>.999999?(B[0]=0,B[1]=0,B[2]=0,B[3]=1,B):(TB(g,Q,C),B[0]=g[0],B[1]=g[1],B[2]=g[2],B[3]=1+E,PB(B,B))}})(),function(){var g=bB(),A=bB();return function(I,B,Q,C,E,i){return uB(g,B,E,i),uB(A,Q,C,i),uB(I,g,A,2*i*(1-i)),I}}(),function(){var g=PQ();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],PB(A,_Q(A,g))}}();function $Q(){var g=new lA(2);return lA!=Float32Array&&(g[0]=0,g[1]=0),g}function AC(g){var A=new lA(2);return A[0]=g[0],A[1]=g[1],A}function pA(g,A){var I=new lA(2);return I[0]=g,I[1]=A,I}function wi(g,A){var I=A[0]-g[0],B=A[1]-g[1];return Math.hypot(I,B)}function Si(g){var A=g[0],I=g[1];return A*A+I*I}function Ri(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 IC(g,A){return g[0]===A[0]&&g[1]===A[1]}function OB(g,A){var I=g[0],B=g[1],Q=A[0],C=A[1];return Math.abs(I-Q)<=fI*Math.max(1,Math.abs(I),Math.abs(Q))&&Math.abs(B-C)<=fI*Math.max(1,Math.abs(B),Math.abs(C))}(function(){var g=$Q();return function(A,I,B,Q,C,E){var i,o;for(I||(I=2),B||(B=0),Q?o=Math.min(Q*I+B,A.length):o=A.length,i=B;i<o;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 kI{min;max;constructor(A,I){this.min=A?CI(A):NA(1/0,1/0,1/0),this.max=I?CI(I):NA(-1/0,-1/0,-1/0)}clone(){return new kI(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=[NA(I[0],I[1],I[2]),NA(I[0],I[1],B[2]),NA(I[0],B[1],I[2]),NA(I[0],B[1],B[2]),NA(B[0],I[1],I[2]),NA(B[0],I[1],B[2]),NA(B[0],B[1],I[2]),NA(B[0],B[1],B[2])];this.min=NA(1/0,1/0,1/0),this.max=NA(-1/0,-1/0,-1/0);const C=rA();for(const E of Q)oB(C,E,A),this.expandWithPoint(C)}}const Ni={position:0,normal:1,uv:2,next_position:3,previous_position:4,direction:5,path_proportion:6,color:7,size:8,marker:9};class $I extends WB{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 kI,Q=rA();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 Ui{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(a=>{const R=Ni[a.type];this.gl_.vertexAttribPointer(R,a.itemSize,this.gl_.FLOAT,!1,i,a.offset),this.gl_.enableVertexAttribArray(R)});const o={vao:I,vbo:C},{indexData:y}=A;if(y.length){const a=this.gl_.ELEMENT_ARRAY_BUFFER,R=this.gl_.createBuffer();if(!R)throw new Error("Failed to create index buffer (EBO)");this.gl_.bindBuffer(a,R),this.gl_.bufferData(a,y,this.gl_.STATIC_DRAW),o.ebo=R}this.buffers_.set(A,o),this.gl_.bindVertexArray(null)}}class ti{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 j.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),o=0;for(let y=0;y<Q;y++)o+=E*i*C*B,E=Math.max(1,E>>1),i=Math.max(1,i>>1);return o}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 zA{min;max;constructor(A,I){this.min=A?AC(A):pA(1/0,1/0),this.max=I?AC(I):pA(-1/0,-1/0)}clone(){return new zA(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 IC(A.min,I.min)&&IC(A.max,I.max)}floor(){return new zA(pA(Math.floor(this.min[0]),Math.floor(this.min[1])),pA(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 ki{gl_;enabledCapabilities_=new Map;depthMaskEnabled_=null;blendSrcFactor_=null;blendDstFactor_=null;currentBlendingMode_=null;currentViewport_=null;currentScissor_=null;currentCullingMode_=null;constructor(A){this.gl_=A}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"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_&&zA.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_&&zA.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}}}const ci=vE(QI(),[1,-1,1]);class gC extends eE{gl_;programs_;bindings_;textures_;state_;renderedObjectsPerFrame_=0;constructor(A){super(A);const I=this.canvas.getContext("webgl2",{depth:!0,antialias:!0});if(!I)throw new Error("Failed to initialize WebGL2 context");this.gl_=I,j.info("WebGLRenderer",`WebGL version ${I.getParameter(I.VERSION)}`),this.programs_=new PE(I),this.bindings_=new Ui(I),this.textures_=new ti(I),this.state_=new ki(I),this.resize(this.canvas.width,this.canvas.height)}render(A){const I=A.getBoxRelativeTo(this.canvas),B=new zA(pA(0,0),pA(this.width,this.height));if(zA.equals(I.floor(),B.floor()))this.state_.setScissorTest(!1);else if(zA.intersects(I,B))this.state_.setScissor(I),this.state_.setScissorTest(!0);else{j.warn("WebGLRenderer",`Viewport ${A.id} is entirely outside canvas bounds, skipping render`);return}this.state_.setViewport(I),this.renderedObjectsPerFrame_=0,this.clear();const{opaque:Q,transparent:C}=A.layerManager.partitionLayers();this.state_.setDepthMask(!0);const E=A.camera.frustum,i={viewport:A};for(const o of Q)o.update(i),o.state==="ready"&&this.renderLayer(o,A.camera,E);this.state_.setDepthMask(!1);for(const o of C)o.update(i),o.state==="ready"&&this.renderLayer(o,A.camera,E);this.state_.setDepthMask(!0),this.renderedObjects_=this.renderedObjectsPerFrame_}get textureInfo(){return this.textures_.textureInfo}renderLayer(A,I,B){this.state_.setBlendingMode(A.transparent?A.blendMode:"none"),A.objects.forEach((Q,C)=>{B.intersectsWithBox3(Q.boundingBox)&&(this.renderObject(A,C,I),this.renderedObjectsPerFrame_+=1)})}renderObject(A,I,B){const Q=A.objects[I];this.state_.setCullFaceMode(Q.cullFaceMode),this.bindings_.bindGeometry(Q.geometry),Q.popStaleTextures().forEach(E=>{this.textures_.disposeTexture(E)}),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=DB(QI(),C.viewMatrix,I.transform.matrix),i=DB(QI(),ci,C.projectionMatrix),o=[this.canvas.width,this.canvas.height],y=I.getUniforms();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,o);break;case"u_opacity":Q.setUniform(N,B.opacity);break;default:N in y&&Q.setUniform(N,y[N])}const a=this.glGetPrimitive(A.primitive),R=A.indexData;R.length?this.gl_.drawElements(a,R.length,this.gl_.UNSIGNED_INT,0):this.gl_.drawArrays(a,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 zA(pA(0,0),pA(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 Li=8;class Ji{maxConcurrent_;pending_=[];running_=new Map;constructor(A=Li){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),j.debug("ChunkQueue","Cancelled pending request");return}const B=this.running_.get(A);B&&(B.controller.abort(),j.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"&&j.error("ChunkQueue",String(E))}).finally(()=>{this.running_.delete(I),this.pump()});this.running_.set(I,{controller:Q,promise:C})}}const BC=[Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array];function QC(g){if(BC.some(I=>g instanceof I))return!0;const A=BC.map(I=>I.name);return j.debug("Chunk",`Unsupported chunk data type: ${g}. Supported data types: ${A}`),!1}function ri(g,A){return Math.round((A-g.translation)/g.scale)}function VB(g,A,I=1e-6){return Math.abs(g-A)<=I}function Jg(g,A,I){return Math.max(A,Math.min(I,g))}const CC=Symbol("INTERNAL_POLICY_KEY");class Yi{store_;policy_;policyChanged_=!1;currentLOD_=0;lastViewBounds2D_=null;lastZBounds_;lastTCoord_;sourceMaxSquareDistance2D_;chunkViewStates_=new Map;constructor(A,I){this.store_=A,this.policy_=I,j.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_=Si(pA(Q.size*Q.scale,C.size*C.scale))}get chunkViewStates(){return this.chunkViewStates_}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.store_.getLowestResLOD();return this.currentLOD_===C?Q:[...B.filter(i=>i.lod===C&&this.chunkViewStates_.get(i)?.visible===!0&&i.state==="loaded"),...Q]}updateChunkStates(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,o=I.getBoxRelativeTo(i).toRect().width,y=E/o,a=Math.log2(1/y);this.setLOD(a);const R=this.getZBounds(A);(this.policyChanged_||this.viewBounds2DChanged(C)||this.zBoundsChanged(R)||this.lastTCoord_!==A.t)&&(this.updateChunkViewStates(A,C),this.policyChanged_=!1,this.lastViewBounds2D_=C.clone(),this.lastZBounds_=R,this.lastTCoord_=A.t)}allVisibleLowestLODLoaded(A){const I=this.store_.getTimeIndex(A),B=this.store_.getChunksAtTime(I).filter(Q=>Q.visible&&Q.lod===this.store_.getLowestResLOD());return B.length>0&&B.every(Q=>Q.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.store_.removeView(this)}setImageSourcePolicy(A,I){if(I!==CC)throw new Error("Unauthorized policy mutation");this.policy_!==A&&(this.policy_=A,this.policyChanged_=!0,j.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(),o=Math.max(0,Math.min(i,this.policy_.lod.min)),y=Math.max(o,Math.min(i,this.policy_.lod.max)),a=Jg(E,o,y);a!==this.currentLOD_&&(this.currentLOD_=a)}updateChunkViewStates(A,I){const B=this.store_.getTimeIndex(A);if(this.store_.getChunksAtTime(B).length===0){j.warn("ChunkStoreView","updateChunkViewStates called with no chunks initialized"),this.chunkViewStates_.clear();return}const C=$Q();Ri(C,I.min,I.max,.5);const[E,i]=this.getZBounds(A),o=new kI(NA(I.min[0],I.min[1],E),NA(I.max[0],I.max[1],i));this.chunkViewStates_.forEach(ni),this.updateChunksAtTimeIndex(B,A,o,C),A.t!==void 0&&this.markTimeChunksForPrefetch(B,o,C)}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);for(const i of E){const o=this.isChunkWithinBounds(i,B),y=this.isChunkChannelInSlice(i,I),a=i.lod===this.currentLOD_,R=i.lod===this.store_.getLowestResLOD(),N=!o&&y&&a&&this.isChunkWithinBounds(i,C),r=o&&y,K=this.computePriority(R,a,o,N,y);if(K!==null){const e=this.squareDistance2D(i,Q);this.chunkViewStates_.set(i,{visible:r,prefetch:N,priority:K,orderKey:e})}}}markTimeChunksForPrefetch(A,I,B){const Q=this.store_.dimensions.t?.lods[0].size??1,C=Math.min(Q-1,A+this.policy_.prefetch.t);for(let E=A+1;E<=C;++E)for(const i of this.store_.getChunksAtTime(E)){if(i.lod!==this.store_.getLowestResLOD()||!this.isChunkWithinBounds(i,I))continue;const o=this.policy_.priorityMap.prefetchTime,y=this.squareDistance2D(i,B),a=Jg(y/this.sourceMaxSquareDistance2D_,0,1-Number.EPSILON),R=E-A+a;this.chunkViewStates_.set(i,{visible:!1,prefetch:!0,priority:o,orderKey:R})}}computePriority(A,I,B,Q,C){if(!C)return null;const E=this.policy_.priorityMap;return A&&B?E.fallbackVisible:I&&B?E.visibleCurrent:A?E.fallbackBackground:I&&Q?E.prefetchSpace:null}isChunkWithinBounds(A,I){const B=new kI(NA(A.offset.x,A.offset.y,A.offset.z),NA(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 kI.intersects(B,I)}getZBounds(A){const I=this.store_.dimensions.z;if(I===void 0||A.z===void 0)return[0,1];const B=I.lods[this.currentLOD_],Q=B.size,C=B.scale,E=B.translation,i=Math.floor((A.z-E)/C),o=B.chunkSize,y=Math.max(0,Math.min(Math.floor(i/o),Math.ceil(Q/o)-1));return[E+y*o*C,E+(y+1)*o*C]}viewBounds2DChanged(A){return this.lastViewBounds2D_===null||!OB(this.lastViewBounds2D_.min,A.min)||!OB(this.lastViewBounds2D_.max,A.max)}zBoundsChanged(A){return!this.lastZBounds_||!OB(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 o=0;return C&&(o=C.chunkSize*C.scale*this.policy_.prefetch.z),new kI(NA(A.min[0]-E,A.min[1]-i,A.min[2]-o),NA(A.max[0]+E,A.max[1]+i,A.max[2]+o))}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 ni(g){g.visible=!1,g.prefetch=!1,g.priority=null,g.orderKey=null}class Ki{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],o=this.dimensions_.y.lods[E],y=this.dimensions_.z?.lods[E],a=i.chunkSize,R=o.chunkSize,N=y?.chunkSize??1,r=Math.ceil(i.size/a),K=Math.ceil(o.size/R),e=Math.ceil((y?.size??1)/N);for(let n=0;n<B;++n)for(let q=0;q<r;++q){const x=i.translation+q*i.chunkSize*i.scale;for(let W=0;W<K;++W){const P=o.translation+W*o.chunkSize*o.scale;for(let b=0;b<e;++b){const m=y!==void 0?y.translation+b*N*y.scale:0;C.push({state:"unloaded",lod:E,visible:!1,prefetch:!1,priority:null,orderKey:null,shape:{x:Math.min(a,i.size-q*a),y:Math.min(R,o.size-W*R),z:Math.min(N,(y?.size??1)-b*N),c:1},rowAlignmentBytes:1,chunkIndex:{x:q,y:W,z:b,c:n,t:Q},scale:{x:i.scale,y:o.scale,z:y?.scale??1},offset:{x,y:P,z:m}})}}}}}}getChunksAtTime(A){return this.chunks_[A]}getTimeIndex(A){return A.t===void 0||this.dimensions_.t===void 0?0:ri(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 Yi(this,A);return this.views_.push(I),this.hasHadViews_=!0,I}removeView(A){const I=this.views_.indexOf(A);if(I===-1)throw new Error("Cannot remove view: view not found in store's view list");const B=Array.from(A.chunkViewStates.keys());this.views_.splice(I,1);for(const Q of B)this.aggregateChunkViewStates(Q)}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 A}aggregateChunkViewStates(A){let I=!1,B=!1,Q=null,C=null;for(const y of this.views_){const a=y.chunkViewStates.get(A);a&&(a.visible&&(I=!0),a.prefetch&&(B=!0),a.priority!==null&&(Q===null||a.priority<Q)&&(Q=a.priority,C=a.orderKey),!a.visible&&!a.prefetch&&a.priority===null&&y.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,j.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(!VB(Q,2,.02)||!VB(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;if(I.chunkSize!==1)throw new Error(`ChunkStore only supports a chunk size of 1 in t. Found ${I.chunkSize} at LOD ${A}`);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.chunkSize!==1)throw new Error(`ChunkStore only supports a chunk size of 1 in c. Found ${I.chunkSize} at LOD ${A}`);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 Mi{stores_=new Map;pendingStores_=new Map;queue_=new Ji;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 Ki(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 rg=function(g=1){var A=0,I=document.createElement("div");I.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",I.addEventListener("click",function(R){R.preventDefault(),Q(++A%I.children.length)},!1);function B(R){return I.appendChild(R.dom),R}function Q(R){for(var N=0;N<I.children.length;N++)I.children[N].style.display=N===R?"block":"none";A=R}var C=(performance||Date).now(),E=C,i=0,o=B(new rg.Panel("FPS","#0ff","#002",g)),y=B(new rg.Panel("MS","#0f0","#020",g));if(self.performance&&self.performance.memory)var a=B(new rg.Panel("MB","#f08","#201",g));return Q(0),{REVISION:16,dom:I,addPanel:B,showPanel:Q,begin:function(){C=(performance||Date).now()},end:function(){i++;var R=(performance||Date).now();if(y.update(R-C,200),R>=E+1e3&&(o.update(i*1e3/(R-E),100),E=R,i=0,a)){var N=performance.memory;a.update(N.usedJSHeapSize/1048576,N.jsHeapSizeLimit/1048576)}return R},update:function(){C=this.end()},domElement:I,setMode:Q}};rg.Panel=function(g,A,I,B){var Q=1/0,C=0,E=Math.round,i=E(window.devicePixelRatio||1),o=E(80*i*B),y=E(48*i*B),a=E(3*i*B),R=E(2*i*B),N=E(3*i*B),r=E(15*i*B),K=E(74*i*B),e=E(30*i*B),n=document.createElement("canvas");n.width=o,n.height=y,n.style.cssText=`width:${E(B*80)}px;height:${E(B*48)}px`;var q=n.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,o,y),q.fillStyle=A,q.fillText(g,a,R),q.fillRect(N,r,K,e),q.fillStyle=I,q.globalAlpha=.9,q.fillRect(N,r,K,e),{dom:n,update:function(x,W){Q=Math.min(Q,x),C=Math.max(C,x),q.fillStyle=I,q.globalAlpha=1,q.fillRect(0,0,o,r),q.fillStyle=A,q.fillText(E(x)+" "+g+" ("+E(Q)+"-"+E(C)+")",a,R),q.drawImage(n,N+i,r,K-i,e,N,r,K-i,e),q.fillRect(N+K-i,r,i,e),q.fillStyle=I,q.globalAlpha=.9,q.fillRect(N+K-i,r,i,E((1-x/W)*e))}}};function ei({scale:g}={scale:1.5}){const A=new rg(g);return A.showPanel(0),document.body.appendChild(A.dom),A}class EC{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 Hi(g){return XB.includes(g)}class qi{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_){j.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_){j.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(!Hi(A.type)){j.error("EventDispatcher",`Unsupported event type ${A.type}`);return}const I=new qi(A.type,A);for(const B of this.listeners_)if(B(I),I.propagationStopped)break}}class iC{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=pA(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,o=I.x-C,y=I.y-E,a=Math.floor(o),R=Math.floor(i-y-I.height),N=Math.floor(I.width),r=Math.floor(I.height);return new zA(pA(a,R),pA(a+N,R+r))}clientToClip(A,I=0){const[B,Q]=A,C=this.element.getBoundingClientRect();return NA(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 zA(pA(B,Q),pA(B+C,Q+E))}updateAspectRatio(){const{width:A,height:I}=this.getBox().toRect();if(A<=0||I<=0){j.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 fi(g){const A=new Map,I=new Set;for(const B of g){if(I.has(B.id))throw new Error(`Duplicate viewport ID "${B.id}". Each viewport must have a unique ID.`);if(I.add(B.id),A.has(B.element)){const Q=A.get(B.element),C=B.element.tagName.toLowerCase()+(B.element.id?`#${B.element.id}`:"[element has no id]");throw new Error(`Multiple viewports cannot share the same HTML element: viewports "${Q}" and "${B.id}" both use ${C}`)}A.set(B.element,B.id)}}function DC(g,A,I){const B=g.map(Q=>{const C=Q.element??A;return{...Q,element:C,id:Q.id??C.id??uQ(),layerManager:new EC(I)}});return fi(B),B.map(Q=>new iC(Q))}class li{elements_;resizeObserver_;mediaQuery_;onMediaQueryChange_;onChange_;constructor(A=[],I){this.elements_=A,this.onChange_=I}connect(){if(this.resizeObserver_){j.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_){j.warn("PixelSizeObserver","Attempted to disconnect already disconnected observer");return}this.resizeObserver_?.disconnect(),this.mediaQuery_&&this.onMediaQueryChange_&&this.mediaQuery_.removeEventListener("change",this.onMediaQueryChange_)}}class pi{chunkManager_;context_;renderer_;viewports_;canvas;overlays;stats_;sizeObserver_;lastAnimationId_;lastTimestamp_=0;constructor(A){if(this.canvas=A.canvas,A.viewports.length===0)throw new Error("At least one viewport config must be specified.");this.renderer_=new gC(this.canvas),this.chunkManager_=new Mi,this.context_={chunkManager:this.chunkManager_},this.viewports_=DC(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 li(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_}getViewport(A){return this.viewports_.find(I=>I.id===A)}start(){if(j.info("Idetik","Idetik runtime starting"),this.lastAnimationId_===void 0){for(const A of this.viewports_)A.events.connect();this.sizeObserver_.connect(),this.lastAnimationId_=requestAnimationFrame(A=>{this.lastTimestamp_=A,this.animate(A)})}else j.warn("Idetik","Idetik runtime already started");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(j.info("Idetik","Idetik runtime stopping"),this.lastAnimationId_===void 0)j.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 Wi extends $I{constructor(A){if(super(),A.primitive!="triangles"){j.warn("WireframeGeometry","Only indexed geometries are supported");return}if(A.indexData.length==0){j.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 o=Math.min(E,i),y=Math.max(E,i);I.has({i0:o,i1:y})||(I.add({i0:o,i1:y}),B.push(o,y))},C=A.indexData;for(let E=0;E<C.length;E+=3){const i=C[E],o=C[E+1],y=C[E+2];Q(i,o),Q(o,y),Q(y,i)}this.indexData_=new Uint32Array(B)}}const mi=NA(0,1,0);class Ti{dirty_=!0;matrix_=QI();rotation_=bB();translation_=rA();scale_=NA(1,1,1);addRotation(A){hi(this.rotation_,this.rotation_,A),this.dirty_=!0}setRotation(A){Fi(this.rotation_,A),this.dirty_=!0}get rotation(){return Gi(this.rotation_)}addTranslation(A){VQ(this.translation_,this.translation_,A),this.dirty_=!0}setTranslation(A){cg(this.translation_,A),this.dirty_=!0}get translation(){return CI(this.translation_)}addScale(A){Bi(this.scale_,this.scale_,A),this.dirty_=!0}setScale(A){cg(this.scale_,A),this.dirty_=!0}targetTo(A){Ei(this.translation_,A)&&(A=CI(A),A[2]+=fI);const I=Ii(QI(),this.translation_,A,mi),B=XE(PQ(),I);_Q(this.rotation_,B),PB(this.rotation_,this.rotation_),this.dirty_=!0}get scale(){return CI(this.scale_)}get matrix(){return this.dirty_&&(this.computeMatrix(),this.dirty_=!1),this.matrix_}get inverse(){return mB(QI(),this.matrix)}computeMatrix(){jE(this.matrix_,this.rotation_,this.translation_,this.scale_)}}class Ag extends WB{wireframeEnabled=!1;wireframeColor=hA.WHITE;textures_=[];staleTextures_=[];transform_=new Ti;geometry_=new $I;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 Wi(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(){if(this.programName_===null)throw new Error("Program name not set");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 lI{normal;signedDistance;constructor(A=NA(0,1,0),I=0){this.normal=CI(A),this.signedDistance=I}set(A,I){this.normal=CI(A),this.signedDistance=I}signedDistanceToPoint(A){return zQ(this.normal,A)+this.signedDistance}normalize(){const A=OQ(this.normal);if(A>0){const I=1/A;XQ(this.normal,this.normal,I),this.signedDistance*=I}}}class oC{planes_;constructor(A){this.planes_=[new lI(rA(),0),new lI(rA(),0),new lI(rA(),0),new lI(rA(),0),new lI(rA(),0),new lI(rA(),0)],this.setWithViewProjection(A)}setWithViewProjection(A){const I=rA();this.planes_[0].set(_I(I,A[3]+A[0],A[7]+A[4],A[11]+A[8]),A[15]+A[12]),this.planes_[1].set(_I(I,A[3]-A[0],A[7]-A[4],A[11]-A[8]),A[15]-A[12]),this.planes_[2].set(_I(I,A[3]-A[1],A[7]-A[5],A[11]-A[9]),A[15]-A[13]),this.planes_[3].set(_I(I,A[3]+A[1],A[7]+A[5],A[11]+A[9]),A[15]+A[13]),this.planes_[4].set(_I(I,A[3]+A[2],A[7]+A[6],A[11]+A[10]),A[15]+A[14]),this.planes_[5].set(_I(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=rA();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 aC extends Ag{projectionMatrix_=QI();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 NA(A[0],A[1],A[2])}get up(){const A=this.transform.matrix;return NA(A[4],A[5],A[6])}get frustum(){return new oC(DB(QI(),this.projectionMatrix,this.viewMatrix))}pan(A){this.transform.addTranslation(A)}get position(){return this.transform.translation}clipToWorld(A){const I=ZB(A[0],A[1],A[2],1),B=mB(QI(),this.projectionMatrix_),Q=aB(Lg(),I,B);ai(Q,Q,1/Q[3]);const C=aB(Lg(),Q,this.transform.matrix);return NA(C[0],C[1],C[2])}}const sC=1.77,yC=128,hC=128/sC;class xi extends aC{width_=yC;height_=hC;viewportAspectRatio_=sC;viewportSize_=[yC,hC];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=ZB(-1,-1,0,1),I=ZB(1,1,0,1);const B=DB(QI(),this.projectionMatrix,this.viewMatrix),Q=mB(QI(),B);return A=aB(Lg(),A,Q),I=aB(Lg(),I,Q),new zA(pA(A[0],A[1]),pA(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],Ai(this.projectionMatrix_,-Q,Q,-C,C,this.near_,this.far_)}}const Zi=60,bi=1.77,sB=.1,vB=180-sB;class ui extends aC{fov_;aspectRatio_;constructor(A={}){const{fov:I=Zi,aspectRatio:B=bi,near:Q=.1,far:C=1e4,position:E=NA(0,0,0)}=A;if(I<sB||I>vB)throw new Error(`Invalid field of view: ${I}, must be in [${sB}, ${vB}] 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(sB,Math.min(vB,this.fov_/A)),this.updateProjectionMatrix()}updateProjectionMatrix(){_E(this.projectionMatrix_,VE(this.fov),this.aspectRatio_,this.near_,this.far_)}}const GC=0;class Pi{camera_;dragActive_=!1;dragStart_=rA();constructor(A){this.camera_=A}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=CI(A.worldPos),Q=I.deltaY<0?1.05:.95;this.camera_.zoom(Q);const C=this.camera_.clipToWorld(A.clipPos),E=xB(rA(),B,C);this.camera_.pan(E)}onPointerDown(A){const I=A.event;!A.worldPos||I.button!==GC||(this.dragStart_=CI(A.worldPos),this.dragActive_=!0,I.target?.setPointerCapture?.(I.pointerId))}onPointerMove(A){if(!this.dragActive_||!A.worldPos)return;const I=xB(rA(),this.dragStart_,A.worldPos);this.camera_.pan(I)}onPointerEnd(A){const I=A.event;!this.dragActive_||I.button!==GC||(this.dragActive_=!1,I.target?.releasePointerCapture?.(I.pointerId))}}class SI{objects_=[];state_="initialized";callbacks_=[];transparent;opacity_;blendMode;constructor({transparent:A=!1,opacity:I=1,blendMode:B="normal"}={}){(I<0||I>1)&&j.warn("Layer",`Layer opacity out of bounds: ${I} — clamping to [0.0, 1.0]`),this.transparent=A,this.opacity_=Jg(I,0,1),this.blendMode=B}get opacity(){return this.opacity_}set opacity(A){(A<0||A>1)&&j.warn("Layer",`Opacity out of bounds: ${A} — clamping to [0.0, 1.0]`),this.opacity_=Jg(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)}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_=[]}}class yB extends $I{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,o)=>E+jQ(i,A[o+1]??i),0);for(const E of[...Array(A.length).keys()]){for(const i of[-1,1]){const o=A[E];I[B++]=o[0],I[B++]=o[1],I[B++]=o[2];const y=A[E-1]??A[E];I[B++]=y[0],I[B++]=y[1],I[B++]=y[2];const a=A[E+1]??A[E];I[B++]=a[0],I[B++]=a[1],I[B++]=a[2],I[B++]=i,I[B++]=Q}Q+=jQ(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 jB extends Ag{color_;width_;taperOffset_=.5;taperPower_=0;constructor({geometry:A,color:I,width:B,taperOffset:Q,taperPower:C}){super(),this.geometry=A,this.color_=hA.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_=hA.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 Oi extends SI{type="AxesLayer";constructor(A){super();const{length:I,width:B}=A;this.addObject(zB({end:[I,0,0],width:B,color:[1,0,0]})),this.addObject(zB({end:[0,I,0],width:B,color:[0,1,0]})),this.addObject(zB({end:[0,0,I],width:B,color:[0,0,1]})),this.setState("ready")}update(){}}function zB(g){const{end:A,width:I,color:B}=g,Q=new yB([[0,0,0],A]);return new jB({geometry:Q,color:B,width:I})}class Vi extends SI{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 yB(I);this.addObject(new jB({geometry:C,color:B,width:Q}))}update(){}get extent(){return Xi(this.paths_.flat())}}function Xi(g){function A(o){const y=g.map(a=>a[o]);return[Math.min(...y),Math.max(...y)]}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 vi extends SI{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=zi({path:A.path,pointsPerSegment:A.interpolation.pointsPerSegment,tangentFactor:A.interpolation.tangentFactor});I=new yB(i)}else I=new yB(A.path);const{color:B,width:Q}=A,C=.5,E=1.5;this.addObject(new jB({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 ji(A.flat())}}function ji(g){function A(o){const y=g.map(a=>a[o]);return[Math.min(...y),Math.max(...y)]}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 zi({path:g,pointsPerSegment:A,tangentFactor:I=1/3}){const B=_i(g),Q=Array((g.length-1)*A);for(let C=0;C<g.length-1;C++){const E=g[C],i=g[C+1],o=CI(B[C]);vQ(o,E,o,I);const y=CI(B[C+1]);vQ(y,i,y,-I);for(let a=0;a<A;a++){const R=a/A,N=Q[C*A+a]=rA();Ci(N,E,o,y,i,R)}}return Q}function _i(g){if(g.length<2)throw new Error("Path must contain at least 2 points");const A=Array(g.length),I=rA(),B=rA();for(let Q=0;Q<g.length;Q++){const C=g[Q],E=g[Q+1]??g[Q];A[Q]=rA(),Q!==0&&cg(I,B),Q!==g.length-1&&xB(B,E,C),Q===0?cg(A[Q],B):Q==g.length-1?cg(A[Q],I):(VQ(A[Q],I,B),XQ(A[Q],A[Q],.5))}return A}class FC extends $I{constructor(A,I,B,Q){super();const C=[],E=[],i=B,o=Q,y=i+1,a=o+1,R=A/i,N=I/o;for(let r=0;r<a;++r){const K=r*N;for(let e=0;e<y;++e){const n=e*R,q=e/i,x=r/o,W=[n,K,0],P=[0,0,1],b=[q,x];C.push(...W,...P,...b)}}for(let r=0;r<o;++r)for(let K=0;K<i;++K){const e=K+y*r,n=K+y*(r+1),q=K+1+y*(r+1),x=K+1+y*r;E.push(e,n,x),E.push(n,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 wC(g){return g===1||g===2||g===4||g===8}function Ig(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 $i(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 _B extends WB{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 SC=32;function $B(g,{visible:A,color:I,contrastLimits:B}){return A===void 0&&(A=!0),I===void 0?I=hA.WHITE:I=hA.from(I),g!==null?B=AD(B,g):B===void 0&&(j.debug("Channel","No texture provided, defaulting channel contrast limits to [0, 1]."),B=[0,1]),{visible:A,color:I,contrastLimits:B}}function RC(g,A){if(A.length>SC)throw new Error(`Maximum number of channels is ${SC}`);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=>$B(g,I))}function AD(g,A){if(g===void 0)return $i(A);if(g[1]<=g[0])throw new Error(`Contrast limits must be strictly increasing: ${g}.`);return g}class AQ extends Ag{channels_;constructor(A,I,B,Q=[]){super(),this.geometry=new FC(A,I,1,1),this.setTexture(0,B),this.channels_=RC(B,Q),this.programName=ID(B)}get type(){return"ImageRenderable"}setChannelProps(A){this.channels_=RC(this.textures[0],A)}setChannelProperty(A,I,B){const Q=$B(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]??$B(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 ID(g){if(g.type==="Texture2D")return gD(g.dataType);if(g.type==="Texture2DArray")return BD(g.dataType);throw new Error(`Unsupported image texture type: ${g.type}`)}function gD(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 BD(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 gg extends _B{data_;width_;height_;depth_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=Ig(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!=Ig(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 gg(B,A.shape.x,A.shape.y);return Q.unpackAlignment=A.rowAlignmentBytes,Q}}function IQ(g,A,I,B,Q=3){switch(g.type){case"pointerdown":{const C=g.event;return pA(C.clientX,C.clientY)}case"pointerup":{if(!A)return A;const C=g.event,E=pA(C.clientX,C.clientY);if(wi(A,E)<Q){if(!B)return null;const o=g.worldPos;if(o){const y=I(o);y!==null&&B({world:o,value:y})}return null}return A}case"pointercancel":return null;default:return A}}class QD{bins_=new Map;acquire(A){const B=this.bins_.get(A)?.pop();return B&&j.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),j.debug("RenderablePool","Renderable object released")}clearAll(A){if(A)for(const I of this.bins_.values())I.forEach(A);this.bins_.clear()}}class gQ extends SI{type="ChunkedImageLayer";source_;sliceCoords_;onPickValue_;visibleChunks_=new Map;pool_=new QD;initialChannelProps_;channelChangeCallbacks_=[];policy_;channelProps_;chunkStoreView_;pointerDownPos_=null;zPrevPointWorld_;debugMode_=!1;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;wireframeColors_=[new hA(.6,.3,.3),new hA(.3,.6,.4),new hA(.4,.4,.7),new hA(.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.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_&&(this.chunkStoreView_.dispose(),this.chunkStoreView_=void 0)}update(A){!A||!this.chunkStoreView_||(this.chunkStoreView_.updateChunkStates(this.sliceCoords_,A.viewport),this.updateChunks(),this.resliceIfZChanged())}updateChunks(){if(!this.chunkStoreView_||(this.state!=="ready"&&this.setState("ready"),this.visibleChunks_.size>0&&!this.chunkStoreView_.allVisibleLowestLODLoaded(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)}}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>gQ.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_=IQ(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,CC))}slicePlane(A,I){if(!A.data)return;const B=(I-A.offset.z)/A.scale.z,Q=Math.round(B),C=Jg(Q,0,A.shape.z-1);VB(B,C,1+1e-6)||j.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(NC(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 AQ(A.shape.x,A.shape.y,gg.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){j.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=oB(rA(),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,o=E*A.shape.x+C;return i[o]}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(NC(I),B),this.visibleChunks_.delete(I))}}}function NC(g){return[`lod${g.lod}`,`shape${g.shape.x}x${g.shape.y}`,`align${g.rowAlignmentBytes}`].join(":")}class hB extends _B{data_;width_;height_;depth_;constructor(A,I,B,Q){super(),this.dataFormat="scalar",this.dataType=Ig(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!=Ig(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 hB(I,A.shape.x,A.shape.y,A.shape.z);return B.unpackAlignment=A.rowAlignmentBytes,B}}class CD extends $I{constructor(A,I,B,Q,C,E){super();const i=[],o=[],y=Math.floor(Q),a=Math.floor(C),R=Math.floor(E);this.buildFace("z","y","x",-1,-1,B,I,A,R,a,1,i,o),this.buildFace("z","y","x",1,-1,B,I,A,R,a,-1,i,o),this.buildFace("x","z","y",1,1,A,B,I,y,R,1,i,o),this.buildFace("x","z","y",1,-1,A,B,I,y,R,-1,i,o),this.buildFace("x","y","z",1,-1,A,I,B,y,a,1,i,o),this.buildFace("x","y","z",-1,-1,A,I,B,y,a,-1,i,o),this.vertexData_=new Float32Array(i),this.indexData_=new Uint32Array(o),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,o,y,a,R,N,r){const K=E/y,e=i/a,n=E/2,q=i/2,x=o/2*R,W=y+1,P=a+1,b=N.length/8;for(let m=0;m<P;m++){const IA=-q+m*e;for(let X=0;X<W;X++){const Z=-n+X*K,gA={x:0,y:0,z:0};gA[A]=Z*Q,gA[I]=IA*C,gA[B]=x;const AA={x:0,y:0,z:0};AA[B]=R;const wA=X/y,tA=1-m/a;N.push(gA.x,gA.y,gA.z,AA.x,AA.y,AA.z,wA,tA)}}for(let m=0;m<a;m++)for(let IA=0;IA<y;IA++){const X=b+IA+W*m,Z=b+IA+W*(m+1),gA=b+(IA+1)+W*(m+1),AA=b+(IA+1)+W*m;R===1?r.push(X,Z,AA,Z,gA,AA):r.push(X,AA,Z,Z,AA,gA)}}}class ED extends Ag{constructor(A,I,B,Q){super(),this.geometry=new CD(A,I,B,1,1,1),this.cullFaceMode="back",this.setTexture(0,Q),this.programName=iD(Q.dataType)}get type(){return"VolumeRenderable"}}function iD(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"}}class DD extends SI{type="VolumeLayer";constructor(){super();const A=new Int8Array([127,0,0,127,127,0,0,127]),I=new hB(A,2,2,2);I.unpackAlignment=1;const B=new ED(1,1,1,I);B.wireframeEnabled=!0,this.addObject(B),this.setState("ready")}update(){}}class oD extends SI{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_=IQ(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 AQ(A.shape.x,A.shape.y,gg.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=oB(rA(),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 Yg extends _B{data_;width_;height_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=Ig(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!=Ig(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 Yg(B,A.shape.x,A.shape.y);return Q.unpackAlignment=A.rowAlignmentBytes,Q}}const aD=[[1,.5,.5],[.5,1,.5],[.5,.5,1],[.5,1,1],[1,.5,1],[1,1,.5]];function sD(g){return g=g??new Map,new Map(Array.from(g.entries()).map(([A,I])=>[A,hA.from(I)]))}function yD(g){return g=g??aD,g.map(hA.from)}class UC{lookupTable;cycle;constructor(A={}){this.lookupTable=sD(A.lookupTable),this.cycle=yD(A.cycle)}}const hD=new Set(["unsigned_byte","unsigned_short","unsigned_int"]);function GD(g){if(g.dataFormat!=="scalar")throw new Error(`Image data format must be scalar, instead found: ${g.dataFormat}`);if(!hD.has(g.dataType))throw new Error(`Image data type must be unsigned, instead found: ${g.dataType}`);return g}class FD extends Ag{outlineSelected_;selectedValue_;constructor(A){super(),this.geometry=new FC(A.width,A.height,1,1),this.setTexture(0,GD(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 Yg(I,A.length,1);return B.dataFormat="rgba",B}makeColorLookupTableTexture(A){A===void 0?A=new Map([[0,hA.TRANSPARENT]]):A.has(0)||(A=new Map([[0,hA.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 Yg(C,Q,2)}}class wD extends SI{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 UC(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 UC(A),this.image_&&this.image_.setColorMap(this.colorMap_)}setSelectedValue(A){this.selectedValue_=A,this.image_&&this.image_.setSelectedValue(this.selectedValue_)}onEvent(A){this.pointerDownPos_=IQ(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 FD({width:A.shape.x,height:A.shape.y,imageData:Yg.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=oB(rA(),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 GB extends Error{constructor(A){super(A),this.name="AbortError",Object.setPrototypeOf(this,GB.prototype)}}class SD{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 GB("shutdown"))}get numRunning(){return this.numRunning_}get numPending(){return this.pending_.length}}class RD{source_;region_;seriesDimensionName_;seriesIndex_;scheduler_=new SD(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 j.debug("ImageSeriesLoader","Ignoring duplicate active setIndex request"),{success:!1,reason:"duplicate"};j.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(N=>N!==void 0),C=Q.find(N=>N.name===this.seriesDimensionName_);if(!C){const N=Q.map(r=>r.name).join(", ");throw new Error(`Series dimension "${this.seriesDimensionName_}" not found in loader dimensions: ${N}`)}const E=C.lods[B].scale,i=C.lods[B].size*E,o=this.seriesIndex_.type==="full",y=o?0:this.seriesIndex_.start,a=o?i:this.seriesIndex_.stop,R=Math.round((a-y)/E);return this.dataChunks_=new Array(R),this.seriesAttributes_={start:y,stop:a,scale:E,length:R},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(y=>y.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,o=await E.loadRegion(C,i,this.scheduler_);return this.dataChunks_[A]=o,I&&I.canceled&&(this.loadingToken_=null),o}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 GB)return Promise.reject(Q.reason);j.error("ImageSeriesLoader",`Error loading slice: ${Q.reason}`)}}async getLoader(){return this.loader_??=await this.source_.open(),this.loader_}}class ND extends SI{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 RD({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_=gg.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 AQ(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}}class ng extends Error{constructor(A,I={}){super(`Node not found: ${A}`,I),this.name="NodeNotFoundError"}}class BQ extends Error{constructor(A){super(`Missing key: ${A}`),this.name="KeyError"}}class QQ{kind="array_to_array";constructor(A,I){if(A.keepbits<0)throw new Error("keepbits must be zero or positive")}static fromConfig(A,I){return new QQ(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}}class tC{#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 CQ{_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 Kg{#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 Kg(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 Mg(g){const A=new TextDecoder().decode(g);return JSON.parse(A)}function kC(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}const UD={int8:Int8Array,int16:Int16Array,int32:Int32Array,int64:globalThis.BigInt64Array,uint8:Uint8Array,uint16:Uint16Array,uint32:Uint32Array,uint64:globalThis.BigUint64Array,float32:Float32Array,float64:Float64Array,bool:tC},tD=/v2:([US])(\d+)/;function cC(g){if(g==="v2:object")return globalThis.Array;let A=g.match(tD);if(A){let[,B,Q]=A;return(B==="U"?Kg:CQ).bind(null,Number(Q))}let I=UD[g];if(!I)throw new Error(`Unknown or unsupported data_type: ${g}`);return I}function pI(g,A){return(A==="C"?kD:cD)(g)}function kD(g){const A=g.length,I=globalThis.Array(A);for(let B=A-1,Q=1;B>=0;B--)I[B]=Q,Q*=g[B];return I}function cD(g){const A=g.length,I=globalThis.Array(A);for(let B=0,Q=1;B<A;B++)I[B]=Q,Q*=g[B];return I}function LD({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 EQ(g){return g.find(I=>I.name==="transpose")?.configuration?.order==="F"?"F":"C"}const JD=/^([<|>])(.*)$/;function rD(g){if(g==="|O")return{data_type:"v2:object"};let A=g.match(JD);if(!A)throw new Error(`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",f4:"float32",f8:"float64"}[B]??(B.startsWith("S")||B.startsWith("U")?`v2:${B}`:void 0);if(!Q)throw new Error(`Unsupported or unknown dtype: ${g}`);return I==="|"?{data_type:Q}:{data_type:Q,endian:I==="<"?"little":"big"}}function YD(g,A={}){let I=[],B=rD(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 nD(g,A={}){return{zarr_format:3,node_type:"group",attributes:A}}function KD(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 MD(g){return g?.name==="sharding_indexed"}function LC(g){return(g.data_type==="uint64"||g.data_type==="int64")&&g.fill_value!=null?BigInt(g.fill_value):g.fill_value}const JC=eD();function eD(){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 FB{kind="array_to_bytes";#A;#I;#g;#Q;#B;constructor(A,I){this.#B=A?.endian,this.#I=cC(I.data_type),this.#Q=I.shape,this.#A=pI(I.shape,EQ(I.codecs));const B=new this.#I(0);this.#g=B.BYTES_PER_ELEMENT}static fromConfig(A,I){return new FB(A,I)}encode(A){let I=new Uint8Array(A.data.buffer);return JC&&this.#B==="big"&&kC(I,rC(this.#I)),I}decode(A){return JC&&this.#B==="big"&&kC(A,rC(this.#I)),{data:new this.#I(A.buffer,A.byteOffset,A.byteLength/this.#g),shape:this.#Q,stride:this.#A}}}class iQ{kind="bytes_to_bytes";static fromConfig(){return new iQ}encode(A){throw new Error("Not implemented")}decode(A){return new Uint8Array(A.buffer,A.byteOffset,A.byteLength-4)}}function HD(g,A){if(Number.isNaN(A))throw new Error("JsonCodec allow_nan is false but NaN was encountered during encoding.");if(A===Number.POSITIVE_INFINITY)throw new Error("JsonCodec allow_nan is false but Infinity was encountered during encoding.");if(A===Number.NEGATIVE_INFINITY)throw new Error("JsonCodec allow_nan is false but -Infinity was encountered during encoding.");return A}function qD(g,A){return A instanceof Object&&!Array.isArray(A)?Object.keys(A).sort().reduce((I,B)=>(I[B]=A[B],I),{}):A}class DQ{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:o,strict:y=!0}=A;let a=A.separators;a||(o?a=[", ",": "]:a=[",",":"]),this.#A={encoding:I,skipkeys:B,ensure_ascii:Q,check_circular:C,allow_nan:E,indent:o,separators:a,sort_keys:i},this.#I={strict:y}}static fromConfig(A){return new DQ(A)}encode(A){const{indent:I,encoding:B,ensure_ascii:Q,check_circular:C,allow_nan:E,sort_keys:i}=this.#A;if(B!=="utf-8")throw new Error("JsonCodec does not yet support non-utf-8 encoding.");const o=[];if(!C)throw new Error("JsonCodec does not yet support skipping the check for circular references during encoding.");E||o.push(HD),i&&o.push(qD);const y=Array.from(A.data);y.push("|O"),y.push(A.shape);let a;o.length&&(a=(N,r)=>{let K=r;for(let e of o)K=e(N,K);return K});let R=JSON.stringify(y,a,I);return Q&&(R=R.replace(/[\u007F-\uFFFF]/g,N=>{const r=`0000${N.charCodeAt(0).toString(16)}`;return`\\u${r.substring(r.length-4)}`})),new TextEncoder().encode(R)}decode(A){const{strict:I}=this.#I;if(!I)throw new Error("JsonCodec does not yet support non-strict decoding.");const B=Mg(A),Q=B.pop();if(B.pop(),!Q)throw new Error("0D not implemented for JsonCodec.");const C=pI(Q,"C");return{data:B,shape:Q,stride:C}}}function YC(g){return g instanceof tC||g instanceof CQ||g instanceof Kg?new Proxy(g,{get(I,B){return I.get(Number(B))},set(I,B,Q){return I.set(Number(B),Q),!0}}):g}function dD(g,A){let I;return g.data instanceof CQ||g.data instanceof Kg?I=new g.constructor(g.data.length,g.data.chars):I=new g.constructor(g.data.length),{data:I,shape:g.shape,stride:pI(g.shape,A)}}function fD(g,A){let I=dD(g,A),B=g.shape.length,Q=g.data.length,C=Array(B).fill(0),E=YC(g.data),i=YC(I.data);for(let o=0;o<Q;o++){let y=0;for(let a=0;a<B;a++)y+=C[a]*I.stride[a];i[y]=E[o],C[0]+=1;for(let a=0;a<B;a++)if(C[a]===g.shape[a]){if(a+1===B)break;C[a]=0,C[a+1]+=1}}return I}function lD(g){if(!g.stride)return"C";let A=pI(g.shape,"C");return g.stride.every((I,B)=>I===A[B])?"C":"F"}class oQ{configuration;kind="array_to_array";constructor(A){this.configuration=A}static fromConfig(A){return new oQ(A)}encode(A){return lD(A)===this.configuration?.order?A:fD(A,this.configuration?.order??"C")}decode(A){return A}}class aQ{kind="array_to_bytes";#A;#I;constructor(A){this.#A=A,this.#I=pI(A,"C")}static fromConfig(A,I){return new aQ(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}}}function pD(){return new Map().set("blosc",()=>Promise.resolve().then(()=>ss).then(g=>g.default)).set("gzip",()=>Promise.resolve().then(()=>ls).then(g=>g.default)).set("lz4",()=>Promise.resolve().then(()=>Zs).then(g=>g.default)).set("zlib",()=>Promise.resolve().then(()=>Ps).then(g=>g.default)).set("zstd",()=>Promise.resolve().then(()=>zs).then(g=>g.default)).set("transpose",()=>oQ).set("bytes",()=>FB).set("crc32c",()=>iQ).set("vlen-utf8",()=>aQ).set("json2",()=>DQ).set("bitround",()=>QQ)}const WD=pD();function sQ(g){let A;return{async encode(I){A||(A=await nC(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 nC(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 nC(g){let A=g.codecs.map(async C=>{let E=await WD.get(C.name)?.();if(!E)throw new Error(`Unknown codec: ${C.name}`);return{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)}}if(!B){if(!mD(g))throw new Error(`Cannot encode ${g.data_type} to bytes without a codec`);B=FB.fromConfig({endian:"little"},g)}return{array_to_array:I,array_to_bytes:B,bytes_to_bytes:Q}}function mD(g){return g.data_type!=="v2:object"}const KC=18446744073709551615n;function TD(g,A,I,B){if(g.store.getRange===void 0)throw new Error("Store does not support range requests");let Q=g.store.getRange.bind(g.store),C=A.map((o,y)=>o/B.chunk_shape[y]),E=sQ({data_type:"uint64",shape:[...C,2],codecs:B.index_codecs}),i={};return async o=>{let y=o.map((x,W)=>Math.floor(x/C[W])),a=g.resolve(I(y)).path,R;if(a in i)R=i[a];else{let x=4,W=16*C.reduce((b,m)=>b*m,1),P=await Q(a,{suffixLength:W+x});R=i[a]=P?await E.decode(P):null}if(R===null)return;let{data:N,shape:r,stride:K}=R,e=o.map((x,W)=>x%r[W]).reduce((x,W,P)=>x+W*K[P],0),n=N[e],q=N[e+1];if(!(n===KC&&q===KC))return Q(a,{offset:Number(n),length:Number(q)})}}class VA{store;path;constructor(A,I="/"){this.store=A,this.path=I}resolve(A){let I=new URL(`file://${this.path.endsWith("/")?this.path:`${this.path}/`}`);return new VA(this.store,new URL(A,I).pathname)}}class yQ extends VA{kind="group";#A;constructor(A,I,B){super(A,I),this.#A=B}get attrs(){return this.#A.attributes}}const eg=Symbol("zarrita.context");function xD(g){return g[eg]}function ZD(g,A){let{configuration:I}=A.codecs.find(MD)??{},B={encode_chunk_key:LD(A.chunk_key_encoding),TypedArray:cC(A.data_type),fill_value:A.fill_value};if(I){let C=EQ(I.codecs);return{...B,kind:"sharded",chunk_shape:I.chunk_shape,codec:sQ({data_type:A.data_type,shape:I.chunk_shape,codecs:I.codecs}),get_strides(E,i){return pI(E,i??C)},get_chunk_bytes:TD(g,A.chunk_grid.configuration.chunk_shape,B.encode_chunk_key,I)}}let Q=EQ(A.codecs);return{...B,kind:"regular",chunk_shape:A.chunk_grid.configuration.chunk_shape,codec:sQ({data_type:A.data_type,shape:A.chunk_grid.configuration.chunk_shape,codecs:A.codecs}),get_strides(C,E){return pI(C,E??Q)},async get_chunk_bytes(C,E){let i=B.encode_chunk_key(C),o=g.resolve(i).path;return g.store.get(o,E)}}}let wB=class extends VA{kind="array";#A;[eg];constructor(A,I,B){super(A,I),this.#A={...B,fill_value:LC(B)},this[eg]=ZD(this,B)}get attrs(){return this.#A.attributes}get shape(){return this.#A.shape}get chunks(){return this[eg].chunk_shape}get dtype(){return this.#A.data_type}async getChunk(A,I){let B=this[eg],Q=await B.get_chunk_bytes(A,I);if(!Q){let C=B.chunk_shape.reduce((i,o)=>i*o,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 KD(this.dtype,A)}},SB=bD();function bD(){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 uD(g){let A=await g.store.get(g.resolve(".zattrs").path);return A?Mg(A):{}}async function PD(g,A={}){let I="store"in g?g:new VA(g),B={};return(A.attrs??!0)&&(B=await uD(I)),A.kind==="array"?MC(I,B):A.kind==="group"?eC(I,B):MC(I,B).catch(Q=>{if(Q instanceof ng)return eC(I,B);throw Q})}async function MC(g,A){let{path:I}=g.resolve(".zarray"),B=await g.store.get(I);if(!B)throw new ng("v2 array",{cause:new BQ(I)});return SB.increment(g.store,"v2"),new wB(g.store,g.path,YD(Mg(B),A))}async function eC(g,A){let{path:I}=g.resolve(".zgroup"),B=await g.store.get(I);if(!B)throw new ng("v2 group",{cause:new BQ(I)});return SB.increment(g.store,"v2"),new yQ(g.store,g.path,nD(Mg(B),A))}async function OD(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 BQ(I)});let Q=Mg(B);return Q.node_type==="array"&&(Q.fill_value=LC(Q)),Q.node_type==="array"?new wB(A,g.path,Q):new yQ(A,g.path,Q)}async function VD(g,A={}){let I="store"in g?g:new VA(g),B=await OD(I);if(SB.increment(I.store,"v3"),A.kind===void 0||A.kind==="array"&&B instanceof wB||A.kind==="group"&&B instanceof yQ)return B;let Q=B instanceof wB?"array":"group";throw new Error(`Expected node of kind ${A.kind}, found ${Q}.`)}async function gI(g,A={}){let I="store"in g?g.store:g,B=SB.version_max(I),Q=B==="v2"?gI.v2:gI.v3,C=B==="v2"?gI.v3:gI.v2;return Q(g,A).catch(E=>{if(E instanceof ng)return C(g,A);throw E})}gI.v2=PD,gI.v3=VD;function HC(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 XD(g,A){return{...g,...A,headers:{...g.headers,...A.headers}}}function qC(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 dC(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 vD(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 HC(g,E-A,E,I)}class Bg{url;#A;#I;constructor(A,I={}){this.url=A,this.#A=I.overrides??{},this.#I=I.useSuffixRequest??!1}#g(A){return XD(this.#A,A)}async get(A,I={}){let B=qC(this.url,A).href,Q=await fetch(B,this.#g(I));return dC(Q)}async getRange(A,I,B={}){let Q=qC(this.url,A),C=this.#g(B),E;return"suffixLength"in I?E=await vD(Q,I.suffixLength,C,this.#I):E=await HC(Q,I.offset,I.length,C),dC(E)}}function*jD(g,A,I=1){A===void 0&&(A=g,g=0);for(let B=g;B<A;B+=I)yield B}function*zD(...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 _D({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 RB(g,A,I=null){return A===void 0&&(A=g,g=null),{start:g,stop:A,step:I}}function $D(){const g=[];return{add:A=>g.push(A()),onIdle:()=>Promise.all(g)}}class hQ extends Error{constructor(A){super(A),this.name="IndexError"}}function Ao(g,A){throw new hQ(`too many indicies for array; expected ${A.length}, got ${g.length}`)}function Io(g){throw new hQ(`index out of bounds for dimension with length ${g}`)}function go(){throw new hQ("only slices with step >= 1 are supported")}function Bo(g,A){g.length>A.length&&Ao(g,A)}function Qo(g,A){return g=Math.trunc(g),g<0&&(g=A+g),(g>=A||g<0)&&Io(A),g}class Co{dim_sel;dim_len;dim_chunk_len;nitems;constructor({dim_sel:A,dim_len:I,dim_chunk_len:B}){A=Qo(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 fC{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]=_D(A,I);this.start=Q,this.stop=C,this.step=E,this.step<1&&go(),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 jD(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,o=0;if(this.start<Q){const r=(Q-this.start)%this.step;r&&(o+=this.step-r),i=Math.ceil((Q-this.start)/this.step)}else o=this.start-Q;const y=this.stop>C?E:this.stop-Q,a=[o,y,this.step],R=Math.ceil((y-o)/this.step),N=[i,i+R,1];yield{dim_chunk_ix:B,dim_chunk_sel:a,dim_out_sel:N}}}}function Eo(g,A){let I=[];return g===null?I=A.map(B=>RB(null)):Array.isArray(g)&&(I=g.map(B=>B??RB(null))),Bo(I,A),I}class io{dim_indexers;shape;constructor({selection:A,shape:I,chunk_shape:B}){this.dim_indexers=Eo(A,I).map((Q,C)=>new(typeof Q=="number"?Co:fC)({dim_sel:Q,dim_len:I[C],dim_chunk_len:B[C]})),this.shape=this.dim_indexers.filter(Q=>Q instanceof fC).map(Q=>Q.nitems)}*[Symbol.iterator](){for(const A of zD(...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 Do(g,A){return"get"in g?g.get(A):g[A]}async function oo(g,A,I,B){let Q=xD(g),C=new io({selection:A,shape:g.shape,chunk_shape:g.chunks}),E=B.prepare(new Q.TypedArray(C.shape.reduce((o,y)=>o*y,1)),C.shape,Q.get_strides(C.shape,I.order)),i=I.create_queue?.()??$D();for(const{chunk_coords:o,mapping:y}of C)i.add(async()=>{let{data:a,shape:R,stride:N}=await g.getChunk(o,I.opts),r=B.prepare(a,R,N);B.set_from_chunk(E,r,y)});return await i.onIdle(),C.shape.length===0?Do(E.data,0):E}function GQ(g,A=0,I){let B=I??g.length-A;return{length:B,subarray(Q,C=B){return GQ(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 FQ(g){return globalThis.Array.isArray(g.data)?{data:GQ(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 ao(g){return"chars"in g?g.constructor.bind(null,g.chars):g.constructor}function so(g,A){if(globalThis.Array.isArray(g.data))return GQ([A]);let I=ao(g.data),B=new I([A]);return new Uint8Array(B.buffer,B.byteOffset,B.byteLength)}const yo={prepare(g,A,I){return{data:g,shape:A,stride:I}},set_scalar(g,A,I){let B=FQ(g);wQ(B,A,so(g,I),B.bytes_per_element)},set_from_chunk(g,A,I){let B=FQ(g);NB(B,FQ(A),B.bytes_per_element,I)}};async function ho(g,A=null,I={}){return oo(g,A,I,yo)}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 wQ(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 N=g.data.subarray(E*Q*B);wQ({data:N,stride:i},C,I,B);return}const[o,y,a]=Q,R=lC(o,y,a);if(C.length===0){for(let N=0;N<R;N++)g.data.set(I,E*(o+a*N)*B);return}for(let N=0;N<R;N++){const r=g.data.subarray(E*(o+a*N)*B);wQ({data:r,stride:i},C,I,B)}}function NB(g,A,I,B){const[Q,...C]=B,[E,...i]=g.stride,[o,...y]=A.stride;if(Q.from===null){if(C.length===0){g.data.set(A.data.subarray(0,I),Q.to*I);return}NB({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}NB(g,{data:A.data.subarray(o*Q.from*I),stride:y},I,C);return}const[a,R,N]=Q.to,[r,K,e]=Q.from,n=lC(a,R,N);if(C.length===0){if(N===1&&e===1&&E===1&&o===1){let q=r*I,x=n*I;g.data.set(A.data.subarray(q,q+x),a*I);return}for(let q=0;q<n;q++){let x=o*(r+e*q)*I;g.data.set(A.data.subarray(x,x+I),E*(a+N*q)*I)}return}for(let q=0;q<n;q++)NB({data:g.data.subarray(E*(a+q*N)*I),stride:i},{data:A.data.subarray(o*(r+q*e)*I),stride:y},I,C)}async function Go(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 SQ{#A;constructor(A){this.#A=A}get directoryHandle(){return this.#A}async get(A){const I=await Go(this.#A,A.slice(1)).catch(()=>{});if(!I)return;const Q=await(await I.getFile()).arrayBuffer();return new Uint8Array(Q)}}function Fo(){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 RQ extends Bg{credentials;region;signingKeyCache_=new Map;overrides;useSuffixRequest;constructor(A){Fo(),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"),o=globalThis.fetch,y=async(R,N)=>{const K=(N?.method||"GET")==="HEAD"?E:i,e={...N,headers:{...N?.headers,...K}};return o(R,e)},a=globalThis.fetch;globalThis.fetch=y;try{return await super.getRange(A,I,B)}finally{globalThis.fetch=a}}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",o=this.getAmzDate(),y=o.slice(0,8),a=new URL(A),R=a.host,N=a.pathname,r=a.search.slice(1),K=`host:${R}
|
|
348
348
|
x-amz-content-sha256:UNSIGNED-PAYLOAD
|
|
349
349
|
x-amz-date:${o}
|
|
350
350
|
`+(C?`x-amz-security-token:${C}
|