@idetik/core 0.31.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -553,7 +553,7 @@ fn vert(@location(0) aPos: vec3f) -> @builtin(position) vec4f {
553
553
  @fragment
554
554
  fn frag() -> @location(0) vec4f {
555
555
  return vec4f(uniforms.color, uniforms.opacity);
556
- }`;class RD{colorFormat_;depthFormat_;device_;pipelines_;shaderModules_;constructor(A,I,g){this.colorFormat_=I,this.depthFormat_=g,this.device_=A,this.pipelines_=[],this.shaderModules_=[]}async compileShader(A){if(this.shaderModules_.some(a=>a.name===A))return;const I=LD(A),g=this.device_.createShaderModule({code:I});await cD(A,g);const B=wD(I),C=sD(B,{vertex:{entryPoint:"vert"},fragment:{entryPoint:"frag"}}),E=C[B.uniforms.uniforms.group];UD(E);const i=B.textures?.texture;let o;if(i){const a=C[i.group];A==="image_scalar_f32"&&kD(a),o=this.device_.createBindGroupLayout(a)}this.shaderModules_.push({name:A,module:g,defs:B,layouts:{uniforms:this.device_.createBindGroupLayout(E),textures:o}})}get(A,I){const g=this.getCachedPipeline(A);if(g)return g;const B=this.shaderModules_.find(F=>F.name===A.shaderName);if(!B)throw new Error("Shader module not found");const C=A.depthTest?"less-equal":"always",E=A.stencil?{compare:"equal",passOp:"increment-clamp"}:{},i={vertex:{module:B.module,entryPoint:"vert",buffers:[{attributes:I.attributes,arrayStride:I.geometry.strideBytes,stepMode:"vertex"}]},fragment:{module:B.module,entryPoint:"frag",targets:[{format:this.colorFormat_,blend:JD(A.blendMode)}]},primitive:{topology:A.topology,frontFace:"ccw",cullMode:A.cullMode},depthStencil:{format:this.depthFormat_,depthWriteEnabled:A.depthWrite,depthCompare:C,stencilFront:E,stencilBack:E,stencilReadMask:255,stencilWriteMask:255},multisample:{count:4}},o=[B.layouts.uniforms];B.layouts.textures&&o.push(B.layouts.textures);const a=this.device_.createPipelineLayout({bindGroupLayouts:o}),D=this.device_.createRenderPipeline({layout:a,...i}),s=la(B.defs.uniforms.uniforms),y={key:A,pipeline:D,uniformsView:s,uniformsData:new Float32Array(s.arrayBuffer),shaderModule:B};return this.pipelines_.push(y),y}getCachedPipeline(A){return this.pipelines_.find(I=>I.key.blendMode===A.blendMode&&I.key.cullMode===A.cullMode&&I.key.depthTest===A.depthTest&&I.key.depthWrite===A.depthWrite&&I.key.shaderName===A.shaderName&&I.key.stencil===A.stencil&&I.key.topology===A.topology&&I.key.vertexAttributesStr===A.vertexAttributesStr)}}async function cD(Q,A){const I=await A.getCompilationInfo();if(I.messages.some(g=>g.type==="error")){for(const g of I.messages)gA.error("WebGPUPipelines",`${g.type}: ${g.message}`);throw new Error(`Failed to compile WGSL shader ${Q}.wgsl`)}}function UD(Q){for(const A of Q.entries)A.buffer&&(A.buffer={...A.buffer,hasDynamicOffset:!0})}function kD(Q){for(const A of Q.entries)A.texture&&(A.texture={...A.texture,sampleType:"unfilterable-float"})}function LD(Q){switch(Q){case"image_scalar_u32":return rD;case"image_scalar_i32":return nD;case"image_scalar_f32":return SD;case"wireframe":return ND}}function JD(Q){let A,I;switch(Q){case"none":return;case"additive":A="src-alpha",I="one";break;case"multiply":A="dst",I="zero";break;case"subtractive":A="zero",I="one-minus-src";break;case"premultiplied":A="one-minus-dst-alpha",I="one";break;case"normal":A="src-alpha",I="one-minus-src-alpha";break}const g={srcFactor:A,dstFactor:I,operation:"add"};return{color:g,alpha:g}}const YD=xo(1,0,0,0,0,-1,0,0,0,0,.5,0,0,0,.5,1);async function KD(Q){if(!navigator.gpu)throw new Error("WebGPU is not supported in this browser");const A=await navigator.gpu.requestAdapter();if(!A)throw new Error("Failed to obtain a WebGPU Adapter");const I=new MD(Q,await A.requestDevice());return await I.compileShaders(),I}class MD extends OC{bindings_;geometryBuffers_;pipelines_;texturePool_;colorFormat_;context_;depthFormat_;device_;currentProjection_=hI();currentModelView_=hI();colorMSAATexture_=null;depthStencilTexture_=null;passEncoder_=null;renderedObjectsPerFrame_=0;needsClear_=!0;currentDepthWrite_=!0;currentStencil_=!1;currentBlendMode_="none";currentLayerOpacity_=1;constructor(A,I){super(A),this.colorFormat_=navigator.gpu.getPreferredCanvasFormat(),this.depthFormat_="depth24plus-stencil8",this.device_=I;const g=A.getContext("webgpu");if(!g)throw new Error("Failed to initialize WebGPU context");g.configure({device:this.device_,format:this.colorFormat_,alphaMode:"premultiplied"}),this.context_=g,this.bindings_=new Sa(I),this.geometryBuffers_=new Na(I),this.texturePool_=new Ua(I),this.pipelines_=new RD(I,this.colorFormat_,this.depthFormat_),gA.info("WebGPURenderer","WebGPU Initialized"),this.resize(this.width,this.height)}async compileShaders(){await Promise.all([this.pipelines_.compileShader("image_scalar_u32"),this.pipelines_.compileShader("image_scalar_i32"),this.pipelines_.compileShader("image_scalar_f32"),this.pipelines_.compileShader("wireframe")])}beginFrame(){this.renderedObjects_=0,this.renderedObjectsPerFrame_=0,this.needsClear_=!0}render(A){const I=[],g=[];for(const o of A.layers)(o.blendMode==="none"?I:g).push(o);for(const o of[...I,...g])o.update(A);if(getComputedStyle(A.element).visibility==="hidden")return;const B=A.getBoxRelativeTo(this.canvas),C=new QI(xA(0,0),xA(this.width,this.height));if(!QI.intersects(B,C)){gA.warn("WebGPURenderer",`Viewport ${A.id} is entirely outside canvas bounds`);return}const E=A.camera.frustum,i=!QI.equals(B.floor(),C.floor());this.bindings_.clearUniformBindings(),this.updateProjection(A.camera.projectionMatrix),this.currentDepthWrite_=!0;for(const o of I)o.state==="ready"&&this.renderLayer(o,A.camera,E,B,i);this.currentDepthWrite_=!1;for(const o of g)o.state==="ready"&&this.renderLayer(o,A.camera,E,B,i);this.renderedObjects_=this.renderedObjectsPerFrame_}renderLayer(A,I,g,B,C){if(A.type!=="ImageLayer")throw new Error("Experimental WebGPU renderer only supports image layers");if(A.objects.length===0)return;const E=this.device_.createCommandEncoder();this.passEncoder_=this.beginRenderPass(E);const{x:i,y:o,width:a,height:D}=B.floor().toRect();this.passEncoder_.setViewport(i,o,a,D,0,1),C&&this.passEncoder_.setScissorRect(i,o,a,D),this.currentStencil_=A.hasMultipleLODs(),this.currentStencil_&&this.passEncoder_.setStencilReference(0),this.currentBlendMode_=A.blendMode,this.currentLayerOpacity_=A.opacity,A.objects.forEach((s,y)=>{g.intersectsWithBox3(s.boundingBox)&&(this.renderObject(A,y,I),this.renderedObjectsPerFrame_+=1)}),this.passEncoder_.end(),this.device_.queue.submit([E.finish()]),this.passEncoder_=null}renderObject(A,I,g){const B=A.objects[I];if(B.type!=="ImageRenderable")throw new Error("Experimental WebGPU renderer only supports image renderables");if(B.popStaleTextures().forEach(o=>{this.texturePool_.dispose(o)}),!B.programName)return;const C=this.passEncoder_,E=this.geometryBuffers_.get(B.geometry),i=this.pipelines_.get({shaderName:dD(B.textures[0]),depthWrite:this.currentDepthWrite_,depthTest:B.depthTest,stencil:this.currentStencil_,blendMode:this.currentBlendMode_,cullMode:"back",topology:"triangle-list",vertexAttributesStr:E.attributesKey},E);C.setPipeline(i.pipeline),this.setUniformsForObject(B,i,g),this.setTexturesForObject(B,i),C.setVertexBuffer(0,E.vertexBuffer),E.indexBuffer?(C.setIndexBuffer(E.indexBuffer,"uint32"),C.drawIndexed(B.geometry.indexData.length)):C.draw(B.geometry.vertexCount),B.wireframeEnabled&&this.renderWireframe(B,g)}renderWireframe(A,I){const g=A.wireframeGeometry;if(g.indexData.length===0)return;const B=this.passEncoder_,C=this.geometryBuffers_.get(g),E=this.pipelines_.get({shaderName:"wireframe",depthWrite:this.currentDepthWrite_,depthTest:A.depthTest,stencil:this.currentStencil_,blendMode:this.currentBlendMode_,cullMode:"none",topology:"line-list",vertexAttributesStr:C.attributesKey},C);B.setPipeline(E.pipeline),Ng(this.currentModelView_,I.viewMatrix,A.transform.matrix),E.uniformsView.set({projection:this.currentProjection_,modelView:this.currentModelView_,color:A.wireframeColor.rgb,opacity:this.currentLayerOpacity_}),this.bindings_.setUniforms(B,E),B.setVertexBuffer(0,C.vertexBuffer),C.indexBuffer&&(B.setIndexBuffer(C.indexBuffer,"uint32"),B.drawIndexed(g.indexData.length))}resize(A,I){this.colorMSAATexture_&&this.colorMSAATexture_.destroy(),this.colorMSAATexture_=this.device_.createTexture({size:{width:A,height:I},format:this.colorFormat_,sampleCount:4,usage:GPUTextureUsage.RENDER_ATTACHMENT}),this.depthStencilTexture_&&this.depthStencilTexture_.destroy(),this.depthStencilTexture_=this.device_.createTexture({size:{width:A,height:I},format:this.depthFormat_,sampleCount:4,usage:GPUTextureUsage.RENDER_ATTACHMENT})}beginRenderPass(A){const I=this.needsClear_?"clear":"load";return this.needsClear_=!1,A.beginRenderPass({colorAttachments:[{view:this.colorMSAATexture_.createView(),resolveTarget:this.context_.getCurrentTexture().createView(),loadOp:I,storeOp:"store",clearValue:{r:this.backgroundColor.r,g:this.backgroundColor.g,b:this.backgroundColor.b,a:this.backgroundColor.a}}],depthStencilAttachment:{view:this.depthStencilTexture_.createView(),depthLoadOp:I,depthStoreOp:"store",depthClearValue:1,stencilLoadOp:"clear",stencilStoreOp:"store",stencilClearValue:0}})}clear(){}uploadTexture(A){this.texturePool_.get(A)}disposeTexture(A){this.texturePool_.dispose(A)}setUniformsForObject(A,I,g){Ng(this.currentModelView_,g.viewMatrix,A.transform.matrix);const B=A.getUniforms(),C=B.Opacity??1;I.uniformsView.set({projection:this.currentProjection_,modelView:this.currentModelView_,color:B.u_color,valueOffset:B.u_valueOffset,valueScale:B.u_valueScale,opacity:this.currentLayerOpacity_*C,zTexCoord:B.u_zTexCoord}),this.bindings_.setUniforms(this.passEncoder_,I)}setTexturesForObject(A,I){if(A.textures.length>1)throw new Error("Experimental WebGPU renderer only supports single textures");this.bindings_.setTexture(this.passEncoder_,I,this.texturePool_.get(A.textures[0]))}updateProjection(A){Ng(this.currentProjection_,YD,A)}get gpuTextureBytes(){return this.texturePool_.gpuTextureBytes}get gpuTextureCount(){return this.texturePool_.textureCount}}function dD(Q){switch(Q.dataType){case"byte":case"unsigned_byte":case"float":return"image_scalar_f32";case"short":case"int":return"image_scalar_i32";case"unsigned_short":case"unsigned_int":return"image_scalar_u32"}}function sB(Q,A){const I=Q.priority??Number.MAX_SAFE_INTEGER,g=A.priority??Number.MAX_SAFE_INTEGER;return I===g?(Q.orderKey??Number.MAX_SAFE_INTEGER)-(A.orderKey??Number.MAX_SAFE_INTEGER):I-g}class HD{maxConcurrent_;pending_=[];running_=new Map;constructor(A){this.maxConcurrent_=Math.max(1,A)}enqueue(A,I){this.running_.has(A)||this.pending_.some(g=>g.chunk===A)||this.pending_.push({chunk:A,fn:I})}flush(){this.pump()}cancel(A){const I=this.pending_.findIndex(B=>B.chunk===A);if(I>=0){this.pending_.splice(I,1),gA.debug("ChunkQueue","Cancelled pending request");return}const g=this.running_.get(A);g&&(g.controller.abort(),gA.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)=>sB(A.chunk,I.chunk));this.running_.size<this.maxConcurrent_&&this.pending_.length>0;)this.start(this.pending_.shift())}start(A){const{chunk:I,fn:g}=A;I.state="loading";const B=new AbortController,C=Promise.resolve().then(()=>g(B.signal)).then(()=>{I.state==="loading"&&(I.state="loaded")},E=>{I.state==="loading"&&(I.state="unloaded"),E.name!=="AbortError"&&gA.error("ChunkQueue",String(E))}).finally(()=>{this.running_.delete(I),this.pump()});this.running_.set(I,{controller:B,promise:C})}}let VB=0,OB=0;function qD(Q,A){Q.data&&(VB-=Q.data.byteLength,OB-=1),Q.data=A,VB+=A.byteLength,OB+=1}function OE(Q){Q.data&&(VB-=Q.data.byteLength,OB-=1),Q.data=void 0,Q.texture?.releaseCpuData()}function lD(){return{cpuChunkBytes:VB,cpuChunkCount:OB}}function vE(Q,A,I=1e-6){return Math.abs(Q-A)<=I}const XE=[Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array];function fD(Q){if(XE.some(I=>Q instanceof I))return!0;const A=XE.map(I=>I.name);return gA.debug("Chunk",`Unsupported chunk data type: ${Q}. Supported data types: ${A}`),!1}function pD(Q,A){return Math.round((A-Q.translation)/Q.scale)}function fI(Q,A,I){return Math.max(A,Math.min(I,Q))}const vB=Symbol("INTERNAL_POLICY_KEY");class uD{store_;policy_;policyChanged_=!1;currentLOD_=0;lastViewBounds2D_=null;lastViewProjection_=null;lastZBounds_;lastTCoord_;lastCCoords_;sourceMaxSquareDistance2D_;chunkViewStates_=new Map;isDisposed_=!1;constructor(A,I){this.store_=A,this.policy_=I,gA.info("ChunkStoreView","Using image source policy:",this.policy_.profile);const g=this.store_.dimensions,B=g.x.lods[0],C=g.y.lods[0];this.sourceMaxSquareDistance2D_=aa(xA(B.size*B.scale,C.size*C.scale))}get chunkViewStates(){return this.chunkViewStates_}get isDisposed(){return this.isDisposed_}get lodCount(){return this.store_.lodCount}get channelCount(){return this.store_.channelCount}getChunksToRender(){const A=this.fallbackLOD(),I=this.currentLOD_,g=[],B=[];for(const[C,E]of this.chunkViewStates_)!E.visible||C.state!=="loaded"||!C.texture||(C.lod===I?g.push(C):C.lod===A&&I!==A&&B.push(C));return[...g,...B]}updateChunksForImage(A,I){const g=I.worldViewRect,C=Math.abs(g.max[0]-g.min[0])/I.bufferWidthPx,E=Math.log2(1/C);this.setLOD(E);const i=this.getZBounds(A);if(!(this.policyChanged_||this.viewBounds2DChanged(g)||this.zBoundsChanged(i)||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const a=this.timeIndex(A);if(!this.store_.hasChunksAtTime(a)){gA.warn("ChunkStoreView","updateChunkViewStates called with no chunks initialized"),this.chunkViewStates_.forEach(hB);return}const D=gE();Da(D,g.min,g.max,.5);const[s,y]=this.getZBounds(A),F=new Bg(nA(g.min[0],g.min[1],s),nA(g.max[0],g.max[1],y));this.chunkViewStates_.forEach(hB);const Y=this.channelsOfInterest(A),p=this.fallbackLOD(),H=this.getPaddedBounds(F),W=this.currentLOD_===p?[this.currentLOD_]:[this.currentLOD_,p];for(const z of W){const x=z===this.currentLOD_,l=z===p;this.iterateChunksInBox(a,z,Y,H,(Z,v)=>{const CA=Bg.intersects(v,F),sA=x&&!CA,DA=this.computePriority(l,x,CA,sA,!0);DA!==null&&this.chunkViewStates_.set(Z,{visible:CA,prefetch:sA,priority:DA,orderKey:this.squareDistance2D(Z,D)})})}this.markTimeChunksForPrefetchImage(a,A,F,D),this.policyChanged_=!1,this.lastViewBounds2D_=g.clone(),this.lastZBounds_=i,this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0}updateChunksForVolume(A,I){if(!(this.policyChanged_||this.hasViewProjectionChanged(I)||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const B=this.timeIndex(A);if(!this.store_.hasChunksAtTime(B)){gA.warn("ChunkStoreView","updateChunksForVolume called with no chunks initialized"),this.chunkViewStates_.forEach(hB);return}this.currentLOD_=this.policy_.lod.min,this.chunkViewStates_.forEach(hB);const C=this.channelsOfInterest(A),E=this.fallbackLOD(),i=o=>{const a=o.lod===E,D=o.lod===this.currentLOD_,s=this.computePriority(a,D,!0,!1,!0);s!==null&&this.chunkViewStates_.set(o,{visible:!0,prefetch:!1,priority:s,orderKey:0})};this.iterateAllChunksAtLod(B,this.currentLOD_,C,i),this.currentLOD_!==E&&this.iterateAllChunksAtLod(B,E,C,i),this.markTimeChunksForPrefetchVolume(B,A),this.policyChanged_=!1,this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0,this.lastViewProjection_=I}allVisibleFallbackLODLoaded(){const A=this.fallbackLOD();let I=!1;for(const[g,B]of this.chunkViewStates_)if(!(!B.visible||g.lod!==A)&&(I=!0,g.texture===void 0))return!1;return I}get currentLOD(){return this.currentLOD_}maybeForgetChunk(A){const I=this.chunkViewStates_.get(A);I&&(I.visible||I.prefetch||I.priority!==null)||this.chunkViewStates_.delete(A)}dispose(){this.isDisposed_=!0,this.chunkViewStates_.forEach(hB)}setImageSourcePolicy(A,I){if(I!==vB)throw new Error("Unauthorized policy mutation");this.policy_!==A&&(this.policy_=A,this.policyChanged_=!0,gA.info("ChunkStoreView","Using image source policy:",this.policy_.profile))}setLOD(A){const g=this.store_.dimensions.x.lods[0].scale,C=this.policy_.lod.bias-Math.log2(g)-A,E=Math.floor(C),i=this.store_.getLowestResLOD(),o=Math.max(0,Math.min(i,this.policy_.lod.min)),a=Math.max(o,Math.min(i,this.policy_.lod.max)),D=fI(E,o,a);D!==this.currentLOD_&&(this.currentLOD_=D)}markTimeChunksForPrefetchImage(A,I,g,B){const C=this.store_.dimensions.t?.lods[0].size??1,E=Math.min(this.policy_.prefetch.t,C-1),i=this.fallbackLOD(),o=this.policy_.priorityMap.prefetchTime,a=this.channelsOfInterest(I);for(let D=1;D<=E;++D){const s=(A+D)%C;this.iterateChunksInBox(s,i,a,g,y=>{const F=this.squareDistance2D(y,B),Y=fI(F/this.sourceMaxSquareDistance2D_,0,1-Number.EPSILON),p=D+Y;this.chunkViewStates_.set(y,{visible:!1,prefetch:!0,priority:o,orderKey:p})})}}markTimeChunksForPrefetchVolume(A,I){const g=this.store_.dimensions.t?.lods[0].size??1,B=Math.min(this.policy_.prefetch.t,g-1),C=this.fallbackLOD(),E=this.policy_.priorityMap.prefetchTime,i=this.channelsOfInterest(I);for(let o=1;o<=B;++o){const a=(A+o)%g;this.iterateAllChunksAtLod(a,C,i,D=>{const s=o;this.chunkViewStates_.set(D,{visible:!1,prefetch:!0,priority:E,orderKey:s})})}}computePriority(A,I,g,B,C){if(!C)return null;const E=this.policy_.priorityMap;return A&&g?E.fallbackVisible:I&&g?E.visibleCurrent:A?E.fallbackBackground:I&&B?E.prefetchSpace:null}channelsOfInterest(A){return A.c??Array.from({length:this.store_.channelCount},(I,g)=>g)}chunkIndexRange(A,I){const g=this.store_.dimensions,B=g.x.lods[I],C=g.y.lods[I],E=g.z?.lods[I],i=Math.ceil(B.size/B.chunkSize),o=Math.ceil(C.size/C.chunkSize),a=E?Math.ceil(E.size/E.chunkSize):1,D=B.chunkSize*B.scale,s=C.chunkSize*C.scale,y=E?E.chunkSize*E.scale:1,F=B.translation,Y=C.translation,p=E?.translation??0,H=Math.max(0,Math.floor((A.min[0]-F)/D)),W=Math.min(i,Math.ceil((A.max[0]-F)/D)),z=Math.max(0,Math.floor((A.min[1]-Y)/s)),x=Math.min(o,Math.ceil((A.max[1]-Y)/s)),l=E?Math.max(0,Math.floor((A.min[2]-p)/y)):0,Z=E?Math.min(a,Math.ceil((A.max[2]-p)/y)):1;return H>=W||z>=x||l>=Z?null:{xMin:H,xMax:W,yMin:z,yMax:x,zMin:l,zMax:Z}}iterateChunksInBox(A,I,g,B,C){const E=this.chunkIndexRange(B,I);if(E)for(const i of g){const o=this.store_.getChunkGrid(I,A,i);if(o)for(let a=E.zMin;a<E.zMax;++a){const D=o[a];for(let s=E.yMin;s<E.yMax;++s){const y=D[s];for(let F=E.xMin;F<E.xMax;++F){const Y=y[F];C(Y,this.getChunkAabb(Y))}}}}}iterateAllChunksAtLod(A,I,g,B){for(const C of g){const E=this.store_.getChunkGrid(I,A,C);if(E)for(const i of E)for(const o of i)for(const a of o)B(a,this.getChunkAabb(a))}}getChunkAabb(A){return new Bg(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))}fallbackLOD(){return Math.min(this.policy_.lod.max,this.store_.getLowestResLOD())}timeIndex(A){const I=this.store_.dimensions.t;return A.t===void 0||I===void 0?0:pD(I.lods[0],A.t)}getZBounds(A){const I=this.store_.dimensions.z;if(I===void 0)return[0,1];if(A.z===void 0){const D=I.lods[this.currentLOD_];return[D.translation,D.translation+D.size*D.scale]}const g=I.lods[this.currentLOD_],B=g.size,C=g.scale,E=g.translation,i=Math.floor((A.z-E)/C),o=g.chunkSize,a=Math.max(0,Math.min(Math.floor(i/o),Math.ceil(B/o)-1));return[E+a*o*C,E+(a+1)*o*C]}viewBounds2DChanged(A){return this.lastViewBounds2D_===null||!JQ(this.lastViewBounds2D_.min,A.min)||!JQ(this.lastViewBounds2D_.max,A.max)}hasViewProjectionChanged(A){return this.lastViewProjection_===null||!vo(this.lastViewProjection_,A)}zBoundsChanged(A){return!this.lastZBounds_||!JQ(this.lastZBounds_,A)}cCoordsChanged(A){return!this.lastCCoords_&&!A?!1:!this.lastCCoords_||!A||this.lastCCoords_.length!==A.length?!0:!this.lastCCoords_.every((I,g)=>I===A[g])}getPaddedBounds(A){const I=this.store_.dimensions,g=I.x.lods[this.currentLOD_],B=I.y.lods[this.currentLOD_],C=I.z?.lods[this.currentLOD_],E=g.chunkSize*g.scale*this.policy_.prefetch.x,i=B.chunkSize*B.scale*this.policy_.prefetch.y;let o=0;return C&&(o=C.chunkSize*C.scale*this.policy_.prefetch.z),new Bg(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 g={x:A.offset.x+.5*A.shape.x*A.scale.x,y:A.offset.y+.5*A.shape.y*A.scale.y},B=g.x-I[0],C=g.y-I[1];return B*B+C*C}}function hB(Q){Q.visible=!1,Q.prefetch=!1,Q.priority=null,Q.orderKey=null}class mD{chunks_;lowestResLOD_;dimensions_;views_=[];hasHadViews_=!1;constructor(A){this.dimensions_=A,this.lowestResLOD_=this.dimensions_.numLods-1,this.validateXYScaleRatios();const{size:I}=this.getAndValidateTimeDimension(),{size:g}=this.getAndValidateChannelDimension(),B=this.dimensions_.numLods;this.chunks_=new Array(B);for(let C=0;C<B;++C){const E=this.dimensions_.x.lods[C],i=this.dimensions_.y.lods[C],o=this.dimensions_.z?.lods[C],a=E.chunkSize,D=i.chunkSize,s=o?.chunkSize??1,y=Math.ceil(E.size/a),F=Math.ceil(i.size/D),Y=o?Math.ceil(o.size/s):1,p=new Array(I);this.chunks_[C]=p;for(let H=0;H<I;++H){const W=new Array(g);p[H]=W;for(let z=0;z<g;++z){const x=new Array(Y);W[z]=x;for(let l=0;l<Y;++l){const Z=o!==void 0?o.translation+l*s*o.scale:0,v=new Array(F);x[l]=v;for(let CA=0;CA<F;++CA){const sA=i.translation+CA*D*i.scale,DA=new Array(y);v[CA]=DA;for(let yA=0;yA<y;++yA){const wA=E.translation+yA*a*E.scale;DA[yA]={state:"unloaded",lod:C,visible:!1,prefetch:!1,priority:null,orderKey:null,shape:{x:Math.min(a,E.size-yA*a),y:Math.min(D,i.size-CA*D),z:Math.min(s,(o?.size??1)-l*s),c:1},rowAlignmentBytes:1,chunkIndex:{x:yA,y:CA,z:l,c:z,t:H},scale:{x:E.scale,y:i.scale,z:o?.scale??1},offset:{x:wA,y:sA,z:Z}}}}}}}}}getChunkGrid(A,I,g){return this.chunks_[A]?.[I]?.[g]}hasChunksAtTime(A){return this.chunks_[0]?.[A]!==void 0}get lodCount(){return this.lowestResLOD_+1}get channelCount(){return this.dimensions_.c?.lods[0].size??1}get dimensions(){return this.dimensions_}getLowestResLOD(){return this.lowestResLOD_}addView(A){const I=new uD(this,A);return this.views_.push(I),this.hasHadViews_=!0,I}get views(){return this.views_}canDispose(){return this.hasHadViews_&&this.views_.length===0}updateAndCollectChunkChanges(){const A=new Set;for(const I of this.views_)for(const[g,B]of I.chunkViewStates)A.add(g);for(const I of A)this.aggregateChunkViewStates(I);return this.removeDisposedViews(),A}removeDisposedViews(){for(let A=this.views_.length-1;A>=0;A--)this.views_[A].isDisposed&&this.views_.splice(A,1)}aggregateChunkViewStates(A){let I=!1,g=!1,B=null,C=null;for(const o of this.views_){const a=o.chunkViewStates.get(A);a&&(a.visible&&(I=!0),a.prefetch&&(g=!0),a.priority!==null&&(B===null||a.priority<B)&&(B=a.priority,C=a.orderKey),!a.visible&&!a.prefetch&&a.priority===null&&o.maybeForgetChunk(A))}if(A.visible=I,A.prefetch=g,A.priority=B,A.orderKey=C,A.priority!==null&&A.state==="unloaded"){A.state="queued";return}A.priority===null&&A.state==="queued"&&(A.state="unloaded")}validateXYScaleRatios(){const A=this.dimensions_.x,I=this.dimensions_.y;for(let g=1;g<this.dimensions_.numLods;g++){const B=A.lods[g].scale/A.lods[g-1].scale,C=I.lods[g].scale/I.lods[g-1].scale;if(!vE(B,2,.02)||!vE(C,2,.02))throw new Error(`Invalid downsampling factor between levels ${g-1} → ${g}: expected (2× in X and Y), but got (${B.toFixed(2)}×, ${C.toFixed(2)}×) from scale [${A.lods[g-1].scale}, ${I.lods[g-1].scale}] → [${A.lods[g].scale}, ${I.lods[g].scale}]`)}}getAndValidateTimeDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.t?.lods[A];if(!I)continue;const g=this.dimensions_.t?.lods[A-1];if(g&&I.size!==g.size)throw new Error(`ChunkStore does not support downsampling in t. Found ${g.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.t?.lods[0].size??1}}getAndValidateChannelDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.c?.lods[A];if(!I)continue;if(I.scale!==1&&gA.warn("ChunkStore",`Idetik does not make use of non-unity scale in c. Found ${I.scale} at LOD ${A}`),I.translation!==0)throw new Error(`ChunkStore does not support translation in c. Found ${I.translation} at LOD ${A}`);const g=this.dimensions_.c?.lods[A-1];if(g&&I.size!==g.size)throw new Error(`ChunkStore does not support downsampling in c. Found ${g.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.c?.lods[0].size??1}}}const xD=8,TD=4;class WD{stores_=[];queue_;uploadTexture_;disposeTexture_;getGpuResidentBytes_;memoryLimitBytes_;maxGpuUploadsPerUpdate_;resident_=new Set;constructor(A,I,g=()=>0,B=1/0,C=xD,E=TD){this.uploadTexture_=A,this.disposeTexture_=I,this.getGpuResidentBytes_=g,this.memoryLimitBytes_=B,this.maxGpuUploadsPerUpdate_=Math.max(1,E),this.queue_=new HD(C)}get memoryLimitBytes(){return this.memoryLimitBytes_}get queueStats(){return{pending:this.queue_.pendingCount,running:this.queue_.runningCount}}get memoryStats(){return lD()}addView(A,I){let g=this.stores_.find(B=>B.source===A)?.store;return g||(g=new mD(A.loader.getSourceDimensionMap()),this.stores_.push({source:A,store:g})),g.addView(I)}update(){const A=[];for(const{source:I,store:g}of this.stores_){const B=g.updateAndCollectChunkChanges();for(const C of B)C.priority===null?this.releaseChunk(C):(C.releasedAt=void 0,C.state==="queued"&&A.push({source:I,chunk:C}));this.uploadLoadedChunks(B)}this.enqueueWithinBudget(A),this.queue_.flush();for(let I=this.stores_.length-1;I>=0;I--)this.stores_[I].store.canDispose()&&this.stores_.splice(I,1)}releaseChunk(A){if(this.queue_.cancel(A),A.texture!==void 0){A.releasedAt??=performance.now();return}OE(A),A.state==="loaded"&&(A.state="unloaded")}enqueueWithinBudget(A){if(A.length===0)return;A.sort((B,C)=>sB(B.chunk,C.chunk));let I=this.getGpuResidentBytes_(),g=null;for(const{source:B,chunk:C}of A){const E=this.chunkBytes(B,C);E>this.memoryLimitBytes_||(I+E>this.memoryLimitBytes_&&(g??=this.evictionCandidates(),I=this.evictWorseChunks(I,E,C,g)),!(I+E>this.memoryLimitBytes_)&&(I+=E,this.queue_.enqueue(C,i=>B.loader.loadChunkData(C,i))))}}evictionCandidates(){const A=[];for(const I of this.resident_)I.visible||A.push(I);return A.sort((I,g)=>{const B=-sB(I,g);return B!==0?B:(I.releasedAt??0)-(g.releasedAt??0)})}evictWorseChunks(A,I,g,B){for(;A+I>this.memoryLimitBytes_&&B.length>0&&sB(B[0],g)>0;){const C=B.shift();C.texture!==void 0&&(A-=BB(C.texture),this.disposeChunkTexture(C),C.state="unloaded",C.releasedAt=void 0)}return A}chunkBytes(A,I){const g=A.loader.getBytesPerElement();return I.shape.x*I.shape.y*I.shape.z*g}uploadLoadedChunks(A){if(!this.uploadTexture_)return;const I=[];for(const B of A)B.state==="loaded"&&B.texture===void 0&&I.push(B);if(I.length===0)return;I.sort(sB);const g=Math.min(I.length,this.maxGpuUploadsPerUpdate_);for(let B=0;B<g;B++){const C=I[B],E=QB.createWithChunk(C);this.uploadTexture_(E),C.texture=E,this.resident_.add(C),OE(C)}}disposeChunkTexture(A){this.disposeTexture_&&A.texture!==void 0&&(this.disposeTexture_(A.texture),A.texture=void 0,this.resident_.delete(A))}}var yB=function(Q=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(s){s.preventDefault(),B(++A%I.children.length)},!1);function g(s){return I.appendChild(s.dom),s}function B(s){for(var y=0;y<I.children.length;y++)I.children[y].style.display=y===s?"block":"none";A=s}var C=(performance||Date).now(),E=C,i=0,o=g(new yB.Panel("FPS","#0ff","#002",Q)),a=g(new yB.Panel("MS","#0f0","#020",Q));if(self.performance&&self.performance.memory)var D=g(new yB.Panel("MB","#f08","#201",Q));return B(0),{REVISION:16,dom:I,addPanel:g,showPanel:B,begin:function(){C=(performance||Date).now()},end:function(){i++;var s=(performance||Date).now();if(a.update(s-C,200),s>=E+1e3&&(o.update(i*1e3/(s-E),100),E=s,i=0,D)){var y=performance.memory;D.update(y.usedJSHeapSize/1048576,y.jsHeapSizeLimit/1048576)}return s},update:function(){C=this.end()},domElement:I,setMode:B}};yB.Panel=function(Q,A,I,g){var B=1/0,C=0,E=Math.round,i=E(window.devicePixelRatio||1),o=E(80*i*g),a=E(48*i*g),D=E(3*i*g),s=E(2*i*g),y=E(3*i*g),F=E(15*i*g),Y=E(74*i*g),p=E(30*i*g),H=document.createElement("canvas");H.width=o,H.height=a,H.style.cssText=`width:${E(g*80)}px;height:${E(g*48)}px`;var W=H.getContext("2d");return W.font="bold "+E(9*i*g)+"px Helvetica,Arial,sans-serif",W.textBaseline="top",W.fillStyle=I,W.fillRect(0,0,o,a),W.fillStyle=A,W.fillText(Q,D,s),W.fillRect(y,F,Y,p),W.fillStyle=I,W.globalAlpha=.9,W.fillRect(y,F,Y,p),{dom:H,update:function(z,x){B=Math.min(B,z),C=Math.max(C,z),W.fillStyle=I,W.globalAlpha=1,W.fillRect(0,0,o,F),W.fillStyle=A,W.fillText(E(z)+" "+Q+" ("+E(B)+"-"+E(C)+")",D,s),W.drawImage(H,y+i,F,Y-i,p,y,F,Y-i,p),W.fillRect(y+Y-i,F,i,p),W.fillStyle=I,W.globalAlpha=.9,W.fillRect(y+Y-i,F,i,E((1-z/x)*p))}}};function bD({scale:Q}={scale:1.5}){const A=new yB(Q);return A.showPanel(0),document.body.appendChild(A.dom),A}const _Q=["pointerdown","pointermove","pointerup","pointercancel","wheel"];function ZD(Q){return _Q.includes(Q)}class PD{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 VD{listeners_=[];element_;isConnected_=!1;constructor(A){this.element_=A}addEventListener(A){this.listeners_.push(A)}connect(){if(this.isConnected_){gA.warn("EventDispatcher","Attempted to connect already connected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!0,_Q.forEach(A=>{this.element_.addEventListener(A,this.handleEvent,{passive:!1})})}disconnect(){if(!this.isConnected_){gA.debug("EventDispatcher","Attempted to disconnect already disconnected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!1,_Q.forEach(A=>{this.element_.removeEventListener(A,this.handleEvent)})}handleEvent=A=>{if(!ZD(A.type)){gA.error("EventDispatcher",`Unsupported event type ${A.type}`);return}const I=new PD(A.type,A);for(const g of this.listeners_)if(g(I),I.propagationStopped)break}}class OD{id;element;camera;events;cameraControls;context_;layers_=[];constructor(A){this.id=A.id,this.element=A.element,this.camera=A.camera,this.context_=A.context,this.cameraControls=A.cameraControls,this.updateAspectRatio(),this.events=new VD(this.element),this.events.addEventListener(I=>{if(I.event instanceof PointerEvent||I.event instanceof WheelEvent){const{clientX:g,clientY:B}=I.event,C=xA(g,B);I.clipPos=this.clientToClip(C,0),I.worldPos=this.camera.clipToWorld(I.clipPos)}for(const g of this.layers_)if(g.onEvent(I),I.propagationStopped)return;this.cameraControls?.onEvent(I)});for(const I of A.layers??[])this.addLayer(I)}get layers(){return this.layers_}addLayer(A){A.onAttached(this.context_),this.layers_.push(A)}removeLayer(A){const I=this.layers_.indexOf(A);if(I===-1)throw new Error(`Layer to remove not found: ${A}`);this.layers_.splice(I,1),A.onDetached(this.context_)}removeAllLayers(){for(const A of this.layers_)A.onDetached(this.context_);this.layers_=[]}updateSize(){this.updateAspectRatio()}getBoxRelativeTo(A){const I=this.getBox().toRect(),g=A.getBoundingClientRect(),B=window.devicePixelRatio||1,C=g.left*B,E=g.top*B,i=g.height*B,o=I.x-C,a=I.y-E,D=Math.floor(o),s=Math.floor(i-a-I.height),y=Math.floor(I.width),F=Math.floor(I.height);return new QI(xA(D,s),xA(D+y,s+F))}getBufferRect(){return this.getBoxRelativeTo(this.element).toRect()}clientToClip(A,I=0){const[g,B]=A,C=this.element.getBoundingClientRect();return nA(2*(g-C.x)/C.width-1,2*(B-C.y)/C.height-1,I)}clientToWorld(A,I=0){const g=this.clientToClip(A,I);return this.camera.clipToWorld(g)}getBox(){const A=this.element.getBoundingClientRect(),I=window.devicePixelRatio||1,g=A.left*I,B=A.top*I,C=A.width*I,E=A.height*I;return new QI(xA(g,B),xA(g+C,B+E))}updateAspectRatio(){const{width:A,height:I}=this.getBox().toRect();if(A<=0||I<=0){gA.debug("Viewport",`Skipping aspect ratio update for viewport ${this.id}: invalid dimensions ${A}x${I}`);return}const g=A/I;this.camera.setAspectRatio(g)}}function jE(Q,A){for(const I of A){if(I.id===Q.id)throw new Error(`Duplicate viewport ID "${Q.id}". Each viewport must have a unique ID.`);if(I.element===Q.element){const g=Q.element.tagName.toLowerCase()+(Q.element.id?`#${Q.element.id}`:"[element has no id]");throw new Error(`Multiple viewports cannot share the same HTML element: viewports "${I.id}" and "${Q.id}" both use ${g}`)}}}function vD(Q){for(let A=0;A<Q.length;A++)jE(Q[A],Q.slice(0,A))}function zE(Q,A,I){const g=Q.map(B=>{const C=B.element??A;return{...B,element:C,id:B.id??C.id??jC("viewport"),context:I}});return vD(g),g.map(B=>new OD(B))}class XD{elements_;resizeObserver_;mediaQuery_;onMediaQueryChange_;onChange_;constructor(A=[],I){this.elements_=[...A],this.onChange_=I}connect(){if(this.resizeObserver_){gA.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_){gA.warn("PixelSizeObserver","Attempted to disconnect already disconnected observer");return}this.resizeObserver_?.disconnect(),this.mediaQuery_&&this.onMediaQueryChange_&&this.mediaQuery_.removeEventListener("change",this.onMediaQueryChange_)}observe(A){if(this.elements_.includes(A)){gA.warn("PixelSizeObserver","Element already being observed");return}this.elements_.push(A),this.resizeObserver_&&this.resizeObserver_.observe(A)}unobserve(A){const I=this.elements_.indexOf(A);if(I===-1){gA.warn("PixelSizeObserver","Element not being observed");return}this.elements_.splice(I,1),this.resizeObserver_&&this.resizeObserver_.unobserve(A)}}const jD=2048;class $Q{chunkManager_;context_;renderer_;viewports_;canvas;overlays;stats_;sizeObserver_;lastAnimationId_;lastTimestamp_=0;static async create(A){const I=A.renderer==="webgpu-experimental"?await KD(A.canvas):new oE(A.canvas);return new $Q(A,I)}constructor(A,I){this.canvas=A.canvas,this.renderer_=I??new oE(this.canvas);const B=(A.memoryLimitMB??jD)*1024*1024;this.chunkManager_=new WD(E=>this.renderer_.uploadTexture(E),E=>this.renderer_.disposeTexture(E),()=>this.renderer_.gpuTextureBytes,B,A.maxConcurrentRequests,A.maxGpuUploadsPerUpdate),this.context_={chunkManager:this.chunkManager_},this.viewports_=zE(A.viewports??[],this.canvas,this.context_),this.overlays=A.overlays??[],A.showStats&&(this.stats_=bD());const C=[this.canvas];for(const E of this.viewports_)E.element!==this.canvas&&C.push(E.element);this.sizeObserver_=new XD(C,()=>{this.renderer_.updateSize(),this.renderer_.beginFrame();for(const E of this.viewports_)E.updateSize(),this.renderer_.render(E)})}get chunkQueueStats(){return this.chunkManager_.queueStats}get memoryStats(){const A=performance.memory;return{...this.chunkManager_.memoryStats,gpuTextureBytes:this.renderer_.gpuTextureBytes,gpuTextureCount:this.renderer_.gpuTextureCount,jsHeapUsedBytes:A?.usedJSHeapSize,jsHeapLimitBytes:A?.jsHeapSizeLimit}}get renderedObjects(){return this.renderer_.renderedObjects}get width(){return this.renderer_.width}get height(){return this.renderer_.height}get viewports(){return this.viewports_}get running(){return this.lastAnimationId_!==void 0}getViewport(A){return this.viewports_.find(I=>I.id===A)}addViewport(A){const[I]=zE([A],this.canvas,this.context_);return jE(I,this.viewports_),this.viewports_.push(I),this.running&&(I.events.connect(),I.element!==this.canvas&&this.sizeObserver_.observe(I.element)),gA.info("Idetik",`Added viewport "${I.id}"`),I}removeViewport(A){const I=this.viewports_.indexOf(A);return I===-1?(gA.warn("Idetik",`Viewport "${A.id}" not found, nothing to remove`),!1):(this.running&&(A.events.disconnect(),A.element!==this.canvas&&this.sizeObserver_.unobserve(A.element)),this.viewports_.splice(I,1),gA.info("Idetik",`Removed viewport "${A.id}"`),!0)}start(){if(gA.info("Idetik","Idetik runtime starting"),this.running)gA.warn("Idetik","Idetik runtime already started");else{for(const A of this.viewports_)A.events.connect();this.sizeObserver_.connect(),this.lastAnimationId_=requestAnimationFrame(A=>{this.lastTimestamp_=A,this.animate(A)})}return this}animate(A){this.stats_&&this.stats_.begin();const I=Math.min(A-this.lastTimestamp_,100)/1e3;this.lastTimestamp_=A,this.renderer_.beginFrame();for(const g of this.viewports_)g.cameraControls?.onUpdate(I),this.renderer_.render(g);this.chunkManager_.update();for(const g of this.overlays)g.update(this);this.stats_&&this.stats_.end(),this.lastAnimationId_=requestAnimationFrame(g=>this.animate(g))}stop(){if(gA.info("Idetik","Idetik runtime stopping"),!this.running)gA.warn("Idetik","Idetik runtime not started");else{this.sizeObserver_.disconnect();for(const A of this.viewports_)A.events.disconnect();cancelAnimationFrame(this.lastAnimationId_),this.lastAnimationId_=void 0}}}function zD(Q,A){return{...Q,...A,headers:{...Q.headers,...A.headers}}}function _E(Q,A){const I=typeof Q=="string"?new URL(Q):Q;I.pathname.endsWith("/")||(I.pathname+="/");const g=new URL(A.slice(1),I);return g.search=I.search,g}async function $E(Q){if(Q.status!==404){if(Q.status===200||Q.status===206)return new Uint8Array(await Q.arrayBuffer());throw new Error(`Unexpected response status ${Q.status} ${Q.statusText}`)}}class tB{url;#A;#I;#g;constructor(A,I={}){this.url=A,this.#A=I.fetch??(g=>fetch(g)),this.#I=I.overrides??{},this.#g=I.useSuffixRequest??!1}#B(A,I){return new Request(A,zD(this.#I,I))}async get(A,I={}){let g=_E(this.url,A).href,B=this.#B(g,I),C=await this.#A(B);return $E(C)}async getRange(A,I,g={}){let B=_E(this.url,A),C;if("suffixLength"in I)C=await this.#Q(B,I.suffixLength,g);else{let E={...g,headers:{...g.headers,Range:`bytes=${I.offset}-${I.offset+I.length-1}`}},i=this.#B(B,E);C=await this.#A(i)}return $E(C)}async#Q(A,I,g){if(this.#g){let D={...g,headers:{...g.headers,Range:`bytes=-${I}`}};return this.#A(this.#B(A,D))}let B=this.#B(A,{...g,method:"HEAD"}),C=await this.#A(B);if(!C.ok)return C;let E=C.headers.get("Content-Length"),i=Number(E),o=i-I,a={...g,headers:{...g.headers,Range:`bytes=${o}-${i-1}`}};return this.#A(this.#B(A,a))}}class GB extends Error{}class Yg extends GB{_tag="NotFoundError";name="NotFoundError";path;found;constructor(A,I={}){super(`Not found: ${A}`,{cause:I.cause}),this.path=I.path,this.found=I.found}}class WA extends GB{_tag="InvalidMetadataError";name="InvalidMetadataError";path;constructor(A,I={}){super(A,{cause:I.cause}),this.path=I.path}}class _D extends GB{_tag="UnknownCodecError";name="UnknownCodecError";codec;constructor(A){super(`Unknown codec: ${A}`),this.codec=A}}class $D extends GB{_tag="CodecPipelineError";name="CodecPipelineError";direction;codec;chunkPath;constructor(A){const I=[`Failed to ${A.direction} chunk`,A.codec&&`via codec "${A.codec}"`,A.chunkPath&&`at ${A.chunkPath}`].filter(Boolean);super(I.join(" "),{cause:A.cause}),this.direction=A.direction,this.codec=A.codec,this.chunkPath=A.chunkPath}}class AC extends GB{_tag="UnsupportedError";name="UnsupportedError";feature;constructor(A){super(`Unsupported: ${A}`),this.feature=A}}function ig(Q){return()=>{throw new AC(`${Q} encode`)}}class XB{kind="array_to_array";constructor(A,I){if(A.keepbits<0)throw new WA("keepbits must be zero or positive")}static fromConfig(A,I){return new XB(A,I)}encode=ig("bitround");decode(A){return A}}function IC(Q){return Q instanceof ArrayBuffer||Q instanceof SharedArrayBuffer}class Ai{#A;constructor(A,I,g){typeof A=="number"?this.#A=new Uint8Array(A):IC(A)?this.#A=new Uint8Array(A,I,g):this.#A=new Uint8Array(Array.from(A,B=>B?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 gC{_data;chars;#A;constructor(A,I,g,B){if(this.chars=A,this.#A=new TextEncoder,typeof I=="number")this._data=new Uint8Array(I*A);else if(IC(I))B&&(B=B*A),this._data=new Uint8Array(I,g,B);else{let C=Array.from(I);this._data=new Uint8Array(C.length*A);for(let E=0;E<C.length;E++)this.set(E,C[E])}}get BYTES_PER_ELEMENT(){return this.chars}get byteOffset(){return this._data.byteOffset}get byteLength(){return this._data.byteLength}get buffer(){return this._data.buffer}get length(){return this.byteLength/this.BYTES_PER_ELEMENT}get(A){const I=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);return new TextDecoder().decode(I).replace(/\x00/g,"")}set(A,I){const g=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);g.fill(0),g.set(this.#A.encode(I))}fill(A){const I=this.#A.encode(A);for(let g=0;g<this.length;g++)this._data.set(I,g*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class wB{#A;chars;constructor(A,I,g,B){if(this.chars=A,typeof I=="number")this.#A=new Int32Array(I*A);else if(IC(I))B&&(B*=A),this.#A=new Int32Array(I,g,B);else{const C=I,E=new wB(A,1);this.#A=new Int32Array((function*(){for(let i of C)E.set(0,i),yield*E.#A})())}}get BYTES_PER_ELEMENT(){return this.#A.BYTES_PER_ELEMENT*this.chars}get byteLength(){return this.#A.byteLength}get byteOffset(){return this.#A.byteOffset}get buffer(){return this.#A.buffer}get length(){return this.#A.length/this.chars}get(A){const I=this.chars*A;let g="";for(let B=0;B<this.chars;B++)g+=String.fromCodePoint(this.#A[I+B]);return g.replace(/\u0000/g,"")}set(A,I){const g=this.chars*A,B=this.#A.subarray(g,g+this.chars);B.fill(0);for(let C=0;C<this.chars;C++)B[C]=I.codePointAt(C)??0}fill(A){this.set(0,A);let I=this.#A.subarray(0,this.chars);for(let g=1;g<this.length;g++)this.#A.set(I,g*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}function As(){if(typeof SharedArrayBuffer>"u")throw new Error("SharedArrayBuffer is not available. In browsers, this requires Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers to be set.")}function Is(Q,A){return new SharedArrayBuffer(Q)}function eB(Q){const A=new TextDecoder().decode(Q);try{return JSON.parse(A)}catch(I){throw new WA("Failed to decode JSON",{cause:I})}}function Ii(Q,A){const I=A/2,g=A-1;let B=0;for(let C=0;C<Q.length;C+=A)for(let E=0;E<I;E+=1)B=Q[C+E],Q[C+E]=Q[C+g-E],Q[C+g-E]=B}function Kg(Q){if(Q==="v2:object")return globalThis.Array;let A=Q.match(/v2:([US])(\d+)/);if(A){let[,g,B]=A;return(g==="U"?wB:gC).bind(null,Number(B))}if(Q==="string")return globalThis.Array;let I={int8:Int8Array,int16:Int16Array,int32:Int32Array,int64:globalThis.BigInt64Array,uint8:Uint8Array,uint16:Uint16Array,uint32:Uint32Array,uint64:globalThis.BigUint64Array,float16:globalThis.Float16Array,float32:Float32Array,float64:Float64Array,bool:Ai}[Q];if(!I)throw new WA(`Unknown or unsupported dataType: ${Q}`);return I}function og(Q,A){const I=Q.length;typeof A=="string"&&(A=A==="C"?Array.from({length:I},(C,E)=>E):Array.from({length:I},(C,E)=>I-1-E)),yI(I===A.length,"Order length must match the number of dimensions.");let g=1,B=new Array(I);for(let C=A.length-1;C>=0;C--)B[A[C]]=g,g*=Q[A[C]];return B}function gs({name:Q,configuration:A}){if(Q==="default"){const I=A?.separator??"/";return g=>["c",...g].join(I)}if(Q==="v2"){const I=A?.separator??".";return g=>g.join(I)||"0"}throw new WA(`Unknown chunk key encoding: ${Q}`)}function gi(Q){if(Q==="|O")return{dataType:"v2:object"};let A=Q.match(/^([<|>])(.*)$/);if(!A)throw new WA(`Invalid dtype: ${Q}`);let[,I,g]=A,B={b1:"bool",i1:"int8",u1:"uint8",i2:"int16",u2:"uint16",i4:"int32",u4:"uint32",i8:"int64",u8:"uint64",f2:"float16",f4:"float32",f8:"float64"}[g]??(g.startsWith("S")||g.startsWith("U")?`v2:${g}`:void 0);if(!B)throw new WA(`Unsupported or unknown dtype: ${Q}`);return I==="|"?{dataType:B}:{dataType:B,endian:I==="<"?"little":"big"}}function Bs(Q){return(Q.id==="fixedscaleoffset"||Q.id==="numcodecs.fixedscaleoffset")&&typeof Q.scale=="number"&&typeof Q.offset=="number"&&(Q.astype===void 0||typeof Q.astype=="string")&&(Q.dtype===void 0||typeof Q.dtype=="string")}function Qs(Q,A={}){let I=[],g=gi(Q.dtype);Q.order==="F"&&I.push({name:"transpose",configuration:{order:"F"}});for(let C of Q.filters??[]){if(C.id==="fixedscaleoffset"||C.id==="numcodecs.fixedscaleoffset"){if(!Bs(C))throw new WA(`Invalid fixedscaleoffset filter: ${JSON.stringify(C)}`);I.push({name:"scale_offset",configuration:{scale:C.scale,offset:C.offset}});let o=C.astype??C.dtype;if(o!==void 0&&o!==Q.dtype){let a=gi(o).dataType;if(!BC(a,"number")&&!BC(a,"bigint"))throw new WA(`fixedscaleoffset astype must be a numeric data type, got ${o}`);I.push({name:"cast_value",configuration:{data_type:a,rounding:"nearest-even",out_of_range:"wrap"}})}continue}let{id:E,...i}=C;I.push({name:`numcodecs.${E}`,configuration:i})}if("endian"in g&&g.endian==="big"&&I.push({name:"bytes",configuration:{endian:"big"}}),Q.compressor){let{id:C,...E}=Q.compressor;I.push({name:`numcodecs.${C}`,configuration:E})}let B;return globalThis.Array.isArray(A._ARRAY_DIMENSIONS)&&(B=A._ARRAY_DIMENSIONS),{zarr_format:3,node_type:"array",shape:Q.shape,data_type:g.dataType,chunk_grid:{name:"regular",configuration:{chunk_shape:Q.chunks}},chunk_key_encoding:{name:"v2",configuration:{separator:Q.dimension_separator??"."}},codecs:I,fill_value:Q.fill_value,dimension_names:B,attributes:A}}function Cs(Q,A={}){return{zarr_format:3,node_type:"group",attributes:A}}function BC(Q,A){if(A!=="number"&&A!=="bigint"&&A!=="boolean"&&A!=="object"&&A!=="string")return Q===A;let I=Q==="bool";if(A==="boolean")return I;let g=Q.startsWith("v2:U")||Q.startsWith("v2:S")||Q==="string";if(A==="string")return g;let B=Q==="int64"||Q==="uint64";if(A==="bigint")return B;let C=Q==="v2:object";return A==="object"?C:!g&&!B&&!I&&!C}function Es(Q){return Q?.name==="sharding_indexed"}function Bi(Q){if((Q.data_type==="uint64"||Q.data_type==="int64")&&Q.fill_value!=null)return BigInt(Q.fill_value);let A=Q.data_type==="float16"||Q.data_type==="float32"||Q.data_type==="float64";if(typeof Q.fill_value=="string"&&A){let I={NaN:NaN,Infinity:1/0,"-Infinity":-1/0};if(Q.fill_value in I)return I[Q.fill_value]}return Q.fill_value}function Qi(Q,...A){if(!A.some(I=>Q instanceof I))throw Q}function yI(Q,A=""){if(!Q)throw new Error(A)}async function Ci(Q,{format:A,signal:I}){let g;if(Q instanceof ArrayBuffer)g=new Response(Q);else{let B=new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength);g=new Response(B.slice().buffer)}yI(g.body,"Response does not contain body.");try{return await new Response(g.body.pipeThrough(new DecompressionStream(A),{signal:I})).arrayBuffer()}catch{throw I?.throwIfAborted(),new Error(`Failed to decode ${A}`)}}const Ei=is();function is(){const Q=new Uint32Array([305419896]);return new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength)[0]!==18}function ii(Q){return"BYTES_PER_ELEMENT"in Q?Q.BYTES_PER_ELEMENT:4}class jB{kind="array_to_bytes";#A;#I;#g;#B;#Q;constructor(A,I){this.#Q=A?.endian,this.#I=Kg(I.dataType),this.#B=I.shape,this.#A=og(I.shape,"C");const g=new this.#I(0);this.#g=g.BYTES_PER_ELEMENT}static fromConfig(A,I){return new jB(A,I)}encode(A){let I=new Uint8Array(A.data.buffer);return Ei&&this.#Q==="big"&&Ii(I,ii(this.#I)),I}computeEncodedSize(A){return A}decode(A){return Ei&&this.#Q==="big"&&Ii(A,ii(this.#I)),{data:new this.#I(A.buffer,A.byteOffset,A.byteLength/this.#g),shape:this.#B,stride:this.#A}}}const oi={NaN:NaN,Infinity:1/0,"-Infinity":-1/0},ai={float16:2,float32:4,float64:8};function zB(Q){return Q in ai}function QC(Q){return Q==="int64"||Q==="uint64"}function os(Q,A){const I=BigInt(Q),g=new ArrayBuffer(A),B=new DataView(g);if(A===2){if(typeof B.getFloat16!="function")throw new AC("float16 hex-encoded scalar decoding (requires DataView.prototype.getFloat16)");return B.setUint16(0,Number(I)),B.getFloat16(0)}return A===4?(B.setUint32(0,Number(I)),B.getFloat32(0)):(B.setBigUint64(0,I),B.getFloat64(0))}function _B(Q,A){if(QC(Q)){if(typeof A!="number"||!Number.isInteger(A))throw new WA(`Expected an integer value for data type "${Q}", got ${JSON.stringify(A)}`);return BigInt(A)}if(typeof A=="number"){if(!zB(Q)&&!Number.isInteger(A))throw new WA(`Expected an integer value for data type "${Q}", got ${A}`);return A}if(!zB(Q))throw new WA(`String-encoded scalar "${A}" is not valid for non-float data type "${Q}"`);return A in oi?oi[A]:os(A,ai[Q])}const Di=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]),CC={int8:[-128,2**7-1],uint8:[0,2**8-1],int16:[-32768,2**15-1],uint16:[0,2**16-1],int32:[-2147483648,2**31-1],uint32:[0,2**32-1]},EC={int64:[-(2n**63n),2n**63n-1n],uint64:[0n,2n**64n-1n]};function si(Q,A,I){return Q.map(([g,B])=>({src:_B(A,g),tgt:_B(I,B)}))}function as(Q,A){for(const I of A)if(typeof I.src=="number"&&Number.isNaN(I.src)){if(typeof Q=="number"&&Number.isNaN(Q))return I.tgt}else if(Q===I.src)return I.tgt}function Ds(Q){if(!Number.isFinite(Q))return Q;if(Math.abs(Q-Math.trunc(Q))===.5){const A=Math.floor(Q),I=Math.ceil(Q);return A%2===0?A:I}return Math.round(Q)}function ss(Q){return Math.sign(Q)*Math.floor(Math.abs(Q)+.5)}function hi(Q){switch(Q){case"nearest-even":return Ds;case"towards-zero":return Math.trunc;case"towards-positive":return Math.ceil;case"towards-negative":return Math.floor;case"nearest-away":return ss}}function iC(Q,A,I){const g=A-Q+1;switch(I){case"clamp":return B=>B<Q?Q:B>A?A:B;case"wrap":return B=>B>=Q&&B<=A?B:((B-Q)%g+g)%g+Q;default:return B=>{if(B>=Q&&B<=A)return B;throw new Error(`Value ${B} out of range [${Q}, ${A}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}function oC(Q,A,I){const g=A-Q+1n;switch(I){case"clamp":return B=>B<Q?Q:B>A?A:B;case"wrap":return B=>B>=Q&&B<=A?B:((B-Q)%g+g)%g+Q;default:return B=>{if(B>=Q&&B<=A)return B;throw new Error(`Value ${B} out of range [${Q}, ${A}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}class aC{kind="array_to_array";#A;#I;#g;#B;constructor(A,I,g,B,C,E){this.#A=I,this.#I=Kg(A),this.#g=yi(I,A,g,B,C),this.#B=yi(A,I,g,B,E)}getEncodedMeta(A){let I=A.fillValue;return I!=null&&(I=this.#B(I)),{...A,dataType:this.#A,fillValue:I}}static fromConfig(A,I){const g=I.dataType,B=A.data_type;if(!Di.has(g))throw new WA(`cast_value codec does not support array data type: ${g}`);if(!Di.has(B))throw new WA(`cast_value codec does not support encoded data type: ${B}`);const C=A.rounding??"nearest-even",E=A.scalar_map?.decode?si(A.scalar_map.decode,B,g):[],i=A.scalar_map?.encode?si(A.scalar_map.encode,g,B):[];return new aC(g,B,C,A.out_of_range,E,i)}encode=ig("cast_value");decode(A){const I=A.data,g=new this.#I(I.length);for(let B=0;B<I.length;B++)g[B]=this.#g(I[B]);return{data:g,shape:A.shape,stride:A.stride}}}function yi(Q,A,I,g,B){const C=zB(Q),E=QC(Q),i=zB(A),o=QC(A);let a;if(C&&i){if(I!=="nearest-even")throw new WA(`cast_value float -> float only supports "nearest-even" rounding, got "${I}"`);a=s=>s}else if(C&&!i&&!o){const s=hi(I),y=iC(...CC[A],g);a=F=>{if(!Number.isFinite(F))throw new Error(`Cannot cast ${F} to integer type without scalar_map`);return y(s(F))}}else if(C&&o){const s=hi(I),y=oC(...EC[A],g);a=F=>{if(!Number.isFinite(F))throw new Error(`Cannot cast ${F} to integer type without scalar_map`);return y(BigInt(s(F)))}}else if(!C&&!E&&i)a=s=>s;else if(E&&i)a=s=>Number(s);else if(!C&&!E&&!i&&!o)a=iC(...CC[A],g);else if(!C&&!E&&o){const s=oC(...EC[A],g);a=y=>s(BigInt(y))}else if(E&&!i&&!o){const s=iC(...CC[A],g);a=y=>s(Number(y))}else if(E&&o)a=oC(...EC[A],g);else throw new Error(`Unhandled type combination: ${Q} -> ${A}`);return B.length===0?a:s=>{const y=as(s,B);return y!==void 0?y:a(s)}}class DC{kind="bytes_to_bytes";static fromConfig(){return new DC}encode=ig("crc32c");decode(A){return new Uint8Array(A.buffer,A.byteOffset,A.byteLength-4)}computeEncodedSize(A){return A+4}}const hs=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);function ti(Q,A){const I=Q.length;let g=I===0||A[I-1]===1;for(let C=I-2;C>=0&&g;C--)g=A[C]===A[C+1]*Q[C+1];if(g)return;let B=I===0||A[0]===1;for(let C=1;C<I&&B;C++)B=A[C]===A[C-1]*Q[C-1];if(!B)throw new Error(`DeltaCodec requires C- or Fortran-contiguous strides, got shape=${JSON.stringify(Q)} stride=${JSON.stringify(A)}`)}class sC{kind="array_to_array";#A;constructor(A){this.#A=A}static fromConfig(A,I){if(!hs.has(I.dataType))throw new WA(`Delta codec does not support data type: ${I.dataType}`);return new sC(Kg(I.dataType))}encode(A){ti(A.shape,A.stride);const I=A.data,g=new this.#A(I.length);g[0]=I[0];for(let B=1;B<I.length;B++)g[B]=I[B]-I[B-1];return{data:g,shape:A.shape,stride:A.stride}}decode(A){ti(A.shape,A.stride);const I=A.data,g=new this.#A(I.length);g[0]=I[0];for(let B=1;B<I.length;B++)g[B]=g[B-1]+I[B];return{data:g,shape:A.shape,stride:A.stride}}}class hC{kind="bytes_to_bytes";static fromConfig(A){return new hC}encode=ig("gzip");async decode(A){const I=await Ci(A,{format:"gzip"});return new Uint8Array(I)}}function ys(Q,A){return yI(!Number.isNaN(A),"JsonCodec allow_nan is false but NaN was encountered during encoding."),yI(A!==Number.POSITIVE_INFINITY,"JsonCodec allow_nan is false but Infinity was encountered during encoding."),yI(A!==Number.NEGATIVE_INFINITY,"JsonCodec allow_nan is false but -Infinity was encountered during encoding."),A}function ts(Q,A){return A instanceof Object&&!Array.isArray(A)?Object.keys(A).sort().reduce((I,g)=>(I[g]=A[g],I),{}):A}class $B{configuration;kind="array_to_bytes";#A;#I;constructor(A={}){this.configuration=A;const{encoding:I="utf-8",skipkeys:g=!1,ensure_ascii:B=!0,check_circular:C=!0,allow_nan:E=!0,sort_keys:i=!0,indent:o,strict:a=!0}=A;let D=A.separators;D||(o?D=[", ",": "]:D=[",",":"]),this.#A={encoding:I,skipkeys:g,ensure_ascii:B,check_circular:C,allow_nan:E,indent:o,separators:D,sort_keys:i},this.#I={strict:a}}static fromConfig(A){return new $B(A)}encode(A){const{indent:I,encoding:g,ensure_ascii:B,check_circular:C,allow_nan:E,sort_keys:i}=this.#A;yI(g==="utf-8","JsonCodec does not yet support non-utf-8 encoding.");const o=[];yI(C,"JsonCodec does not yet support skipping the check for circular references during encoding."),E||o.push(ys),i&&o.push(ts);const a=Array.from(A.data);a.push("|O"),a.push(A.shape);let D;o.length&&(D=(y,F)=>{let Y=F;for(let p of o)Y=p(y,Y);return Y});let s=JSON.stringify(a,D,I);return B&&(s=s.replace(/[\u007F-\uFFFF]/g,y=>{const F=`0000${y.charCodeAt(0).toString(16)}`;return`\\u${F.substring(F.length-4)}`})),new TextEncoder().encode(s)}decode(A){const{strict:I}=this.#I;yI(I,"JsonCodec does not yet support non-strict decoding.");const g=eB(A),B=g.pop();g.pop(),yI(B,"0D not implemented for JsonCodec.");const C=og(B,"C");return{data:g,shape:B,stride:C}}}const Gs=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);class yC{kind="array_to_array";#A;#I;#g;constructor(A,I,g){this.#I=A,this.#g=I,this.#A=g}static fromConfig(A,I){if(!Gs.has(I.dataType))throw new WA(`scale_offset codec does not support data type: ${I.dataType}`);return new yC(_B(I.dataType,A.scale??1),_B(I.dataType,A.offset??0),Kg(I.dataType))}encode=ig("scale_offset");decode(A){const I=A.data,g=new this.#A(I.length);for(let B=0;B<I.length;B++)g[B]=I[B]/this.#I+this.#g;return{data:g,shape:A.shape,stride:A.stride}}}class tC{kind="bytes_to_bytes";#A;constructor(A,I){if(I){let g=new(Kg(I.dataType))(0);yI("BYTES_PER_ELEMENT"in g,`Shuffle codec requires a fixed-size dtype, got "${I.dataType}"`),this.#A=g.BYTES_PER_ELEMENT}else this.#A=A.elementsize??4}static fromConfig(A,I){return new tC(A,I)}encode(A){return ws(A,this.#A)}decode(A){return es(A,this.#A)}}function ws(Q,A){let I=Q.length,g=Math.floor(I/A),B=new Uint8Array(I);for(let C=0;C<A;C++)for(let E=0;E<g;E++)B[C*g+E]=Q[E*A+C];return B}function es(Q,A){let I=Q.length,g=Math.floor(I/A),B=new Uint8Array(I);for(let C=0;C<A;C++)for(let E=0;E<g;E++)B[E*A+C]=Q[C*g+E];return B}function Gi(Q){return Q instanceof Ai||Q instanceof gC||Q instanceof wB?new Proxy(Q,{get(I,g){return I.get(Number(g))},set(I,g,B){return I.set(Number(g),B),!0}}):Q}function Fs(Q,A){let I;return Q.data instanceof gC||Q.data instanceof wB?I=new Q.constructor(Q.data.length,Q.data.chars):I=new Q.constructor(Q.data.length),{data:I,shape:Q.shape,stride:og(Q.shape,A)}}function rs(Q,A){let I=Fs(Q,A),g=Q.shape.length,B=Q.data.length,C=Array(g).fill(0),E=Gi(Q.data),i=Gi(I.data);for(let o=0;o<B;o++){let a=0;for(let D=0;D<g;D++)a+=C[D]*I.stride[D];i[a]=E[o],C[0]+=1;for(let D=0;D<g;D++)if(C[D]===Q.shape[D]){if(D+1===g)break;C[D]=0,C[D+1]+=1}}return I}function ns(Q){let A=Q.shape.length;return yI(A===Q.stride.length,"Shape and stride must have the same length."),Q.stride.map((I,g)=>({stride:I,index:g})).sort((I,g)=>g.stride-I.stride).map(I=>I.index)}function Ss(Q,A){let I=ns(Q);return yI(I.length===A.length,"Orders must match"),I.every((g,B)=>g===A[B])}class GC{kind="array_to_array";#A;#I;constructor(A,I){let g=A.order??"C",B=I.shape.length,C=new Array(B),E=new Array(B);if(g==="C")for(let i=0;i<B;++i)C[i]=i,E[i]=i;else if(g==="F")for(let i=0;i<B;++i)C[i]=B-i-1,E[i]=B-i-1;else C=g,C.forEach((i,o)=>{yI(E[i]===void 0,`Invalid permutation: ${JSON.stringify(g)}`),E[i]=o});this.#A=C,this.#I=E}static fromConfig(A,I){return new GC(A,I)}encode(A){return Ss(A,this.#I)?A:rs(A,this.#I)}decode(A){return{data:A.data,shape:A.shape,stride:og(A.shape,this.#A)}}}class AQ{kind="array_to_bytes";#A;#I;constructor(A){this.#A=A,this.#I=og(A,"C")}static fromConfig(A,I){return new AQ(I.shape)}encode=ig("vlen-utf8");decode(A){let I=new TextDecoder,g=new DataView(A.buffer),B=Array(g.getUint32(0,!0)),C=4;for(let E=0;E<B.length;E++){let i=g.getUint32(C,!0);C+=4,B[E]=I.decode(A.buffer.slice(C,C+i)),C+=i}return{data:B,shape:this.#A,stride:this.#I}}}class wC{kind="bytes_to_bytes";static fromConfig(A){return new wC}encode=ig("zlib");async decode(A){const I=await Ci(A,{format:"deflate"});return new Uint8Array(I)}}function Ns(){let Q=()=>Promise.resolve().then(()=>py).then(C=>C.default),A=()=>Promise.resolve().then(()=>by).then(C=>C.default),I=()=>Promise.resolve().then(()=>Xy).then(C=>C.default),g=()=>hC,B=()=>wC;return new Map().set("blosc",Q).set("lz4",A).set("zstd",I).set("gzip",g).set("zlib",B).set("transpose",()=>GC).set("bytes",()=>jB).set("crc32c",()=>DC).set("vlen-utf8",()=>AQ).set("json2",()=>$B).set("bitround",()=>XB).set("cast_value",()=>aC).set("scale_offset",()=>yC).set("numcodecs.blosc",Q).set("numcodecs.lz4",A).set("numcodecs.zstd",I).set("numcodecs.gzip",g).set("numcodecs.zlib",B).set("numcodecs.vlen-utf8",()=>AQ).set("numcodecs.shuffle",()=>tC).set("numcodecs.delta",()=>sC).set("numcodecs.bitround",()=>XB).set("numcodecs.json2",()=>$B)}const Rs=Ns();function eC(Q){let A;function I(){return A||(A=cs(Q)),A}async function g(B,C,E){try{return await E()}catch(i){throw new $D({direction:B,codec:C,cause:i})}}return{async encode(B){let C=await I();for(const{name:i,codec:o}of C.arrayToArray)B=await g("encode",i,()=>o.encode(B));let E=await g("encode",C.arrayToBytes.name,()=>C.arrayToBytes.codec.encode(B));for(const{name:i,codec:o}of C.bytesToBytes)E=await g("encode",i,()=>o.encode(E));return E},async decode(B){let C=await I();for(let i=C.bytesToBytes.length-1;i>=0;i--){const{name:o,codec:a}=C.bytesToBytes[i];B=await g("decode",o,()=>a.decode(B))}let E=await g("decode",C.arrayToBytes.name,()=>C.arrayToBytes.codec.decode(B));for(let i=C.arrayToArray.length-1;i>=0;i--){const{name:o,codec:a}=C.arrayToArray[i];E=await g("decode",o,()=>a.decode(E))}return E},async computeEncodedSize(B){let C=await I(),E=wi(C.arrayToBytes.name,C.arrayToBytes.codec,B);for(const{name:i,codec:o}of C.bytesToBytes)E=wi(i,o,E);return E}}}function wi(Q,A,I){if(!A.computeEncodedSize)throw new WA(`Codec "${Q}" cannot compute its encoded size; it is not a fixed-size codec and cannot be used in a sharding index pipeline`);return A.computeEncodedSize(I)}async function cs(Q){let A=Q.codecs.map(async E=>{let i=await Rs.get(E.name)?.();if(!i)throw new _D(E.name);return{Codec:i,meta:E}}),I=[],g,B=[],C={...Q};for await(let{Codec:E,meta:i}of A){let o=E.fromConfig(i.configuration,C);switch(o.kind){case"array_to_array":I.push({name:i.name,codec:o}),o.getEncodedMeta&&(C=o.getEncodedMeta(C));break;case"array_to_bytes":g={name:i.name,codec:o};break;default:B.push({name:i.name,codec:o})}}if(!g){if(!Us(C))throw new WA(`Cannot encode ${C.dataType} to bytes without a codec`);g={name:"bytes",codec:jB.fromConfig({endian:"little"},C)}}return{arrayToArray:I,arrayToBytes:g,bytesToBytes:B}}function Us(Q){return Q.dataType!=="v2:object"&&Q.dataType!=="string"}const ei=18446744073709551615n;function ks(Q,A,I,g){if(!Q.store.getRange)throw new AC("sharding requires a store with getRange");let B=Q.store.getRange.bind(Q.store),C=A.map((a,D)=>a/g.chunk_shape[D]),E=eC({dataType:"uint64",shape:[...C,2],codecs:g.index_codecs,fillValue:null}),i=16*C.reduce((a,D)=>a*D,1),o={};return async(a,D)=>{let s=a.map((l,Z)=>Math.floor(l/C[Z])),y=Q.resolve(I(s)).path;y in o||(o[y]=(async()=>{let l=await E.computeEncodedSize(i),Z=await B(y,{suffixLength:l},D);return Z?await E.decode(Z):null})().catch(l=>{throw delete o[y],l}));let F=await o[y];if(F===null)return;let{data:Y,shape:p,stride:H}=F,W=a.map((l,Z)=>l%p[Z]).reduce((l,Z,v)=>l+Z*H[v],0),z=Y[W],x=Y[W+1];if(!(z===ei&&x===ei))return B(y,{offset:Number(z),length:Number(x)},D)}}class FI{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 FI(this.store,decodeURIComponent(new URL(A,I).pathname))}}class FC extends FI{kind="group";#A;constructor(A,I,g){super(A,I),this.#A=g}get attrs(){return this.#A.attributes}}function Fi(Q){return Q.find(I=>I.name==="transpose")?.configuration?.order??"C"}const IQ=Symbol("zarrita.context");function Ls(Q,A){let{configuration:I}=A.codecs.find(Es)??{},g={encodeChunkKey:gs(A.chunk_key_encoding),TypedArray:Kg(A.data_type),fillValue:A.fill_value};if(I){let C=Fi(I.codecs);return{...g,kind:"sharded",chunkShape:I.chunk_shape,codec:eC({dataType:A.data_type,shape:I.chunk_shape,codecs:I.codecs,fillValue:A.fill_value}),getStrides(E){return og(E,C)},getChunkBytes:ks(Q,A.chunk_grid.configuration.chunk_shape,g.encodeChunkKey,I)}}let B=Fi(A.codecs);return{...g,kind:"regular",chunkShape:A.chunk_grid.configuration.chunk_shape,codec:eC({dataType:A.data_type,shape:A.chunk_grid.configuration.chunk_shape,codecs:A.codecs,fillValue:A.fill_value}),getStrides(C){return og(C,B)},async getChunkBytes(C,E){let i=g.encodeChunkKey(C),o=Q.resolve(i).path;return Q.store.get(o,E)}}}let gQ=class extends FI{kind="array";#A;[IQ];constructor(A,I,g){super(A,I),this.#A={...g,fill_value:Bi(g)},this[IQ]=Ls(this,this.#A)}get attrs(){return this.#A.attributes}get dimensionNames(){return this.#A.dimension_names}get fillValue(){return this.#A.fill_value}get shape(){return this.#A.shape}get chunks(){return this[IQ].chunkShape}get dtype(){return this.#A.data_type}async getChunk(A,I,g){g?.useSharedArrayBuffer&&As();let B=this[IQ],C=await B.getChunkBytes(A,I);if(!C){let E=B.chunkShape.reduce((o,a)=>o*a,1),i;if(g?.useSharedArrayBuffer){let o=new B.TypedArray(0);if(!("BYTES_PER_ELEMENT"in o))console.warn("zarrita: useSharedArrayBuffer is not supported for non-buffer-backed data types."),i=new B.TypedArray(E);else{let a=Is(E*o.BYTES_PER_ELEMENT);i=new B.TypedArray(a,0,E)}}else i=new B.TypedArray(E);return i.fill(B.fillValue),{data:i,shape:B.chunkShape,stride:B.getStrides(B.chunkShape)}}return B.codec.decode(C)}is(A){return BC(this.dtype,A)}};function Js(Q,A){let I=Q;for(let g of A)I instanceof Promise?I=I.then(B=>g(B)):I=g(I);return I}function Ys(Q,...A){return Js(Q,A)}async function ri(Q){let A=Q.store.arrayExtensions;return A?.length?await Ys(Q,...A):Q}let BQ=Ks();function Ks(){let Q=new WeakMap;function A(I){let g=Q.get(I)??{v2:0,v3:0};return Q.set(I,g),g}return{increment(I,g){A(I)[g]+=1},versionMax(I){let g=A(I);return g.v3>g.v2?"v3":"v2"}}}async function Ms(Q,A){let I=await Q.store.get(Q.resolve(".zattrs").path,{signal:A});return I?eB(I):{}}async function ds(Q,A={}){let I="store"in Q?Q:new FI(Q),{signal:g}=A,B={};return(A.attrs??!0)&&(B=await Ms(I,g)),g?.throwIfAborted(),A.kind==="array"?ni(I,B,g):A.kind==="group"?Si(I,B,g):ni(I,B,g).catch(C=>(Qi(C,Yg,WA),Si(I,B,g)))}async function ni(Q,A,I){let{path:g}=Q.resolve(".zarray"),B=await Q.store.get(g,{signal:I});if(!B)throw new Yg("v2 array",{path:g});return BQ.increment(Q.store,"v2"),ri(new gQ(Q.store,Q.path,Qs(eB(B),A)))}async function Si(Q,A,I){let{path:g}=Q.resolve(".zgroup"),B=await Q.store.get(g,{signal:I});if(!B)throw new Yg("v2 group",{path:g});return BQ.increment(Q.store,"v2"),new FC(Q.store,Q.path,Cs(eB(B),A))}async function Hs(Q,A){let{store:I,path:g}=Q.resolve("zarr.json"),B=await Q.store.get(g,{signal:A});if(!B)throw new Yg("v3 array or group",{path:g});let C=eB(B);return C.node_type==="array"&&(C.fill_value=Bi(C)),C.node_type==="array"?ri(new gQ(I,Q.path,C)):new FC(I,Q.path,C)}async function qs(Q,A={}){let I="store"in Q?Q:new FI(Q),g=await Hs(I,A.signal);if(BQ.increment(I.store,"v3"),A.kind===void 0||A.kind==="array"&&g instanceof gQ||A.kind==="group"&&g instanceof FC)return g;let B=g instanceof gQ?"array":"group";throw new Yg(`${A.kind} at ${I.path}`,{path:I.path,found:B})}async function rI(Q,A={}){let I="store"in Q?Q.store:Q,g=BQ.versionMax(I),B=g==="v2"?rI.v2:rI.v3,C=g==="v2"?rI.v3:rI.v2;return B(Q,A).catch(E=>(Qi(E,Yg,WA),C(Q,A)))}rI.v2=ds,rI.v3=qs;async function ls(Q,A){const I=A.split("/"),g=I.pop();if(!g)throw new Error("Invalid path");for(const B of I)Q=await Q.getDirectoryHandle(B);return Q.getFileHandle(g)}class rC{#A;constructor(A){this.#A=A}get directoryHandle(){return this.#A}async get(A){const I=await ls(this.#A,A.slice(1)).catch(()=>{});if(!I)return;const B=await(await I.getFile()).arrayBuffer();return new Uint8Array(B)}}async function FB(Q,A){if(A==="v2")try{return rI.v2(Q,{kind:"group",attrs:!0})}catch{throw new Error(`Failed to open Zarr v2 group at ${Q}`)}if(A==="v3")try{return rI.v3(Q,{kind:"group"})}catch{throw new Error(`Failed to open Zarr v3 group at ${Q}`)}try{return rI(Q,{kind:"group"})}catch{throw new Error(`Failed to open Zarr group at ${Q}`)}}async function fs(Q,A){if(A==="v2")try{return rI.v2(Q,{kind:"array",attrs:!1})}catch{throw new Error(`Failed to open Zarr v2 array at ${Q}`)}if(A==="v3")try{return rI.v3(Q,{kind:"array"})}catch{throw new Error(`Failed to open Zarr v3 array at ${Q}`)}try{return rI(Q,{kind:"array"})}catch{throw new Error(`Failed to open Zarr array at ${Q}`)}}async function ps(Q){let A;switch(Q.type){case"fetch":{const g=new tB(Q.url);A=new FI(g);break}case"filesystem":{A=new FI(new rC(Q.directoryHandle),Q.path);break}default:{const g=Q;throw new Error(`Unsupported store type: ${g}`)}}const I=Q.arrayPath?A.resolve(Q.arrayPath):A;return fs(I,Q.zarrVersion)}function us(Q,A,I){if(Q.store instanceof tB)return{type:"fetch",arrayPath:A,zarrVersion:I,url:Q.store.url.toString()};if(Q.store instanceof rC)return{type:"filesystem",arrayPath:A,zarrVersion:I,directoryHandle:Q.store.directoryHandle,path:Q.path};throw new Error(`Unsupported store type: ${Q.store.constructor.name}`)}function ms(Q,A,I,g){return xs(Q,A,I,g)}function xs(Q,A,I,g){const{targetShape:B,chunkIndex:C,dimIndices:E}=g;let i=1;for(let Z=A.length-1;Z>=0;Z--){if(I[Z]!==i)throw new Error(`Chunk data is not tightly packed, stride=${JSON.stringify(I)}, shape=${JSON.stringify(A)}`);i*=A[Z]}const o={x:A[E.x],y:A[E.y],z:E.z!==void 0?A[E.z]:B.z};if(o.x<B.x||o.y<B.y||o.z<B.z)throw new Error(`Received chunk too small: expected ${JSON.stringify(B)}, got ${JSON.stringify(o)}`);const a=g.cChunkSize?C.c%g.cChunkSize:0,D=g.tChunkSize?C.t%g.tChunkSize:0,s=B.x*B.y*B.z,y=E.c!==void 0?I[E.c]:0,F=E.t!==void 0?I[E.t]:0,Y=D*F+a*y,p=o.x===B.x&&o.y===B.y&&o.z===B.z;if(Y===0&&Q.length===s&&p)return Q;const W=new Q.constructor(s),z=E.z!==void 0?I[E.z]:0,x=I[E.y];let l=0;for(let Z=0;Z<B.z;Z++){const v=Y+Z*z;for(let CA=0;CA<B.y;CA++){const sA=v+CA*x,DA=sA+B.x;W.set(Q.subarray(sA,DA),l),l+=B.x}}return W}const Ni=`function xg(B, A) {
556
+ }`;class RD{colorFormat_;depthFormat_;device_;pipelines_;shaderModules_;constructor(A,I,g){this.colorFormat_=I,this.depthFormat_=g,this.device_=A,this.pipelines_=[],this.shaderModules_=[]}async compileShader(A){if(this.shaderModules_.some(a=>a.name===A))return;const I=LD(A),g=this.device_.createShaderModule({code:I});await cD(A,g);const B=wD(I),C=sD(B,{vertex:{entryPoint:"vert"},fragment:{entryPoint:"frag"}}),E=C[B.uniforms.uniforms.group];UD(E);const i=B.textures?.texture;let o;if(i){const a=C[i.group];A==="image_scalar_f32"&&kD(a),o=this.device_.createBindGroupLayout(a)}this.shaderModules_.push({name:A,module:g,defs:B,layouts:{uniforms:this.device_.createBindGroupLayout(E),textures:o}})}get(A,I){const g=this.getCachedPipeline(A);if(g)return g;const B=this.shaderModules_.find(F=>F.name===A.shaderName);if(!B)throw new Error("Shader module not found");const C=A.depthTest?"less-equal":"always",E=A.stencil?{compare:"equal",passOp:"increment-clamp"}:{},i={vertex:{module:B.module,entryPoint:"vert",buffers:[{attributes:I.attributes,arrayStride:I.geometry.strideBytes,stepMode:"vertex"}]},fragment:{module:B.module,entryPoint:"frag",targets:[{format:this.colorFormat_,blend:JD(A.blendMode)}]},primitive:{topology:A.topology,frontFace:"ccw",cullMode:A.cullMode},depthStencil:{format:this.depthFormat_,depthWriteEnabled:A.depthWrite,depthCompare:C,stencilFront:E,stencilBack:E,stencilReadMask:255,stencilWriteMask:255},multisample:{count:4}},o=[B.layouts.uniforms];B.layouts.textures&&o.push(B.layouts.textures);const a=this.device_.createPipelineLayout({bindGroupLayouts:o}),D=this.device_.createRenderPipeline({layout:a,...i}),s=la(B.defs.uniforms.uniforms),y={key:A,pipeline:D,uniformsView:s,uniformsData:new Float32Array(s.arrayBuffer),shaderModule:B};return this.pipelines_.push(y),y}getCachedPipeline(A){return this.pipelines_.find(I=>I.key.blendMode===A.blendMode&&I.key.cullMode===A.cullMode&&I.key.depthTest===A.depthTest&&I.key.depthWrite===A.depthWrite&&I.key.shaderName===A.shaderName&&I.key.stencil===A.stencil&&I.key.topology===A.topology&&I.key.vertexAttributesStr===A.vertexAttributesStr)}}async function cD(Q,A){const I=await A.getCompilationInfo();if(I.messages.some(g=>g.type==="error")){for(const g of I.messages)gA.error("WebGPUPipelines",`${g.type}: ${g.message}`);throw new Error(`Failed to compile WGSL shader ${Q}.wgsl`)}}function UD(Q){for(const A of Q.entries)A.buffer&&(A.buffer={...A.buffer,hasDynamicOffset:!0})}function kD(Q){for(const A of Q.entries)A.texture&&(A.texture={...A.texture,sampleType:"unfilterable-float"})}function LD(Q){switch(Q){case"image_scalar_u32":return rD;case"image_scalar_i32":return nD;case"image_scalar_f32":return SD;case"wireframe":return ND}}function JD(Q){let A,I;switch(Q){case"none":return;case"additive":A="src-alpha",I="one";break;case"multiply":A="dst",I="zero";break;case"subtractive":A="zero",I="one-minus-src";break;case"premultiplied":A="one-minus-dst-alpha",I="one";break;case"normal":A="src-alpha",I="one-minus-src-alpha";break}const g={srcFactor:A,dstFactor:I,operation:"add"};return{color:g,alpha:g}}const YD=xo(1,0,0,0,0,-1,0,0,0,0,.5,0,0,0,.5,1);async function KD(Q){if(!navigator.gpu)throw new Error("WebGPU is not supported in this browser");const A=await navigator.gpu.requestAdapter();if(!A)throw new Error("Failed to obtain a WebGPU Adapter");const I=new MD(Q,await A.requestDevice());return await I.compileShaders(),I}class MD extends OC{bindings_;geometryBuffers_;pipelines_;texturePool_;colorFormat_;context_;depthFormat_;device_;currentProjection_=hI();currentModelView_=hI();colorMSAATexture_=null;depthStencilTexture_=null;passEncoder_=null;renderedObjectsPerFrame_=0;needsClear_=!0;currentDepthWrite_=!0;currentStencil_=!1;currentBlendMode_="none";currentLayerOpacity_=1;constructor(A,I){super(A),this.colorFormat_=navigator.gpu.getPreferredCanvasFormat(),this.depthFormat_="depth24plus-stencil8",this.device_=I;const g=A.getContext("webgpu");if(!g)throw new Error("Failed to initialize WebGPU context");g.configure({device:this.device_,format:this.colorFormat_,alphaMode:"premultiplied"}),this.context_=g,this.bindings_=new Sa(I),this.geometryBuffers_=new Na(I),this.texturePool_=new Ua(I),this.pipelines_=new RD(I,this.colorFormat_,this.depthFormat_),gA.info("WebGPURenderer","WebGPU Initialized"),this.resize(this.width,this.height)}async compileShaders(){await Promise.all([this.pipelines_.compileShader("image_scalar_u32"),this.pipelines_.compileShader("image_scalar_i32"),this.pipelines_.compileShader("image_scalar_f32"),this.pipelines_.compileShader("wireframe")])}beginFrame(){this.renderedObjects_=0,this.renderedObjectsPerFrame_=0,this.needsClear_=!0}render(A){const I=[],g=[];for(const o of A.layers)(o.blendMode==="none"?I:g).push(o);for(const o of[...I,...g])o.update(A);if(getComputedStyle(A.element).visibility==="hidden")return;const B=A.getBoxRelativeTo(this.canvas),C=new QI(xA(0,0),xA(this.width,this.height));if(!QI.intersects(B,C)){gA.warn("WebGPURenderer",`Viewport ${A.id} is entirely outside canvas bounds`);return}const E=A.camera.frustum,i=!QI.equals(B.floor(),C.floor());this.bindings_.clearUniformBindings(),this.updateProjection(A.camera.projectionMatrix),this.currentDepthWrite_=!0;for(const o of I)o.state==="ready"&&this.renderLayer(o,A.camera,E,B,i);this.currentDepthWrite_=!1;for(const o of g)o.state==="ready"&&this.renderLayer(o,A.camera,E,B,i);this.renderedObjects_=this.renderedObjectsPerFrame_}renderLayer(A,I,g,B,C){if(A.type!=="ImageLayer")throw new Error("Experimental WebGPU renderer only supports image layers");if(A.objects.length===0)return;const E=this.device_.createCommandEncoder();this.passEncoder_=this.beginRenderPass(E);const{x:i,y:o,width:a,height:D}=B.floor().toRect();this.passEncoder_.setViewport(i,o,a,D,0,1),C&&this.passEncoder_.setScissorRect(i,o,a,D),this.currentStencil_=A.hasMultipleLODs(),this.currentStencil_&&this.passEncoder_.setStencilReference(0),this.currentBlendMode_=A.blendMode,this.currentLayerOpacity_=A.opacity,A.objects.forEach((s,y)=>{g.intersectsWithBox3(s.boundingBox)&&(this.renderObject(A,y,I),this.renderedObjectsPerFrame_+=1)}),this.passEncoder_.end(),this.device_.queue.submit([E.finish()]),this.passEncoder_=null}renderObject(A,I,g){const B=A.objects[I];if(B.type!=="ImageRenderable")throw new Error("Experimental WebGPU renderer only supports image renderables");if(B.popStaleTextures().forEach(o=>{this.texturePool_.dispose(o)}),!B.programName)return;const C=this.passEncoder_,E=this.geometryBuffers_.get(B.geometry),i=this.pipelines_.get({shaderName:dD(B.textures[0]),depthWrite:this.currentDepthWrite_,depthTest:B.depthTest,stencil:this.currentStencil_,blendMode:this.currentBlendMode_,cullMode:"back",topology:"triangle-list",vertexAttributesStr:E.attributesKey},E);C.setPipeline(i.pipeline),this.setUniformsForObject(B,i,g),this.setTexturesForObject(B,i),C.setVertexBuffer(0,E.vertexBuffer),E.indexBuffer?(C.setIndexBuffer(E.indexBuffer,"uint32"),C.drawIndexed(B.geometry.indexData.length)):C.draw(B.geometry.vertexCount),B.wireframeEnabled&&this.renderWireframe(B,g)}renderWireframe(A,I){const g=A.wireframeGeometry;if(g.indexData.length===0)return;const B=this.passEncoder_,C=this.geometryBuffers_.get(g),E=this.pipelines_.get({shaderName:"wireframe",depthWrite:this.currentDepthWrite_,depthTest:A.depthTest,stencil:this.currentStencil_,blendMode:this.currentBlendMode_,cullMode:"none",topology:"line-list",vertexAttributesStr:C.attributesKey},C);B.setPipeline(E.pipeline),Ng(this.currentModelView_,I.viewMatrix,A.transform.matrix),E.uniformsView.set({projection:this.currentProjection_,modelView:this.currentModelView_,color:A.wireframeColor.rgb,opacity:this.currentLayerOpacity_}),this.bindings_.setUniforms(B,E),B.setVertexBuffer(0,C.vertexBuffer),C.indexBuffer&&(B.setIndexBuffer(C.indexBuffer,"uint32"),B.drawIndexed(g.indexData.length))}resize(A,I){this.colorMSAATexture_&&this.colorMSAATexture_.destroy(),this.colorMSAATexture_=this.device_.createTexture({size:{width:A,height:I},format:this.colorFormat_,sampleCount:4,usage:GPUTextureUsage.RENDER_ATTACHMENT}),this.depthStencilTexture_&&this.depthStencilTexture_.destroy(),this.depthStencilTexture_=this.device_.createTexture({size:{width:A,height:I},format:this.depthFormat_,sampleCount:4,usage:GPUTextureUsage.RENDER_ATTACHMENT})}beginRenderPass(A){const I=this.needsClear_?"clear":"load";return this.needsClear_=!1,A.beginRenderPass({colorAttachments:[{view:this.colorMSAATexture_.createView(),resolveTarget:this.context_.getCurrentTexture().createView(),loadOp:I,storeOp:"store",clearValue:{r:this.backgroundColor.r,g:this.backgroundColor.g,b:this.backgroundColor.b,a:this.backgroundColor.a}}],depthStencilAttachment:{view:this.depthStencilTexture_.createView(),depthLoadOp:I,depthStoreOp:"store",depthClearValue:1,stencilLoadOp:"clear",stencilStoreOp:"store",stencilClearValue:0}})}clear(){}uploadTexture(A){this.texturePool_.get(A)}disposeTexture(A){this.texturePool_.dispose(A)}setUniformsForObject(A,I,g){Ng(this.currentModelView_,g.viewMatrix,A.transform.matrix);const B=A.getUniforms(),C=B.Opacity??1;I.uniformsView.set({projection:this.currentProjection_,modelView:this.currentModelView_,color:B.u_color,valueOffset:B.u_valueOffset,valueScale:B.u_valueScale,opacity:this.currentLayerOpacity_*C,zTexCoord:B.u_zTexCoord}),this.bindings_.setUniforms(this.passEncoder_,I)}setTexturesForObject(A,I){if(A.textures.length>1)throw new Error("Experimental WebGPU renderer only supports single textures");this.bindings_.setTexture(this.passEncoder_,I,this.texturePool_.get(A.textures[0]))}updateProjection(A){Ng(this.currentProjection_,YD,A)}get gpuTextureBytes(){return this.texturePool_.gpuTextureBytes}get gpuTextureCount(){return this.texturePool_.textureCount}}function dD(Q){switch(Q.dataType){case"byte":case"unsigned_byte":case"float":return"image_scalar_f32";case"short":case"int":return"image_scalar_i32";case"unsigned_short":case"unsigned_int":return"image_scalar_u32"}}function sB(Q,A){const I=Q.priority??Number.MAX_SAFE_INTEGER,g=A.priority??Number.MAX_SAFE_INTEGER;return I===g?(Q.orderKey??Number.MAX_SAFE_INTEGER)-(A.orderKey??Number.MAX_SAFE_INTEGER):I-g}class HD{maxConcurrent_;pending_=[];running_=new Map;constructor(A){this.maxConcurrent_=Math.max(1,A)}enqueue(A,I){this.running_.has(A)||this.pending_.some(g=>g.chunk===A)||this.pending_.push({chunk:A,fn:I})}flush(){this.pump()}cancel(A){const I=this.pending_.findIndex(B=>B.chunk===A);if(I>=0){this.pending_.splice(I,1),gA.debug("ChunkQueue","Cancelled pending request");return}const g=this.running_.get(A);g&&(g.controller.abort(),gA.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)=>sB(A.chunk,I.chunk));this.running_.size<this.maxConcurrent_&&this.pending_.length>0;)this.start(this.pending_.shift())}start(A){const{chunk:I,fn:g}=A;I.state="loading";const B=new AbortController,C=Promise.resolve().then(()=>g(B.signal)).then(()=>{I.state==="loading"&&(I.state="loaded")},E=>{I.state==="loading"&&(I.state="unloaded"),E.name!=="AbortError"&&gA.error("ChunkQueue",String(E))}).finally(()=>{this.running_.delete(I),this.pump()});this.running_.set(I,{controller:B,promise:C})}}let VB=0,OB=0;function qD(Q,A){Q.data&&(VB-=Q.data.byteLength,OB-=1),Q.data=A,VB+=A.byteLength,OB+=1}function OE(Q){Q.data&&(VB-=Q.data.byteLength,OB-=1),Q.data=void 0,Q.texture?.releaseCpuData()}function lD(){return{cpuChunkBytes:VB,cpuChunkCount:OB}}function vE(Q,A,I=1e-6){return Math.abs(Q-A)<=I}const XE=[Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array];function fD(Q){if(XE.some(I=>Q instanceof I))return!0;const A=XE.map(I=>I.name);return gA.debug("Chunk",`Unsupported chunk data type: ${Q}. Supported data types: ${A}`),!1}function pD(Q,A){return Math.round((A-Q.translation)/Q.scale)}function fI(Q,A,I){return Math.max(A,Math.min(I,Q))}const vB=Symbol("INTERNAL_POLICY_KEY");class uD{store_;policy_;policyChanged_=!1;currentLOD_=0;lastViewBounds2D_=null;lastViewProjection_=null;lastZBounds_;lastTCoord_;lastCCoords_;sourceMaxSquareDistance2D_;chunkViewStates_=new Map;isDisposed_=!1;constructor(A,I){this.store_=A,this.policy_=I,gA.info("ChunkStoreView","Using image source policy:",this.policy_.profile);const g=this.store_.dimensions,B=g.x.lods[0],C=g.y.lods[0];this.sourceMaxSquareDistance2D_=aa(xA(B.size*B.scale,C.size*C.scale))}get chunkViewStates(){return this.chunkViewStates_}get isDisposed(){return this.isDisposed_}get lodCount(){return this.store_.lodCount}get channelCount(){return this.store_.channelCount}getChunksToRender(){const A=this.fallbackLOD(),I=this.currentLOD_,g=[],B=[];for(const[C,E]of this.chunkViewStates_)!E.visible||C.state!=="loaded"||!C.texture||(C.lod===I?g.push(C):C.lod===A&&I!==A&&B.push(C));return[...g,...B]}updateChunksForImage(A,I){const g=I.worldViewRect,C=Math.abs(g.max[0]-g.min[0])/I.bufferWidthPx,E=Math.log2(1/C);this.setLOD(E);const i=this.getZBounds(A);if(!(this.policyChanged_||this.viewBounds2DChanged(g)||this.zBoundsChanged(i)||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const a=this.timeIndex(A);if(!this.store_.hasChunksAtTime(a)){gA.warn("ChunkStoreView","updateChunkViewStates called with no chunks initialized"),this.chunkViewStates_.forEach(hB);return}const D=gE();Da(D,g.min,g.max,.5);const[s,y]=this.getZBounds(A),F=new Bg(nA(g.min[0],g.min[1],s),nA(g.max[0],g.max[1],y));this.chunkViewStates_.forEach(hB);const Y=this.channelsOfInterest(A),p=this.fallbackLOD(),H=this.getPaddedBounds(F),W=this.currentLOD_===p?[this.currentLOD_]:[this.currentLOD_,p];for(const z of W){const x=z===this.currentLOD_,l=z===p;this.iterateChunksInBox(a,z,Y,H,(Z,v)=>{const CA=Bg.intersects(v,F),sA=x&&!CA,DA=this.computePriority(l,x,CA,sA,!0);DA!==null&&this.chunkViewStates_.set(Z,{visible:CA,prefetch:sA,priority:DA,orderKey:this.squareDistance2D(Z,D)})})}this.markTimeChunksForPrefetchImage(a,A,F,D),this.policyChanged_=!1,this.lastViewBounds2D_=g.clone(),this.lastZBounds_=i,this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0}updateChunksForVolume(A,I){if(!(this.policyChanged_||this.hasViewProjectionChanged(I)||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const B=this.timeIndex(A);if(!this.store_.hasChunksAtTime(B)){gA.warn("ChunkStoreView","updateChunksForVolume called with no chunks initialized"),this.chunkViewStates_.forEach(hB);return}this.currentLOD_=this.policy_.lod.min,this.chunkViewStates_.forEach(hB);const C=this.channelsOfInterest(A),E=this.fallbackLOD(),i=o=>{const a=o.lod===E,D=o.lod===this.currentLOD_,s=this.computePriority(a,D,!0,!1,!0);s!==null&&this.chunkViewStates_.set(o,{visible:!0,prefetch:!1,priority:s,orderKey:0})};this.iterateAllChunksAtLod(B,this.currentLOD_,C,i),this.currentLOD_!==E&&this.iterateAllChunksAtLod(B,E,C,i),this.markTimeChunksForPrefetchVolume(B,A),this.policyChanged_=!1,this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0,this.lastViewProjection_=I}allVisibleFallbackLODLoaded(){const A=this.fallbackLOD();let I=!1;for(const[g,B]of this.chunkViewStates_)if(!(!B.visible||g.lod!==A)&&(I=!0,g.texture===void 0))return!1;return I}get currentLOD(){return this.currentLOD_}maybeForgetChunk(A){const I=this.chunkViewStates_.get(A);I&&(I.visible||I.prefetch||I.priority!==null)||this.chunkViewStates_.delete(A)}dispose(){this.isDisposed_=!0,this.chunkViewStates_.forEach(hB)}setImageSourcePolicy(A,I){if(I!==vB)throw new Error("Unauthorized policy mutation");this.policy_!==A&&(this.policy_=A,this.policyChanged_=!0,gA.info("ChunkStoreView","Using image source policy:",this.policy_.profile))}setLOD(A){const g=this.store_.dimensions.x.lods[0].scale,C=this.policy_.lod.bias-Math.log2(g)-A,E=Math.floor(C),i=this.store_.getLowestResLOD(),o=Math.max(0,Math.min(i,this.policy_.lod.min)),a=Math.max(o,Math.min(i,this.policy_.lod.max)),D=fI(E,o,a);D!==this.currentLOD_&&(this.currentLOD_=D)}markTimeChunksForPrefetchImage(A,I,g,B){const C=this.store_.dimensions.t?.lods[0].size??1,E=Math.min(this.policy_.prefetch.t,C-1),i=this.fallbackLOD(),o=this.policy_.priorityMap.prefetchTime,a=this.channelsOfInterest(I);for(let D=1;D<=E;++D){const s=(A+D)%C;this.iterateChunksInBox(s,i,a,g,y=>{const F=this.squareDistance2D(y,B),Y=fI(F/this.sourceMaxSquareDistance2D_,0,1-Number.EPSILON),p=D+Y;this.chunkViewStates_.set(y,{visible:!1,prefetch:!0,priority:o,orderKey:p})})}}markTimeChunksForPrefetchVolume(A,I){const g=this.store_.dimensions.t?.lods[0].size??1,B=Math.min(this.policy_.prefetch.t,g-1),C=this.fallbackLOD(),E=this.policy_.priorityMap.prefetchTime,i=this.channelsOfInterest(I);for(let o=1;o<=B;++o){const a=(A+o)%g;this.iterateAllChunksAtLod(a,C,i,D=>{const s=o;this.chunkViewStates_.set(D,{visible:!1,prefetch:!0,priority:E,orderKey:s})})}}computePriority(A,I,g,B,C){if(!C)return null;const E=this.policy_.priorityMap;return A&&g?E.fallbackVisible:I&&g?E.visibleCurrent:A?E.fallbackBackground:I&&B?E.prefetchSpace:null}channelsOfInterest(A){return A.c??Array.from({length:this.store_.channelCount},(I,g)=>g)}chunkIndexRange(A,I){const g=this.store_.dimensions,B=g.x.lods[I],C=g.y.lods[I],E=g.z?.lods[I],i=Math.ceil(B.size/B.chunkSize),o=Math.ceil(C.size/C.chunkSize),a=E?Math.ceil(E.size/E.chunkSize):1,D=B.chunkSize*B.scale,s=C.chunkSize*C.scale,y=E?E.chunkSize*E.scale:1,F=B.translation,Y=C.translation,p=E?.translation??0,H=Math.max(0,Math.floor((A.min[0]-F)/D)),W=Math.min(i,Math.ceil((A.max[0]-F)/D)),z=Math.max(0,Math.floor((A.min[1]-Y)/s)),x=Math.min(o,Math.ceil((A.max[1]-Y)/s)),l=E?Math.max(0,Math.floor((A.min[2]-p)/y)):0,Z=E?Math.min(a,Math.ceil((A.max[2]-p)/y)):1;return H>=W||z>=x||l>=Z?null:{xMin:H,xMax:W,yMin:z,yMax:x,zMin:l,zMax:Z}}iterateChunksInBox(A,I,g,B,C){const E=this.chunkIndexRange(B,I);if(E)for(const i of g){const o=this.store_.getChunkGrid(I,A,i);if(o)for(let a=E.zMin;a<E.zMax;++a){const D=o[a];for(let s=E.yMin;s<E.yMax;++s){const y=D[s];for(let F=E.xMin;F<E.xMax;++F){const Y=y[F];C(Y,this.getChunkAabb(Y))}}}}}iterateAllChunksAtLod(A,I,g,B){for(const C of g){const E=this.store_.getChunkGrid(I,A,C);if(E)for(const i of E)for(const o of i)for(const a of o)B(a,this.getChunkAabb(a))}}getChunkAabb(A){return new Bg(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))}fallbackLOD(){return Math.min(this.policy_.lod.max,this.store_.getLowestResLOD())}timeIndex(A){const I=this.store_.dimensions.t;return A.t===void 0||I===void 0?0:pD(I.lods[0],A.t)}getZBounds(A){const I=this.store_.dimensions.z;if(I===void 0)return[0,1];if(A.z===void 0){const D=I.lods[this.currentLOD_];return[D.translation,D.translation+D.size*D.scale]}const g=I.lods[this.currentLOD_],B=g.size,C=g.scale,E=g.translation,i=Math.floor((A.z-E)/C),o=g.chunkSize,a=Math.max(0,Math.min(Math.floor(i/o),Math.ceil(B/o)-1));return[E+a*o*C,E+(a+1)*o*C]}viewBounds2DChanged(A){return this.lastViewBounds2D_===null||!JQ(this.lastViewBounds2D_.min,A.min)||!JQ(this.lastViewBounds2D_.max,A.max)}hasViewProjectionChanged(A){return this.lastViewProjection_===null||!vo(this.lastViewProjection_,A)}zBoundsChanged(A){return!this.lastZBounds_||!JQ(this.lastZBounds_,A)}cCoordsChanged(A){return!this.lastCCoords_&&!A?!1:!this.lastCCoords_||!A||this.lastCCoords_.length!==A.length?!0:!this.lastCCoords_.every((I,g)=>I===A[g])}getPaddedBounds(A){const I=this.store_.dimensions,g=I.x.lods[this.currentLOD_],B=I.y.lods[this.currentLOD_],C=I.z?.lods[this.currentLOD_],E=g.chunkSize*g.scale*this.policy_.prefetch.x,i=B.chunkSize*B.scale*this.policy_.prefetch.y;let o=0;return C&&(o=C.chunkSize*C.scale*this.policy_.prefetch.z),new Bg(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 g={x:A.offset.x+.5*A.shape.x*A.scale.x,y:A.offset.y+.5*A.shape.y*A.scale.y},B=g.x-I[0],C=g.y-I[1];return B*B+C*C}}function hB(Q){Q.visible=!1,Q.prefetch=!1,Q.priority=null,Q.orderKey=null}class mD{chunks_;lowestResLOD_;dimensions_;views_=[];hasHadViews_=!1;constructor(A){this.dimensions_=A,this.lowestResLOD_=this.dimensions_.numLods-1,this.validateXYScaleRatios();const{size:I}=this.getAndValidateTimeDimension(),{size:g}=this.getAndValidateChannelDimension(),B=this.dimensions_.numLods;this.chunks_=new Array(B);for(let C=0;C<B;++C){const E=this.dimensions_.x.lods[C],i=this.dimensions_.y.lods[C],o=this.dimensions_.z?.lods[C],a=E.chunkSize,D=i.chunkSize,s=o?.chunkSize??1,y=Math.ceil(E.size/a),F=Math.ceil(i.size/D),Y=o?Math.ceil(o.size/s):1,p=new Array(I);this.chunks_[C]=p;for(let H=0;H<I;++H){const W=new Array(g);p[H]=W;for(let z=0;z<g;++z){const x=new Array(Y);W[z]=x;for(let l=0;l<Y;++l){const Z=o!==void 0?o.translation+l*s*o.scale:0,v=new Array(F);x[l]=v;for(let CA=0;CA<F;++CA){const sA=i.translation+CA*D*i.scale,DA=new Array(y);v[CA]=DA;for(let yA=0;yA<y;++yA){const wA=E.translation+yA*a*E.scale;DA[yA]={state:"unloaded",lod:C,visible:!1,prefetch:!1,priority:null,orderKey:null,shape:{x:Math.min(a,E.size-yA*a),y:Math.min(D,i.size-CA*D),z:Math.min(s,(o?.size??1)-l*s),c:1},rowAlignmentBytes:1,chunkIndex:{x:yA,y:CA,z:l,c:z,t:H},scale:{x:E.scale,y:i.scale,z:o?.scale??1},offset:{x:wA,y:sA,z:Z}}}}}}}}}getChunkGrid(A,I,g){return this.chunks_[A]?.[I]?.[g]}hasChunksAtTime(A){return this.chunks_[0]?.[A]!==void 0}get lodCount(){return this.lowestResLOD_+1}get channelCount(){return this.dimensions_.c?.lods[0].size??1}get dimensions(){return this.dimensions_}getLowestResLOD(){return this.lowestResLOD_}addView(A){const I=new uD(this,A);return this.views_.push(I),this.hasHadViews_=!0,I}get views(){return this.views_}canDispose(){return this.hasHadViews_&&this.views_.length===0}updateAndCollectChunkChanges(){const A=new Set;for(const I of this.views_)for(const[g,B]of I.chunkViewStates)A.add(g);for(const I of A)this.aggregateChunkViewStates(I);return this.removeDisposedViews(),A}removeDisposedViews(){for(let A=this.views_.length-1;A>=0;A--)this.views_[A].isDisposed&&this.views_.splice(A,1)}aggregateChunkViewStates(A){let I=!1,g=!1,B=null,C=null;for(const o of this.views_){const a=o.chunkViewStates.get(A);a&&(a.visible&&(I=!0),a.prefetch&&(g=!0),a.priority!==null&&(B===null||a.priority<B)&&(B=a.priority,C=a.orderKey),!a.visible&&!a.prefetch&&a.priority===null&&o.maybeForgetChunk(A))}if(A.visible=I,A.prefetch=g,A.priority=B,A.orderKey=C,A.priority!==null&&A.state==="unloaded"){A.state="queued";return}A.priority===null&&A.state==="queued"&&(A.state="unloaded")}validateXYScaleRatios(){const A=this.dimensions_.x,I=this.dimensions_.y;for(let g=1;g<this.dimensions_.numLods;g++){const B=A.lods[g].scale/A.lods[g-1].scale,C=I.lods[g].scale/I.lods[g-1].scale;if(!vE(B,2,.02)||!vE(C,2,.02))throw new Error(`Invalid downsampling factor between levels ${g-1} → ${g}: expected (2× in X and Y), but got (${B.toFixed(2)}×, ${C.toFixed(2)}×) from scale [${A.lods[g-1].scale}, ${I.lods[g-1].scale}] → [${A.lods[g].scale}, ${I.lods[g].scale}]`)}}getAndValidateTimeDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.t?.lods[A];if(!I)continue;const g=this.dimensions_.t?.lods[A-1];if(g&&I.size!==g.size)throw new Error(`ChunkStore does not support downsampling in t. Found ${g.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.t?.lods[0].size??1}}getAndValidateChannelDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.c?.lods[A];if(!I)continue;if(I.scale!==1&&gA.warn("ChunkStore",`Idetik does not make use of non-unity scale in c. Found ${I.scale} at LOD ${A}`),I.translation!==0)throw new Error(`ChunkStore does not support translation in c. Found ${I.translation} at LOD ${A}`);const g=this.dimensions_.c?.lods[A-1];if(g&&I.size!==g.size)throw new Error(`ChunkStore does not support downsampling in c. Found ${g.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.c?.lods[0].size??1}}}const xD=8,TD=4;class WD{stores_=[];queue_;uploadTexture_;disposeTexture_;getGpuResidentBytes_;memoryLimitBytes_;maxGpuUploadsPerUpdate_;resident_=new Set;constructor(A,I,g=()=>0,B=1/0,C=xD,E=TD){this.uploadTexture_=A,this.disposeTexture_=I,this.getGpuResidentBytes_=g,this.memoryLimitBytes_=B,this.maxGpuUploadsPerUpdate_=Math.max(1,E),this.queue_=new HD(C)}get memoryLimitBytes(){return this.memoryLimitBytes_}set memoryLimitBytes(A){this.memoryLimitBytes_=A}get queueStats(){return{pending:this.queue_.pendingCount,running:this.queue_.runningCount}}get memoryStats(){return lD()}addView(A,I){let g=this.stores_.find(B=>B.source===A)?.store;return g||(g=new mD(A.loader.getSourceDimensionMap()),this.stores_.push({source:A,store:g})),g.addView(I)}update(){const A=[];for(const{source:I,store:g}of this.stores_){const B=g.updateAndCollectChunkChanges();for(const C of B)C.priority===null?this.releaseChunk(C):(C.releasedAt=void 0,C.state==="queued"&&A.push({source:I,chunk:C}));this.uploadLoadedChunks(B)}this.enqueueWithinBudget(A),this.queue_.flush();for(let I=this.stores_.length-1;I>=0;I--)this.stores_[I].store.canDispose()&&this.stores_.splice(I,1)}releaseChunk(A){if(this.queue_.cancel(A),A.texture!==void 0){A.releasedAt??=performance.now();return}OE(A),A.state==="loaded"&&(A.state="unloaded")}enqueueWithinBudget(A){if(A.length===0)return;A.sort((B,C)=>sB(B.chunk,C.chunk));let I=this.getGpuResidentBytes_(),g=null;for(const{source:B,chunk:C}of A){const E=this.chunkBytes(B,C);E>this.memoryLimitBytes_||(I+E>this.memoryLimitBytes_&&(g??=this.evictionCandidates(),I=this.evictWorseChunks(I,E,C,g)),!(I+E>this.memoryLimitBytes_)&&(I+=E,this.queue_.enqueue(C,i=>B.loader.loadChunkData(C,i))))}}evictionCandidates(){const A=[];for(const I of this.resident_)I.visible||A.push(I);return A.sort((I,g)=>{const B=-sB(I,g);return B!==0?B:(I.releasedAt??0)-(g.releasedAt??0)})}evictWorseChunks(A,I,g,B){for(;A+I>this.memoryLimitBytes_&&B.length>0&&sB(B[0],g)>0;){const C=B.shift();C.texture!==void 0&&(A-=BB(C.texture),this.disposeChunkTexture(C),C.state="unloaded",C.releasedAt=void 0)}return A}chunkBytes(A,I){const g=A.loader.getBytesPerElement();return I.shape.x*I.shape.y*I.shape.z*g}uploadLoadedChunks(A){if(!this.uploadTexture_)return;const I=[];for(const B of A)B.state==="loaded"&&B.texture===void 0&&I.push(B);if(I.length===0)return;I.sort(sB);const g=Math.min(I.length,this.maxGpuUploadsPerUpdate_);for(let B=0;B<g;B++){const C=I[B],E=QB.createWithChunk(C);this.uploadTexture_(E),C.texture=E,this.resident_.add(C),OE(C)}}disposeChunkTexture(A){this.disposeTexture_&&A.texture!==void 0&&(this.disposeTexture_(A.texture),A.texture=void 0,this.resident_.delete(A))}}var yB=function(Q=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(s){s.preventDefault(),B(++A%I.children.length)},!1);function g(s){return I.appendChild(s.dom),s}function B(s){for(var y=0;y<I.children.length;y++)I.children[y].style.display=y===s?"block":"none";A=s}var C=(performance||Date).now(),E=C,i=0,o=g(new yB.Panel("FPS","#0ff","#002",Q)),a=g(new yB.Panel("MS","#0f0","#020",Q));if(self.performance&&self.performance.memory)var D=g(new yB.Panel("MB","#f08","#201",Q));return B(0),{REVISION:16,dom:I,addPanel:g,showPanel:B,begin:function(){C=(performance||Date).now()},end:function(){i++;var s=(performance||Date).now();if(a.update(s-C,200),s>=E+1e3&&(o.update(i*1e3/(s-E),100),E=s,i=0,D)){var y=performance.memory;D.update(y.usedJSHeapSize/1048576,y.jsHeapSizeLimit/1048576)}return s},update:function(){C=this.end()},domElement:I,setMode:B}};yB.Panel=function(Q,A,I,g){var B=1/0,C=0,E=Math.round,i=E(window.devicePixelRatio||1),o=E(80*i*g),a=E(48*i*g),D=E(3*i*g),s=E(2*i*g),y=E(3*i*g),F=E(15*i*g),Y=E(74*i*g),p=E(30*i*g),H=document.createElement("canvas");H.width=o,H.height=a,H.style.cssText=`width:${E(g*80)}px;height:${E(g*48)}px`;var W=H.getContext("2d");return W.font="bold "+E(9*i*g)+"px Helvetica,Arial,sans-serif",W.textBaseline="top",W.fillStyle=I,W.fillRect(0,0,o,a),W.fillStyle=A,W.fillText(Q,D,s),W.fillRect(y,F,Y,p),W.fillStyle=I,W.globalAlpha=.9,W.fillRect(y,F,Y,p),{dom:H,update:function(z,x){B=Math.min(B,z),C=Math.max(C,z),W.fillStyle=I,W.globalAlpha=1,W.fillRect(0,0,o,F),W.fillStyle=A,W.fillText(E(z)+" "+Q+" ("+E(B)+"-"+E(C)+")",D,s),W.drawImage(H,y+i,F,Y-i,p,y,F,Y-i,p),W.fillRect(y+Y-i,F,i,p),W.fillStyle=I,W.globalAlpha=.9,W.fillRect(y+Y-i,F,i,E((1-z/x)*p))}}};function bD({scale:Q}={scale:1.5}){const A=new yB(Q);return A.showPanel(0),document.body.appendChild(A.dom),A}const _Q=["pointerdown","pointermove","pointerup","pointercancel","wheel"];function ZD(Q){return _Q.includes(Q)}class PD{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 VD{listeners_=[];element_;isConnected_=!1;constructor(A){this.element_=A}addEventListener(A){this.listeners_.push(A)}connect(){if(this.isConnected_){gA.warn("EventDispatcher","Attempted to connect already connected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!0,_Q.forEach(A=>{this.element_.addEventListener(A,this.handleEvent,{passive:!1})})}disconnect(){if(!this.isConnected_){gA.debug("EventDispatcher","Attempted to disconnect already disconnected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!1,_Q.forEach(A=>{this.element_.removeEventListener(A,this.handleEvent)})}handleEvent=A=>{if(!ZD(A.type)){gA.error("EventDispatcher",`Unsupported event type ${A.type}`);return}const I=new PD(A.type,A);for(const g of this.listeners_)if(g(I),I.propagationStopped)break}}class OD{id;element;camera;events;cameraControls;context_;layers_=[];constructor(A){this.id=A.id,this.element=A.element,this.camera=A.camera,this.context_=A.context,this.cameraControls=A.cameraControls,this.updateAspectRatio(),this.events=new VD(this.element),this.events.addEventListener(I=>{if(I.event instanceof PointerEvent||I.event instanceof WheelEvent){const{clientX:g,clientY:B}=I.event,C=xA(g,B);I.clipPos=this.clientToClip(C,0),I.worldPos=this.camera.clipToWorld(I.clipPos)}for(const g of this.layers_)if(g.onEvent(I),I.propagationStopped)return;this.cameraControls?.onEvent(I)});for(const I of A.layers??[])this.addLayer(I)}get layers(){return this.layers_}addLayer(A){A.onAttached(this.context_),this.layers_.push(A)}removeLayer(A){const I=this.layers_.indexOf(A);if(I===-1)throw new Error(`Layer to remove not found: ${A}`);this.layers_.splice(I,1),A.onDetached(this.context_)}removeAllLayers(){for(const A of this.layers_)A.onDetached(this.context_);this.layers_=[]}updateSize(){this.updateAspectRatio()}getBoxRelativeTo(A){const I=this.getBox().toRect(),g=A.getBoundingClientRect(),B=window.devicePixelRatio||1,C=g.left*B,E=g.top*B,i=g.height*B,o=I.x-C,a=I.y-E,D=Math.floor(o),s=Math.floor(i-a-I.height),y=Math.floor(I.width),F=Math.floor(I.height);return new QI(xA(D,s),xA(D+y,s+F))}getBufferRect(){return this.getBoxRelativeTo(this.element).toRect()}clientToClip(A,I=0){const[g,B]=A,C=this.element.getBoundingClientRect();return nA(2*(g-C.x)/C.width-1,2*(B-C.y)/C.height-1,I)}clientToWorld(A,I=0){const g=this.clientToClip(A,I);return this.camera.clipToWorld(g)}getBox(){const A=this.element.getBoundingClientRect(),I=window.devicePixelRatio||1,g=A.left*I,B=A.top*I,C=A.width*I,E=A.height*I;return new QI(xA(g,B),xA(g+C,B+E))}updateAspectRatio(){const{width:A,height:I}=this.getBox().toRect();if(A<=0||I<=0){gA.debug("Viewport",`Skipping aspect ratio update for viewport ${this.id}: invalid dimensions ${A}x${I}`);return}const g=A/I;this.camera.setAspectRatio(g)}}function jE(Q,A){for(const I of A){if(I.id===Q.id)throw new Error(`Duplicate viewport ID "${Q.id}". Each viewport must have a unique ID.`);if(I.element===Q.element){const g=Q.element.tagName.toLowerCase()+(Q.element.id?`#${Q.element.id}`:"[element has no id]");throw new Error(`Multiple viewports cannot share the same HTML element: viewports "${I.id}" and "${Q.id}" both use ${g}`)}}}function vD(Q){for(let A=0;A<Q.length;A++)jE(Q[A],Q.slice(0,A))}function zE(Q,A,I){const g=Q.map(B=>{const C=B.element??A;return{...B,element:C,id:B.id??C.id??jC("viewport"),context:I}});return vD(g),g.map(B=>new OD(B))}class XD{elements_;resizeObserver_;mediaQuery_;onMediaQueryChange_;onChange_;constructor(A=[],I){this.elements_=[...A],this.onChange_=I}connect(){if(this.resizeObserver_){gA.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_){gA.warn("PixelSizeObserver","Attempted to disconnect already disconnected observer");return}this.resizeObserver_?.disconnect(),this.mediaQuery_&&this.onMediaQueryChange_&&this.mediaQuery_.removeEventListener("change",this.onMediaQueryChange_)}observe(A){if(this.elements_.includes(A)){gA.warn("PixelSizeObserver","Element already being observed");return}this.elements_.push(A),this.resizeObserver_&&this.resizeObserver_.observe(A)}unobserve(A){const I=this.elements_.indexOf(A);if(I===-1){gA.warn("PixelSizeObserver","Element not being observed");return}this.elements_.splice(I,1),this.resizeObserver_&&this.resizeObserver_.unobserve(A)}}const jD=2048;class $Q{chunkManager_;context_;renderer_;viewports_;canvas;overlays;stats_;sizeObserver_;lastAnimationId_;lastTimestamp_=0;static async create(A){const I=A.renderer==="webgpu-experimental"?await KD(A.canvas):new oE(A.canvas);return new $Q(A,I)}constructor(A,I){this.canvas=A.canvas,this.renderer_=I??new oE(this.canvas);const B=(A.memoryLimitMB??jD)*1024*1024;this.chunkManager_=new WD(E=>this.renderer_.uploadTexture(E),E=>this.renderer_.disposeTexture(E),()=>this.renderer_.gpuTextureBytes,B,A.maxConcurrentRequests,A.maxGpuUploadsPerUpdate),this.context_={chunkManager:this.chunkManager_},this.viewports_=zE(A.viewports??[],this.canvas,this.context_),this.overlays=[...A.overlays??[]],A.showStats&&(this.stats_=bD());const C=[this.canvas];for(const E of this.viewports_)E.element!==this.canvas&&C.push(E.element);this.sizeObserver_=new XD(C,()=>{this.renderer_.updateSize(),this.renderer_.beginFrame();for(const E of this.viewports_)E.updateSize(),this.renderer_.render(E)})}get chunkQueueStats(){return this.chunkManager_.queueStats}get memoryStats(){const A=performance.memory;return{...this.chunkManager_.memoryStats,gpuTextureBytes:this.renderer_.gpuTextureBytes,gpuTextureCount:this.renderer_.gpuTextureCount,jsHeapUsedBytes:A?.usedJSHeapSize,jsHeapLimitBytes:A?.jsHeapSizeLimit}}get renderedObjects(){return this.renderer_.renderedObjects}get width(){return this.renderer_.width}get height(){return this.renderer_.height}get viewports(){return this.viewports_}get running(){return this.lastAnimationId_!==void 0}getViewport(A){return this.viewports_.find(I=>I.id===A)}addViewport(A){const[I]=zE([A],this.canvas,this.context_);return jE(I,this.viewports_),this.viewports_.push(I),this.running&&(I.events.connect(),I.element!==this.canvas&&this.sizeObserver_.observe(I.element)),gA.info("Idetik",`Added viewport "${I.id}"`),I}removeViewport(A){const I=this.viewports_.indexOf(A);return I===-1?(gA.warn("Idetik",`Viewport "${A.id}" not found, nothing to remove`),!1):(this.running&&(A.events.disconnect(),A.element!==this.canvas&&this.sizeObserver_.unobserve(A.element)),this.viewports_.splice(I,1),gA.info("Idetik",`Removed viewport "${A.id}"`),!0)}addOverlay(A){this.overlays.push(A)}removeOverlay(A){const I=this.overlays.indexOf(A);return I===-1?(gA.warn("Idetik","Overlay not found, nothing to remove"),!1):(this.overlays.splice(I,1),!0)}setMemoryLimitMB(A){this.chunkManager_.memoryLimitBytes=A*1024*1024}start(){if(gA.info("Idetik","Idetik runtime starting"),this.running)gA.warn("Idetik","Idetik runtime already started");else{for(const A of this.viewports_)A.events.connect();this.sizeObserver_.connect(),this.lastAnimationId_=requestAnimationFrame(A=>{this.lastTimestamp_=A,this.animate(A)})}return this}animate(A){this.stats_&&this.stats_.begin();const I=Math.min(A-this.lastTimestamp_,100)/1e3;this.lastTimestamp_=A,this.renderer_.beginFrame();for(const g of this.viewports_)g.cameraControls?.onUpdate(I),this.renderer_.render(g);this.chunkManager_.update();for(const g of this.overlays)g.update(this);this.stats_&&this.stats_.end(),this.lastAnimationId_=requestAnimationFrame(g=>this.animate(g))}stop(){if(gA.info("Idetik","Idetik runtime stopping"),!this.running)gA.warn("Idetik","Idetik runtime not started");else{this.sizeObserver_.disconnect();for(const A of this.viewports_)A.events.disconnect();cancelAnimationFrame(this.lastAnimationId_),this.lastAnimationId_=void 0}}}function zD(Q,A){return{...Q,...A,headers:{...Q.headers,...A.headers}}}function _E(Q,A){const I=typeof Q=="string"?new URL(Q):Q;I.pathname.endsWith("/")||(I.pathname+="/");const g=new URL(A.slice(1),I);return g.search=I.search,g}async function $E(Q){if(Q.status!==404){if(Q.status===200||Q.status===206)return new Uint8Array(await Q.arrayBuffer());throw new Error(`Unexpected response status ${Q.status} ${Q.statusText}`)}}class tB{url;#A;#I;#g;constructor(A,I={}){this.url=A,this.#A=I.fetch??(g=>fetch(g)),this.#I=I.overrides??{},this.#g=I.useSuffixRequest??!1}#B(A,I){return new Request(A,zD(this.#I,I))}async get(A,I={}){let g=_E(this.url,A).href,B=this.#B(g,I),C=await this.#A(B);return $E(C)}async getRange(A,I,g={}){let B=_E(this.url,A),C;if("suffixLength"in I)C=await this.#Q(B,I.suffixLength,g);else{let E={...g,headers:{...g.headers,Range:`bytes=${I.offset}-${I.offset+I.length-1}`}},i=this.#B(B,E);C=await this.#A(i)}return $E(C)}async#Q(A,I,g){if(this.#g){let D={...g,headers:{...g.headers,Range:`bytes=-${I}`}};return this.#A(this.#B(A,D))}let B=this.#B(A,{...g,method:"HEAD"}),C=await this.#A(B);if(!C.ok)return C;let E=C.headers.get("Content-Length"),i=Number(E),o=i-I,a={...g,headers:{...g.headers,Range:`bytes=${o}-${i-1}`}};return this.#A(this.#B(A,a))}}class GB extends Error{}class Yg extends GB{_tag="NotFoundError";name="NotFoundError";path;found;constructor(A,I={}){super(`Not found: ${A}`,{cause:I.cause}),this.path=I.path,this.found=I.found}}class WA extends GB{_tag="InvalidMetadataError";name="InvalidMetadataError";path;constructor(A,I={}){super(A,{cause:I.cause}),this.path=I.path}}class _D extends GB{_tag="UnknownCodecError";name="UnknownCodecError";codec;constructor(A){super(`Unknown codec: ${A}`),this.codec=A}}class $D extends GB{_tag="CodecPipelineError";name="CodecPipelineError";direction;codec;chunkPath;constructor(A){const I=[`Failed to ${A.direction} chunk`,A.codec&&`via codec "${A.codec}"`,A.chunkPath&&`at ${A.chunkPath}`].filter(Boolean);super(I.join(" "),{cause:A.cause}),this.direction=A.direction,this.codec=A.codec,this.chunkPath=A.chunkPath}}class AC extends GB{_tag="UnsupportedError";name="UnsupportedError";feature;constructor(A){super(`Unsupported: ${A}`),this.feature=A}}function ig(Q){return()=>{throw new AC(`${Q} encode`)}}class XB{kind="array_to_array";constructor(A,I){if(A.keepbits<0)throw new WA("keepbits must be zero or positive")}static fromConfig(A,I){return new XB(A,I)}encode=ig("bitround");decode(A){return A}}function IC(Q){return Q instanceof ArrayBuffer||Q instanceof SharedArrayBuffer}class Ai{#A;constructor(A,I,g){typeof A=="number"?this.#A=new Uint8Array(A):IC(A)?this.#A=new Uint8Array(A,I,g):this.#A=new Uint8Array(Array.from(A,B=>B?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 gC{_data;chars;#A;constructor(A,I,g,B){if(this.chars=A,this.#A=new TextEncoder,typeof I=="number")this._data=new Uint8Array(I*A);else if(IC(I))B&&(B=B*A),this._data=new Uint8Array(I,g,B);else{let C=Array.from(I);this._data=new Uint8Array(C.length*A);for(let E=0;E<C.length;E++)this.set(E,C[E])}}get BYTES_PER_ELEMENT(){return this.chars}get byteOffset(){return this._data.byteOffset}get byteLength(){return this._data.byteLength}get buffer(){return this._data.buffer}get length(){return this.byteLength/this.BYTES_PER_ELEMENT}get(A){const I=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);return new TextDecoder().decode(I).replace(/\x00/g,"")}set(A,I){const g=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);g.fill(0),g.set(this.#A.encode(I))}fill(A){const I=this.#A.encode(A);for(let g=0;g<this.length;g++)this._data.set(I,g*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class wB{#A;chars;constructor(A,I,g,B){if(this.chars=A,typeof I=="number")this.#A=new Int32Array(I*A);else if(IC(I))B&&(B*=A),this.#A=new Int32Array(I,g,B);else{const C=I,E=new wB(A,1);this.#A=new Int32Array((function*(){for(let i of C)E.set(0,i),yield*E.#A})())}}get BYTES_PER_ELEMENT(){return this.#A.BYTES_PER_ELEMENT*this.chars}get byteLength(){return this.#A.byteLength}get byteOffset(){return this.#A.byteOffset}get buffer(){return this.#A.buffer}get length(){return this.#A.length/this.chars}get(A){const I=this.chars*A;let g="";for(let B=0;B<this.chars;B++)g+=String.fromCodePoint(this.#A[I+B]);return g.replace(/\u0000/g,"")}set(A,I){const g=this.chars*A,B=this.#A.subarray(g,g+this.chars);B.fill(0);for(let C=0;C<this.chars;C++)B[C]=I.codePointAt(C)??0}fill(A){this.set(0,A);let I=this.#A.subarray(0,this.chars);for(let g=1;g<this.length;g++)this.#A.set(I,g*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}function As(){if(typeof SharedArrayBuffer>"u")throw new Error("SharedArrayBuffer is not available. In browsers, this requires Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers to be set.")}function Is(Q,A){return new SharedArrayBuffer(Q)}function eB(Q){const A=new TextDecoder().decode(Q);try{return JSON.parse(A)}catch(I){throw new WA("Failed to decode JSON",{cause:I})}}function Ii(Q,A){const I=A/2,g=A-1;let B=0;for(let C=0;C<Q.length;C+=A)for(let E=0;E<I;E+=1)B=Q[C+E],Q[C+E]=Q[C+g-E],Q[C+g-E]=B}function Kg(Q){if(Q==="v2:object")return globalThis.Array;let A=Q.match(/v2:([US])(\d+)/);if(A){let[,g,B]=A;return(g==="U"?wB:gC).bind(null,Number(B))}if(Q==="string")return globalThis.Array;let I={int8:Int8Array,int16:Int16Array,int32:Int32Array,int64:globalThis.BigInt64Array,uint8:Uint8Array,uint16:Uint16Array,uint32:Uint32Array,uint64:globalThis.BigUint64Array,float16:globalThis.Float16Array,float32:Float32Array,float64:Float64Array,bool:Ai}[Q];if(!I)throw new WA(`Unknown or unsupported dataType: ${Q}`);return I}function og(Q,A){const I=Q.length;typeof A=="string"&&(A=A==="C"?Array.from({length:I},(C,E)=>E):Array.from({length:I},(C,E)=>I-1-E)),yI(I===A.length,"Order length must match the number of dimensions.");let g=1,B=new Array(I);for(let C=A.length-1;C>=0;C--)B[A[C]]=g,g*=Q[A[C]];return B}function gs({name:Q,configuration:A}){if(Q==="default"){const I=A?.separator??"/";return g=>["c",...g].join(I)}if(Q==="v2"){const I=A?.separator??".";return g=>g.join(I)||"0"}throw new WA(`Unknown chunk key encoding: ${Q}`)}function gi(Q){if(Q==="|O")return{dataType:"v2:object"};let A=Q.match(/^([<|>])(.*)$/);if(!A)throw new WA(`Invalid dtype: ${Q}`);let[,I,g]=A,B={b1:"bool",i1:"int8",u1:"uint8",i2:"int16",u2:"uint16",i4:"int32",u4:"uint32",i8:"int64",u8:"uint64",f2:"float16",f4:"float32",f8:"float64"}[g]??(g.startsWith("S")||g.startsWith("U")?`v2:${g}`:void 0);if(!B)throw new WA(`Unsupported or unknown dtype: ${Q}`);return I==="|"?{dataType:B}:{dataType:B,endian:I==="<"?"little":"big"}}function Bs(Q){return(Q.id==="fixedscaleoffset"||Q.id==="numcodecs.fixedscaleoffset")&&typeof Q.scale=="number"&&typeof Q.offset=="number"&&(Q.astype===void 0||typeof Q.astype=="string")&&(Q.dtype===void 0||typeof Q.dtype=="string")}function Qs(Q,A={}){let I=[],g=gi(Q.dtype);Q.order==="F"&&I.push({name:"transpose",configuration:{order:"F"}});for(let C of Q.filters??[]){if(C.id==="fixedscaleoffset"||C.id==="numcodecs.fixedscaleoffset"){if(!Bs(C))throw new WA(`Invalid fixedscaleoffset filter: ${JSON.stringify(C)}`);I.push({name:"scale_offset",configuration:{scale:C.scale,offset:C.offset}});let o=C.astype??C.dtype;if(o!==void 0&&o!==Q.dtype){let a=gi(o).dataType;if(!BC(a,"number")&&!BC(a,"bigint"))throw new WA(`fixedscaleoffset astype must be a numeric data type, got ${o}`);I.push({name:"cast_value",configuration:{data_type:a,rounding:"nearest-even",out_of_range:"wrap"}})}continue}let{id:E,...i}=C;I.push({name:`numcodecs.${E}`,configuration:i})}if("endian"in g&&g.endian==="big"&&I.push({name:"bytes",configuration:{endian:"big"}}),Q.compressor){let{id:C,...E}=Q.compressor;I.push({name:`numcodecs.${C}`,configuration:E})}let B;return globalThis.Array.isArray(A._ARRAY_DIMENSIONS)&&(B=A._ARRAY_DIMENSIONS),{zarr_format:3,node_type:"array",shape:Q.shape,data_type:g.dataType,chunk_grid:{name:"regular",configuration:{chunk_shape:Q.chunks}},chunk_key_encoding:{name:"v2",configuration:{separator:Q.dimension_separator??"."}},codecs:I,fill_value:Q.fill_value,dimension_names:B,attributes:A}}function Cs(Q,A={}){return{zarr_format:3,node_type:"group",attributes:A}}function BC(Q,A){if(A!=="number"&&A!=="bigint"&&A!=="boolean"&&A!=="object"&&A!=="string")return Q===A;let I=Q==="bool";if(A==="boolean")return I;let g=Q.startsWith("v2:U")||Q.startsWith("v2:S")||Q==="string";if(A==="string")return g;let B=Q==="int64"||Q==="uint64";if(A==="bigint")return B;let C=Q==="v2:object";return A==="object"?C:!g&&!B&&!I&&!C}function Es(Q){return Q?.name==="sharding_indexed"}function Bi(Q){if((Q.data_type==="uint64"||Q.data_type==="int64")&&Q.fill_value!=null)return BigInt(Q.fill_value);let A=Q.data_type==="float16"||Q.data_type==="float32"||Q.data_type==="float64";if(typeof Q.fill_value=="string"&&A){let I={NaN:NaN,Infinity:1/0,"-Infinity":-1/0};if(Q.fill_value in I)return I[Q.fill_value]}return Q.fill_value}function Qi(Q,...A){if(!A.some(I=>Q instanceof I))throw Q}function yI(Q,A=""){if(!Q)throw new Error(A)}async function Ci(Q,{format:A,signal:I}){let g;if(Q instanceof ArrayBuffer)g=new Response(Q);else{let B=new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength);g=new Response(B.slice().buffer)}yI(g.body,"Response does not contain body.");try{return await new Response(g.body.pipeThrough(new DecompressionStream(A),{signal:I})).arrayBuffer()}catch{throw I?.throwIfAborted(),new Error(`Failed to decode ${A}`)}}const Ei=is();function is(){const Q=new Uint32Array([305419896]);return new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength)[0]!==18}function ii(Q){return"BYTES_PER_ELEMENT"in Q?Q.BYTES_PER_ELEMENT:4}class jB{kind="array_to_bytes";#A;#I;#g;#B;#Q;constructor(A,I){this.#Q=A?.endian,this.#I=Kg(I.dataType),this.#B=I.shape,this.#A=og(I.shape,"C");const g=new this.#I(0);this.#g=g.BYTES_PER_ELEMENT}static fromConfig(A,I){return new jB(A,I)}encode(A){let I=new Uint8Array(A.data.buffer);return Ei&&this.#Q==="big"&&Ii(I,ii(this.#I)),I}computeEncodedSize(A){return A}decode(A){return Ei&&this.#Q==="big"&&Ii(A,ii(this.#I)),{data:new this.#I(A.buffer,A.byteOffset,A.byteLength/this.#g),shape:this.#B,stride:this.#A}}}const oi={NaN:NaN,Infinity:1/0,"-Infinity":-1/0},ai={float16:2,float32:4,float64:8};function zB(Q){return Q in ai}function QC(Q){return Q==="int64"||Q==="uint64"}function os(Q,A){const I=BigInt(Q),g=new ArrayBuffer(A),B=new DataView(g);if(A===2){if(typeof B.getFloat16!="function")throw new AC("float16 hex-encoded scalar decoding (requires DataView.prototype.getFloat16)");return B.setUint16(0,Number(I)),B.getFloat16(0)}return A===4?(B.setUint32(0,Number(I)),B.getFloat32(0)):(B.setBigUint64(0,I),B.getFloat64(0))}function _B(Q,A){if(QC(Q)){if(typeof A!="number"||!Number.isInteger(A))throw new WA(`Expected an integer value for data type "${Q}", got ${JSON.stringify(A)}`);return BigInt(A)}if(typeof A=="number"){if(!zB(Q)&&!Number.isInteger(A))throw new WA(`Expected an integer value for data type "${Q}", got ${A}`);return A}if(!zB(Q))throw new WA(`String-encoded scalar "${A}" is not valid for non-float data type "${Q}"`);return A in oi?oi[A]:os(A,ai[Q])}const Di=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]),CC={int8:[-128,2**7-1],uint8:[0,2**8-1],int16:[-32768,2**15-1],uint16:[0,2**16-1],int32:[-2147483648,2**31-1],uint32:[0,2**32-1]},EC={int64:[-(2n**63n),2n**63n-1n],uint64:[0n,2n**64n-1n]};function si(Q,A,I){return Q.map(([g,B])=>({src:_B(A,g),tgt:_B(I,B)}))}function as(Q,A){for(const I of A)if(typeof I.src=="number"&&Number.isNaN(I.src)){if(typeof Q=="number"&&Number.isNaN(Q))return I.tgt}else if(Q===I.src)return I.tgt}function Ds(Q){if(!Number.isFinite(Q))return Q;if(Math.abs(Q-Math.trunc(Q))===.5){const A=Math.floor(Q),I=Math.ceil(Q);return A%2===0?A:I}return Math.round(Q)}function ss(Q){return Math.sign(Q)*Math.floor(Math.abs(Q)+.5)}function hi(Q){switch(Q){case"nearest-even":return Ds;case"towards-zero":return Math.trunc;case"towards-positive":return Math.ceil;case"towards-negative":return Math.floor;case"nearest-away":return ss}}function iC(Q,A,I){const g=A-Q+1;switch(I){case"clamp":return B=>B<Q?Q:B>A?A:B;case"wrap":return B=>B>=Q&&B<=A?B:((B-Q)%g+g)%g+Q;default:return B=>{if(B>=Q&&B<=A)return B;throw new Error(`Value ${B} out of range [${Q}, ${A}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}function oC(Q,A,I){const g=A-Q+1n;switch(I){case"clamp":return B=>B<Q?Q:B>A?A:B;case"wrap":return B=>B>=Q&&B<=A?B:((B-Q)%g+g)%g+Q;default:return B=>{if(B>=Q&&B<=A)return B;throw new Error(`Value ${B} out of range [${Q}, ${A}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}class aC{kind="array_to_array";#A;#I;#g;#B;constructor(A,I,g,B,C,E){this.#A=I,this.#I=Kg(A),this.#g=yi(I,A,g,B,C),this.#B=yi(A,I,g,B,E)}getEncodedMeta(A){let I=A.fillValue;return I!=null&&(I=this.#B(I)),{...A,dataType:this.#A,fillValue:I}}static fromConfig(A,I){const g=I.dataType,B=A.data_type;if(!Di.has(g))throw new WA(`cast_value codec does not support array data type: ${g}`);if(!Di.has(B))throw new WA(`cast_value codec does not support encoded data type: ${B}`);const C=A.rounding??"nearest-even",E=A.scalar_map?.decode?si(A.scalar_map.decode,B,g):[],i=A.scalar_map?.encode?si(A.scalar_map.encode,g,B):[];return new aC(g,B,C,A.out_of_range,E,i)}encode=ig("cast_value");decode(A){const I=A.data,g=new this.#I(I.length);for(let B=0;B<I.length;B++)g[B]=this.#g(I[B]);return{data:g,shape:A.shape,stride:A.stride}}}function yi(Q,A,I,g,B){const C=zB(Q),E=QC(Q),i=zB(A),o=QC(A);let a;if(C&&i){if(I!=="nearest-even")throw new WA(`cast_value float -> float only supports "nearest-even" rounding, got "${I}"`);a=s=>s}else if(C&&!i&&!o){const s=hi(I),y=iC(...CC[A],g);a=F=>{if(!Number.isFinite(F))throw new Error(`Cannot cast ${F} to integer type without scalar_map`);return y(s(F))}}else if(C&&o){const s=hi(I),y=oC(...EC[A],g);a=F=>{if(!Number.isFinite(F))throw new Error(`Cannot cast ${F} to integer type without scalar_map`);return y(BigInt(s(F)))}}else if(!C&&!E&&i)a=s=>s;else if(E&&i)a=s=>Number(s);else if(!C&&!E&&!i&&!o)a=iC(...CC[A],g);else if(!C&&!E&&o){const s=oC(...EC[A],g);a=y=>s(BigInt(y))}else if(E&&!i&&!o){const s=iC(...CC[A],g);a=y=>s(Number(y))}else if(E&&o)a=oC(...EC[A],g);else throw new Error(`Unhandled type combination: ${Q} -> ${A}`);return B.length===0?a:s=>{const y=as(s,B);return y!==void 0?y:a(s)}}class DC{kind="bytes_to_bytes";static fromConfig(){return new DC}encode=ig("crc32c");decode(A){return new Uint8Array(A.buffer,A.byteOffset,A.byteLength-4)}computeEncodedSize(A){return A+4}}const hs=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);function ti(Q,A){const I=Q.length;let g=I===0||A[I-1]===1;for(let C=I-2;C>=0&&g;C--)g=A[C]===A[C+1]*Q[C+1];if(g)return;let B=I===0||A[0]===1;for(let C=1;C<I&&B;C++)B=A[C]===A[C-1]*Q[C-1];if(!B)throw new Error(`DeltaCodec requires C- or Fortran-contiguous strides, got shape=${JSON.stringify(Q)} stride=${JSON.stringify(A)}`)}class sC{kind="array_to_array";#A;constructor(A){this.#A=A}static fromConfig(A,I){if(!hs.has(I.dataType))throw new WA(`Delta codec does not support data type: ${I.dataType}`);return new sC(Kg(I.dataType))}encode(A){ti(A.shape,A.stride);const I=A.data,g=new this.#A(I.length);g[0]=I[0];for(let B=1;B<I.length;B++)g[B]=I[B]-I[B-1];return{data:g,shape:A.shape,stride:A.stride}}decode(A){ti(A.shape,A.stride);const I=A.data,g=new this.#A(I.length);g[0]=I[0];for(let B=1;B<I.length;B++)g[B]=g[B-1]+I[B];return{data:g,shape:A.shape,stride:A.stride}}}class hC{kind="bytes_to_bytes";static fromConfig(A){return new hC}encode=ig("gzip");async decode(A){const I=await Ci(A,{format:"gzip"});return new Uint8Array(I)}}function ys(Q,A){return yI(!Number.isNaN(A),"JsonCodec allow_nan is false but NaN was encountered during encoding."),yI(A!==Number.POSITIVE_INFINITY,"JsonCodec allow_nan is false but Infinity was encountered during encoding."),yI(A!==Number.NEGATIVE_INFINITY,"JsonCodec allow_nan is false but -Infinity was encountered during encoding."),A}function ts(Q,A){return A instanceof Object&&!Array.isArray(A)?Object.keys(A).sort().reduce((I,g)=>(I[g]=A[g],I),{}):A}class $B{configuration;kind="array_to_bytes";#A;#I;constructor(A={}){this.configuration=A;const{encoding:I="utf-8",skipkeys:g=!1,ensure_ascii:B=!0,check_circular:C=!0,allow_nan:E=!0,sort_keys:i=!0,indent:o,strict:a=!0}=A;let D=A.separators;D||(o?D=[", ",": "]:D=[",",":"]),this.#A={encoding:I,skipkeys:g,ensure_ascii:B,check_circular:C,allow_nan:E,indent:o,separators:D,sort_keys:i},this.#I={strict:a}}static fromConfig(A){return new $B(A)}encode(A){const{indent:I,encoding:g,ensure_ascii:B,check_circular:C,allow_nan:E,sort_keys:i}=this.#A;yI(g==="utf-8","JsonCodec does not yet support non-utf-8 encoding.");const o=[];yI(C,"JsonCodec does not yet support skipping the check for circular references during encoding."),E||o.push(ys),i&&o.push(ts);const a=Array.from(A.data);a.push("|O"),a.push(A.shape);let D;o.length&&(D=(y,F)=>{let Y=F;for(let p of o)Y=p(y,Y);return Y});let s=JSON.stringify(a,D,I);return B&&(s=s.replace(/[\u007F-\uFFFF]/g,y=>{const F=`0000${y.charCodeAt(0).toString(16)}`;return`\\u${F.substring(F.length-4)}`})),new TextEncoder().encode(s)}decode(A){const{strict:I}=this.#I;yI(I,"JsonCodec does not yet support non-strict decoding.");const g=eB(A),B=g.pop();g.pop(),yI(B,"0D not implemented for JsonCodec.");const C=og(B,"C");return{data:g,shape:B,stride:C}}}const Gs=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);class yC{kind="array_to_array";#A;#I;#g;constructor(A,I,g){this.#I=A,this.#g=I,this.#A=g}static fromConfig(A,I){if(!Gs.has(I.dataType))throw new WA(`scale_offset codec does not support data type: ${I.dataType}`);return new yC(_B(I.dataType,A.scale??1),_B(I.dataType,A.offset??0),Kg(I.dataType))}encode=ig("scale_offset");decode(A){const I=A.data,g=new this.#A(I.length);for(let B=0;B<I.length;B++)g[B]=I[B]/this.#I+this.#g;return{data:g,shape:A.shape,stride:A.stride}}}class tC{kind="bytes_to_bytes";#A;constructor(A,I){if(I){let g=new(Kg(I.dataType))(0);yI("BYTES_PER_ELEMENT"in g,`Shuffle codec requires a fixed-size dtype, got "${I.dataType}"`),this.#A=g.BYTES_PER_ELEMENT}else this.#A=A.elementsize??4}static fromConfig(A,I){return new tC(A,I)}encode(A){return ws(A,this.#A)}decode(A){return es(A,this.#A)}}function ws(Q,A){let I=Q.length,g=Math.floor(I/A),B=new Uint8Array(I);for(let C=0;C<A;C++)for(let E=0;E<g;E++)B[C*g+E]=Q[E*A+C];return B}function es(Q,A){let I=Q.length,g=Math.floor(I/A),B=new Uint8Array(I);for(let C=0;C<A;C++)for(let E=0;E<g;E++)B[E*A+C]=Q[C*g+E];return B}function Gi(Q){return Q instanceof Ai||Q instanceof gC||Q instanceof wB?new Proxy(Q,{get(I,g){return I.get(Number(g))},set(I,g,B){return I.set(Number(g),B),!0}}):Q}function Fs(Q,A){let I;return Q.data instanceof gC||Q.data instanceof wB?I=new Q.constructor(Q.data.length,Q.data.chars):I=new Q.constructor(Q.data.length),{data:I,shape:Q.shape,stride:og(Q.shape,A)}}function rs(Q,A){let I=Fs(Q,A),g=Q.shape.length,B=Q.data.length,C=Array(g).fill(0),E=Gi(Q.data),i=Gi(I.data);for(let o=0;o<B;o++){let a=0;for(let D=0;D<g;D++)a+=C[D]*I.stride[D];i[a]=E[o],C[0]+=1;for(let D=0;D<g;D++)if(C[D]===Q.shape[D]){if(D+1===g)break;C[D]=0,C[D+1]+=1}}return I}function ns(Q){let A=Q.shape.length;return yI(A===Q.stride.length,"Shape and stride must have the same length."),Q.stride.map((I,g)=>({stride:I,index:g})).sort((I,g)=>g.stride-I.stride).map(I=>I.index)}function Ss(Q,A){let I=ns(Q);return yI(I.length===A.length,"Orders must match"),I.every((g,B)=>g===A[B])}class GC{kind="array_to_array";#A;#I;constructor(A,I){let g=A.order??"C",B=I.shape.length,C=new Array(B),E=new Array(B);if(g==="C")for(let i=0;i<B;++i)C[i]=i,E[i]=i;else if(g==="F")for(let i=0;i<B;++i)C[i]=B-i-1,E[i]=B-i-1;else C=g,C.forEach((i,o)=>{yI(E[i]===void 0,`Invalid permutation: ${JSON.stringify(g)}`),E[i]=o});this.#A=C,this.#I=E}static fromConfig(A,I){return new GC(A,I)}encode(A){return Ss(A,this.#I)?A:rs(A,this.#I)}decode(A){return{data:A.data,shape:A.shape,stride:og(A.shape,this.#A)}}}class AQ{kind="array_to_bytes";#A;#I;constructor(A){this.#A=A,this.#I=og(A,"C")}static fromConfig(A,I){return new AQ(I.shape)}encode=ig("vlen-utf8");decode(A){let I=new TextDecoder,g=new DataView(A.buffer),B=Array(g.getUint32(0,!0)),C=4;for(let E=0;E<B.length;E++){let i=g.getUint32(C,!0);C+=4,B[E]=I.decode(A.buffer.slice(C,C+i)),C+=i}return{data:B,shape:this.#A,stride:this.#I}}}class wC{kind="bytes_to_bytes";static fromConfig(A){return new wC}encode=ig("zlib");async decode(A){const I=await Ci(A,{format:"deflate"});return new Uint8Array(I)}}function Ns(){let Q=()=>Promise.resolve().then(()=>py).then(C=>C.default),A=()=>Promise.resolve().then(()=>by).then(C=>C.default),I=()=>Promise.resolve().then(()=>Xy).then(C=>C.default),g=()=>hC,B=()=>wC;return new Map().set("blosc",Q).set("lz4",A).set("zstd",I).set("gzip",g).set("zlib",B).set("transpose",()=>GC).set("bytes",()=>jB).set("crc32c",()=>DC).set("vlen-utf8",()=>AQ).set("json2",()=>$B).set("bitround",()=>XB).set("cast_value",()=>aC).set("scale_offset",()=>yC).set("numcodecs.blosc",Q).set("numcodecs.lz4",A).set("numcodecs.zstd",I).set("numcodecs.gzip",g).set("numcodecs.zlib",B).set("numcodecs.vlen-utf8",()=>AQ).set("numcodecs.shuffle",()=>tC).set("numcodecs.delta",()=>sC).set("numcodecs.bitround",()=>XB).set("numcodecs.json2",()=>$B)}const Rs=Ns();function eC(Q){let A;function I(){return A||(A=cs(Q)),A}async function g(B,C,E){try{return await E()}catch(i){throw new $D({direction:B,codec:C,cause:i})}}return{async encode(B){let C=await I();for(const{name:i,codec:o}of C.arrayToArray)B=await g("encode",i,()=>o.encode(B));let E=await g("encode",C.arrayToBytes.name,()=>C.arrayToBytes.codec.encode(B));for(const{name:i,codec:o}of C.bytesToBytes)E=await g("encode",i,()=>o.encode(E));return E},async decode(B){let C=await I();for(let i=C.bytesToBytes.length-1;i>=0;i--){const{name:o,codec:a}=C.bytesToBytes[i];B=await g("decode",o,()=>a.decode(B))}let E=await g("decode",C.arrayToBytes.name,()=>C.arrayToBytes.codec.decode(B));for(let i=C.arrayToArray.length-1;i>=0;i--){const{name:o,codec:a}=C.arrayToArray[i];E=await g("decode",o,()=>a.decode(E))}return E},async computeEncodedSize(B){let C=await I(),E=wi(C.arrayToBytes.name,C.arrayToBytes.codec,B);for(const{name:i,codec:o}of C.bytesToBytes)E=wi(i,o,E);return E}}}function wi(Q,A,I){if(!A.computeEncodedSize)throw new WA(`Codec "${Q}" cannot compute its encoded size; it is not a fixed-size codec and cannot be used in a sharding index pipeline`);return A.computeEncodedSize(I)}async function cs(Q){let A=Q.codecs.map(async E=>{let i=await Rs.get(E.name)?.();if(!i)throw new _D(E.name);return{Codec:i,meta:E}}),I=[],g,B=[],C={...Q};for await(let{Codec:E,meta:i}of A){let o=E.fromConfig(i.configuration,C);switch(o.kind){case"array_to_array":I.push({name:i.name,codec:o}),o.getEncodedMeta&&(C=o.getEncodedMeta(C));break;case"array_to_bytes":g={name:i.name,codec:o};break;default:B.push({name:i.name,codec:o})}}if(!g){if(!Us(C))throw new WA(`Cannot encode ${C.dataType} to bytes without a codec`);g={name:"bytes",codec:jB.fromConfig({endian:"little"},C)}}return{arrayToArray:I,arrayToBytes:g,bytesToBytes:B}}function Us(Q){return Q.dataType!=="v2:object"&&Q.dataType!=="string"}const ei=18446744073709551615n;function ks(Q,A,I,g){if(!Q.store.getRange)throw new AC("sharding requires a store with getRange");let B=Q.store.getRange.bind(Q.store),C=A.map((a,D)=>a/g.chunk_shape[D]),E=eC({dataType:"uint64",shape:[...C,2],codecs:g.index_codecs,fillValue:null}),i=16*C.reduce((a,D)=>a*D,1),o={};return async(a,D)=>{let s=a.map((l,Z)=>Math.floor(l/C[Z])),y=Q.resolve(I(s)).path;y in o||(o[y]=(async()=>{let l=await E.computeEncodedSize(i),Z=await B(y,{suffixLength:l},D);return Z?await E.decode(Z):null})().catch(l=>{throw delete o[y],l}));let F=await o[y];if(F===null)return;let{data:Y,shape:p,stride:H}=F,W=a.map((l,Z)=>l%p[Z]).reduce((l,Z,v)=>l+Z*H[v],0),z=Y[W],x=Y[W+1];if(!(z===ei&&x===ei))return B(y,{offset:Number(z),length:Number(x)},D)}}class FI{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 FI(this.store,decodeURIComponent(new URL(A,I).pathname))}}class FC extends FI{kind="group";#A;constructor(A,I,g){super(A,I),this.#A=g}get attrs(){return this.#A.attributes}}function Fi(Q){return Q.find(I=>I.name==="transpose")?.configuration?.order??"C"}const IQ=Symbol("zarrita.context");function Ls(Q,A){let{configuration:I}=A.codecs.find(Es)??{},g={encodeChunkKey:gs(A.chunk_key_encoding),TypedArray:Kg(A.data_type),fillValue:A.fill_value};if(I){let C=Fi(I.codecs);return{...g,kind:"sharded",chunkShape:I.chunk_shape,codec:eC({dataType:A.data_type,shape:I.chunk_shape,codecs:I.codecs,fillValue:A.fill_value}),getStrides(E){return og(E,C)},getChunkBytes:ks(Q,A.chunk_grid.configuration.chunk_shape,g.encodeChunkKey,I)}}let B=Fi(A.codecs);return{...g,kind:"regular",chunkShape:A.chunk_grid.configuration.chunk_shape,codec:eC({dataType:A.data_type,shape:A.chunk_grid.configuration.chunk_shape,codecs:A.codecs,fillValue:A.fill_value}),getStrides(C){return og(C,B)},async getChunkBytes(C,E){let i=g.encodeChunkKey(C),o=Q.resolve(i).path;return Q.store.get(o,E)}}}let gQ=class extends FI{kind="array";#A;[IQ];constructor(A,I,g){super(A,I),this.#A={...g,fill_value:Bi(g)},this[IQ]=Ls(this,this.#A)}get attrs(){return this.#A.attributes}get dimensionNames(){return this.#A.dimension_names}get fillValue(){return this.#A.fill_value}get shape(){return this.#A.shape}get chunks(){return this[IQ].chunkShape}get dtype(){return this.#A.data_type}async getChunk(A,I,g){g?.useSharedArrayBuffer&&As();let B=this[IQ],C=await B.getChunkBytes(A,I);if(!C){let E=B.chunkShape.reduce((o,a)=>o*a,1),i;if(g?.useSharedArrayBuffer){let o=new B.TypedArray(0);if(!("BYTES_PER_ELEMENT"in o))console.warn("zarrita: useSharedArrayBuffer is not supported for non-buffer-backed data types."),i=new B.TypedArray(E);else{let a=Is(E*o.BYTES_PER_ELEMENT);i=new B.TypedArray(a,0,E)}}else i=new B.TypedArray(E);return i.fill(B.fillValue),{data:i,shape:B.chunkShape,stride:B.getStrides(B.chunkShape)}}return B.codec.decode(C)}is(A){return BC(this.dtype,A)}};function Js(Q,A){let I=Q;for(let g of A)I instanceof Promise?I=I.then(B=>g(B)):I=g(I);return I}function Ys(Q,...A){return Js(Q,A)}async function ri(Q){let A=Q.store.arrayExtensions;return A?.length?await Ys(Q,...A):Q}let BQ=Ks();function Ks(){let Q=new WeakMap;function A(I){let g=Q.get(I)??{v2:0,v3:0};return Q.set(I,g),g}return{increment(I,g){A(I)[g]+=1},versionMax(I){let g=A(I);return g.v3>g.v2?"v3":"v2"}}}async function Ms(Q,A){let I=await Q.store.get(Q.resolve(".zattrs").path,{signal:A});return I?eB(I):{}}async function ds(Q,A={}){let I="store"in Q?Q:new FI(Q),{signal:g}=A,B={};return(A.attrs??!0)&&(B=await Ms(I,g)),g?.throwIfAborted(),A.kind==="array"?ni(I,B,g):A.kind==="group"?Si(I,B,g):ni(I,B,g).catch(C=>(Qi(C,Yg,WA),Si(I,B,g)))}async function ni(Q,A,I){let{path:g}=Q.resolve(".zarray"),B=await Q.store.get(g,{signal:I});if(!B)throw new Yg("v2 array",{path:g});return BQ.increment(Q.store,"v2"),ri(new gQ(Q.store,Q.path,Qs(eB(B),A)))}async function Si(Q,A,I){let{path:g}=Q.resolve(".zgroup"),B=await Q.store.get(g,{signal:I});if(!B)throw new Yg("v2 group",{path:g});return BQ.increment(Q.store,"v2"),new FC(Q.store,Q.path,Cs(eB(B),A))}async function Hs(Q,A){let{store:I,path:g}=Q.resolve("zarr.json"),B=await Q.store.get(g,{signal:A});if(!B)throw new Yg("v3 array or group",{path:g});let C=eB(B);return C.node_type==="array"&&(C.fill_value=Bi(C)),C.node_type==="array"?ri(new gQ(I,Q.path,C)):new FC(I,Q.path,C)}async function qs(Q,A={}){let I="store"in Q?Q:new FI(Q),g=await Hs(I,A.signal);if(BQ.increment(I.store,"v3"),A.kind===void 0||A.kind==="array"&&g instanceof gQ||A.kind==="group"&&g instanceof FC)return g;let B=g instanceof gQ?"array":"group";throw new Yg(`${A.kind} at ${I.path}`,{path:I.path,found:B})}async function rI(Q,A={}){let I="store"in Q?Q.store:Q,g=BQ.versionMax(I),B=g==="v2"?rI.v2:rI.v3,C=g==="v2"?rI.v3:rI.v2;return B(Q,A).catch(E=>(Qi(E,Yg,WA),C(Q,A)))}rI.v2=ds,rI.v3=qs;async function ls(Q,A){const I=A.split("/"),g=I.pop();if(!g)throw new Error("Invalid path");for(const B of I)Q=await Q.getDirectoryHandle(B);return Q.getFileHandle(g)}class rC{#A;constructor(A){this.#A=A}get directoryHandle(){return this.#A}async get(A){const I=await ls(this.#A,A.slice(1)).catch(()=>{});if(!I)return;const B=await(await I.getFile()).arrayBuffer();return new Uint8Array(B)}}async function FB(Q,A){if(A==="v2")try{return rI.v2(Q,{kind:"group",attrs:!0})}catch{throw new Error(`Failed to open Zarr v2 group at ${Q}`)}if(A==="v3")try{return rI.v3(Q,{kind:"group"})}catch{throw new Error(`Failed to open Zarr v3 group at ${Q}`)}try{return rI(Q,{kind:"group"})}catch{throw new Error(`Failed to open Zarr group at ${Q}`)}}async function fs(Q,A){if(A==="v2")try{return rI.v2(Q,{kind:"array",attrs:!1})}catch{throw new Error(`Failed to open Zarr v2 array at ${Q}`)}if(A==="v3")try{return rI.v3(Q,{kind:"array"})}catch{throw new Error(`Failed to open Zarr v3 array at ${Q}`)}try{return rI(Q,{kind:"array"})}catch{throw new Error(`Failed to open Zarr array at ${Q}`)}}async function ps(Q){let A;switch(Q.type){case"fetch":{const g=new tB(Q.url);A=new FI(g);break}case"filesystem":{A=new FI(new rC(Q.directoryHandle),Q.path);break}default:{const g=Q;throw new Error(`Unsupported store type: ${g}`)}}const I=Q.arrayPath?A.resolve(Q.arrayPath):A;return fs(I,Q.zarrVersion)}function us(Q,A,I){if(Q.store instanceof tB)return{type:"fetch",arrayPath:A,zarrVersion:I,url:Q.store.url.toString()};if(Q.store instanceof rC)return{type:"filesystem",arrayPath:A,zarrVersion:I,directoryHandle:Q.store.directoryHandle,path:Q.path};throw new Error(`Unsupported store type: ${Q.store.constructor.name}`)}function ms(Q,A,I,g){return xs(Q,A,I,g)}function xs(Q,A,I,g){const{targetShape:B,chunkIndex:C,dimIndices:E}=g;let i=1;for(let Z=A.length-1;Z>=0;Z--){if(I[Z]!==i)throw new Error(`Chunk data is not tightly packed, stride=${JSON.stringify(I)}, shape=${JSON.stringify(A)}`);i*=A[Z]}const o={x:A[E.x],y:A[E.y],z:E.z!==void 0?A[E.z]:B.z};if(o.x<B.x||o.y<B.y||o.z<B.z)throw new Error(`Received chunk too small: expected ${JSON.stringify(B)}, got ${JSON.stringify(o)}`);const a=g.cChunkSize?C.c%g.cChunkSize:0,D=g.tChunkSize?C.t%g.tChunkSize:0,s=B.x*B.y*B.z,y=E.c!==void 0?I[E.c]:0,F=E.t!==void 0?I[E.t]:0,Y=D*F+a*y,p=o.x===B.x&&o.y===B.y&&o.z===B.z;if(Y===0&&Q.length===s&&p)return Q;const W=new Q.constructor(s),z=E.z!==void 0?I[E.z]:0,x=I[E.y];let l=0;for(let Z=0;Z<B.z;Z++){const v=Y+Z*z;for(let CA=0;CA<B.y;CA++){const sA=v+CA*x,DA=sA+B.x;W.set(Q.subarray(sA,DA),l),l+=B.x}}return W}const Ni=`function xg(B, A) {
557
557
  return {
558
558
  ...B,
559
559
  ...A,