rayzee 11.1.0 → 11.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -244,7 +244,7 @@ fn rayzee_encode( mapped: vec3<f32>, mode: u32 ) -> vec3<f32> {
244
244
  fn rayzee_to_u8( srgb: vec3<f32> ) -> vec3<u32> {
245
245
  return vec3<u32>( clamp( round( srgb * 255.0 + vec3<f32>( 0.5 ) ), vec3<f32>( 0.0 ), vec3<f32>( 255.0 ) ) );
246
246
  }
247
- `,bindings:n}}function yo(){So.length=0,So.push(...io),Co.clear();for(let e of So)Co.set(e.id,e);oo()}var bo,xo,So,Co,wo,To,Eo,Do,Oo,ko=g((()=>{ao(),bo=200,xo=12,So=[...io],Co=new Map(So.map(e=>[e.id,e])),wo=1,To=new Set,Eo=Co,Do=r.NoToneMapping,Oo=r.AgXToneMapping}));ko();var Ao=e=>(t,n,r,i,a)=>e(t>0?t:0,n>0?n:0,r>0?r:0,i,a),jo=new Map;function Mo(){jo.clear();for(let e of Eo.values())jo.set(e.id,Ao(e.cpu))}Mo(),co(Mo);function No(e){return lo(e)?.outputEncoded===!0}function Po(e){return e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055}function Fo(e,t){let n=lo(t);return n?n.appliesExposure?e:1:t===r.NoToneMapping?1:e}var Io=.2126,Lo=.7152,Ro=.0722;function zo(e,t){if(t===1)return;let n=e[0]*Io+e[1]*Lo+e[2]*Ro;e[0]=n+(e[0]-n)*t,e[1]=n+(e[1]-n)*t,e[2]=n+(e[2]-n)*t}function Bo(e,{exposure:t,toneMapping:n,saturation:i=1,preserveAlpha:a=!1}){let o=jo.get(n)??jo.get(r.NoToneMapping),s=Fo(t,n),c=No(n),l=new Uint8ClampedArray(e.length),u=[0,0,0];for(let t=0;t<e.length;t+=4)u[0]=e[t]*s,u[1]=e[t+1]*s,u[2]=e[t+2]*s,zo(u,i),o(u[0],u[1],u[2],1,u),c?(l[t]=u[0]*255+.5,l[t+1]=u[1]*255+.5,l[t+2]=u[2]*255+.5):(l[t]=Po(u[0])*255+.5,l[t+1]=Po(u[1])*255+.5,l[t+2]=Po(u[2])*255+.5),l[t+3]=a?e[t+3]*255+.5:255;return l}wt(),X(),Ae();var Vo=ye(`textures`),Ho={MAX_BUFFER_MEMORY:1024*1024*1024,MAX_TEXTURE_MEMORY:2048*1024*1024,CLEANUP_THRESHOLD:.8,STREAM_BATCH_SIZE:4},Uo=8*2**20,Wo=16,Go=4,Ko=8192*8192,qo={busy:0,waiting:[]};async function Jo(){return qo.busy<Math.max(1,ar()-1)?qo.busy++:await new Promise(e=>qo.waiting.push(e)),()=>{let e=qo.waiting.shift();e?e():qo.busy--}}var Yo={toSRGB:null,toLinear:null};function Xo(e){if(!Yo[e]){let t=new Uint8Array(256);for(let n=0;n<256;n++){let r=n/255,i=e===`toSRGB`?Po(r):r<=.04045?r/12.92:((r+.055)/1.055)**2.4;t[n]=Math.max(0,Math.min(255,Math.round(i*255)))}Yo[e]=t}return Yo[e]}var Zo=class{constructor(){this.canvasContextPairs=[],this.maxPoolSize=Nt.CANVAS_POOL_SIZE}getCanvasWithContext(e,t,n=!1,r={}){let i={willReadFrequently:!0,alpha:!0,desynchronized:!0,...r},a=this.canvasContextPairs.pop();if(!a){let r;r=n&&typeof OffscreenCanvas<`u`?new OffscreenCanvas(e,t):document.createElement(`canvas`);let o=r.getContext(`2d`,i);a={canvas:r,context:o}}return a.canvas.width=e,a.canvas.height=t,a}releaseCanvasWithContext(e){this.canvasContextPairs.length<this.maxPoolSize&&(e.context.globalAlpha=1,e.context.globalCompositeOperation=`source-over`,e.context.imageSmoothingEnabled=!0,e.context.clearRect(0,0,e.canvas.width,e.canvas.height),e.canvas.width=1,e.canvas.height=1,this.canvasContextPairs.push(e))}getCanvas(e,t,n=!1){return this.getCanvasWithContext(e,t,n).canvas}getContext(e,t={}){let n=this.canvasContextPairs.find(t=>t.canvas===e);return n?n.context:e.getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0,...t})}dispose(){this.canvasContextPairs=[]}},Qo=class{constructor(e={}){this.pools=new Map,this.memoryUsage=0,this.maxMemoryUsage=e.maxMemory||Ho.MAX_BUFFER_MEMORY,this.allocatedBuffers=new WeakMap,this.sizeStrategy=e.sizeStrategy||`adaptive`}getOptimalSize(e){switch(this.sizeStrategy){case`exact`:return e;case`power2`:return 2**Math.ceil(Math.log2(e));default:return e<1024?e:e<1024*1024?Math.ceil(e/1024)*1024:2**Math.ceil(Math.log2(e))}}getBuffer(e,t=Float32Array){let n=this.getOptimalSize(e),r=`${t.name}-${n}`,i=(this.pools.get(r)||[]).pop();if(!i)try{i=new t(n),this.memoryUsage+=i.byteLength,this.allocatedBuffers.set(i,!0)}catch{this.cleanup();try{i=new t(n),this.memoryUsage+=i.byteLength,this.allocatedBuffers.set(i,!0)}catch(e){let r=n*t.BYTES_PER_ELEMENT/(1024*1024),i=this.memoryUsage/(1024*1024);throw Error(`Buffer allocation failed: requested ${r.toFixed(1)}MB, current usage: ${i.toFixed(1)}MB, max: ${(this.maxMemoryUsage/(1024*1024)).toFixed(1)}MB. Original error: ${e.message}`)}}return this.memoryUsage>this.maxMemoryUsage*Ho.CLEANUP_THRESHOLD&&this.cleanup(),this.checkMemoryHealth(),i.byteOffset+e*t.BYTES_PER_ELEMENT>i.buffer.byteLength&&(i=new t(e),this.memoryUsage+=i.byteLength),new t(i.buffer,i.byteOffset,e)}forget(e){this.memoryUsage=Math.max(0,this.memoryUsage-e.buffer.byteLength)}releaseBuffer(e,t=Float32Array){let n=(e.buffer.byteLength-e.byteOffset)/t.BYTES_PER_ELEMENT,r=this.getOptimalSize(n),i=`${t.name}-${r}`,a=this.pools.get(i)||[];a.length<Nt.BUFFER_POOL_SIZE?(a.push(new t(e.buffer,e.byteOffset,n)),this.pools.set(i,a)):this.allocatedBuffers.has(e)&&(this.memoryUsage-=e.byteLength,this.allocatedBuffers.delete(e))}cleanup(){let e=Array.from(this.pools.entries());e.slice(0,Math.floor(e.length/2)).forEach(([e,t])=>{t.forEach(e=>{this.allocatedBuffers.has(e)&&(this.memoryUsage-=e.byteLength,this.allocatedBuffers.delete(e))}),this.pools.delete(e)})}dispose(){this.pools.forEach(e=>{e.forEach(e=>{this.allocatedBuffers.has(e)&&this.allocatedBuffers.delete(e)})}),this.pools.clear(),this.memoryUsage=0}getMemoryStats(){return{currentUsage:this.memoryUsage,maxUsage:this.maxMemoryUsage,utilizationPercentage:this.memoryUsage/this.maxMemoryUsage*100,poolCount:this.pools.size,allocatedBufferCount:this.allocatedBuffers&&this.allocatedBuffers.size||0}}checkMemoryHealth(){let e=this.getMemoryStats();return e.utilizationPercentage>90?(console.warn(`Memory pool critical: ${e.utilizationPercentage.toFixed(1)}% used (${(e.currentUsage/(1024*1024)).toFixed(1)}MB / ${(e.maxUsage/(1024*1024)).toFixed(1)}MB)`),`critical`):e.utilizationPercentage>70?(console.warn(`Memory pool high: ${e.utilizationPercentage.toFixed(1)}% used (${(e.currentUsage/(1024*1024)).toFixed(1)}MB / ${(e.maxUsage/(1024*1024)).toFixed(1)}MB)`),`high`):`normal`}},$o=class{constructor(e=Nt.CACHE_SIZE_LIMIT){this.cache=new Map,this.accessOrder=[],this.maxSize=e}generateHash(e){let t=``;for(let n of e)if(n?.image){let e=n.image.width||0,r=n.image.height||0,i=n.image.src||n.uuid||``,a=n.flipY===!1?`n`:`f`,o=`${n.colorSpace??``}|${n.userData?.ocioColorSpace??``}`;t+=`${e}x${r}_${i.slice(-8)}_${a}_${o}_`}return t+e.length}get(e){if(this.cache.has(e)){let t=this.cache.get(e);if(t?.userData&&t.userData.buffer===null){this.cache.delete(e);let t=this.accessOrder.indexOf(e);return t>-1&&this.accessOrder.splice(t,1),null}let n=this.accessOrder.indexOf(e);return n>-1&&this.accessOrder.splice(n,1),this.accessOrder.push(e),t}return null}set(e,t){if(this.cache.has(e)){let t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1)}else this.cache.size>=this.maxSize&&this.evictLRU();this.cache.set(e,t),this.accessOrder.push(e)}evictLRU(){if(this.accessOrder.length>0){let e=this.accessOrder.shift(),t=this.cache.get(e);t&&t.dispose&&t.dispose(),this.cache.delete(e)}}dispose(){this.cache.forEach(e=>{e&&e.dispose&&e.dispose()}),this.cache.clear(),this.accessOrder=[]}},es=class{constructor(e={}){this.useWorkers=typeof Worker<`u`,this.maxConcurrentWorkers=Nt.MAX_CONCURRENT_WORKERS,this.activeWorkers=0,this._issues=e.issues??null,this.maxTextureSize=this._clampTextureSize(e.maxTextureSize??Nt.DEFAULT_MAX_TEXTURE_SIZE),this.canvasPool=new Zo,this.bufferPool=new Qo({maxMemory:e.maxBufferMemory||Ho.MAX_BUFFER_MEMORY,sizeStrategy:e.bufferSizeStrategy||`adaptive`}),this.textureCache=new $o,this.capabilities=this.detectCapabilities(),this.optimalMethod=this.selectOptimalMethod()}_reportTextureFailure(e,t){if(t instanceof Gt)throw t;this._issues?.record(Y.TEXTURE_BUILD_FAILED,`${e} texture array failed to build — those surfaces render untextured`,{map:e,cause:String(t?.message??t)})}_reportTextureLayer(e,t){this._issues?.record(Y.TEXTURE_BUILD_FAILED,`texture ${e} could not be read — its surfaces show a white placeholder`,{layer:e,cause:String(t?.message??t)})}_clampTextureSize(e){let t=Math.floor(Number(e)||Nt.DEFAULT_MAX_TEXTURE_SIZE);return Math.max(Nt.MIN_TEXTURE_WIDTH,Math.min(t,Nt.MAX_TEXTURE_SIZE))}setMaxTextureSize(e){let t=this._clampTextureSize(e);return t===this.maxTextureSize?t:(this.maxTextureSize=t,this.textureCache?.dispose(),this.textureCache=new $o,this.maxTextureSize)}detectCapabilities(){return{offscreenCanvas:typeof OffscreenCanvas<`u`,imageBitmap:typeof createImageBitmap<`u`,workers:typeof Worker<`u`,hardwareConcurrency:ar()}}selectOptimalMethod(){return this.capabilities.workers&&this.capabilities.offscreenCanvas?`worker-offscreen`:this.capabilities.imageBitmap?`imageBitmap`:`canvas`}_applyColorManagement(e,t,n,i=new Set){let a=Or();if(!a?.hasConfig)return;let o=e?.image?.data;if(!o||!n)return;let s=t.filter(e=>e?.image),c=e.image.width*e.image.height*4,l=0,u=0,d=[];for(let e=0;e<s.length;e++){let t=e*c,n=Math.min(t+c,o.length);if(t>=o.length)break;let f=s[e],p=o.subarray(t,n),m=null;try{m=a.resolveTexture(f)}catch(t){Vo.warn(`could not resolve the colour space of layer ${e}: ${t.message}`)}let h=m&&m.via!==`three`?m.colorSpace:null,g=f.type===r.FloatType||f.type===r.HalfFloatType;h&&(i.has(e)||g)&&(d.push(`${f.name||`layer ${e}`} (${h})`),h=null);try{a.convertTextureBytes(p,{space:h,encoding:`srgb`})&&(h?l++:u++)}catch(t){this._issues?.warn(Y.TEXTURE_PROCESSING_FALLBACK,`colour conversion failed for layer ${e} — left in its original space`,{cause:String(t?.message??t),space:h})}}d.length&&this._issues?.warn(Y.TEXTURE_PROCESSING_FALLBACK,`${d.length} colour map(s) name a colour space their stored bytes are no longer in (re-encoded or quantized on the way in); converted by primaries only`,{textures:d.slice(0,8)}),l+u!==0&&(e.needsUpdate=!0,Vo.info(`colour maps into ${a.workingSpace}: ${l} by named space, ${u} by primaries, of ${s.length}`))}_harmonizeTransfer(e,t,n){let i=new Set,a=e?.image?.data;if(!a)return i;let o=t.filter(e=>e?.image),s=n?r.SRGBColorSpace:r.LinearSRGBColorSpace,c=e.image.width*e.image.height*4,l=[];for(let e=0;e<o.length;e++){let t=o[e].colorSpace;if(t!==r.SRGBColorSpace&&t!==r.LinearSRGBColorSpace||t===s)continue;let u=Xo(n?`toSRGB`:`toLinear`),d=e*c,f=Math.min(d+c,a.length);for(let e=d;e<f;e+=4)a[e]=u[a[e]],a[e+1]=u[a[e+1]],a[e+2]=u[a[e+2]];l.push(o[e].name||o[e].source?.uuid?.slice(0,8)||`layer ${e}`),i.add(e)}if(l.length===0)return i;e.needsUpdate=!0;let u=l.slice(0,4).join(`, `)+(l.length>4?`, +${l.length-4} more`:``);return n?Vo.info(`re-encoded ${l.length}/${o.length} linear-declared colour map(s) to sRGB so the GPU decode round-trips: ${u}`):Vo.warn(`decoded ${l.length}/${o.length} sRGB-declared data map(s) to linear — precision is lost in the darks, check the asset: ${u}`),i}async createTexturesToDataTexture(e,{srgbPool:t=!1}={}){if(!e||e.length===0)return null;let n=Or()?.inputKey??`-`,r=`${t?`s`:`l`}:${n}:${this.textureCache.generateHash(e)}`,i=this.textureCache.get(r);if(i)return i;if(typeof createImageBitmap>`u`){let n=await this.processOnCPU(e),i=this._harmonizeTransfer(n,e,t);return this._applyColorManagement(n,e,t,i),this.textureCache.set(r,n),n}let{normalized:a,bitmapsToClose:o}=await this._normalizeTexturesForProcessing(e),s=this.selectProcessingStrategy(a),c;try{switch(s.method){case`worker-direct`:c=await this.processWithWorkerDirect(a);break;case`worker-streaming`:c=await this.processInWorkerStreaming(a);break;case`main-batch`:c=await this.processOnMainThreadBatch(a,s.batchSize);break;case`main-streaming`:c=await this.processOnMainThreadStreaming(a);break;default:c=await this.processOnMainThreadSync(a)}if(c){let n=this._harmonizeTransfer(c,e,t);this._applyColorManagement(c,e,t,n),this.textureCache.set(r,c)}return c}catch(n){if(n instanceof Gt)throw n;this._issues?.warn(Y.TEXTURE_PROCESSING_FALLBACK,`worker texture processing failed — retrying on the main thread`,{cause:String(n?.message??n)});let r=await this.processOnMainThreadSync(a),i=this._harmonizeTransfer(r,e,t);return this._applyColorManagement(r,e,t,i),r}finally{for(let e of o)e.close()}}selectProcessingStrategy(e){let t=e.reduce((e,t)=>e+(t.image?.width||0)*(t.image?.height||0),0),n=t*4;return this.capabilities.workers&&n>Ho.MAX_TEXTURE_MEMORY?{method:`worker-streaming`}:this.capabilities.workers&&t>2097152?{method:`worker-direct`}:t>524288?{method:`main-batch`,batchSize:Math.min(4,e.length)}:e.length>8?{method:`main-streaming`}:{method:`main-sync`}}async processWithWorkerDirect(e){for(;this.activeWorkers>=this.maxConcurrentWorkers;)await new Promise(e=>setTimeout(e,10));this.activeWorkers++;let t=1,n=null;try{let r=await this.prepareTexturesForWorkerDirect(e),i=this._sharedPackSlots(r);if(i>0)return t+=i,this.activeWorkers+=i,this.createDataArrayTextureFromResult(await this._packAcrossWorkers(r,t));n=new Ba;let a=await new Promise((e,t)=>{n.onmessage=n=>{n.data.error?t(Error(n.data.error)):e(n.data)},n.onerror=t;let i=[];r.forEach(e=>{e.data instanceof ArrayBuffer?i.push(e.data):e.bitmap&&i.push(e.bitmap)}),n.postMessage({textures:r,maxTextureSize:this.maxTextureSize,method:`direct-transfer`},i)});return this.createDataArrayTextureFromResult(a)}finally{n?.terminate(),this.activeWorkers-=t}}_sharedPackSlots(e){if(typeof SharedArrayBuffer>`u`||!globalThis.crossOriginIsolated||e.reduce((e,t)=>e+t.width*t.height,0)<Ko)return 0;let t=this.maxConcurrentWorkers-this.activeWorkers;return Math.max(0,Math.min(e.length,Go,t+1)-1)}async _packAcrossWorkers(e,t){let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(e.map(e=>({image:e}))),i=e.length,a=new SharedArrayBuffer(n*r*i*4),o=Array.from({length:t},()=>({cost:0,layers:[],transfer:[]})),s=e.map((e,t)=>t),c=t=>e[t].width*e[t].height;s.sort((e,t)=>c(t)-c(e));for(let t of s){let n=o.reduce((e,t)=>t.cost<e.cost?t:e),r=e[t];n.layers.push({index:t,texture:r}),n.cost+=c(t),r.data instanceof ArrayBuffer?n.transfer.push(r.data):r.bitmap&&n.transfer.push(r.bitmap)}let l=[];try{await Promise.all(o.filter(e=>e.layers.length).map(e=>new Promise((t,i)=>{let o=ur(Ba);l.push(o),o.onmessage=({data:e})=>e.error?i(Error(e.error)):t(),o.onerror=e=>i(Error(e.message||`texture worker failed`)),o.postMessage({shared:a,width:n,height:r,layers:e.layers,maxTextureSize:this.maxTextureSize},e.transfer)})))}finally{for(let e of l)e.terminate()}return{data:a,width:n,height:r,depth:i}}async processInWorkerStreaming(e){let t=e.filter(e=>e?.image);if(t.length===0)return this.createFallbackTexture();let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t),i=t.length;for(;this.activeWorkers>=this.maxConcurrentWorkers;)await new Promise(e=>setTimeout(e,10));this.activeWorkers++;let a=ur(Ba);try{let e=0,o=null,s,c=new Promise((e,t)=>s={resolve:e,reject:t});c.catch(()=>{}),a.onmessage=({data:t})=>{t.error?s.reject(Error(t.error)):t.stream===`ack`?e++:s.resolve(t),o?.()},a.onerror=e=>{s.reject(Error(e.message||`texture worker failed`)),o?.()},a.postMessage({stream:`begin`,width:n,height:r,depth:i});let l=performance.now();for(let s=0;s<i;s++){for(;s-e>=Ho.STREAM_BATCH_SIZE;)await Promise.race([new Promise(e=>o=e),c]),l=performance.now();let i=t[s],u=await createImageBitmap(i.image,{resizeWidth:n,resizeHeight:r,resizeQuality:`high`,imageOrientation:i.flipY===!1?`none`:`flipY`});a.postMessage({stream:`layer`,index:s,bitmap:u},[u]),performance.now()-l>Wo&&(await new Promise(e=>setTimeout(e,0)),l=performance.now())}return a.postMessage({stream:`end`}),this.createDataArrayTextureFromResult(await c)}finally{a.terminate(),this.activeWorkers--}}async prepareTexturesForWorkerDirect(e){let t=[],n=()=>({data:new Uint8ClampedArray([255,255,255,255]).buffer,width:1,height:1,isImageData:!0});for(let r=0;r<e.length;r++){let i=e[r];if(!i?.image){this._reportTextureLayer(r,`no image`),t.push(n());continue}let a=i.flipY!==!1;try{let e=i.image;if(typeof createImageBitmap<`u`&&(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&e instanceof OffscreenCanvas)){let e=await createImageBitmap(i.image,{imageOrientation:a?`flipY`:`none`});t.push({bitmap:e,width:i.image.width,height:i.image.height,isDirect:!0})}else{let e=i.image.width,n=i.image.height,r=await createImageBitmap(i.image,{imageOrientation:a?`flipY`:`none`}),o=this.canvasPool.getCanvasWithContext(e,n);o.context.drawImage(r,0,0),r.close();let s=o.context.getImageData(0,0,e,n);t.push({data:s.data.buffer,width:e,height:n,isImageData:!0}),this.canvasPool.releaseCanvasWithContext(o)}}catch(e){this._reportTextureLayer(r,e),t.push(n())}}return t}async processOnCPU(e){let t=e.map((e,t)=>{let n=e?.image,r=e?.isCompressedTexture?e.mipmaps?.[0]:n,i=r?.data;return i&&r.width>0&&r.height>0&&i.byteLength>=r.width*r.height*4?{data:new Uint8Array(i.buffer,i.byteOffset,r.width*r.height*4),width:r.width,height:r.height,flipY:e.flipY!==!1}:(this._reportTextureLayer(t,n?`not decoded to pixels, and there is no browser to decode it`:`no image`),{data:new Uint8Array([255,255,255,255]),width:1,height:1,flipY:!1})}),{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t.map(e=>({image:e}))),i=n*r*4,a=sr()&&i*t.length>=Uo?await this._packInWorker(t,n,r):null;if(a)return this.createDataArrayTextureFromBuffer(a,n,r,t.length);let o=this.bufferPool.getBuffer(i*t.length,Uint8Array);return t.forEach((e,t)=>Wa(e,o,t*i,n,r)),this.createDataArrayTextureFromBuffer(o,n,r,t.length)}async _packInWorker(e,t,n){let r=await Jo(),i=null;try{let r=[],a=e.map(e=>{if(typeof SharedArrayBuffer<`u`&&e.data.buffer instanceof SharedArrayBuffer)return e;let t=e.data.slice();return r.push(t.buffer),{...e,data:t}});return i=ur(Ua),await new Promise((e,o)=>{i.onmessage=t=>t.data.error?o(Error(t.data.error)):e(t.data.data),i.onerror=e=>o(e.error??Error(e.message??`texture pack worker failed`)),i.postMessage({layers:a,width:t,height:n},r)})}catch(e){return this._issues?.warn(Y.TEXTURE_PROCESSING_FALLBACK,`worker texture packing failed — packing on the main thread`,{cause:String(e?.message??e)}),null}finally{i?.terminate(),r()}}async processOnMainThreadBatch(e,t){let n=e.filter(e=>e?.image);if(n.length===0)return this.createFallbackTexture();let{maxWidth:r,maxHeight:i}=this.calculateOptimalDimensions(n),a=n.length,o=this.bufferPool.getBuffer(r*i*a*4,Uint8Array);for(let e=0;e<n.length;e+=t){let a=Math.min(e+t,n.length),s=[];for(let t=e;t<a;t++){let e=n[t],a=e.flipY!==!1,o=createImageBitmap(e.image,{resizeWidth:r,resizeHeight:i,resizeQuality:`high`,imageOrientation:a?`flipY`:`none`});s.push(o.then(e=>({bitmap:e,index:t})))}let c=await Promise.all(s),l=this.canvasPool.getCanvasWithContext(r,i);l.context.imageSmoothingEnabled=!1;for(let{bitmap:e,index:t}of c){l.context.clearRect(0,0,r,i),l.context.drawImage(e,0,0);let n=l.context.getImageData(0,0,r,i),a=r*i*4*t;o.set(n.data,a),e.close()}this.canvasPool.releaseCanvasWithContext(l)}return this.createDataArrayTextureFromBuffer(o,r,i,a)}async processOnMainThreadStreaming(e){let t=e.filter(e=>e?.image);if(t.length===0)return this.createFallbackTexture();let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t),i=t.length,a=this.bufferPool.getBuffer(n*r*i*4,Uint8Array),o=this.canvasPool.getCanvasWithContext(n,r);o.context.imageSmoothingEnabled=!0,o.context.imageSmoothingQuality=`high`;for(let e=0;e<t.length;e++){let i=t[e],s=await createImageBitmap(i.image,{resizeWidth:n,resizeHeight:r,resizeQuality:`high`,imageOrientation:i.flipY===!1?`none`:`flipY`});o.context.clearRect(0,0,n,r),o.context.drawImage(s,0,0),s.close();let c=o.context.getImageData(0,0,n,r),l=n*r*4*e;a.set(c.data,l),e%Ho.STREAM_BATCH_SIZE===0&&await new Promise(e=>setTimeout(e,0))}return this.canvasPool.releaseCanvasWithContext(o),this.createDataArrayTextureFromBuffer(a,n,r,i)}async processOnMainThreadSync(e){let t=e.filter(e=>e?.image);if(t.length===0)return this.createFallbackTexture();let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t),i=t.length,a=this.bufferPool.getBuffer(n*r*i*4,Uint8Array),o=this.canvasPool.getCanvasWithContext(n,r);o.context.imageSmoothingEnabled=!0,o.context.imageSmoothingQuality=`high`;for(let e=0;e<t.length;e++){let i=t[e],s=await createImageBitmap(i.image,{resizeWidth:n,resizeHeight:r,resizeQuality:`high`,imageOrientation:i.flipY===!1?`none`:`flipY`});o.context.clearRect(0,0,n,r),o.context.drawImage(s,0,0),s.close();let c=o.context.getImageData(0,0,n,r),l=n*r*4*e;a.set(c.data,l)}return this.canvasPool.releaseCanvasWithContext(o),this.createDataArrayTextureFromBuffer(a,n,r,i)}createMaterialRawData(e){let t=q.FLOATS_PER_MATERIAL,n=new Float32Array(e.length*t);for(let r=0;r<e.length;r++)Mt(n,r*t,e[r]);return n}createBVHRawData(e){let t=[],n=e=>{let r=t.length;if(t.push(e),e.leftChild){let t=n(e.leftChild),r=n(e.rightChild);e.leftChild=t,e.rightChild=r}return r};n(e);let r=Nt.VEC4_PER_BVH_NODE*Nt.FLOATS_PER_VEC4;gt(t.length,`BVH node count`);let i=t.length*r,a=new Float32Array(i),o=ht(a);for(let e=0;e<t.length;e++){let n=e*r,i=t[e];if(i.leftChild!==null){let e=i.leftChild,r=i.rightChild,s=t[e],c=t[r];a[n]=s.boundsMin.x,a[n+1]=s.boundsMin.y,a[n+2]=s.boundsMin.z,o[n+3]=e,a[n+4]=s.boundsMax.x,a[n+5]=s.boundsMax.y,a[n+6]=s.boundsMax.z,o[n+7]=r,a[n+8]=c.boundsMin.x,a[n+9]=c.boundsMin.y,a[n+10]=c.boundsMin.z,a[n+12]=c.boundsMax.x,a[n+13]=c.boundsMax.y,a[n+14]=c.boundsMax.z}else o[n]=i.triangleOffset,o[n+1]=i.triangleCount,o[n+3]=St.TRIANGLE_LEAF}return a}async createMaterialTextures(e){let{materials:t,maps:n,normalMaps:i,bumpMaps:a,roughnessMaps:o,metalnessMaps:s,emissiveMaps:c,displacementMaps:l}=e;console.log(`[TextureCreator] Creating material textures only`);let u=performance.now();try{if(!t||t.length===0)throw Error(`No materials provided for texture creation`);this.textureCache.dispose(),this.textureCache=new $o;let e=[];for(let[t,r]of[[`albedo`,n],[`normal`,i],[`bump`,a],[`roughness`,o],[`metalness`,s],[`emissive`,c],[`displacement`,l]])!r||r.length===0||e.push(this.createTexturesToDataTexture(r).then(e=>({type:t,texture:e})).catch(e=>(this._reportTextureFailure(t,e),{type:t,texture:null})));let d=await Promise.allSettled(e),f=d.find(e=>e.status===`rejected`);if(f)throw f.reason;let p={};d.forEach(e=>{if(e.status===`fulfilled`&&e.value){let{type:t,texture:n}=e.value;if(n)switch(t){case`albedo`:n.colorSpace=r.SRGBColorSpace,p.albedoTexture=n;break;case`normal`:p.normalTexture=n;break;case`bump`:p.bumpTexture=n;break;case`roughness`:p.roughnessTexture=n;break;case`metalness`:p.metalnessTexture=n;break;case`emissive`:n.colorSpace=r.SRGBColorSpace,p.emissiveTexture=n;break;case`displacement`:p.displacementTexture=n;break}}});let m=performance.now()-u;return console.log(`[TextureCreator] Material texture creation complete (${m.toFixed(2)}ms)`),p}catch(e){throw console.error(`[TextureCreator] Material texture creation error:`,e),Error(`Material texture creation failed: ${e.message}`)}}calculateOptimalDimensions(e){let t=0,n=0;for(let r of e)t=Math.max(t,r.image.width),n=Math.max(n,r.image.height);let r=Math.max(t,n);if(r>this.maxTextureSize){let e=this.maxTextureSize/r;t=Math.round(t*e),n=Math.round(n*e)}return{maxWidth:Ft(t,this.maxTextureSize),maxHeight:Math.max(1,n)}}createDataArrayTextureFromResult(e){let t=(e.data instanceof ArrayBuffer,new Uint8Array(e.data));return this.createDataArrayTextureFromBuffer(t,e.width,e.height,e.depth)}createDataArrayTextureFromBuffer(e,t,n,i){let a=new r.DataArrayTexture(e,t,n,i);a.minFilter=r.LinearFilter,a.magFilter=r.LinearFilter,a.wrapS=r.RepeatWrapping,a.wrapT=r.RepeatWrapping,a.format=r.RGBAFormat,a.type=r.UnsignedByteType,a.needsUpdate=!0,a.generateMipmaps=!1,a.userData={buffer:e,bufferType:Uint8Array},a.onUpdate=()=>{let e=a.userData.buffer;e&&(this.bufferPool.forget(e),a.userData.buffer=null,a.image.data=null)};let o=a.dispose.bind(a);return a.dispose=()=>{a.userData.buffer&&(this.bufferPool.releaseBuffer(a.userData.buffer,a.userData.bufferType),a.userData.buffer=null),o()},a}async _normalizeTexturesForProcessing(e){let t=[],n=[],i=[];for(let n of e){if(!n?.image){this._reportTextureLayer(t.length,`no image`),t.push(null);continue}if(n.isCompressedTexture&&n.format===r.RGBAFormat&&n.mipmaps?.[0]?.data){let e=n.mipmaps[0],r=t.length;t.push(null),i.push({index:r,flipY:n.flipY,promise:ts(e.data,e.width,e.height)});continue}if(n.isCompressedTexture){console.warn(`[TextureCreator] GPU-compressed texture in mixed group — using placeholder`),t.push(null);continue}if(n.image.data&&!(typeof HTMLImageElement<`u`&&n.image instanceof HTMLImageElement)&&!(typeof HTMLCanvasElement<`u`&&n.image instanceof HTMLCanvasElement)&&!(typeof ImageBitmap<`u`&&n.image instanceof ImageBitmap)){let e=t.length;t.push(null),i.push({index:e,flipY:n.flipY,promise:ts(n.image.data,n.image.width,n.image.height)});continue}t.push(n)}if(i.length>0){let e=await Promise.allSettled(i.map(e=>e.promise));for(let r=0;r<i.length;r++){let{index:a,flipY:o}=i[r],s=e[r];if(s.status===`fulfilled`){let e=s.value;n.push(e),t[a]={image:e,flipY:o}}else this._reportTextureLayer(a,s.reason)}}for(let e=0;e<t.length;e++)if(t[e]===null){let r=new Uint8ClampedArray([255,255,255,255]),i=await createImageBitmap(new ImageData(r,1,1));n.push(i),t[e]={image:i,flipY:!1}}return{normalized:t,bitmapsToClose:n}}createFallbackTexture(){let e=new r.DataArrayTexture(new Uint8Array([255,255,255,255]),1,1,1);return e.minFilter=r.LinearFilter,e.magFilter=r.LinearFilter,e.format=r.RGBAFormat,e.type=r.UnsignedByteType,e.needsUpdate=!0,e.generateMipmaps=!1,e}dispose(){this.canvasPool.dispose(),this.bufferPool.dispose(),this.textureCache.dispose()}};function ts(e,t,n){let r=new Uint8ClampedArray(e.buffer,e.byteOffset,e.byteLength);return createImageBitmap(new ImageData(r,t,n))}var ns=class{constructor(){this.maxLeafSize=8}build(e){let t=e.length;if(t===0){let e=new Float32Array(16);return e[7]=1,e[14]=1,e[15]=-1,{nodeData:e,nodeCount:1,sortedPerm:new Int32Array,bitTrails:new Float32Array}}let n=new Int32Array(t);for(let e=0;e<t;e++)n[e]=e;let r=2*t+4,i=new Float32Array(r*16),a=0,o=new Float32Array(t),s=(t,r,c,l)=>{let u=a++,d=u*16,f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,_=-1/0,v=0,y=1/0,b=1/0,x=1/0,S=-1/0,C=-1/0,w=-1/0;for(let i=t;i<r;i++){let t=e[n[i]];f=Math.min(f,t.bMinX),p=Math.min(p,t.bMinY),m=Math.min(m,t.bMinZ),h=Math.max(h,t.bMaxX),g=Math.max(g,t.bMaxY),_=Math.max(_,t.bMaxZ),v+=t.power,y=Math.min(y,t.cx),b=Math.min(b,t.cy),x=Math.min(x,t.cz),S=Math.max(S,t.cx),C=Math.max(C,t.cy),w=Math.max(w,t.cz)}i[d+0]=f,i[d+1]=p,i[d+2]=m,i[d+3]=v,i[d+4]=h,i[d+5]=g,i[d+6]=_;let T=r-t,E;if(T<=this.maxLeafSize){i[d+7]=1,i[d+8]=t,i[d+9]=T,i[d+10]=0,i[d+11]=0,E=null;for(let i=t;i<r;i++){let t=e[n[i]];E=is(E,rs(t)),o[i]=c}E||={ax:0,ay:0,az:1,cosO:-1}}else{let a=S-y,o=C-b,u=w-x,f;f=a>=o&&a>=u?0:o>=u?1:2;let p=[`cx`,`cy`,`cz`][f],m=t+r>>1;this._nthElement(n,e,t,r,m,p),i[d+7]=0;let h=s(t,m,c,l+1),g=s(m,r,c+2**l,l+1);i[d+8]=h.nodeIndex,i[d+9]=g.nodeIndex,i[d+10]=0,i[d+11]=0,E=is(h.cone,g.cone)}return i[d+12]=E.ax,i[d+13]=E.ay,i[d+14]=E.az,i[d+15]=E.cosO,{nodeIndex:u,cone:E}};s(0,t,0,0);let c=new Int32Array(t);for(let e=0;e<t;e++)c[e]=n[e];let l=new Float32Array(a*16);return l.set(i.subarray(0,a*16)),console.log(`[LightBVHBuilder] Built BVH: ${a} nodes for ${t} emissive triangles`),{nodeData:l,nodeCount:a,sortedPerm:c,bitTrails:o}}_nthElement(e,t,n,r,i,a){for(;n<r-1;){let o=n+r>>1,s=t[e[o]][a],c=e[o];e[o]=e[r-1],e[r-1]=c;let l=n;for(let i=n;i<r-1;i++)t[e[i]][a]<s&&(c=e[i],e[i]=e[l],e[l]=c,l++);if(c=e[l],e[l]=e[r-1],e[r-1]=c,l===i)return;l<i?n=l+1:r=l}}};function rs(e){return e.twoSided?{ax:e.nx,ay:e.ny,az:e.nz,cosO:-1}:{ax:e.nx,ay:e.ny,az:e.nz,cosO:1}}function is(e,t){if(!e)return t;if(!t||e.cosO<=-1)return e;if(t.cosO<=-1)return t;let n=Math.min(Math.max(e.cosO,-1),1),r=Math.min(Math.max(t.cosO,-1),1),i=Math.acos(n),a=Math.acos(r),o=Math.min(Math.max(e.ax*t.ax+e.ay*t.ay+e.az*t.az,-1),1),s=Math.acos(o);if(Math.min(s+a,Math.PI)<=i)return e;if(Math.min(s+i,Math.PI)<=a)return t;let c=(i+a+s)*.5;if(c>=Math.PI)return{ax:e.ax,ay:e.ay,az:e.az,cosO:-1};let l=c-i,u=e.ay*t.az-e.az*t.ay,d=e.az*t.ax-e.ax*t.az,f=e.ax*t.ay-e.ay*t.ax,p=Math.sqrt(u*u+d*d+f*f);if(p<1e-8)return{ax:e.ax,ay:e.ay,az:e.az,cosO:-1};u/=p,d/=p,f/=p;let m=Math.cos(l),h=Math.sin(l),g=u*e.ax+d*e.ay+f*e.az,_=d*e.az-f*e.ay,v=f*e.ax-u*e.az,y=u*e.ay-d*e.ax,b=e.ax*m+_*h+u*g*(1-m),x=e.ay*m+v*h+d*g*(1-m),S=e.az*m+y*h+f*g*(1-m),C=Math.sqrt(b*b+x*x+S*S)||1;return{ax:b/C,ay:x/C,az:S/C,cosO:Math.cos(c)}}wt(),Ae(),Fn();var as=Object.freeze({r:0,g:0,b:0});function os(e){if(!e)return as;if(!kn())return e;let t=[e.r,e.g,e.b];return jn(t),{r:t[0],g:t[1],b:t[2]}}var ss=ye(`emissive`),cs=class{constructor(){this.emissiveTriangles=[],this.emissiveCount=0,this.totalEmissivePower=0,this.emissiveIndicesArray=null,this.emissivePowerArray=null,this.cdfArray=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._totalTriangleCount=0,this._hiddenMeshes=new Set}extractEmissiveTriangles(e,t,n,r=null){this.emissiveTriangles=[],this._emissiveMeshes=null,this.totalEmissivePower=0,this._totalTriangleCount=n;let i=K.FLOATS_PER_TRIANGLE,a=K.MATERIAL_FLAGS_OFFSET,o=K.MESH_INDEX_OFFSET,s=e&&e.chunks?e:null,c=s?s.viewAs(Float32Array):null,l=s?null:e,u=s?null:new Float32Array(e.buffer,e.byteOffset,e.length),d=new Map;for(let e=0;e<n;e++){if(s?.spilledChunks&&!s.isResident(e,1)){e=((e/s.recordsPerChunk|0)+1)*s.recordsPerChunk-1;continue}let n=s?s.chunkFor(e):l,f=s?c.chunkFor(e):u,p=s?s.baseOf(e):e*i,m=n[p+a]&_t,h=n[p+o],g=t[m];if(!g)continue;let _=d.get(g);_===void 0&&(_=os(g.emissive),d.set(g,_));let v=g.emissiveIntensity||0;if(v>0&&(_.r>0||_.g>0||_.b>0)){let t=r?.placementRunOf?.(h)?.start??-1,n=t>=0&&r.isSet[t],i=n?r.world:null,a=n?t*16:0,o=(e,t,n)=>i?i[a]*e+i[a+4]*t+i[a+8]*n+i[a+12]:e,s=(e,t,n)=>i?i[a+1]*e+i[a+5]*t+i[a+9]*n+i[a+13]:t,c=(e,t,n)=>i?i[a+2]*e+i[a+6]*t+i[a+10]*n+i[a+14]:n,l=f[p+0],u=f[p+1],d=f[p+2],y=f[p+4],b=f[p+5],x=f[p+6],S=f[p+8],C=f[p+9],w=f[p+10],T=o(l,u,d),E=s(l,u,d),D=c(l,u,d),O=o(y,b,x),k=s(y,b,x),A=c(y,b,x),j=o(S,C,w),M=s(S,C,w),N=c(S,C,w),P=this._calculateTriangleArea(T,E,D,O,k,A,j,M,N),F=(.2126*_.r+.7152*_.g+.0722*_.b)*v*P,I=(k-E)*(N-D)-(A-D)*(M-E),L=(A-D)*(j-T)-(O-T)*(N-D),ee=(O-T)*(M-E)-(k-E)*(j-T),te=Math.sqrt(I*I+L*L+ee*ee)||1,R=g.side===1?-1:1;I=I/te*R,L=L/te*R,ee=ee/te*R;let ne=g.side===2,re=(T+O+j)/3,ie=(E+k+M)/3,ae=(D+A+N)/3,oe=Math.min(T,O,j),se=Math.min(E,k,M),ce=Math.min(D,A,N),le=Math.max(T,O,j),ue=Math.max(E,k,M),z=Math.max(D,A,N);this.emissiveTriangles.push({triangleIndex:e,materialIndex:m,meshIndex:h,sideSign:R,instanceLeaf:n?r.tlasLeafIndex[t]:-1,power:F,area:P,emissive:{r:_.r,g:_.g,b:_.b},emissiveIntensity:v,cx:re,cy:ie,cz:ae,bMinX:oe,bMinY:se,bMinZ:ce,bMaxX:le,bMaxY:ue,bMaxZ:z,nx:I,ny:L,nz:ee,twoSided:ne}),this.totalEmissivePower+=F}}return this.emissiveCount=this.emissiveTriangles.length,this.emissiveCount>0&&ss.debug(`${H.n(this.emissiveCount)} emissive tris (${(this.emissiveCount/n*100).toFixed(2)}%) · total power ${this.totalEmissivePower.toFixed(2)}`),this._buildDataArrays(),this.emissiveCount}get emissiveMeshes(){return this._emissiveMeshes??=new Set(this.emissiveTriangles.map(e=>e.meshIndex))}refreshTransforms(e,t){let n=e&&e.chunks?e:null,r=n?n.viewAs(Float32Array):null,i=n?null:new Float32Array(e.buffer,e.byteOffset,e.length),a=K.FLOATS_PER_TRIANGLE,o=t.world;this.totalEmissivePower=0;for(let e of this.emissiveTriangles){let s=n?r.chunkFor(e.triangleIndex):i,c=n?n.baseOf(e.triangleIndex):e.triangleIndex*a,l=[s[c],s[c+1],s[c+2],s[c+4],s[c+5],s[c+6],s[c+8],s[c+9],s[c+10]],u=t.placementRunOf?.(e.meshIndex)?.start??-1;if(u>=0&&t.isSet[u]){let e=u*16;for(let t=0;t<9;t+=3){let n=l[t],r=l[t+1],i=l[t+2];l[t]=o[e]*n+o[e+4]*r+o[e+8]*i+o[e+12],l[t+1]=o[e+1]*n+o[e+5]*r+o[e+9]*i+o[e+13],l[t+2]=o[e+2]*n+o[e+6]*r+o[e+10]*i+o[e+14]}}let[d,f,p,m,h,g,_,v,y]=l,b=this._calculateTriangleArea(d,f,p,m,h,g,_,v,y),x=e.emissive;e.power=(.2126*x.r+.7152*x.g+.0722*x.b)*e.emissiveIntensity*b,e.area=b;let S=(h-f)*(y-p)-(g-p)*(v-f),C=(g-p)*(_-d)-(m-d)*(y-p),w=(m-d)*(v-f)-(h-f)*(_-d),T=(Math.sqrt(S*S+C*C+w*w)||1)/e.sideSign;e.nx=S/T,e.ny=C/T,e.nz=w/T,e.cx=(d+m+_)/3,e.cy=(f+h+v)/3,e.cz=(p+g+y)/3,e.bMinX=Math.min(d,m,_),e.bMinY=Math.min(f,h,v),e.bMinZ=Math.min(p,g,y),e.bMaxX=Math.max(d,m,_),e.bMaxY=Math.max(f,h,v),e.bMaxZ=Math.max(p,g,y),this.totalEmissivePower+=e.power}this._buildDataArrays()}_calculateTriangleArea(e,t,n,r,i,a,o,s,c){let l=r-e,u=i-t,d=a-n,f=o-e,p=s-t,m=c-n,h=u*m-d*p,g=d*f-l*m,_=l*p-u*f;return Math.sqrt(h*h+g*g+_*_)*.5}_buildDataArrays(){this.emissiveIndicesArray=new Int32Array(this.emissiveCount),this.emissivePowerArray=new Float32Array(this.emissiveCount);for(let e=0;e<this.emissiveCount;e++)this.emissiveIndicesArray[e]=this.emissiveTriangles[e].triangleIndex,this.emissivePowerArray[e]=this.emissiveTriangles[e].power;this._buildCDF()}_buildCDF(){if(this.emissiveCount===0){this.cdfArray=new Float32Array(1),this.cdfArray[0]=0;return}this.cdfArray=new Float32Array(this.emissiveCount);let e=0;for(let t=0;t<this.emissiveCount;t++)e+=this.emissivePowerArray[t],this.cdfArray[t]=e;if(e>0)for(let t=0;t<this.emissiveCount;t++)this.cdfArray[t]/=e}sampleCDF(e){if(this.emissiveCount===0)return-1;if(this.emissiveCount===1)return 0;let t=0,n=this.emissiveCount-1;for(;t<n;){let r=Math.floor((t+n)/2);this.cdfArray[r]<e?t=r+1:n=r}return t}getGPUData(){return{emissiveIndices:this.emissiveIndicesArray,emissivePower:this.emissivePowerArray,emissiveCDF:this.cdfArray,emissiveCount:this.emissiveCount,totalPower:this.totalEmissivePower}}createEmissiveTexture(){if(this.emissiveCount===0)return new r.DataTexture(new Float32Array(4),1,1,r.RGBAFormat,r.FloatType);let e=new Float32Array(this.emissiveCount*4);for(let t=0;t<this.emissiveCount;t++){let n=t*4;e[n+0]=this.emissiveIndicesArray[t],e[n+1]=this.emissivePowerArray[t],e[n+2]=this.cdfArray[t],e[n+3]=0}let t=Math.ceil(Math.sqrt(this.emissiveCount)),n=Math.ceil(this.emissiveCount/t),i=t*n*4,a=new Float32Array(i);a.set(e);let o=new r.DataTexture(a,t,n,r.RGBAFormat,r.FloatType);return o.needsUpdate=!0,o.generateMipmaps=!1,o.minFilter=r.NearestFilter,o.magFilter=r.NearestFilter,ss.debug(`emissive texture ${H.px(t,n)} · ${H.n(this.emissiveCount)} entries`),o}createEmissiveRawData(){if(this.emissiveCount===0)return new Float32Array(8);let e=new Float32Array(this.emissiveCount*8);for(let t=0;t<this.emissiveCount;t++){let n=this.emissiveTriangles[t],r=t*8;e[r+0]=n.triangleIndex,e[r+1]=n.power,e[r+2]=this.cdfArray[t],e[r+3]=n.instanceLeaf,e[r+4]=n.emissive.r*n.emissiveIntensity,e[r+5]=n.emissive.g*n.emissiveIntensity,e[r+6]=n.emissive.b*n.emissiveIntensity,e[r+7]=n.area}return ss.debug(`emissive raw data ${H.n(this.emissiveCount)} entries (${H.mb(e.byteLength)})`),e}getStats(){if(this.emissiveCount===0)return{count:0,totalPower:0,averagePower:0,minPower:0,maxPower:0};let e=1/0,t=-1/0;for(let n=0;n<this.emissiveCount;n++){let r=this.emissivePowerArray[n];e=Math.min(e,r),t=Math.max(t,r)}return{count:this.emissiveCount,totalPower:this.totalEmissivePower,averagePower:this.totalEmissivePower/this.emissiveCount,minPower:e,maxPower:t}}updateMaterialEmissive(e,t,n,r,i){let a=os(t.emissive),o=t.emissiveIntensity||0,s=o>0&&(a.r>0||a.g>0||a.b>0);if(s!==this.emissiveTriangles.some(t=>t.materialIndex===e))return this.extractEmissiveTriangles(n,r,i),!0;if(!s)return!1;let c=.2126*a.r+.7152*a.g+.0722*a.b;for(let t of this.emissiveTriangles)t.materialIndex===e&&(t.power=c*o*t.area,t.emissive={r:a.r,g:a.g,b:a.b},t.emissiveIntensity=o);return!0}setHiddenMeshes(e){let t=new Set;for(let e of this.emissiveTriangles)t.add(e.meshIndex);let n=new Set;for(let r of e)t.has(r)&&n.add(r);let r=this._hiddenMeshes,i=n.size!==r.size;if(!i){for(let e of n)if(!r.has(e)){i=!0;break}}return this._hiddenMeshes=n,i}buildLightBVH(){let e=this._hiddenMeshes.size===0?this.emissiveTriangles:this.emissiveTriangles.filter(e=>!this._hiddenMeshes.has(e.meshIndex));this.emissiveCount=e.length,this.totalEmissivePower=0;for(let t of e)this.totalEmissivePower+=t.power;if(e.length===0)return this.lightBVHNodeData=new Float32Array(16),this.lightBVHNodeData[7]=1,this.lightBVHNodeData[14]=1,this.lightBVHNodeData[15]=-1,this.lightBVHNodeCount=1,this.emissiveBitTrailMap=new Float32Array(Math.max(this._totalTriangleCount,1)).fill(-1),this.emissiveIndicesArray=new Int32Array,this.emissivePowerArray=new Float32Array,this._buildCDF(),this.emissiveTriangleData=new Float32Array(8),1;let{nodeData:t,nodeCount:n,sortedPerm:r,bitTrails:i}=new ns().build(e);this.lightBVHNodeData=t,this.lightBVHNodeCount=n,this._rebuildSortedEmissiveData(r,e),this.emissiveBitTrailMap=new Float32Array(Math.max(this._totalTriangleCount,1)).fill(-1);for(let t=0;t<r.length;t++){let n=e[r[t]].triangleIndex;this.emissiveBitTrailMap[n]=i[t]}return n}_rebuildSortedEmissiveData(e,t){let n=e.length;this.emissiveIndicesArray=new Int32Array(n),this.emissivePowerArray=new Float32Array(n);for(let r=0;r<n;r++){let n=e[r];this.emissiveIndicesArray[r]=t[n].triangleIndex,this.emissivePowerArray[r]=t[n].power}this._buildCDF();let r=new Float32Array(n*8);for(let i=0;i<n;i++){let n=t[e[i]],a=i*8;r[a+0]=n.triangleIndex,r[a+1]=n.power,r[a+2]=this.cdfArray[i],r[a+3]=n.instanceLeaf,r[a+4]=n.emissive.r*n.emissiveIntensity,r[a+5]=n.emissive.g*n.emissiveIntensity,r[a+6]=n.emissive.b*n.emissiveIntensity,r[a+7]=n.area}this.emissiveTriangleData=r,ss.debug(`rebuilt sorted emissive data · ${H.n(n)} entries`)}clear(){this.emissiveTriangles=[],this.emissiveCount=0,this.totalEmissivePower=0,this.emissiveIndicesArray=null,this.emissivePowerArray=null,this.cdfArray=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._totalTriangleCount=0,this._hiddenMeshes=new Set}};Ae();var ls=class{constructor(e=`Build`,{namespace:t=`build`,level:n=`debug`}={}){this.label=e,this.level=n,this.logger=ye(t),this.entries=new Map,this.order=[],this.totalStart=performance.now()}start(e){return this.entries.set(e,{start:performance.now(),end:null}),this.order.includes(e)||this.order.push(e),this}end(e){let t=this.entries.get(e);return t&&(t.end=performance.now(),t.duration=t.end-t.start),this}getDuration(e){return this.entries.get(e)?.duration??0}print(e=[]){let t=performance.now()-this.totalStart,n=this.order.map(e=>{let t=this.entries.get(e)?.duration??0;return t>=1?`${e} ${Math.round(t)}ms`:null}).filter(Boolean),r=H.list([this.label,...e,H.ms(t)]);return this.level===`info`?this.logger.summary(r,n):this.logger.debug(H.list([r,n.join(` · `)])),{steps:Object.fromEntries(this.order.map(e=>[e,Math.round(this.entries.get(e)?.duration??0)])),total:Math.round(t)}}};nn();var us=1<<20,ds=1<<21,fs=()=>new Promise(e=>setTimeout(e,0)),ps=[0,1,2,4,5,6,8,9,10];function ms(e,t,n,r=ps){let i=e.lanesPerRecord,a=r.length,o=0,s=0,c=0;for(;c<n;){let l=t+c,u=e.chunkFor(l),d=Math.min(e.recordsPerChunk-l%e.recordsPerChunk,n-c),f=e.baseOf(l);for(let e=0;e<d;e++,f+=i){let e=2166136261,t=2654435769;for(let n=0;n<a;n++){let i=u[f+r[n]];e=Math.imul(e^i,16777619),t=Math.imul(t+i|0,2246822507)^t>>>13}o=o+e>>>0,s=s+t>>>0}c+=d}return`${o.toString(16)}.${s.toString(16)}`}async function hs(e,t){let n=[],r=0;for(let{triOffset:i,triCount:a}of t)n.push(ms(e,i,a)),r+=a,r>=ds&&(r=0,await fs());return n}async function gs(e,t){let n=await e?.area(tn.SCENES).open(t);if(!n)return null;try{let e=await n.json(`index.json`),t=await n.file(`nodes.f32`),r=await n.file(`order.u32`);return e?.v!==2||!t||!r?(n.release(),null):{index:e,nodes:t,order:r,release:()=>n.release()}}catch{return n.release(),null}}async function _s(e,t,{index:n,bvh:r,orders:i,isStale:a,label:o=``}){let s=e?.area(tn.SCENES);if(!s)return!1;let c=n.totalNodes-n.tlasNodeCount,l=i.reduce((e,t)=>e+(t?.byteLength??0),0),u=await s.create(t,{label:`${o} (BVH)`,expectedBytes:c*64+l});if(!u)return!1;try{for(let e=n.tlasNodeCount;e<n.totalNodes;){if(a())throw Error(`scene changed while it was being stored`);let t=r.chunkFor(e),i=r.recordsPerChunk-e%r.recordsPerChunk,o=Math.min(i,n.totalNodes-e,us),s=r.baseOf(e);await u.write(`nodes.f32`,t.subarray(s,s+o*16)),e+=o}for(let e of i)if(e)for(let t=0;t<e.length;t+=us*4)await u.write(`order.u32`,e.subarray(t,Math.min(e.length,t+us*4)));if(l===0&&await u.write(`order.u32`,new Uint8Array),a())throw Error(`scene changed while it was being stored`);return await u.writeJSON(`index.json`,n),await u.commit(),!0}catch{return await u.abort(),!1}}async function vs(e,t,n,r){for(let i=0;i<r;i+=us){let a=Math.min(us,r-i),o=await e.slice(i*64,(i+a)*64).arrayBuffer();t.setRecords(n+i,new Float32Array(o))}}async function ys(e,t,n){return new Uint32Array(await e.slice(t*4,(t+n)*4).arrayBuffer())}wt();var bs=16,xs=K.POSITION_A_OFFSET,Ss=K.POSITION_B_OFFSET,Cs=K.POSITION_C_OFFSET;async function ws(e,t,n,r,{pause:i=null}={}){let a=e.lanesPerRecord,o=[new Float32Array(n),new Float32Array(n),new Float32Array(n)],[s,c,l]=o;for(let r=0;r<n;){let i=e.chunkFor(t+r),o=new Float32Array(i.buffer,i.byteOffset,i.length),u=Math.min(n,(((t+r)/e.recordsPerChunk|0)+1)*e.recordsPerChunk-t);for(let n=e.baseOf(t+r);r<u;r++,n+=a)s[r]=o[n+xs]+o[n+Ss]+o[n+Cs],c[r]=o[n+xs+1]+o[n+Ss+1]+o[n+Cs+1],l[r]=o[n+xs+2]+o[n+Ss+2]+o[n+Cs+2]}let u=new Uint32Array(n);for(let e=0;e<n;e++)u[e]=e;let d=[],f=(e,t)=>{if(t-e<=r)return d.push({start:e,count:t-e}),{piece:d.length-1};let n=e+(t-e>>1);return Es(u,o,Ts(o,e,t),e,t,n),{left:f(e,n),right:f(n,t)}},p=f(0,n);return await i?.(),await Ds(e,t,n,u,i),{order:u,pieces:d,tree:p}}function Ts(e,t,n){let r=0,i=-1;for(let a=0;a<3;a++){let o=e[a],s=1/0,c=-1/0;for(let e=t;e<n;e++){let t=o[e];t<s&&(s=t),t>c&&(c=t)}c-s>i&&(i=c-s,r=a)}return r}function Es(e,t,n,r,i,a){let o=t[n],[s,c,l]=t,u=(t,n)=>{let r=e[t];e[t]=e[n],e[n]=r,r=s[t],s[t]=s[n],s[n]=r,r=c[t],c[t]=c[n],c[n]=r,r=l[t],l[t]=l[n],l[n]=r},d=2654435769,f=()=>(d^=d<<13,d^=d>>>17,d^=d<<5,o[r+(d>>>0)%(i-r)]);for(;i-r>1;){let e=f(),t=f(),n=f(),s=e<t?t<n?t:e<n?n:e:e<n?e:t<n?n:t,c=r,l=r,d=i;for(;l<d;){let e=o[l];e<s?u(c++,l++):e>s?u(l,--d):l++}if(a<c)i=c;else if(a>=d)r=d;else return}}async function Ds(e,t,n,r,i){let a=e.lanesPerRecord,o=new Uint32Array(a),s=new Uint8Array(n),c=0;for(let l=0;l<n;l++){if(s[l]||(s[l]=1,r[l]===l))continue;let n=e.chunkFor(t+l),u=e.baseOf(t+l);for(let e=0;e<a;e++)o[e]=n[u+e];for(let d=l;;){let f=r[d],p=n,m=u;if(f===l){for(let e=0;e<a;e++)p[m+e]=o[e];break}n=e.chunkFor(t+f),u=e.baseOf(t+f);for(let e=0;e<a;e++)p[m+e]=n[u+e];s[f]=1,d=f,i&&!(++c&1048575)&&await i()}}}function Os(e,t,n,r){let i=t.length-1,a=[],o=i;for(let{bvhData:e}of n)a.push(o),o+=e.length/bs;let s=new Float32Array(i*bs),c=new Uint32Array(s.buffer),l=[s],u=new Uint32Array(r.length);for(let e=0;e<t.length;e++){let{bvhData:i,originalToBvh:o}=n[e];n[e].bvhData=n[e].originalToBvh=null;let s=a[e],{start:c,count:d}=t[e];vi(new Uint32Array(i.buffer,i.byteOffset,i.length),s,c),l.push(i);for(let e=0;e<d;e++)u[r[c+e]]=c+(o?o[e]:e)}let d=0,f=e=>{if(e.piece!==void 0)return{index:a[e.piece],box:n[e.piece].aabb};let t=d++,r=f(e.left),i=f(e.right),o=t*bs;return s[o]=r.box[0],s[o+1]=r.box[1],s[o+2]=r.box[2],c[o+3]=r.index,s[o+4]=r.box[3],s[o+5]=r.box[4],s[o+6]=r.box[5],c[o+7]=i.index,s[o+8]=i.box[0],s[o+9]=i.box[1],s[o+10]=i.box[2],s[o+12]=i.box[3],s[o+13]=i.box[4],s[o+14]=i.box[5],{index:t,box:[0,1,2].map(e=>Math.min(r.box[e],i.box[e])).concat([3,4,5].map(e=>Math.max(r.box[e],i.box[e])))}};return f(e),{bvhData:l,nodeCount:o,originalToBvh:u}}var ks,As=g((()=>{ks=`11.1.0`})),js,Ms=g((()=>{As(),js=ks}));function Ns(e,t,n=Ps){return e>=n&&t/Fs<e/3}var Ps,Fs,Is=g((()=>{Ps=1e4,Fs=15e5}));Ms(),Is();var Ls="const e={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_PACKED_OFFSET:3,NORMAL_B_PACKED_OFFSET:7,NORMAL_C_PACKED_OFFSET:11,UV_AB_OFFSET:12,UV_C_OFFSET:16,MATERIAL_FLAGS_OFFSET:18,MESH_INDEX_OFFSET:19};function t(e,t,n){let r=Math.sqrt(e*e+t*t+n*n);r>0?(e/=r,t/=r,n/=r):(e=0,t=0,n=1);let i=Math.abs(e)+Math.abs(t)+Math.abs(n),a=e/i,o=t/i;if(n<0){let e=a,t=o;a=(1-Math.abs(t))*(e>=0?1:-1),o=(1-Math.abs(e))*(t>=0?1:-1)}let s=Math.round(Math.min(1,Math.max(-1,a))*32767)&65535;return((Math.round(Math.min(1,Math.max(-1,o))*32767)&65535)<<16|s)>>>0}const n={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826};n.TRIANGLE_LEAF;const r=e=>e>=2147483648,i=e=>~e>>>0>>>4,a=e=>~e&15,o=e.FLOATS_PER_TRIANGLE,s=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),c=e=>e instanceof Uint32Array?e:new Uint32Array(e.buffer,e.byteOffset,e.length),l=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:e,idx:t?e.viewAs(Uint32Array):c(e)}},u=(e,t)=>e.chunked?e.f.chunkFor(t):e.f,d=(e,t)=>e.chunked?e.idx.chunkFor(t):e.idx,f=(e,t)=>e.chunked?e.chunked.baseOf(t):t*m,p=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:t?t.viewAs(Float32Array):s(e),u:t?e:c(e)}},m=16,h=n.TRIANGLE_LEAF,g=n.BLAS_POINTER_LEAF;function _(e,t,n,r,i,a){let o=e[t+4],s=e[t+5],c=e[t+6],l=e[t+7],u=e[t+8],d=e[t+9],f=e[t+10],p=e[t+11],m=e[t+12],h=e[t+13],g=e[t+14],_=e[t+15],v=d*g-f*h,y=f*m-u*g,b=u*h-d*m,x=o*v+s*y+c*b,S=o===1&&d===1&&g===1&&s===0&&c===0&&u===0&&f===0&&m===0&&h===0&&l===0&&p===0&&_===0,C=(Math.abs(o)+Math.abs(s)+Math.abs(c))*(Math.abs(u)+Math.abs(d)+Math.abs(f))*(Math.abs(m)+Math.abs(h)+Math.abs(g));if(S||!Number.isFinite(x)||Math.abs(x)<=1e-12*C){for(let e=0;e<6;e++)i[a+e]=n[r+e];return}let w=1/x,T=v*w,E=y*w,D=b*w,O=(c*h-s*g)*w,k=(o*g-c*m)*w,A=(s*m-o*h)*w,j=(s*f-c*d)*w,M=(c*u-o*f)*w,N=(o*d-s*u)*w,P=1/0,F=1/0,I=1/0,L=-1/0,R=-1/0,z=-1/0;for(let e=0;e<8;e++){let t=(e&1?n[r+3]:n[r])-l,i=(e&2?n[r+4]:n[r+1])-p,a=(e&4?n[r+5]:n[r+2])-_,o=T*t+O*i+j*a,s=E*t+k*i+M*a,c=D*t+A*i+N*a;o<P&&(P=o),o>L&&(L=o),s<F&&(F=s),s>R&&(R=s),c<I&&(I=c),c>z&&(z=c)}i[a]=P,i[a+1]=F,i[a+2]=I,i[a+3]=L,i[a+4]=R,i[a+5]=z}function v(t,n,r,i,a){let s=e.POSITION_A_OFFSET,c=e.POSITION_B_OFFSET,l=e.POSITION_C_OFFSET,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0;for(let e=0;e<r;e++){let r=n+e,i=t.chunked?t.f.chunkFor(r):t.f,a=t.chunked?t.chunked.baseOf(r):r*o;u=Math.min(u,i[a+s],i[a+c],i[a+l]),d=Math.min(d,i[a+s+1],i[a+c+1],i[a+l+1]),f=Math.min(f,i[a+s+2],i[a+c+2],i[a+l+2]),p=Math.max(p,i[a+s],i[a+c],i[a+l]),m=Math.max(m,i[a+s+1],i[a+c+1],i[a+l+1]),h=Math.max(h,i[a+s+2],i[a+c+2],i[a+l+2])}i[a]=u,i[a+1]=d,i[a+2]=f,i[a+3]=p,i[a+4]=m,i[a+5]=h}const y=new Float32Array(12);function b(e,t,n,r){let i=u(e,t),a=d(e,t),o=f(e,t);if(a[o+3]===h){v(n,a[o],a[o+1],r,0);return}for(let e=0;e<3;e++)r[e]=Math.min(i[o+e],i[o+8+e]),r[3+e]=Math.max(i[o+4+e],i[o+12+e])}function x(e,t,n,o,s){let c=u(e,t),l=d(e,t),p=f(e,t),m=(t-s)*6,b=l[p+3];if(b===h){v(n,l[p],l[p+1],o,m);return}if(b===g){_(c,p,o,(l[p]-s)*6,o,m);return}let x=l[p+7],S=o,C=(b-s)*6;r(b)&&(v(n,i(b),a(b),y,0),S=y,C=0);let w=o,T=(x-s)*6;r(x)&&(v(n,i(x),a(x),y,6),w=y,T=6),c[p]=S[C],c[p+1]=S[C+1],c[p+2]=S[C+2],c[p+4]=S[C+3],c[p+5]=S[C+4],c[p+6]=S[C+5],c[p+8]=w[T],c[p+9]=w[T+1],c[p+10]=w[T+2],c[p+12]=w[T+3],c[p+13]=w[T+4],c[p+14]=w[T+5];for(let e=0;e<3;e++)o[m+e]=Math.min(S[C+e],w[T+e]),o[m+3+e]=Math.max(S[C+3+e],w[T+3+e])}var S=class{constructor(){this._bounds=null,this._boundsNodeCount=0,this._tlasBounds=null,this._rootBox=null}updateTrianglePositions(n,r,i){let a=i.length,s=p(n);for(let n=0;n<a;n++){let a=i[n],c=s.chunked?s.f.chunkFor(n):s.f,l=s.chunked?s.u.chunkFor(n):s.u,u=s.chunked?s.chunked.baseOf(n):n*o,d=a*9,f=r[d],p=r[d+1],m=r[d+2],h=r[d+3],g=r[d+4],_=r[d+5],v=r[d+6],y=r[d+7],b=r[d+8];c[u+e.POSITION_A_OFFSET]=f,c[u+e.POSITION_A_OFFSET+1]=p,c[u+e.POSITION_A_OFFSET+2]=m,c[u+e.POSITION_B_OFFSET]=h,c[u+e.POSITION_B_OFFSET+1]=g,c[u+e.POSITION_B_OFFSET+2]=_,c[u+e.POSITION_C_OFFSET]=v,c[u+e.POSITION_C_OFFSET+1]=y,c[u+e.POSITION_C_OFFSET+2]=b;let x=h-f,S=g-p,C=_-m,w=v-f,T=y-p,E=b-m,D=t(S*E-C*T,C*w-x*E,x*T-S*w);l[u+e.NORMAL_A_PACKED_OFFSET]=D,l[u+e.NORMAL_B_PACKED_OFFSET]=D,l[u+e.NORMAL_C_PACKED_OFFSET]=D}}refitRange(e,t,n,r){let i=p(t);r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let a=l(e);for(let e=n+r-1;e>=n;e--)x(a,e,i,this._bounds,n)}refitPartial(e,t,n,r){for(let r=0;r<n.length;r+=2)this.refitRange(e,t,n[r],n[r+1]);let i=p(t),a=l(e);(!this._tlasBounds||this._tlasBounds.length<r*6)&&(this._tlasBounds=new Float32Array(r*6));let o=this._tlasBounds,s=this._rootBox||=new Float32Array(6);for(let e=r-1;e>=0;e--){let t=d(a,e),n=f(a,e);t[n+3]===g?(b(a,t[n],i,s),_(u(a,e),n,s,0,o,e*6)):x(a,e,i,o,0)}}refit(e,t,n){let r=p(t);n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let i=l(e);for(let e=n-1;e>=0;e--)x(i,e,r,this._bounds,0)}};const C=64*1024*1024;function w(e,t,n){return n?new e(new SharedArrayBuffer(t*e.BYTES_PER_ELEMENT)):new e(t)}var T=class e{constructor(e,t,n,r=C,i=!1){let a=t*n.BYTES_PER_ELEMENT,o=Math.max(1,Math.floor(r/a));this.recordCount=e,this.lanesPerRecord=t,this.LaneType=n,this.recordsPerChunk=e<=o?Math.max(e,1):o,this.shared=i,this.chunks=[];let s=e;for(;s>0;){let e=Math.min(s,this.recordsPerChunk);this.chunks.push(w(n,e*t,i)),s-=e}this.chunks.length===0&&this.chunks.push(w(n,0,i))}static adopt(t,n,r,i){let a=Object.create(e.prototype);return a.recordCount=n,a.lanesPerRecord=r,a.LaneType=t[0]?.constructor??null,a.recordsPerChunk=i,a.chunks=t,a.shared=typeof SharedArrayBuffer<`u`&&t[0]?.buffer instanceof SharedArrayBuffer,a}static lazy(t,n,r,i=C,a=!1){let o=Math.max(1,Math.floor(i/(n*r.BYTES_PER_ELEMENT))),s=Object.create(e.prototype);return s.recordCount=t,s.lanesPerRecord=n,s.LaneType=r,s.recordsPerChunk=t<=o?Math.max(t,1):o,s.shared=a,s.chunks=Array(Math.max(1,Math.ceil(t/s.recordsPerChunk))),s._views=[],s}_materialize(e){if(this._owner)return this._owner._materialize(e),this.chunks[e];let t=e*this.recordsPerChunk,n=Math.min(this.recordsPerChunk,this.recordCount-t)*this.lanesPerRecord,r=this.chunks[e]=w(this.LaneType,n,this.shared);for(let t of this._liveViews())t.chunks[e]=new t.LaneType(r.buffer,r.byteOffset,r.byteLength/t.LaneType.BYTES_PER_ELEMENT);return r}materializeAll(){for(let e=0;e<this.chunks.length;e++)!this.chunks[e]&&!this._spilled?.has(e)&&this._materialize(e);return this}get chunkCount(){return this.chunks.length}get single(){return this.chunks.length===1?this.chunks[0]:null}get byteLength(){let e=0;for(let t of this.chunks)t&&(e+=t.byteLength);return e}chunkFor(e){let t=e/this.recordsPerChunk|0,n=this.chunks[t];if(n)return n;if(this._spilled?.has(t))throw Error(`ChunkedRecords: chunk ${t} is on disk — await ensureResident() before touching record ${e}`);return this._materialize(t)}async spill(e,{keep:t=()=>!1}={}){if(this._owner)throw Error(`ChunkedRecords: spill the storage, not a view of it`);this._store=e,this._spilled??=new Set;let n=0;for(let r=0;r<this.chunks.length;r++){let i=this.chunks[r];if(!(!i||t(r))){await e.write(r,i),this.chunks[r]=null;for(let e of this._liveViews())e.chunks[r]=null;this._spilled.add(r),n+=i.byteLength}}return n}async spillChunk(e,t){let n=this.chunks[e];if(!n)return 0;this._store=t,this._spilled??=new Set,await t.write(e,n),this.chunks[e]=null;for(let t of this._liveViews())t.chunks[e]=null;return this._spilled.add(e),n.byteLength}async ensureResident(e=0,t=this.recordCount){if(!this._spilled?.size||t<=0)return;let n=e/this.recordsPerChunk|0,r=(e+t-1)/this.recordsPerChunk|0;for(let e=n;e<=r;e++){if(!this._spilled.has(e))continue;let t=Math.min(this.recordsPerChunk,this.recordCount-e*this.recordsPerChunk)*this.lanesPerRecord,n=await this._store.read(e,t*this.LaneType.BYTES_PER_ELEMENT),r=w(this.LaneType,t,this.shared);new Uint8Array(r.buffer,r.byteOffset,r.byteLength).set(new Uint8Array(n)),this.chunks[e]=r;for(let t of this._liveViews())t.chunks[e]=new t.LaneType(r.buffer,r.byteOffset,r.byteLength/t.LaneType.BYTES_PER_ELEMENT);this._spilled.delete(e)}}_liveViews(){return this._weakViews&&=this._weakViews.filter(e=>e.deref()),[...this._views??[],...(this._weakViews??[]).map(e=>e.deref())]}isResident(e=0,t=this.recordCount){if(!this._spilled?.size||t<=0)return!0;let n=e/this.recordsPerChunk|0,r=(e+t-1)/this.recordsPerChunk|0;for(let e=n;e<=r;e++)if(this._spilled.has(e))return!1;return!0}get spilledChunks(){return this._spilled?.size??0}baseOf(e){return e%this.recordsPerChunk*this.lanesPerRecord}isContiguous(e,t){return t<=0?!0:(e/this.recordsPerChunk|0)==((e+t-1)/this.recordsPerChunk|0)}slice(e,t){let n=this.baseOf(e),r=t*this.lanesPerRecord;if(this.isContiguous(e,t))return this.chunkFor(e).subarray(n,n+r);let i=new this.LaneType(r);return this.readRecords(e,t,i),i}readRecords(e,t,n){let r=0;for(;r<t;){let i=e+r,a=this.chunkFor(i),o=this.baseOf(i),s=this.recordsPerChunk-i%this.recordsPerChunk,c=Math.min(s,t-r);n.set(a.subarray(o,o+c*this.lanesPerRecord),r*this.lanesPerRecord),r+=c}return n}setRecords(e,t){let n=t.length/this.lanesPerRecord,r=0;for(;r<n;){let i=e+r,a=this.chunkFor(i),o=this.baseOf(i),s=this.recordsPerChunk-i%this.recordsPerChunk,c=Math.min(s,n-r);a.set(t.subarray(r*this.lanesPerRecord,(r+c)*this.lanesPerRecord),o),r+=c}}copyOf(e,t){return this.readRecords(e,t,new this.LaneType(t*this.lanesPerRecord))}trimTo(t){let n=Math.max(1,Math.ceil(t/this.recordsPerChunk)),r=this.chunks.slice(0,n),i=(t-(n-1)*this.recordsPerChunk)*this.lanesPerRecord,a=r[n-1];return a.length>i&&(r[n-1]=a.subarray(0,Math.max(0,i))),e.adopt(r,t,this.lanesPerRecord,this.recordsPerChunk)}grow(e){if(e<=this.recordCount)return;let t=this.chunks.length-1,n=(e,t)=>Math.min(this.recordsPerChunk,t-e*this.recordsPerChunk)*this.lanesPerRecord,r=this.chunks[t];this.recordCount=e;for(let t of this._liveViews())t.recordCount=e;if(this.chunks.length*this.recordsPerChunk<e){this.chunks.length=Math.ceil(e/this.recordsPerChunk);for(let e of this._liveViews())e.chunks.length=this.chunks.length}if(r&&r.length<n(t,e)){let i=w(this.LaneType,n(t,e),this.shared);i.set(r),this.chunks[t]=i;for(let e of this._liveViews())e.chunks[t]=new e.LaneType(i.buffer,i.byteOffset,i.byteLength/e.LaneType.BYTES_PER_ELEMENT)}else if(!r&&this._spilled?.has(t))throw Error(`ChunkedRecords: cannot grow past chunk ${t}, which is on disk`)}release(e,t){let n=this.recordsPerChunk,r=Math.ceil(e/n),i=Math.floor((e+t)/n),a=0;for(let e=r;e<i;e++){let t=this.chunks[e];if(t){a+=t.byteLength,this.chunks[e]=void 0;for(let t of this._liveViews())t.chunks[e]=void 0}}return a}trimInPlace(e){let t=Math.max(1,Math.ceil(e/this.recordsPerChunk)),n=Math.max(0,(e-(t-1)*this.recordsPerChunk)*this.lanesPerRecord),r=[this,...this._liveViews()];for(let i of r){i.chunks.length=t;let r=i.chunks[t-1];r&&r.length>n&&(i.chunks[t-1]=r.subarray(0,n)),i.recordCount=e}if(this._spilled)for(let e of this._spilled)e>=t&&this._spilled.delete(e);return this}viewAs(t){let n=e=>new t(e.buffer,e.byteOffset,e.byteLength/t.BYTES_PER_ELEMENT),r=e.adopt(this.chunks.map(e=>e?n(e):void 0),this.recordCount,this.lanesPerRecord,this.recordsPerChunk);return r.LaneType=t,r._owner=this,this._views?this._views.push(r):(this._weakViews??=[]).push(new WeakRef(r)),r._spilled=this._spilled??=new Set,r}};const E=new S;let D=null,O=null,k=0;self.onmessage=function(e){let{type:t}=e.data;if(t===`init`){D=T.adopt(e.data.sharedBvhBufs.map(e=>new Float32Array(e)),e.data.bvhRecordCount,16,e.data.bvhRecordsPerChunk),O=T.adopt(e.data.sharedTriBufs.map(e=>new Uint32Array(e)),e.data.triRecordCount,e.data.triLanesPerRecord,e.data.triRecordsPerChunk),k=D.recordCount;return}if(t===`refit`)try{let t=performance.now(),{blasRanges:n,tlasNodeCount:r}=e.data;n?E.refitPartial(D,O,n,r):E.refit(D,O,k),self.postMessage({type:`refitComplete`,refitTimeMs:performance.now()-t})}catch(e){console.error(`[BVHRefitWorker] Refit error:`,e),self.postMessage({type:`error`,error:e.message})}};",Rs=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Ls],{type:`text/javascript;charset=utf-8`});function zs(e){let t;try{if(t=Rs&&(self.URL||self.webkitURL).createObjectURL(Rs),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Ls),{type:`module`,name:e?.name})}}var Bs="const e={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826};function t(e){return new Uint32Array(e.buffer,e.byteOffset,e.length)}function n(e,t){if(e>=1073741824)throw RangeError(`${t} is ${e.toLocaleString()}, at or past the BVH index limit of ${1073741824 .toLocaleString()}. Node indices are stored as u32 bit patterns and the leaf tags occupy everything above that.`);return e}const r=Float64Array.from([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function i(e,t){return e[t]*(e[t+5]*e[t+10]-e[t+6]*e[t+9])-e[t+4]*(e[t+1]*e[t+10]-e[t+2]*e[t+9])+e[t+8]*(e[t+1]*e[t+6]-e[t+2]*e[t+5])}function a(e,t,n){let a=i(e,t);if(!Number.isFinite(a)||Math.abs(a)<1e-20)return n.set(r),n;let o=1/a;return n[0]=(e[t+5]*e[t+10]-e[t+6]*e[t+9])*o,n[1]=(e[t+2]*e[t+9]-e[t+1]*e[t+10])*o,n[2]=(e[t+1]*e[t+6]-e[t+2]*e[t+5])*o,n[3]=0,n[4]=(e[t+6]*e[t+8]-e[t+4]*e[t+10])*o,n[5]=(e[t]*e[t+10]-e[t+2]*e[t+8])*o,n[6]=(e[t+2]*e[t+4]-e[t]*e[t+6])*o,n[7]=0,n[8]=(e[t+4]*e[t+9]-e[t+5]*e[t+8])*o,n[9]=(e[t+1]*e[t+8]-e[t]*e[t+9])*o,n[10]=(e[t]*e[t+5]-e[t+1]*e[t+4])*o,n[11]=0,n[12]=-(n[0]*e[t+12]+n[4]*e[t+13]+n[8]*e[t+14]),n[13]=-(n[1]*e[t+12]+n[5]*e[t+13]+n[9]*e[t+14]),n[14]=-(n[2]*e[t+12]+n[6]*e[t+13]+n[10]*e[t+14]),n[15]=1,n}function o(e,t){for(let n=0;n<16;n++)if(e[t+n]!==r[n])return!1;return!0}const s=e=>e<32?e:32,c=new Float64Array(16);var l=class r{constructor(){this._flatBuffer=null,this._flatBufferCapacity=0,this._binCounts=new Int32Array(96),this._binBounds=new Float64Array(576),this._binSuffix=new Float64Array(32),this._binSuffixCount=new Int32Array(32),this._order=null,this._stackI=null,this._stackB=null,this._stackFrames=0,this._sortScratch=[],this._suffix=null,this._bounds=new Float64Array(12),this._extent=new Float64Array(3),this._cMin=new Float64Array(3)}static nodeCountFor(e){return e>0?e*2-1:0}releaseFlattenBuffer(){this._flatBuffer=null,this._flatBufferCapacity=0}build(e){let t=new Float64Array(e.count*6);e.writeWorldAABBs(t);let n=this.buildStructure(t,e.count);return r.fillLeaves(n.data,n.nodeCount,e),n}buildStructure(i,a){let o=r.nodeCountFor(a);if(a===0)return{data:new Float32Array,nodeCount:0};n(o,`TLAS node count`);let s=o*16;s>this._flatBufferCapacity&&(this._flatBuffer=new Float32Array(s),this._flatBufferCapacity=s);let c=this._flatBuffer,l=t(c);(!this._order||this._order.length<a)&&(this._order=new Int32Array(a));let u=this._order;for(let e=0;e<a;e++)u[e]=e;this._ensureStack(64);let d=0,f=0,p=0,m=a,h=this._bounds;this._rangeBounds(i,u,p,m,h,0);let g=h[0],_=h[1],v=h[2],y=h[3],b=h[4],x=h[5];for(;;){if(m-p===1){let t=f*16;l[t]=0,l[t+1]=u[p],c[t+2]=0,l[t+3]=e.BLAS_POINTER_LEAF}else{let e=this._partition(i,u,p,m,g,_,v,y,b,x),t=e-p,n=f+1,r=n+(t*2-1),a=f*16;c[a]=h[0],c[a+1]=h[1],c[a+2]=h[2],l[a+3]=n,c[a+4]=h[3],c[a+5]=h[4],c[a+6]=h[5],l[a+7]=r,c[a+8]=h[6],c[a+9]=h[7],c[a+10]=h[8],c[a+11]=0,c[a+12]=h[9],c[a+13]=h[10],c[a+14]=h[11],c[a+15]=0;let o=t<=m-e,s=o?0:6,S=o?6:0;d=this._push(d,o?r:n,o?e:p,o?m:e,h,S),f=o?n:r,o?m=e:p=e,g=h[s],_=h[s+1],v=h[s+2],y=h[s+3],b=h[s+4],x=h[s+5];continue}if(d===0)break;d--;let t=d*3,n=d*6;f=this._stackI[t],p=this._stackI[t+1],m=this._stackI[t+2],g=this._stackB[n],_=this._stackB[n+1],v=this._stackB[n+2],y=this._stackB[n+3],b=this._stackB[n+4],x=this._stackB[n+5]}return{data:c.subarray(0,s),nodeCount:o}}_push(e,t,n,r,i,a){e>=this._stackFrames&&this._ensureStack(this._stackFrames*2);let o=e*3,s=e*6;this._stackI[o]=t,this._stackI[o+1]=n,this._stackI[o+2]=r;for(let e=0;e<6;e++)this._stackB[s+e]=i[a+e];return e+1}_ensureStack(e){if(this._stackFrames>=e)return;let t=new Int32Array(e*3),n=new Float64Array(e*6);this._stackI&&(t.set(this._stackI),n.set(this._stackB)),this._stackI=t,this._stackB=n,this._stackFrames=e}static fillLeaves(n,i,a){let o=a.world,s=a.sourceMesh,c=a.tplBlasOffset,l=a.visible,u=a.tlasLeafIndex,d=t(n);for(let t=0;t<i;t++){let i=t*16;if(d[i+3]!==e.BLAS_POINTER_LEAF)continue;let a=d[i+1]&1073741823;d[i]=c[s[a]],n[i+2]=+!!l[a],r.writeLeafMatrix(n,d,i,o,a),u[a]=t}}static writeLeafMatrix(e,t,n,r,i){let s=c;a(r,i*16,s),e[n+4]=s[0],e[n+5]=s[4],e[n+6]=s[8],e[n+7]=s[12],e[n+8]=s[1],e[n+9]=s[5],e[n+10]=s[9],e[n+11]=s[13],e[n+12]=s[2],e[n+13]=s[6],e[n+14]=s[10],e[n+15]=s[14],t[n+1]=(i|(o(r,i*16)?1073741824:0))>>>0}_partition(e,t,n,r,i,a,o,s,c,l){let u=r-n,d=0;if(u===2)d=n+1;else if(u<=8)d=n+(u>>1),this._insertionSortRange(e,t,n,r,this._widestCentroidAxis(e,t,n,r));else{if(d=this._binnedSplit(e,t,n,r,i,a,o,s,c,l),d>n&&d<r)return d;if(d=this._sweepSplit(e,t,n,r,i,a,o,s,c,l),!(d>n&&d<r)){let f=s-i,p=c-a,m=l-o,h=p>f&&p>m?1:m>f?2:0;this._sortRange(e,t,n,r,h),d=n+(u>>1)}}let f=this._bounds;return this._rangeBounds(e,t,n,d,f,0),this._rangeBounds(e,t,d,r,f,6),d}_binnedSplit(e,t,n,r,i,a,o,c,l,u){let d=this._surfaceArea(i,a,o,c,l,u);if(!(d>0)||!isFinite(d))return n;let f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,_=-1/0;for(let i=n;i<r;i++){let n=t[i]*6,r=(e[n]+e[n+3])*.5,a=(e[n+1]+e[n+4])*.5,o=(e[n+2]+e[n+5])*.5;r<f&&(f=r),r>h&&(h=r),a<p&&(p=a),a>g&&(g=a),o<m&&(m=o),o>_&&(_=o)}let v=this._extent,y=this._cMin;v[0]=h-f,v[1]=g-p,v[2]=_-m,y[0]=f,y[1]=p,y[2]=m;let b=1/0,x=-1,S=-1,C=this._binCounts,w=this._binBounds,T=v[0]>1e-12,E=v[1]>1e-12,D=v[2]>1e-12;if(!T&&!E&&!D)return n;let O=s(r-n),k=T?O/v[0]:0,A=E?O/v[1]:0,j=D?O/v[2]:0;C.fill(0,0,O*3);for(let e=0;e<O*3;e++){let t=e*6;w[t]=w[t+1]=w[t+2]=1/0,w[t+3]=w[t+4]=w[t+5]=-1/0}for(let i=n;i<r;i++){let n=t[i]*6,r=e[n],a=e[n+1],o=e[n+2],s=e[n+3],c=e[n+4],l=e[n+5];for(let e=0;e<3;e++){let t=e===0?k:e===1?A:j;if(t===0)continue;let n=((e===0?(r+s)*.5:e===1?(a+c)*.5:(o+l)*.5)-y[e])*t|0;n<0?n=0:n>=O&&(n=O-1),n+=e*O,C[n]++;let i=n*6;r<w[i]&&(w[i]=r),a<w[i+1]&&(w[i+1]=a),o<w[i+2]&&(w[i+2]=o),s>w[i+3]&&(w[i+3]=s),c>w[i+4]&&(w[i+4]=c),l>w[i+5]&&(w[i+5]=l)}}for(let e=0;e<3;e++){if(!(v[e]>1e-12))continue;let t=e*O,n=this._binSuffix,r=this._binSuffixCount,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0,u=0;for(let e=O-1;e>=1;e--){let d=(t+e)*6;w[d]<i&&(i=w[d]),w[d+1]<a&&(a=w[d+1]),w[d+2]<o&&(o=w[d+2]),w[d+3]>s&&(s=w[d+3]),w[d+4]>c&&(c=w[d+4]),w[d+5]>l&&(l=w[d+5]),u+=C[t+e],n[e]=u?this._surfaceArea(i,a,o,s,c,l):0,r[e]=u}let f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,_=-1/0,y=0;for(let i=1;i<O;i++){let a=(t+i-1)*6;if(w[a]<f&&(f=w[a]),w[a+1]<p&&(p=w[a+1]),w[a+2]<m&&(m=w[a+2]),w[a+3]>h&&(h=w[a+3]),w[a+4]>g&&(g=w[a+4]),w[a+5]>_&&(_=w[a+5]),y+=C[t+i-1],y===0||r[i]===0)continue;let o=1+(this._surfaceArea(f,p,m,h,g,_)*y+n[i]*r[i])/d;o<b&&(b=o,x=e,S=i)}}if(x<0)return n;let M=O/v[x],N=y[x],P=this._bounds;P[0]=P[1]=P[2]=P[6]=P[7]=P[8]=1/0,P[3]=P[4]=P[5]=P[9]=P[10]=P[11]=-1/0;let F=n,I=r-1;for(;F<=I;){let n=t[F]*6,r=((e[n+x]+e[n+3+x])*.5-N)*M|0;r<0?r=0:r>=O&&(r=O-1);let i=r<S?0:6;if(e[n]<P[i]&&(P[i]=e[n]),e[n+1]<P[i+1]&&(P[i+1]=e[n+1]),e[n+2]<P[i+2]&&(P[i+2]=e[n+2]),e[n+3]>P[i+3]&&(P[i+3]=e[n+3]),e[n+4]>P[i+4]&&(P[i+4]=e[n+4]),e[n+5]>P[i+5]&&(P[i+5]=e[n+5]),i===0)F++;else{let e=t[F];t[F]=t[I],t[I]=e,I--}}return F}_sweepSplit(e,t,n,r,i,a,o,s,c,l){let u=r-n,d=this._surfaceArea(i,a,o,s,c,l);if(!(d>0)||!isFinite(d))return n;let f=this._suffixBuffer(u),p=1/0,m=-1,h=-1;for(let i=0;i<3;i++){this._sortRange(e,t,n,r,i);let a=1/0,o=1/0,s=1/0,c=-1/0,l=-1/0,g=-1/0;for(let r=u-1;r>=1;r--){let i=t[n+r]*6;e[i]<a&&(a=e[i]),e[i+1]<o&&(o=e[i+1]),e[i+2]<s&&(s=e[i+2]),e[i+3]>c&&(c=e[i+3]),e[i+4]>l&&(l=e[i+4]),e[i+5]>g&&(g=e[i+5]);let u=r*6;f[u]=a,f[u+1]=o,f[u+2]=s,f[u+3]=c,f[u+4]=l,f[u+5]=g}let _=1/0,v=1/0,y=1/0,b=-1/0,x=-1/0,S=-1/0;for(let r=1;r<u;r++){let a=t[n+r-1]*6;e[a]<_&&(_=e[a]),e[a+1]<v&&(v=e[a+1]),e[a+2]<y&&(y=e[a+2]),e[a+3]>b&&(b=e[a+3]),e[a+4]>x&&(x=e[a+4]),e[a+5]>S&&(S=e[a+5]);let o=r*6,s=this._surfaceArea(_,v,y,b,x,S),c=this._surfaceArea(f[o],f[o+1],f[o+2],f[o+3],f[o+4],f[o+5]),l=1+(s*r+c*(u-r))/d;l<p&&(p=l,m=i,h=r)}}return m<0||h<=0?n:(m!==2&&this._sortRange(e,t,n,r,m),n+h)}_widestCentroidAxis(e,t,n,r){let i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let u=n;u<r;u++){let n=t[u]*6,r=(e[n]+e[n+3])*.5,d=(e[n+1]+e[n+4])*.5,f=(e[n+2]+e[n+5])*.5;r<i&&(i=r),r>s&&(s=r),d<a&&(a=d),d>c&&(c=d),f<o&&(o=f),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o;return d>u&&d>f?1:f>u?2:0}_insertionSortRange(e,t,n,r,i){let a=i,o=3+i;for(let i=n+1;i<r;i++){let r=t[i],s=e[r*6+a]+e[r*6+o],c=i-1;for(;c>=n&&e[t[c]*6+a]+e[t[c]*6+o]>s;)t[c+1]=t[c],c--;t[c+1]=r}}_sortRange(e,t,n,r,i){let a=r-n,o=this._sortScratch;o.length=a;for(let e=0;e<a;e++)o[e]=t[n+e];let s=i,c=3+i;o.sort((t,n)=>e[t*6+s]+e[t*6+c]-(e[n*6+s]+e[n*6+c]));for(let e=0;e<a;e++)t[n+e]=o[e]}_suffixBuffer(e){let t=e*6;return(!this._suffix||this._suffix.length<t)&&(this._suffix=new Float64Array(t)),this._suffix}_rangeBounds(e,t,n,r,i,a){let o=1/0,s=1/0,c=1/0,l=-1/0,u=-1/0,d=-1/0;for(let i=n;i<r;i++){let n=t[i]*6;e[n]<o&&(o=e[n]),e[n+1]<s&&(s=e[n+1]),e[n+2]<c&&(c=e[n+2]),e[n+3]>l&&(l=e[n+3]),e[n+4]>u&&(u=e[n+4]),e[n+5]>d&&(d=e[n+5])}i[a]=o,i[a+1]=s,i[a+2]=c,i[a+3]=l,i[a+4]=u,i[a+5]=d}_surfaceArea(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}};const u={silent:0,error:1,warn:2,info:3,debug:4},d=`info`,f=`rayzeeLogLevel`,p=`rayzeeLogNamespaces`,m=`color:#7c8494`,h=`color:inherit`;let g=null,_=null;function v(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function y(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function b(){if(g!==null)return g;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in u?(g=u[e],g):(g=u[v(f)]??u[d],g)}function x(){if(_!==null)return _;let e=globalThis.__RAYZEE_LOG_NS__??v(p);return _=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],_}function S(e,t){if(t<u.debug)return!0;let n=x();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function C(e,t,n){if(e>b()||!S(t,e))return;let r=e===u.error?console.error:e===u.warn?console.warn:console.log,i=`[${t}]`;typeof n[0]==`string`?r(`%c${i}%c ${n[0]}`,m,h,...n.slice(1)):r(`%c${i}`,m,...n)}const w={n:e=>Number(e).toLocaleString(`en-US`),ms:e=>e<10?`${Number(e).toFixed(1)} ms`:`${Math.round(e)} ms`,mb:e=>{let t=e/(1024*1024);return t<10?`${t.toFixed(1)} MB`:`${Math.round(t)} MB`},px:(e,t)=>`${e}×${t}`,count:(e,t,n=`${t}s`)=>`${w.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},T={levels:u,setLevel(e){return e in u?(globalThis.__RAYZEE_LOG_LEVEL__=e,g=u[e],y(f,e===d?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(u).join(`, `)}`),this.getLevel())},getLevel(){let e=b();return Object.keys(u).find(t=>u[t]===e)},isEnabled(e){return(u[e]??u.debug)<=b()},only(...e){let t=e.flat().filter(Boolean);return _=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),y(p,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return g=null,_=null,this.getLevel()}};function E(e){return{namespace:e,error:(...t)=>C(u.error,e,t),warn:(...t)=>C(u.warn,e,t),info:(...t)=>C(u.info,e,t),debug:(...t)=>C(u.debug,e,t),isEnabled:e=>T.isEnabled(e),summary(t,n=[]){let r=n.filter(Boolean);if(r.length===0||!console.groupCollapsed){C(u.info,e,[t]),r.forEach(t=>C(u.debug,e,[t]));return}u.info>b()||((b()>=u.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,m,h),r.forEach(e=>console.log(e)),console.groupEnd())}}}function D(e){e&&e in u&&(globalThis.__RAYZEE_LOG_LEVEL__=e,g=u[e])}const O=E(`bvh`);self.onmessage=function(e){let{aabbs:t,count:n,logLevel:r}=e.data;D(r);try{let e=performance.now(),{data:r,nodeCount:i}=new l().buildStructure(new Float64Array(t),n);O.debug(`TLAS ${w.n(i)} nodes in ${w.ms(performance.now()-e)}`),self.postMessage({tlasData:r,nodeCount:i},[r.buffer])}catch(e){O.error(`TLAS build failed:`,e),self.postMessage({error:e.message})}};",Vs=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Bs],{type:`text/javascript;charset=utf-8`});function Hs(e){let t;try{if(t=Vs&&(self.URL||self.webkitURL).createObjectURL(Vs),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Bs),{type:`module`,name:e?.name})}}$t(),Ae(),wt(),X(),Nr(),zr();var Us=5e4,Ws=2e5,Gs=2e6,Ks=1<<19,qs=4e7,Js=1.5*1024**3,Ys=256*1024*1024,Xs=ye(`scene`),Zs=e=>Array.isArray(e)?e:[e],Qs=e=>Zs(e).reduce((e,t)=>e+t.byteLength,0),$s=64*1024*1024;async function ec(e,t,n){for(let r of Zs(n))await e.writeAt(t,r),t+=r.byteLength}function tc(e){let t=0;return e.traverse(e=>{let n=e.isMesh?e.geometry:null;n&&(t=Math.max(t,Math.ceil((n.index?n.index.count:n.attributes.position?.count??0)/3)))}),t}var nc=class{constructor(e={}){this.config={useWorkers:!0,bvhDepth:30,maxLeafSize:4,verbose:!1,useFloat32Array:!0,textureQuality:`adaptive`,maxTextureSize:Nt.DEFAULT_MAX_TEXTURE_SIZE,enableTextureCache:!0,maxConcurrentTextureTasks:Math.min(ar(),6),maxSceneBytes:ja,sceneCache:!0,sceneCacheMinBuildMs:Ps,...e},this.triangleData=null,this.triangleFloats=null,this.triangleCount=0,this.materials=[],this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.roughnessMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.displacementMaps=[],this.anisotropyMaps=[],this.transmissionMaps=[],this.clearcoatMaps=[],this.clearcoatRoughnessMaps=[],this.sheenColorMaps=[],this.sheenRoughnessMaps=[],this.iridescenceMaps=[],this.iridescenceThicknessMaps=[],this.specularIntensityMaps=[],this.specularColorMaps=[],this.diffuseTransmissionMaps=[],this.diffuseTransmissionColorMaps=[],this.directionalLights=[],this.cameras=[],this.spheres=[],this.bvhRoot=null,this.bvh=null,this.bvhData=null,this.bvhIndexChunks=null,this.bvhIndex=null,this.materialData=null,this.instanceTable=null,this._refitWorker=null,this._refitSharedBuffers=null,this._rebuildGeneration=0,this._pendingRebuilds=new Map,this.srgbBucketTextures=null,this.linearBucketTextures=null,this.emissiveTriangleData=null,this.emissiveTriangleCount=0,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._initProcessors(),this.isProcessing=!1,this.processingStage=null,this.memory=new Ia,this.memoryPreflight=null,this.performanceMetrics={textureCreationTime:0,geometryExtractionTime:0,bvhBuildTime:0,blasBuildTime:0,blasWorkerTime:0,tlasBuildTime:0,bvhAssembleTime:0,totalProcessingTime:0}}setMaxTextureSize(e){return this.config.maxTextureSize=e,this.textureCreator?.setMaxTextureSize(e)}_initProcessors(){this.geometryExtractor=new Dn({issues:this.config.issues}),this.bvhBuilder=new Di,this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.textureCreator=new es({maxTextureSize:this.config.maxTextureSize,issues:this.config.issues}),this.emissiveTriangleBuilder=new cs,this.tlasBuilder=new xa,this._tlasWorker=null,this._tlasWorkerFailed=!1}_log(e,t){t===void 0?Xs.debug(e):Xs.debug(e,t)}_preflightMemory(e){let t=this.config.maxSceneBytes??9663676416,n=this.geometryExtractor.surveyScene(e),r=Ca(n);if(this._progressive&&(r.total-=r.bvh),this._streaming){let t=Js+tc(e)*(K.FLOATS_PER_TRIANGLE*4+44);r.total-=Math.max(0,r.triangles-t)}let i={...n,estimate:r,safeBytes:Aa,maxBytes:t,fits:r.total<=Aa};if(this.memoryPreflight=i,r.total<1610612736)return i;if(Xs.debug(H.list([`memory preflight: ${H.mb(r.total)} estimated`,`triangles ${H.mb(r.triangles)} · bvh ${H.mb(r.bvh)} · geometry ${H.mb(r.geometry)}`,`${H.n(n.triangles)} tris · ${H.n(n.placements)} placements`])),r.total>t){let e=`Scene needs about ${H.mb(r.total)} of CPU memory, past the ${H.mb(t)} a browser tab can hold — loading it would crash the tab rather than fail. Reduce the scene (it has ${H.n(n.triangles)} triangles), or raise maxSceneBytes to try anyway.`;throw this.config.issues?.record(Y.SCENE_MEMORY_BUDGET,e,{...n,estimate:r,maxBytes:t}),Error(e)}return i.fits||this.config.issues?.warn(Y.SCENE_MEMORY_BUDGET,`Scene needs about ${H.mb(r.total)} of CPU memory, above the ${H.mb(Aa)} a fresh browser session can usually place. It may still load, but a long-running session will probably fail during BVH assembly; restarting the browser recovers the address space.`,{...n,estimate:r,safeBytes:Aa}),i}_checkAssemblyHeadroom(e){let t=e*64;if(t<1610612736)return!0;let n=wa(Math.ceil(t*Pa),{shared:Xt});return this.memoryPreflight&&(this.memoryPreflight.assemblyProbed=n.placed),n.exhausted&&this.config.issues?.warn(Y.SCENE_MEMORY_BUDGET,`BVH assembly needs ${H.mb(t)} but only ${H.mb(n.placed)} could be allocated. Restarting the browser usually recovers the address space.`,{totalNodes:e,need:t,placeable:n.placed}),!n.exhausted}_liveMemoryParts(){let e=this.instanceTable,t={triangles:this.triangles?.byteLength??0,bvh:this.bvh?.byteLength??0,geometry:this._geometryBytes??this.memoryPreflight?.geometryBytes??0,placements:e?.world?.byteLength??0,blasScratch:0,orderMaps:0};if(e){for(let n of e.blasData.values())t.blasScratch+=n?Qs(n):0;for(let n of e.bvhToOriginal.values())t.orderMaps+=n?.byteLength??0;for(let n of e.originalToBvhMap.values())t.orderMaps+=n?.byteLength??0}return t}sceneBounds(){if(!this.bvh||this.bvh.recordCount===0)return null;let e=this.bvh.chunkFor(0),t=this.bvh.baseOf(0),n=[],r=[];for(let i=0;i<3;i++)n.push(Math.min(e[t+i],e[t+8+i])),r.push(Math.max(e[t+4+i],e[t+12+i]));return{min:n,max:r}}_sampleMemory(e){this.memory.sample(e,this._liveMemoryParts())}_logMemoryReport(){let{allocatedBytes:e,peakLiveBytes:t,byPhase:n}=this.memory;if(e===0)return;let r=Object.keys(n).filter(e=>n[e].allocated>0).map(e=>`${e} ${H.mb(n[e].allocated)}`),i=this.memoryPreflight?.estimate?.total;Xs.debug(H.list([`memory: peak live ${H.mb(t)}`,`allocated ${H.mb(e)}`,i?`predicted ${H.mb(i)}`:null,r.join(` · `)]))}async buildBVH(e,{sceneKey:t=null,progressive:n=null}={}){if(this.isProcessing)throw Error(`Already processing a scene. Call dispose() first.`);this.isProcessing=!0,this.processingStage=`init`,this.memory.reset(),this._geometryBytes=0,qt(e=>this.memory.alloc(e));let r=new ls(e.name??``,{namespace:`scene`});try{this._reset(),this._sceneKey=t,this._blasKey=null,this._blasRestored=!1,this._progressive=n?.storage&&n.uploader?n:null;let i=this.geometryExtractor._countStoredTriangles(e);this._streaming=!!this._progressive&&i>Math.floor(67108864/(K.FLOATS_PER_TRIANGLE*4)),this._foldLeaves=i>qs,this.bvhBuilder.foldLeaves=this._foldLeaves,this._log(`Starting scene processing`),this.memory.mark(`preflight`),this._preflightMemory(e),this.processingStage=`extraction`,this.memory.mark(`extraction`),r.start(`Geometry extraction`),this._streaming?await this._extractStreaming(e):await this._extractGeometry(e),r.end(`Geometry extraction`),this.performanceMetrics.geometryExtractionTime=r.getDuration(`Geometry extraction`),this._geometryBytes=xn(e),this._sampleMemory(`after extraction`),this.processingStage=`bvh`,r.start(`BVH construction (worker)`),r.start(`Material textures (parallel)`);let a=!1,o=this._buildBVH().then(()=>r.end(`BVH construction (worker)`)),s=this._createMaterialTextures().then(()=>{r.end(`Material textures (parallel)`),a=!0});return await o,z({status:`Building light data...`,progress:77}),r.start(`Emissive extraction + Light BVH`),this._buildEmissiveData(),r.end(`Emissive extraction + Light BVH`),a||z({status:`Processing material textures...`,progress:80}),await s,this.performanceMetrics.bvhBuildTime=r.getDuration(`BVH construction (worker)`),this.performanceMetrics.textureCreationTime=r.getDuration(`Material textures (parallel)`),this.processingStage=`finalize`,r.start(`BVH data packing`),this.bvhRoot&&!this.bvh&&this._setBVHData(this.textureCreator.createBVHRawData(this.bvhRoot)),r.end(`BVH data packing`),this.spheres=this._createSpheres(),this.performanceMetrics.totalProcessingTime=performance.now()-r.totalStart,r.print(),this.processingStage=`complete`,await this._restoreGeometry(e),z({status:`Scene data ready`,progress:85}),this._blasKey&&!this._blasRestored&&this.performanceMetrics.totalProcessingTime>=this.config.sceneCacheMinBuildMs&&(this._blasStoring=this._storeBLASes(e.name??``).catch(e=>Xs.debug(`storing BLASes failed:`,e))),this}catch(e){throw this.processingStage=`error`,Xs.error(`processing failed:`,e),z({status:`Error: ${e.message}`,failed:!0,progress:100}),e}finally{this._disposeGeometrySpill(),qt(null),this._sampleMemory(`at ${this.processingStage}`),this._logMemoryReport(),this.isProcessing=!1}}async _extractGeometry(e){z({isLoading:!0,title:`Processing`,status:`Extracting geometry...`,progress:15}),await new Promise(e=>setTimeout(e,0)),this._log(`Extracting geometry`);let t=performance.now();try{this._adoptExtraction(this.geometryExtractor.extract(e));let n=performance.now()-t;this._log(`Geometry extraction complete (${n.toFixed(2)}ms)`,{triangleCount:this.triangleCount,materials:this.materials.length}),z({status:`Extracted ${this.triangleCount.toLocaleString()} triangles`,progress:25})}catch(e){throw Xs.error(`geometry extraction failed:`,e),z({status:`Extraction error: ${e.message}`,failed:!0,progress:25}),e}}async _extractStreaming(e){z({isLoading:!0,title:`Processing`,status:`Extracting geometry and building BVHs...`,progress:15}),await new Promise(e=>setTimeout(e,0));let t=performance.now(),n=this.geometryExtractor,{storage:r,uploader:i}=this._progressive,a=`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`,o=n._countStoredTriangles(e),s=Qt.lazy(o,K.FLOATS_PER_TRIANGLE,Uint32Array),c=s.recordsPerChunk*s.lanesPerRecord*4,l=await on.create(r,`${a}:tri`,c,{label:`Triangle records`,expectedBytes:o*c/s.recordsPerChunk}),u=l&&await on.create(r,`${a}:blas`,0,{label:`BLAS nodes (while building)`});if(!u)return await l?.dispose(),this._streaming=!1,this._extractGeometry(e);let d=await fn.create(r,`${a}:geo`,this.memoryPreflight?.geometryBytes??0);this._geometrySpill=d;let f={key:a,triStore:l,blasStore:u,bvhStore:null,blasBytes:0,blasAt:new Map,pending:[],extractedChunks:0,emitterChunks:new Set,isEmitter:e=>n._emissiveMaterial(e),uploadTriangles:null,chain:Promise.resolve(),error:null};this._spillStores=[l],this._blasKey=null;let p=new Map,m=this._blasWorkerOpts(),h=[],g=()=>new Promise(e=>h.push(e)),_=()=>{let e=h;h=[];for(let t of e)t()},v=null,y=(e,t,n)=>{let r=n.bvhData,i=new Float32Array(6);pa.rootAABB(Zs(r)[0],v,t.start,t.count,i,0),p.set(e,{result:n,aabb:i});let a=f.blasBytes;f.blasBytes+=Qs(r),f.blasAt.set(e,a),n.nodeCount=Qs(r)/64,n.bvhData=null,this._queueSpill(f,()=>ec(u,a,r)),this._forEachChunk(v,t.start,t.count,e=>{--f.pending[e]===0&&e<f.extractedChunks&&this._finishTriangleChunk(f,e)}),_()},b=0,x=this._blasPool(m,()=>b++,(e,t,n)=>y(e,t,n)),S=Promise.resolve(),C=0,w=e=>{let t=e>=v.recordCount?v.chunks.length:Math.floor(e/v.recordsPerChunk);for(let e=f.extractedChunks;e<t;e++)f.pending[e]||this._finishTriangleChunk(f,e);f.extractedChunks=Math.max(f.extractedChunks,t)},T;try{if(T=await n.extractStreaming(e,{onStore:e=>{v=e,this._setTriangleData(e),f.uploadTriangles=i(e,`triangles`)},onRange:(e,t)=>{this._forEachChunk(v,t.start,t.count,e=>f.pending[e]=(f.pending[e]??0)+1),this._isLargeMesh(t)?(C++,S=S.then(async()=>{y(e,t,await this._buildLargeBLAS(t,m)),C--}),S.catch(e=>{f.error??=e,_()})):x.submit({m:e,range:t})},releaseGeometry:d?e=>d.add(e):null,pause:async e=>{for(w(e),d?.queuedBytes>Ys&&await d.written(),z({status:`Extracted ${e.toLocaleString()} triangles, ${b.toLocaleString()} BVHs built...`,progress:15+Math.floor(20*e/Math.max(1,o))}),await new Promise(e=>setTimeout(e,0));v.byteLength>Js&&(x.pending>0||C>0)&&!f.error&&!x.error;)await Promise.race([g(),new Promise(e=>setTimeout(e,50))]);if(f.error||x.error)throw f.error??x.error}}),w(1/0),await Promise.all([x.close(),S]),await f.chain,f.error)throw f.error}catch(e){throw x.abort(e),Xs.error(`streamed extraction failed:`,e),z({status:`Extraction error: ${e.message}`,failed:!0,progress:25}),e}this._adoptExtraction(T),this._streamed={state:f,templates:p},this._log(`Geometry extracted and ${p.size} BLASes built together (${(performance.now()-t).toFixed(0)}ms)`)}_adoptExtraction(e){if(this._setTriangleData(e.triangleData),this.geometryExtractor.releaseTriangles(),this.triangleCount=gt(e.triangleCount,`triangle count`),this._foldLeaves&&this.triangleCount>134217728)throw RangeError(`${this.triangleCount.toLocaleString()} triangles is past the ${Ct.toLocaleString()} a folded BVH leaf can address`);this.expandedTriangleCount=e.expandedTriangleCount??e.triangleCount,this.instanceSource=e.instanceSource||null,this.instanceMatrices=e.instanceMatrices||null,this.instanceCount=e.instanceCount||0,this.bakeInverse=e.bakeInverse||null,this._log(`Using Float32Array format: ${this.triangleCount} triangles, ${(this.triangles.byteLength/(1024*1024)).toFixed(2)}MB`),this.materials=e.materials,this.materialTriangleCounts=e.materialTriangleCounts,this.meshes=e.meshes,this.meshTriangleRanges=e.meshTriangleRanges,this.maps=e.maps,this.normalMaps=e.normalMaps,this.bumpMaps=e.bumpMaps,this.roughnessMaps=e.roughnessMaps,this.metalnessMaps=e.metalnessMaps,this.emissiveMaps=e.emissiveMaps,this.displacementMaps=e.displacementMaps,this.anisotropyMaps=e.anisotropyMaps,this.transmissionMaps=e.transmissionMaps,this.clearcoatMaps=e.clearcoatMaps,this.clearcoatRoughnessMaps=e.clearcoatRoughnessMaps,this.sheenColorMaps=e.sheenColorMaps,this.sheenRoughnessMaps=e.sheenRoughnessMaps,this.iridescenceMaps=e.iridescenceMaps,this.iridescenceThicknessMaps=e.iridescenceThicknessMaps,this.specularIntensityMaps=e.specularIntensityMaps,this.specularColorMaps=e.specularColorMaps,this.diffuseTransmissionMaps=e.diffuseTransmissionMaps??[],this.diffuseTransmissionColorMaps=e.diffuseTransmissionColorMaps??[],this.directionalLights=e.directionalLights,this.cameras=e.cameras}async _buildBVH(){if(z({status:`Building BVH...`,progress:25}),this.triangleCount===0)throw Error(`No triangles to build BVH from`);this._log(`Building two-level BVH (TLAS/BLAS)`),this.memory.mark(`blas`);let e=performance.now();try{let t=this.meshTriangleRanges;if(!t||t.length===0)throw Error(`No mesh triangle ranges available for TLAS/BLAS build`);let n=this.instanceCount>0,r=n?this.instanceCount:t.length,i=this.instanceSource,a=n?this.instanceMatrices:null,o=e=>n?i[e]:e;this.instanceTable=new pa,this.instanceTable.allocate(r,t.length,a,n?i:null),this.instanceTable.tplBakeInverse=this.bakeInverse;let s=this._streamed;this._streamed=null;let c=[],l=[],u=[],d=new Map,f=new Map;for(let e=0;e<r;e++){let n=t[o(e)];if(!n||n.count===0)continue;let r=f.get(n.start);if(r!==void 0){d.set(e,r);continue}f.set(n.start,e),s?u.push({m:e,range:n}):this._isLargeMesh(n)?l.push({m:e,range:n}):c.push({m:e,range:n})}let p=this._blasWorkerOpts(),m=c.length+l.length,h=0,g=()=>{h++,z({status:`Building BLAS ${h}/${m}...`,progress:25+Math.floor(h/m*45)})},_=[...c,...l].map(({m:e,range:t})=>({m:e,range:t,t:o(e),triOffset:t.start,triCount:t.count})).sort((e,t)=>e.t-t.t),v=s?null:await this._restoreBLASes(_,xa.nodeCountFor(r),p),y=s?s.state:!v&&this._progressive&&this.triangles.chunks.length>1?await this._beginProgressiveSpill(_):null,b=y&&!s?(e,t,n)=>this._onBLASBuilt(y,o(e),t,n):null;if(s)for(let[e,t]of s.templates)this.instanceTable.tplObjectAABB.set(t.aabb,e*6);v&&(c.length=0,l.length=0,z({status:`Restored stored BVHs`,progress:68}));let x=v?Promise.resolve(v.results):s?Promise.resolve(u.map(({m:e,range:t})=>({m:e,range:t,result:s.templates.get(o(e)).result}))):this._buildBLASesWithPool(c,p,g,b),S=[],C=(async()=>{for(let{m:e,range:t}of l){let n=await this._buildLargeBLAS(t,p);b?.(e,t,n),S.push({m:e,range:t,result:n}),g()}})(),[w]=await Promise.all([x,C]);if(y&&(await y.chain,y.error))throw y.error;let T={sah:0,objMed:0,spatMed:0,failed:0};for(let{m:e,range:t,result:r}of[...w,...S]){let i=r.splitStats;i&&(T.sah+=i.sahSplits??0,T.objMed+=i.objectMedianSplits??0,T.spatMed+=i.spatialMedianSplits??0,T.failed+=i.failedSplits??0,this.performanceMetrics.blasWorkerTime+=i.totalBuildTime??0),this.instanceTable.setEntry({meshIndex:e,blasNodeCount:r.nodeCount??Qs(r.bvhData)/64,triOffset:t.start,triCount:t.count,originalToBvhMap:r.originalToBvh||null,bvhData:r.bvhData,matrixWorld:n?a:this.meshes?.[e]?.matrixWorld?.elements??null,matrixOffset:n?e*16:0,expandedStart:t.expandedStart,sourceMesh:o(e)})}for(let[e,r]of d)this.instanceTable.setAlias(e,r,n?a:this.meshes?.[e]?.matrixWorld?.elements??null,t[o(e)].expandedStart,o(e),n?e*16:0);z({status:`Built all BLASes`,progress:70}),this.performanceMetrics.blasBuildTime=performance.now()-e,z({status:`Building TLAS...`,progress:72}),this._sampleMemory(`BLASes built`),this.memory.mark(`tlas`);let E=performance.now(),D=this.instanceTable;this.instanceTable.computeAABBs(this.triangles,{owners:!y}),this.instanceTable.assignOffsets(xa.nodeCountFor(D.count));let O=this.instanceTable.totalNodeCount,k=await this._buildTLAS(D);this.performanceMetrics.tlasBuildTime=performance.now()-E,this.memory.mark(`assemble`);let A=performance.now();y||this._checkAssemblyHeadroom(O),this._setBVHData(Qt.lazy(O,16,Float32Array,void 0,Xt));let j=y?await this._beginBVHSpill(y,D.tlasNodeCount):null;this.bvh.setRecords(0,k),k=null,this.tlasBuilder.releaseFlattenBuffer();let M=Math.max(1,Math.ceil(D.templateCount/32));if(v){try{let e=performance.now();await vs(v.nodes,this.bvh,D.tlasNodeCount,O-D.tlasNodeCount),this.performanceMetrics.blasRestore.readMs=performance.now()-e}finally{v.release()}D.blasData.clear()}else{for(let e=0;e<D.templateCount;e++){let t=y?await this._readSpilledBLAS(y,e):D.blasData.get(e);if(!t)continue;let n=D.tplBlasOffset[e],r=n;for(let e of Zs(t))this.bvh.setRecords(r,e),r+=e.length/16;this._offsetBLASInPlace(n,r-n,n,D.tplTriOffset[e]),D.blasData.delete(e),await j?.(r),e%M===0&&this._sampleMemory(`assembling ${e}/${D.templateCount}`)}await j?.(O,!0),y&&await y.blasStore.dispose()}if(this._setBVHData(this.bvh.materializeAll()),v)for(let[e,t]of v.orders)D.bvhToOriginal.set(e,t);else this._buildBvhToOriginalMaps();this.performanceMetrics.bvhAssembleTime=performance.now()-A,D.originalToBvhMap.clear(),D.blasData.clear(),this.bvhRoot=!0,this._disposeRefitWorker();let N=performance.now()-e;Xs.debug(H.list([`${H.n(D.setCount)} BLASes + TLAS`,`${H.n(this.bvh.recordCount)} nodes`,`SAH ${H.n(T.sah)} · objMed ${T.objMed} · spatMed ${T.spatMed} · failed ${T.failed}`,H.ms(N)])),z({status:`BVH construction complete`,progress:75})}catch(e){throw Xs.error(`BVH build failed:`,e),z({status:`BVH error: ${e.message}`,failed:!0,progress:75}),e}}_blasWorkerOpts(){return{depth:this.config.bvhDepth,reinsertionOptimization:{enabled:this.bvhBuilder.enableReinsertionOptimization,batchSizeRatio:this.bvhBuilder.reinsertionBatchSizeRatio,maxIterations:this.bvhBuilder.reinsertionMaxIterations},maxLeafSize:this.bvhBuilder.maxLeafSize,foldLeaves:this._foldLeaves===!0,numBins:this.bvhBuilder.numBins,maxBins:this.bvhBuilder.maxBins,minBins:this.bvhBuilder.minBins,logLevel:be()}}_isLargeMesh(e){return e.count>=Ws&&aa(e.count)}async _buildLargeBLAS(e,t){if(e.count>Gs)return this._buildSplitBLAS(e,t);let n=new Uint32Array(new SharedArrayBuffer(e.count*this.triangles.lanesPerRecord*4));this.triangles.readRecords(e.start,e.count,n),this.triangles.release(e.start,e.count);let r=await na(n,this.config.bvhDepth,null,t);return r.reorderedTriangles?(this.triangles.setRecords(e.start,r.reorderedTriangles),delete r.reorderedTriangles):r.order&&(this._writeInOrder(e.start,r.triangles,r.order),delete r.order,delete r.triangles),r}async _buildSplitBLAS(e,t){let n=this.triangles,{order:r,pieces:i,tree:a}=await ws(n,e.start,e.count,Ks,{pause:()=>new Promise(e=>setTimeout(e,0))}),o=this._blasPool(t,null,null,Math.min(ar(),8));i.forEach((t,n)=>o.submit({m:n,range:{start:e.start+t.start,count:t.count}}));let s=[],c={};for(let{m:e,range:t,result:r}of await o.close()){r.aabb=new Float32Array(6),pa.rootAABB(r.bvhData,n,t.start,t.count,r.aabb,0),s[e]=r;for(let[e,t]of Object.entries(r.splitStats??{}))typeof t==`number`&&(c[e]=(c[e]??0)+t)}return{...Os(a,i,s,r),splitStats:c}}_blasCacheKey(e){let t={...e};delete t.logLevel;let n=typeof navigator<`u`?navigator.hardwareConcurrency:0;return`blas:2:${js}:${JSON.stringify(t)}:${n}:${this._sceneKey}`}async _restoreBLASes(e,t,n){if(!this._sceneKey||this.config.sceneCache===!1)return null;let r=jr(Ir().cacheNamespace);if(!r)return null;this._blasKey=this._blasCacheKey(n);let i=await gs(r,this._blasKey);if(!i)return null;let a=e=>(Xs.debug(`stored BLASes not used: ${e}`),i.release(),null),{index:o}=i;if(o.tlasNodeCount!==t||o.templates.length!==e.length)return a(`layout changed`);let s=t;for(let t=0;t<e.length;t++){let[n,r,i,c,l]=o.templates[t],u=e[t];if(u.t!==n||u.triOffset!==r||u.triCount!==i||l!==s)return a(`layout changed`);s+=c}if(s!==o.totalNodes)return a(`layout changed`);let c=performance.now(),l=await hs(this.triangles,e);for(let t=0;t<e.length;t++)if(l[t]!==o.templates[t][6])return a(`triangles changed`);let u=performance.now();try{let t=new Map,n=[];for(let r=0;r<e.length;r++){let[a,s,c,l,,u,,d]=o.templates[r],f=await ys(i.order,u,c);this._permuteRange(s,c,f),t.set(a,f),n.push({m:e[r].m,range:e[r].range,result:{bvhData:new Float32Array(Uint32Array.from(d).buffer),originalToBvh:null,nodeCount:l}})}return this._blasRestored=!0,this.performanceMetrics.blasRestore={checksumMs:u-c,permuteMs:performance.now()-u},Xs.debug(`restored ${H.n(e.length)} stored BLASes`),{results:n,orders:t,nodes:i.nodes,release:i.release}}catch(e){throw i.release(),e}}_writeInOrder(e,t,n){let r=this.triangles,i=r.lanesPerRecord;for(let a=0,o=n.length;a<o;){let s=r.chunkFor(e+a),c=Math.min(o,(((e+a)/r.recordsPerChunk|0)+1)*r.recordsPerChunk-e);for(let o=r.baseOf(e+a);a<c;a++,o+=i){let e=n[a]*i;for(let n=0;n<i;n++)s[o+n]=t[e+n]}}}_permuteRange(e,t,n){let r=!0;for(let e=0;e<t&&r;e++)r=n[e]===e;if(r)return;let i=this.triangles.lanesPerRecord,a=this.triangles.slice(e,t),o=new a.constructor(a.length);if(i===20)for(let e=0,r=0;e<t;e++,r+=20){let t=n[e]*20;o[r]=a[t],o[r+1]=a[t+1],o[r+2]=a[t+2],o[r+3]=a[t+3],o[r+4]=a[t+4],o[r+5]=a[t+5],o[r+6]=a[t+6],o[r+7]=a[t+7],o[r+8]=a[t+8],o[r+9]=a[t+9],o[r+10]=a[t+10],o[r+11]=a[t+11],o[r+12]=a[t+12],o[r+13]=a[t+13],o[r+14]=a[t+14],o[r+15]=a[t+15],o[r+16]=a[t+16],o[r+17]=a[t+17],o[r+18]=a[t+18],o[r+19]=a[t+19]}else for(let e=0;e<t;e++){let t=n[e]*i,r=e*i;for(let e=0;e<i;e++)o[r+e]=a[t+e]}this.triangles.setRecords(e,o)}async _storeBLASes(e){let t=jr(Ir().cacheNamespace),n=this.instanceTable;if(!t||!n||!this.bvh)return!1;let r=this._blasKey,i=this._geometryVersion,a=()=>this._geometryVersion!==i||this._blasKey!==r,o=[];for(let e=0;e<n.templateCount;e++){let t=n.tplOwner[e];t<0||n.sourceMesh[t]!==e||o.push({t:e,triOffset:n.tplTriOffset[e],triCount:n.tplTriCount[e],nodeCount:n.tplNodeCount[e],blasOffset:n.tplBlasOffset[e]})}let s=await hs(this.triangles,o);if(a())return!1;let c=e=>{let t=this.bvhIndexChunks.chunkFor(e),n=this.bvhIndexChunks.baseOf(e);return Array.from(t.subarray(n,n+16))},l=0,u=[],d=o.map((e,t)=>{u.push(n.bvhToOriginal.get(e.t)??Uint32Array.from({length:e.triCount},(e,t)=>t));let r=[e.t,e.triOffset,e.triCount,e.nodeCount,e.blasOffset,l,s[t],c(e.blasOffset)];return l+=e.triCount,r}),f=await _s(t,r,{index:{v:2,tlasNodeCount:n.tlasNodeCount,totalNodes:n.totalNodeCount,templates:d},bvh:this.bvh,orders:u,isStale:a,label:e});return f&&Xs.debug(`stored ${H.n(o.length)} BLASes for the next load`),f}async _beginProgressiveSpill(e){let{storage:t,uploader:n}=this._progressive,r=this.triangles,i=`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`,a=r.recordsPerChunk*r.lanesPerRecord*r.LaneType.BYTES_PER_ELEMENT,o=await on.create(t,`${i}:tri`,a,{label:`Triangle records`,expectedBytes:r.byteLength}),s=o&&await on.create(t,`${i}:blas`,0,{label:`BLAS nodes (while building)`});if(!s)return await o?.dispose(),null;let c={key:i,triStore:o,blasStore:s,bvhStore:null,blasBytes:0,blasAt:new Map,pending:new Int32Array(r.chunks.length),emitterChunks:new Set,isEmitter:e=>{let t=this.materials[e];return(t?.emissiveIntensity??0)>0&&!!t.emissive&&(t.emissive.r>0||t.emissive.g>0||t.emissive.b>0)},uploadTriangles:n(r,`triangles`),chain:Promise.resolve(),error:null};this._spillStores=[o],this._blasKey=null;for(let{triOffset:t,triCount:n}of e)this._forEachChunk(r,t,n,e=>c.pending[e]++);for(let e=0;e<r.chunks.length;e++)c.pending[e]===0&&this._finishTriangleChunk(c,e);return c}_forEachChunk(e,t,n,r){if(n<=0)return;let i=(t+n-1)/e.recordsPerChunk|0;for(let n=t/e.recordsPerChunk|0;n<=i;n++)r(n)}_onBLASBuilt(e,t,n,r){let i=this.instanceTable,a=r.bvhData;i.tplTriOffset[t]=n.start,i.tplTriCount[t]=n.count,i._readRootAABB(Zs(a)[0],t,this.triangles,i.tplObjectAABB,t*6);let o=e.blasBytes;e.blasBytes+=Qs(a),e.blasAt.set(t,o),r.nodeCount=Qs(a)/64,r.bvhData=null,this._queueSpill(e,()=>ec(e.blasStore,o,a)),this._forEachChunk(this.triangles,n.start,n.count,t=>{--e.pending[t]===0&&this._finishTriangleChunk(e,t)})}_queueSpill(e,t){e.chain=e.chain.then(t).catch(t=>{e.error??=t})}_finishTriangleChunk(e,t){this._queueSpill(e,async()=>{let n=this.triangles,r=n.chunks[t];if(!r)return;e.uploadTriangles(t);let i=n.lanesPerRecord;for(let n=K.MATERIAL_FLAGS_OFFSET;n<r.length;n+=i)if(e.isEmitter(r[n]&16777215)){e.emitterChunks.add(t);return}await n.spillChunk(t,e.triStore)})}async _readSpilledBLAS(e,t){let n=e.blasAt.get(t);if(n===void 0)return null;let r=this.instanceTable.tplNodeCount[t]*64,i=[];for(let t=0;t<r;t+=$s)i.push(new Float32Array(await e.blasStore.readAt(n+t,Math.min($s,r-t))));return i}async _beginBVHSpill(e,t){let{storage:n,uploader:r}=this._progressive,i=this.bvh,a=i.recordsPerChunk*i.lanesPerRecord*i.LaneType.BYTES_PER_ELEMENT,o=await on.create(n,`${e.key}:bvh`,a,{label:`BLAS nodes`,expectedBytes:i.recordCount*64}),s=r(i),c=Math.ceil(t/i.recordsPerChunk);o&&this._spillStores.push(o);let l=c;return async(e,t=!1)=>{for(;l<i.chunks.length&&(t||(l+1)*i.recordsPerChunk<=e);)i.chunks[l]||i._materialize(l),s(l),o&&await i.spillChunk(l,o),l++;if(t)for(let e=0;e<Math.min(c,i.chunks.length);e++)i.chunks[e]||i._materialize(e),s(e)}}_offsetBLASInPlace(e,t,n,r){let i=this.bvhIndexChunks;for(let a=e,o=e+t;a<o;){let e=i.chunkFor(a),t=Math.min(o,((a/i.recordsPerChunk|0)+1)*i.recordsPerChunk),s=i.baseOf(a);vi(e,n,r,s,s+(t-a)*16),a=t}}_buildBLASesWithPool(e,t,n,r=null){let i=this._blasPool(t,n,r);for(let t of e)i.submit(t);return i.close()}_blasPool(e,t,n=null,r=this.config.maxConcurrentTextureTasks||4){let i=[],a=[],o=[],s=[],c=!1,l=0,u=0,d=null,f,p=new Promise((e,t)=>f={resolve:e,reject:t});p.catch(()=>{});let m=e=>{d||(d=e,o.forEach(e=>e.terminate()),f.reject(e))},h=()=>{d||!c||i.length>0||l>0||(o.forEach(e=>e.terminate()),f.resolve(a))},g=t=>{let n=i.shift();if(!n){s.push(t),h();return}let{m:r,range:a}=n;l++;try{let n=this.triangles.copyOf(a.start,a.count),i=a.count;t._currentTask={m:r,range:a},t.postMessage({triangleData:n.buffer,triangleByteOffset:n.byteOffset,triangleByteLength:n.byteLength,triangleCount:i,depth:e.depth,reportProgress:!1,sharedReorderBuffer:null,reinsertionOptimization:e.reinsertionOptimization,maxLeafSize:e.maxLeafSize,foldLeaves:e.foldLeaves,numBins:e.numBins,maxBins:e.maxBins,minBins:e.minBins,logLevel:e.logLevel},[n.buffer])}catch(e){m(e)}},_=(e,r)=>{let i=r.data;if(i.error){m(Error(i.error));return}if(i.progress!==void 0)return;let{m:o,range:s}=e._currentTask;l--;try{i.triangles&&this.triangles.setRecords(s.start,i.triangles);let e={bvhData:i.bvhData,originalToBvh:i.originalToBvh||null,splitStats:i.splitStats||null};n?.(o,s,e),a.push({m:o,range:s,result:e})}catch(e){m(e);return}u++,t?.(u),g(e)},v=()=>{let e=ur(Ji);return e.onmessage=t=>_(e,t),e.onerror=e=>m(e),o.push(e),e};return{submit(e){if(!d){i.push(e);try{let e=s.pop()??(o.length<r?v():null);e&&g(e)}catch(e){m(e)}}},close(){return c=!0,h(),p},abort(e){m(e??Error(`BLAS pool aborted`))},get pending(){return i.length+l},get error(){return d}}}_buildBvhToOriginalMaps(){let e=this.instanceTable;for(let t=0;t<e.count;t++){if(!e.isSet[t]||!e.isOwner(t))continue;let n=e.sourceMesh[t],r=e.tplTriCount[n],i=e.originalToBvhMap.get(n),a=new Uint32Array(r);if(i)for(let e=0;e<r;e++)a[i[e]]=e;else for(let e=0;e<r;e++)a[e]=e;e.bvhToOriginal.set(n,a),e.originalToBvhMap.delete(n)}}async _createMaterialTextures(){this._log(`Creating material textures (parallel with BVH)`);try{let{srgbLists:e,linearLists:t,remap:n}=this._bucketTextures();this._remapMaterialTextureIndices(n),this.materials?.length&&(this.materialData=this.textureCreator.createMaterialRawData(this.materials));let i=(e,t)=>e.length===0?Promise.resolve(null):this.textureCreator.createTexturesToDataTexture(e,{srgbPool:t}).then(e=>(e&&t&&(e.colorSpace=r.SRGBColorSpace),e)),[a,o]=await Promise.all([Promise.all(e.map(e=>i(e,!0))),Promise.all(t.map(e=>i(e,!1)))]);this.srgbBucketTextures=a,this.linearBucketTextures=o,this._log(`Material textures complete`,{materialData:!!this.materialData,srgbBuckets:a.map(e=>e?`${e.image.width}x${e.image.height}x${e.image.depth}`:`-`).join(`,`),linearBuckets:o.map(e=>e?`${e.image.width}x${e.image.height}x${e.image.depth}`:`-`).join(`,`)})}catch(e){throw Xs.error(`texture creation failed:`,e),e}}_bucketTextures(){let e=this.config.maxTextureSize,t=Nt.MATERIAL_BUCKET_COUNT,n=Nt.BUCKET_LAYER_STRIDE,r=e=>{let t=new Set,n=[];for(let r of e)for(let e of r||[]){if(!e?.image)continue;let r=e.source?.uuid??e.uuid;t.has(r)||(t.add(r),n.push({width:e.image.width,height:e.image.height}))}return n},i=[this.maps,this.emissiveMaps,this.sheenColorMaps,this.specularColorMaps,this.diffuseTransmissionColorMaps],a=[this.normalMaps,this.bumpMaps,this.roughnessMaps,this.metalnessMaps,this.displacementMaps,this.anisotropyMaps,this.transmissionMaps,this.clearcoatMaps,this.clearcoatRoughnessMaps,this.sheenRoughnessMaps,this.iridescenceMaps,this.iridescenceThicknessMaps,this.specularIntensityMaps,this.diffuseTransmissionMaps],o=Vt(r(i),e,t),s=Vt(r(a),e,t);this._srgbBucketShapes=o,this._linearBucketShapes=s;let c=Array.from({length:t},()=>[]),l=Array.from({length:t},()=>[]),u=Array.from({length:t},()=>new Map),d=Array.from({length:t},()=>new Map);this._srgbTexPacked=new Map,this._linearTexPacked=new Map;let f=!1,p=!1,m=(e,t,r,i,a)=>{if(!e)return-1;if(!e.image)return p||this.config.issues?.record(Y.TEXTURE_BUILD_FAILED,`a material map had not finished decoding when the scene was packed; it renders untextured`,{texture:e.name||e.source?.uuid||e.uuid}),p=!0,-1;let o=Ht(e.image.width,e.image.height,a),s=e.source?.uuid??e.uuid,c=r[o].get(s);if(c!==void 0)return Ut(o,c);if(t[o].length>=n)return Xs.warn(`texture bucket ${o} full (${n}); dropping a map`),f||this.config.issues?.record(Y.TEXTURE_LIMIT_EXCEEDED,`texture bucket ${o} full (${n} layers); the rest render untextured`,{bucket:o,limit:n}),f=!0,-1;t[o].push(e);let l=t[o].length-1;r[o].set(s,l);let u=Ut(o,l);return i.set(s,u),u},h=(e,t,n,r,i)=>(e||[]).map(e=>m(e,t,n,r,i));return{srgbLists:c,linearLists:l,remap:{albedo:h(this.maps,c,u,this._srgbTexPacked,o),emissive:h(this.emissiveMaps,c,u,this._srgbTexPacked,o),normal:h(this.normalMaps,l,d,this._linearTexPacked,s),bump:h(this.bumpMaps,l,d,this._linearTexPacked,s),roughness:h(this.roughnessMaps,l,d,this._linearTexPacked,s),metalness:h(this.metalnessMaps,l,d,this._linearTexPacked,s),displacement:h(this.displacementMaps,l,d,this._linearTexPacked,s),anisotropy:h(this.anisotropyMaps,l,d,this._linearTexPacked,s),transmission:h(this.transmissionMaps,l,d,this._linearTexPacked,s),clearcoat:h(this.clearcoatMaps,l,d,this._linearTexPacked,s),clearcoatRoughness:h(this.clearcoatRoughnessMaps,l,d,this._linearTexPacked,s),sheenColor:h(this.sheenColorMaps,c,u,this._srgbTexPacked,o),sheenRoughness:h(this.sheenRoughnessMaps,l,d,this._linearTexPacked,s),iridescence:h(this.iridescenceMaps,l,d,this._linearTexPacked,s),iridescenceThickness:h(this.iridescenceThicknessMaps,l,d,this._linearTexPacked,s),specularIntensity:h(this.specularIntensityMaps,l,d,this._linearTexPacked,s),specularColor:h(this.specularColorMaps,c,u,this._srgbTexPacked,o),diffuseTransmission:h(this.diffuseTransmissionMaps,l,d,this._linearTexPacked,s),diffuseTransmissionColor:h(this.diffuseTransmissionColorMaps,c,u,this._srgbTexPacked,o)}}}_remapMaterialTextureIndices(e){let t=(e,t)=>e>=0&&e<t.length?t[e]:-1;for(let n of this.materials)n.map=t(n.map,e.albedo),n.emissiveMap=t(n.emissiveMap,e.emissive),n.normalMap=t(n.normalMap,e.normal),n.bumpMap=t(n.bumpMap,e.bump),n.roughnessMap=t(n.roughnessMap,e.roughness),n.metalnessMap=t(n.metalnessMap,e.metalness),n.displacementMap=t(n.displacementMap,e.displacement),n.anisotropyMap=t(n.anisotropyMap,e.anisotropy),n.transmissionMap=t(n.transmissionMap,e.transmission),n.clearcoatMap=t(n.clearcoatMap,e.clearcoat),n.clearcoatRoughnessMap=t(n.clearcoatRoughnessMap,e.clearcoatRoughness),n.sheenColorMap=t(n.sheenColorMap,e.sheenColor),n.sheenRoughnessMap=t(n.sheenRoughnessMap,e.sheenRoughness),n.iridescenceMap=t(n.iridescenceMap,e.iridescence),n.iridescenceThicknessMap=t(n.iridescenceThicknessMap,e.iridescenceThickness),n.specularIntensityMap=t(n.specularIntensityMap,e.specularIntensity),n.specularColorMap=t(n.specularColorMap,e.specularColor),n.diffuseTransmissionMap=t(n.diffuseTransmissionMap,e.diffuseTransmission),n.diffuseTransmissionColorMap=t(n.diffuseTransmissionColorMap,e.diffuseTransmissionColor)}_buildEmissiveData(){this.emissiveTriangleCount=this.emissiveTriangleBuilder.extractEmissiveTriangles(this.triangles,this.materials,this.triangleCount,this.instanceTable??null),this.emissiveTriangleData=this.emissiveTriangleBuilder.createEmissiveRawData(),this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower,this._log(`Emissive triangle extraction complete`,this.emissiveTriangleBuilder.getStats()),this.emissiveTriangleBuilder.buildLightBVH(),this.lightBVHNodeData=this.emissiveTriangleBuilder.lightBVHNodeData,this.lightBVHNodeCount=this.emissiveTriangleBuilder.lightBVHNodeCount,this.emissiveTriangleData=this.emissiveTriangleBuilder.emissiveTriangleData||this.emissiveTriangleData,this.emissiveBitTrailMap=this.emissiveTriangleBuilder.emissiveBitTrailMap,this.emissiveTriangleCount=this.emissiveTriangleBuilder.emissiveCount,this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower}_createSpheres(){return[]}_reset(){this._geometryVersion=(this._geometryVersion??0)+1,this._disposeSpill(),this._disposeGeometrySpill(),this._disposeTextures(),this.triangles=[],this._setTriangleData(null),this.triangleCount=0,this.materials=[],this.meshTriangleRanges=null,this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.roughnessMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.displacementMaps=[],this.anisotropyMaps=[],this.transmissionMaps=[],this.clearcoatMaps=[],this.clearcoatRoughnessMaps=[],this.sheenColorMaps=[],this.sheenRoughnessMaps=[],this.iridescenceMaps=[],this.iridescenceThicknessMaps=[],this.specularIntensityMaps=[],this.specularColorMaps=[],this.diffuseTransmissionMaps=[],this.diffuseTransmissionColorMaps=[],this.directionalLights=[],this.cameras=[],this.spheres=[],this.bvhRoot=null,this.bvh=null,this.bvhData=null,this.bvhIndexChunks=null,this.bvhIndex=null,this.instanceTable=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this.performanceMetrics={textureCreationTime:0,geometryExtractionTime:0,bvhBuildTime:0,blasBuildTime:0,blasWorkerTime:0,tlasBuildTime:0,bvhAssembleTime:0,totalProcessingTime:0}}_disposeTextures(){this._disposeBucketTextures()}_disposeBucketTextures(){for(let e of[`srgbBucketTextures`,`linearBucketTextures`]){let t=this[e];if(t){for(let n of t)if(n&&typeof n.dispose==`function`)try{n.dispose()}catch(t){Xs.warn(`error disposing ${e}:`,t)}this[e]=null}}}async rebuildMaterials(e){if(this.isProcessing)throw Error(`Already processing. Cannot rebuild materials during processing.`);this._log(`Rebuilding materials and textures`);let t=performance.now();try{this.isProcessing=!0;let n=this.geometryExtractor.extractMaterialsOnly(e);this._disposeMaterialTextures(),this.materials=n.materials,this.meshes=n.meshes,this.maps=n.maps,this.normalMaps=n.normalMaps,this.bumpMaps=n.bumpMaps,this.roughnessMaps=n.roughnessMaps,this.metalnessMaps=n.metalnessMaps,this.emissiveMaps=n.emissiveMaps,this.displacementMaps=n.displacementMaps,await this._createMaterialTextures();let r=performance.now()-t;return this._log(`Material rebuild complete (${r.toFixed(2)}ms)`,{materials:this.materials.length,textures:this.maps.length}),this}catch(e){throw Xs.error(`material rebuild failed:`,e),e}finally{this.isProcessing=!1}}_disposeMaterialTextures(){this._disposeBucketTextures(),this.textureCreator&&this.textureCreator.textureCache&&(this.textureCreator.textureCache.dispose(),this.textureCreator.textureCache=new this.textureCreator.textureCache.constructor)}getStatistics(){let e={triangleCount:this.triangleCount,materialCount:this.materials.length,textureCount:this.maps.length,lightCount:this.directionalLights.length,cameraCount:this.cameras.length,processingComplete:this.processingStage===`complete`,hasBVH:!!this.bvhRoot,hasTextures:!!this.materialData&&!!this.bvh,useFloat32Array:this.config.useFloat32Array,triangleDataSize:this.triangles?(this.triangles.byteLength/(1024*1024)).toFixed(2)+`MB`:`0MB`};return this.performanceMetrics.totalProcessingTime>0&&(e.performance={totalTime:this.performanceMetrics.totalProcessingTime,textureTime:this.performanceMetrics.textureCreationTime,bvhTime:this.performanceMetrics.bvhBuildTime,extractionTime:this.performanceMetrics.geometryExtractionTime,texturePercentage:(this.performanceMetrics.textureCreationTime/this.performanceMetrics.totalProcessingTime*100).toFixed(1)+`%`}),this.textureCreator&&this.textureCreator.capabilities&&(e.textureCapabilities=this.textureCreator.capabilities),e}updateConfig(e){Object.assign(this.config,e),this.bvhBuilder&&(this.bvhBuilder.maxLeafSize=this.config.maxLeafSize),this._log(`Configuration updated`,this.config)}_adoptSharedChunks(e,t){let n=this[e];if(n.shared)return;let r=n.chunks.map(e=>{let n=new t(new SharedArrayBuffer(e.byteLength));return n.set(e),n}),i=Qt.adopt(r,n.recordCount,n.lanesPerRecord,n.recordsPerChunk);e===`bvh`?this._setBVHData(i):this._setTriangleData(i)}_meshSource(e,t){if(e==null)return null;let n=this.instanceTable;if(typeof e==`function`)return r=>{let i=n.sourceMesh[r],a=e(i,n.triCountOf(r)),o=n.triCountOf(r)*9;if(a&&a.length!==o)throw Error(`SceneProcessor: ${t}s for mesh ${i} must be ${o} floats (${n.triCountOf(r)} triangles × 9), got ${a.length}.`);return a??null};let r=(this.expandedTriangleCount??this.triangleCount)*9;if(e.length!==r)throw Error(`SceneProcessor: expected ${r} ${t} floats (${r/9} triangles × 9, full scene), got ${e.length}. Pass a per-mesh callback instead to avoid building one array for the whole scene.`);return t=>{let r=n.expandedStartOf(t)*9;return e.subarray(r,r+n.triCountOf(t)*9)}}async refitBVH(e,t){if(this._geometryVersion=(this._geometryVersion??0)+1,this._tlasLeafBoxesOf=null,!this.bvh||!this.triangles||!this.instanceTable)throw Error(`No BVH data available for refit. Run buildBVH() first.`);let n=this._meshSource(e,`position`),r=this._meshSource(t,`normal`);if(!n)throw Error(`SceneProcessor.refitBVH: positions are required.`);if(this._refitWorker||=ur(zs),!this._refitSharedBuffers){this._adoptSharedChunks(`bvh`,Float32Array),this._adoptSharedChunks(`triangles`,Uint32Array);let e=this.bvh.chunks.map(e=>e.buffer),t=this.triangles.chunks.map(e=>e.buffer);this._refitSharedBuffers={bvhBufs:e,triBufs:t},this._refitWorker.postMessage({type:`init`,sharedBvhBufs:e,bvhRecordCount:this.bvh.recordCount,bvhRecordsPerChunk:this.bvh.recordsPerChunk,sharedTriBufs:t,triRecordCount:this.triangles.recordCount,triLanesPerRecord:this.triangles.lanesPerRecord,triRecordsPerChunk:this.triangles.recordsPerChunk})}let i=this.instanceTable,a=K.FLOATS_PER_TRIANGLE,o=[],s=[],c=0;for(let e=0;e<i.count;e++){if(!i.isSet[e]||!i.isOwner(e))continue;c++;let t=n(e);if(!t)continue;if(this._updateMeshTrianglePositions(e,t),s.push(i.blasOffsetOf(e),i.blasNodeCountOf(e)),r){let t=r(e);t&&this._patchMeshSmoothNormals(e,t)}let l=i.triOffsetOf(e)*a,u=i.triCountOf(e)*a,d=o.at(-1);d&&d.offset+d.count===l?d.count+=u:o.push({offset:l,count:u})}let l=i.tlasNodeCount,u=l>0&&s.length/2<c,d=u?[this.computeTLASDirtyRange()]:null;for(let e=0;u&&e<s.length;e+=2)d.push({offset:s[e]*16,count:s[e+1]*16});return new Promise((e,t)=>{this._refitWorker.onmessage=n=>{let r=n.data;r.type===`refitComplete`?e({refitTimeMs:r.refitTimeMs,triRanges:o,bvhRanges:d}):r.type===`error`&&t(Error(r.error))},this._refitWorker.postMessage({type:`refit`,blasRanges:u?s:null,tlasNodeCount:l})})}_patchSmoothNormals(e){let t=this.instanceTable;if(t)for(let n=0;n<t.count;n++){if(!t.isSet[n]||!t.isOwner(n))continue;let r=e(n);r&&this._patchMeshSmoothNormals(n,r)}}_placementOf(e){return this.instanceTable?.placementRunOf(e)?.start??-1}refitBLASes(e,t,n){if(this._geometryVersion=(this._geometryVersion??0)+1,!this.instanceTable||!this.bvh||!this.triangles)throw Error(`No TLAS/BLAS data available. Run buildBVH() first.`);let r=this._meshSource(t,`position`),i=this._meshSource(n,`normal`);if(!r)throw Error(`SceneProcessor.refitBLASes: positions are required.`);let a=performance.now();this._blasRefitter||=new Gi;let o=this.instanceTable;for(let t of e){let e=this._placementOf(t);if(e<0||!o.isSet[e])continue;if(!o.isOwner(e)){let n=o.tplOwner[o.sourceMesh[e]];this.config.issues?.record(Y.REFIT_SHARED_GEOMETRY,`mesh ${t} shares its triangles with another placement; deforming it would move every copy, so it was skipped`,{meshIndex:t,owner:o.sourceMesh[n]??n});continue}let n=r(e);if(n){if(this._updateMeshTrianglePositions(e,n),i){let t=i(e);t&&this._patchMeshSmoothNormals(e,t)}this._blasRefitter.refitRange(this.bvh,this.triangles,o.blasOffsetOf(e),o.blasNodeCountOf(e)),this.instanceTable.recomputeAABB(e,this.bvh,this.triangles)}}return this._refitTLAS(),{refitTimeMs:performance.now()-a}}updateMeshTransforms(e){if(!this.instanceTable||!this.bvh)throw Error(`No TLAS/BLAS data available. Run buildBVH() first.`);let t=performance.now(),n=this.instanceTable,r=this._transformScratch??=new Float32Array(16);this._movedPlacements?.length!==n.count&&(this._movedPlacements=new Uint8Array(n.count));let i=this._movedPlacements,a=0;for(let t of e){let e=this.meshes?.[t],o=n.placementRunOf(t);if(!e||!o)continue;e.updateMatrixWorld(!0);let s=e.matrixWorld.elements,c=e.isInstancedMesh?this._ownInstanceMatrices(e):null,l=n.tplBakeInverse?.get(n.sourceMesh[o.start])??null;for(let e=0;e<o.count;e++){let t=o.start+e;n.isSet[t]&&(c?(la(s,c,e*16,r),n.setPlacementMatrix(t,r)):l?(la(s,l,0,r),n.setPlacementMatrix(t,r)):n.setPlacementMatrix(t,s),this._writeLeafMatrix(t),i[t]=1,a++)}}return this._refitTLAS(i),i.fill(0),{refitTimeMs:performance.now()-t,placements:a}}_ownInstanceMatrices(e){let t=e.instanceMatrix;return t?.array?(t.array.buffer===this.instanceTable.world.buffer&&(t.array=t.array.slice(),t.needsUpdate=!0),t.array):null}_writeLeafMatrix(e){let t=this.instanceTable.tlasLeafIndex[e];t<0||xa.writeLeafMatrix(this.bvh.chunkFor(t),this.bvhIndexChunks.chunkFor(t),this.bvh.baseOf(t),this.instanceTable.world,e)}computeTLASDirtyRange(){return{offset:0,count:this.instanceTable.tlasNodeCount*16}}computeBLASDirtyRanges(e){let t=K.FLOATS_PER_TRIANGLE,n=[],r=[];for(let i of e){let e=this.instanceTable,a=this._placementOf(i);a<0||!e.isSet[a]||(n.push({offset:e.triOffsetOf(a)*t,count:e.triCountOf(a)*t}),r.push({offset:e.blasOffsetOf(a)*16,count:e.blasNodeCountOf(a)*16}))}return r.push({offset:0,count:this.instanceTable.tlasNodeCount*16}),{triRanges:n,bvhRanges:r}}uploadToPathTracer(e,t,n,r,{keepUserLights:i=!1}={}){return this.triangles?(e.setTriangleData(this.triangles,this.triangleCount),this.bvh?(e.setBVHData(this.bvh),e.setInstanceTable(this.instanceTable),this.materialData?e.materialData.setMaterialData(this.materialData,this.materials.map(e=>e.sources)):Xs.warn(`no material data, using defaults`),r&&e.environment.setEnvironmentTexture(r),e.materialData.setMaterialTextures({srgbBuckets:this.srgbBucketTextures,linearBuckets:this.linearBucketTextures}),e.materialData.setTexturePackMaps?.(this._srgbTexPacked,this._linearTexPacked),this.emissiveTriangleData&&(e.setEmissiveTriangleData(this.emissiveTriangleData,this.emissiveTriangleCount,this.emissiveTotalPower,this.emissiveBitTrailMap),this._releaseBitTrailMap()),this.lightBVHNodeData&&e.setLightBVHData(this.lightBVHNodeData,this.lightBVHNodeCount),t.transferSceneLights(n,{keepUserLights:i}),!0):(Xs.error(`failed to get BVH data`),!1)):(Xs.error(`failed to get triangle data`),!1)}updateMaterialEmissive(e,t,n){if(!this.emissiveTriangleBuilder)return null;let r=this.materials[e];return!r||(t===`emissive`?r.emissive=n:t===`emissiveIntensity`&&(r.emissiveIntensity=n),!this.emissiveTriangleBuilder.updateMaterialEmissive(e,r,this.triangles,this.materials,this.triangleCount))?null:this._collectEmissivePayload()}rebuildEmissiveColors(){return!this.emissiveTriangleBuilder||!this.triangleCount?null:(this.emissiveTriangleBuilder.extractEmissiveTriangles(this.triangles,this.materials,this.triangleCount,this.instanceTable??null),this.emissiveTriangleBuilder.createEmissiveRawData(),this._collectEmissivePayload())}rebuildEmissiveForVisibility(e,t=!1){return!this.emissiveTriangleBuilder||!this.emissiveTriangleBuilder.setHiddenMeshes(e)&&!t?null:this._collectEmissivePayload()}movesEmitters(e){let t=this.emissiveTriangleBuilder?.emissiveMeshes;return!!t?.size&&e.some(e=>t.has(e))}refreshEmissiveTransforms(){let e=this.emissiveTriangleBuilder;return!e?.emissiveTriangles.length||!this.instanceTable||!this.triangles?null:(e.refreshTransforms(this.triangles,this.instanceTable),this._collectEmissivePayload())}_collectEmissivePayload(){this.emissiveTriangleBuilder.buildLightBVH(),this.lightBVHNodeData=this.emissiveTriangleBuilder.lightBVHNodeData,this.lightBVHNodeCount=this.emissiveTriangleBuilder.lightBVHNodeCount,this.emissiveTriangleData=this.emissiveTriangleBuilder.emissiveTriangleData,this.emissiveBitTrailMap=this.emissiveTriangleBuilder.emissiveBitTrailMap,this.emissiveTriangleCount=this.emissiveTriangleBuilder.emissiveCount,this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower;let e=this.emissiveBitTrailMap;return this._releaseBitTrailMap(),{rawData:this.emissiveTriangleData,emissiveCount:this.emissiveTriangleCount,totalPower:this.emissiveTotalPower,bitTrailMap:e,lightBVHNodeData:this.lightBVHNodeData,lightBVHNodeCount:this.lightBVHNodeCount}}get spilled(){return!!(this.triangles?.spilledChunks||this.bvh?.spilledChunks)}async spillToDisk(e){let t=this.triangles,n=this.bvh;if(!e||this.spilled||this._spillStores||!t?.chunks||t.chunks.length<2||!n?.chunks)return null;await this._blasStoring;let r=this._geometryVersion,i=performance.now(),a=`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`,o=e=>e.recordsPerChunk*e.lanesPerRecord*e.LaneType.BYTES_PER_ELEMENT,s=await on.create(e,`${a}:tri`,o(t),{label:`Triangle records`,expectedBytes:t.byteLength}),c=s&&await on.create(e,`${a}:bvh`,o(n),{label:`BLAS nodes`,expectedBytes:n.byteLength});if(!s||!c)return await s?.dispose(),null;this._spillStores=[s,c];let l=Math.ceil((this.instanceTable?.tlasNodeCount??1)/n.recordsPerChunk),u=await t.spill(s);if(u+=await n.spill(c,{keep:e=>e<l}),await s.flush(),await c.flush(),r!==this._geometryVersion)return null;let d=performance.now()-i;return Xs.info(`spilled ${(u/1048576).toFixed(0)} MB of triangles and BLAS nodes to disk in ${d.toFixed(0)} ms`),{bytes:u,ms:d}}ensureResident(){return this._paging??=(async()=>{await this.triangles?.ensureResident?.(),await this.bvh?.ensureResident?.(),this.spilled||this._disposeSpill()})().finally(()=>{this._paging=null}),this._paging}async _restoreGeometry(e){let t=this._geometrySpill;if(!t?.bytes)return;z({status:`Reading scene geometry back...`,progress:84});let n=performance.now(),r=t.bytes;await t.restore(),this._disposeGeometrySpill(),this._geometryBytes=xn(e),Xs.info(`read ${H.mb(r)} of scene geometry back from disk in ${H.ms(performance.now()-n)}`),t.error&&Xs.warn(`some scene geometry stayed in memory, its spill write failed:`,t.error)}_disposeGeometrySpill(){let e=this._geometrySpill;this._geometrySpill=null,e?.dispose().catch(()=>{})}_disposeSpill(){let e=this._spillStores;this._spillStores=null;for(let t of e??[])t.dispose().catch(()=>{})}_releaseBitTrailMap(){this.emissiveBitTrailMap=null,this.emissiveTriangleBuilder&&(this.emissiveTriangleBuilder.emissiveBitTrailMap=null)}async _buildTLAS(e){let t=e.count;if(t>=Us&&!this._tlasWorkerFailed)try{let n=new Float64Array(t*6);e.writeWorldAABBs(n);let{tlasData:r,nodeCount:i}=await this._runTLASWorker(n,t);return xa.fillLeaves(r,i,e),r}catch(e){this._tlasWorkerFailed=!0,Xs.warn(`TLAS worker unavailable (${e.message}); building on the main thread`)}return this.tlasBuilder.build(e).data}_runTLASWorker(e,t){this._tlasWorker||=ur(Hs);let n=this._tlasWorker;return new Promise((r,i)=>{let a=e=>{n.removeEventListener(`message`,a),n.removeEventListener(`error`,o),e.data?.error?i(Error(e.data.error)):r(e.data)},o=e=>{n.removeEventListener(`message`,a),n.removeEventListener(`error`,o),i(Error(e.message||`worker error`))};n.addEventListener(`message`,a),n.addEventListener(`error`,o),n.postMessage({aabbs:e.buffer,count:t,logLevel:be()},[e.buffer])})}_setBVHData(e){this._tlasLeafBoxesOf=null;let t=e?e instanceof Qt?e:Qt.adopt([e],e.length/16,16,e.length/16):null;this.bvh=t,t&&this._foldLeaves&&(t.foldedLeaves=!0),this.bvhIndexChunks=t?t.viewAs(Uint32Array):null,this.bvhData=t?t.single:null,this.bvhIndex=this.bvhIndexChunks?this.bvhIndexChunks.single:null}_setTriangleData(e){let t=K.FLOATS_PER_TRIANGLE,n=e?e instanceof Qt?e:Qt.adopt([e],e.length/t,t,e.length/t):null;this.triangles=n,this.triangleFloatChunks=n?n.viewAs(Float32Array):null,this.triangleData=n?n.single:null,this.triangleFloats=this.triangleFloatChunks?this.triangleFloatChunks.single:null}_updateMeshTrianglePositions(e,t){let n=K.POSITION_A_OFFSET,r=K.POSITION_B_OFFSET,i=K.POSITION_C_OFFSET,a=K.NORMAL_A_PACKED_OFFSET,o=K.NORMAL_B_PACKED_OFFSET,s=K.NORMAL_C_PACKED_OFFSET,c=this.triangles,l=this.triangleFloatChunks,u=this.instanceTable,d=u.bvhToOriginalOf(e),f=u.triOffsetOf(e),p=u.triCountOf(e),m=u.matrixInverseOf(e),h=ua(m);for(let e=0;e<p;e++){let u=d?d[e]:e,p=f+e,g=l.chunkFor(p),_=c.chunkFor(p),v=c.baseOf(p),y=u*9,b=t[y],x=t[y+1],S=t[y+2],C=t[y+3],w=t[y+4],T=t[y+5],E=t[y+6],D=t[y+7],O=t[y+8];if(!h){let e=(e,t,n)=>m[0]*e+m[4]*t+m[8]*n+m[12],t=(e,t,n)=>m[1]*e+m[5]*t+m[9]*n+m[13],n=(e,t,n)=>m[2]*e+m[6]*t+m[10]*n+m[14],r=[e(b,x,S),t(b,x,S),n(b,x,S)],i=[e(C,w,T),t(C,w,T),n(C,w,T)],a=[e(E,D,O),t(E,D,O),n(E,D,O)];b=r[0],x=r[1],S=r[2],C=i[0],w=i[1],T=i[2],E=a[0],D=a[1],O=a[2]}g[v+n]=b,g[v+n+1]=x,g[v+n+2]=S,g[v+r]=C,g[v+r+1]=w,g[v+r+2]=T,g[v+i]=E,g[v+i+1]=D,g[v+i+2]=O;let k=C-b,A=w-x,j=T-S,M=E-b,N=D-x,P=O-S,F=mt(A*P-j*N,j*M-k*P,k*N-A*M);_[v+a]=F,_[v+o]=F,_[v+s]=F}}_patchMeshSmoothNormals(e,t){let n=this.instanceTable;this._patchNormalsRange(t,n.triOffsetOf(e),n.triCountOf(e),n.matrixWorldOf(e),n.bvhToOriginalOf(e))}_patchNormalsRange(e,t,n,r,i){let a=K.NORMAL_A_PACKED_OFFSET,o=K.NORMAL_B_PACKED_OFFSET,s=K.NORMAL_C_PACKED_OFFSET,c=r,l=!c||ua(c),u=[a,o,s];for(let r=0;r<n;r++){let n=t+r,a=this.triangles.chunkFor(n),o=this.triangles.baseOf(n),s=(i?i[r]:r)*9;for(let t=0;t<3;t++){let n=s+t*3,r=e[n],i=e[n+1],d=e[n+2],f=r,p=i,m=d;if(!l){f=c[0]*r+c[1]*i+c[2]*d,p=c[4]*r+c[5]*i+c[6]*d,m=c[8]*r+c[9]*i+c[10]*d;let e=Math.hypot(f,p,m)||1;f/=e,p/=e,m/=e}a[o+u[t]]=mt(f,p,m)}}}_refitTLAS(e=null){let t=this.instanceTable.tlasNodeCount;(!this._tlasBounds||this._tlasBounds.length<t*6)&&(this._tlasBounds=new Float32Array(t*6),this._tlasLeafBoxesOf=null);let n=this.instanceTable,r=e&&this._tlasLeafBoxesOf===n;for(let i=t-1;i>=0;i--){let t=this.bvhIndexChunks.chunkFor(i),a=this.bvh.chunkFor(i),o=this.bvh.baseOf(i),s=t[o+3];if(s===St.BLAS_POINTER_LEAF){let a=t[o+1]&xt;a<n.count&&!(r&&!e[a])&&n.writeWorldAABB(a,this._tlasBounds,i*6)}else if(s<St.TRIANGLE_LEAF){let e=s,n=t[o+7],r=e*6,c=n*6,l=this._tlasBounds;a[o]=l[r],a[o+1]=l[r+1],a[o+2]=l[r+2],a[o+4]=l[r+3],a[o+5]=l[r+4],a[o+6]=l[r+5],a[o+8]=l[c],a[o+9]=l[c+1],a[o+10]=l[c+2],a[o+12]=l[c+3],a[o+13]=l[c+4],a[o+14]=l[c+5];let u=i*6;l[u]=Math.min(l[r],l[c]),l[u+1]=Math.min(l[r+1],l[c+1]),l[u+2]=Math.min(l[r+2],l[c+2]),l[u+3]=Math.max(l[r+3],l[c+3]),l[u+4]=Math.max(l[r+4],l[c+4]),l[u+5]=Math.max(l[r+5],l[c+5])}}this._tlasLeafBoxesOf=n}scheduleBackgroundRebuild(e,t){if(!this.instanceTable||!this.triangles)return;this._rebuildGeneration++;let n=this._rebuildGeneration,r=(e,r,i)=>{let a=this.triangles.copyOf(r.triOffset,r.triCount);this._pendingRebuilds.set(e,i),i.onmessage=a=>{let o=a.data;if(i.terminate(),this._pendingRebuilds.delete(e),o.error){Xs.error(`background BLAS rebuild failed (mesh ${e}):`,o.error);return}n===this._rebuildGeneration&&this._swapBLAS(e,r,o,t)},i.onerror=t=>{Xs.error(`background BLAS rebuild worker failed (mesh ${e}):`,t),i.terminate(),this._pendingRebuilds.delete(e)},i.postMessage({triangleData:a.buffer,triangleByteOffset:a.byteOffset,triangleByteLength:a.byteLength,triangleCount:r.triCount,depth:this.config.bvhDepth,maxLeafSize:this.bvhBuilder.maxLeafSize,numBins:this.bvhBuilder.numBins,maxBins:this.bvhBuilder.maxBins,minBins:this.bvhBuilder.minBins,reportProgress:!1,sharedReorderBuffer:null,reinsertionOptimization:{enabled:this.bvhBuilder.enableReinsertionOptimization,batchSizeRatio:this.bvhBuilder.reinsertionBatchSizeRatio,maxIterations:this.bvhBuilder.reinsertionMaxIterations}},[a.buffer])};for(let t of e){let e=this._placementOf(t);if(e<0)continue;let n=this.instanceTable.entryAt(e);if(!n||!this.instanceTable.isOwner(e))continue;let i=this._pendingRebuilds.get(e);i&&i.terminate(),r(e,n,ur(Ji))}}_swapBLAS(e,t,n,r){this._geometryVersion=(this._geometryVersion??0)+1;let i=n.bvhData,a=i.length/16;if(a>t.blasNodeCount){Xs.warn(`background rebuild does not fit for mesh ${e} (${a} nodes vs ${t.blasNodeCount} reserved), skipping swap`);return}this.bvh.setRecords(t.blasOffset,i),this._offsetBLASInPlace(t.blasOffset,a,t.blasOffset,t.triOffset);let o=n.triangles;o&&this.triangles.setRecords(t.triOffset,o),this.instanceTable.setBlasNodeCount(e,a);let s=n.originalToBvh;if(s){let n=this.instanceTable.bvhToOriginalOf(e),r=new Uint32Array(t.triCount);for(let e=0;e<t.triCount;e++)r[s[e]]=n?n[e]:e;this.instanceTable.setBvhToOriginal(e,r)}this.instanceTable.recomputeAABB(e,this.bvh,this.triangles),this._refitTLAS(),this._log(`Background BLAS rebuild complete for mesh ${e}`),r?.(this.instanceTable.sourceMesh[e]??e)}cancelBackgroundRebuilds(){for(let e of this._pendingRebuilds.values())e.terminate();this._pendingRebuilds.clear()}_disposeRefitWorker(){this._refitWorker&&=(this._refitWorker.terminate(),null),this._refitSharedBuffers=null,this.cancelBackgroundRebuilds()}_disposeTLASWorker(){this._tlasWorker&&=(this._tlasWorker.terminate(),null)}dispose(){this._geometryVersion=(this._geometryVersion??0)+1,this._log(`Disposing resources`),this._disposeRefitWorker(),this._disposeTLASWorker(),this._disposeTextures(),this._reset(),this.textureCreator&&=(this.textureCreator.dispose(),null),this.geometryExtractor=null,this.bvhBuilder=null,this.tlasBuilder=null,this._blasRefitter=null}},rc=[[1619.19106,-.00205010916,5.02995757],[2488.45471,-.00111330907,3.22621544],[3341.43193,-.000486551192,1.76486769],[4094.61742,-.000127446582,.725731635],[4670.28036,291258199e-13,.126703442],[4595.09185,287495649e-13,.15034502],[3787.1745,935907826e-14,.399075871]],ic=[[-488.999748,.000604330754,-.0755807526],[-755.994277,.000316730098,.478306139],[-1023.63977,.00012022347,.936662319],[-1265.71316,487340896e-14,1.27054498],[-1425.29332,-401150431e-13,1.43972784],[-1175.54822,-216378048e-13,1.30408023],[-500.799571,-459832026e-14,1.09098763]],ac=[[596945309e-19,-4.85742887e-8,-970622247e-13,-.00407936148],[240430366e-19,5.55021075e-8,-.000198503712,.0289312858],[-140949732e-19,1.89878968e-7,-.000356632824,.0910767778],[-361460868e-19,2.84822009e-7,-.000493211319,.15672344],[-197075738e-19,1.75359352e-7,-.000250542825,-.0222783266],[-161997957e-21,-1.64216008e-8,.000386216271,-.738077418],[672650283e-21,-2.73078809e-8,.000424098264,-.752335691]];function oc(e){let t,n,r;if(e>=12e3)t=.8262954810464208,n=.9945080501520986,r=1.566307710274283;else if(e<800)t=5.413294490189271,n=-.20319390035873933,r=-.0822535242887164;else{let i=e>=6365?6:e>=3315?5:e>=1902?4:e>=1449?3:e>=1167?2:+(e>=965),a=rc[i],o=ic[i],s=ac[i],c=1/e;t=a[0]*c+a[1]*e+a[2],n=o[0]*c+o[1]*e+o[2],r=((s[0]*e+s[1])*e+s[2])*e+s[3]}return[Math.max(0,t),Math.max(0,n),Math.max(0,r)]}Fn();var sc=1/(4*Math.PI);function cc(e){let t=e.userData||{},n=Number.isFinite(t.exposure)?t.exposure:0,r=e.intensity*2**n,i=[e.color.r,e.color.g,e.color.b];if(t.useTemperature){let[e,n,r]=oc(t.temperature??6500);i[0]*=e,i[1]*=n,i[2]*=r}return jn(i),{r:i[0],g:i[1],b:i[2],intensity:r}}var lc=class{constructor(){this.lightData={directional:[],rectArea:[],point:[],spot:[]},this.directionalLightCache=[],this.areaLightCache=[],this.pointLightCache=[],this.spotLightCache=[]}clear(){this.lightData.directional=[],this.lightData.rectArea=[],this.lightData.point=[],this.lightData.spot=[],this.directionalLightCache=[],this.areaLightCache=[],this.pointLightCache=[],this.spotLightCache=[]}calculateLightImportance(e,t=`directional`){let n=.2126*e.color.r+.7152*e.color.g+.0722*e.color.b,r=e.intensity*n;if(t===`area`){let t=e.width*e.height;r*=Math.sqrt(t)}else if(t===`point`)r*=Math.sqrt(e.distance||100);else if(t===`spot`){let t=Math.sin(e.angle||Math.PI/4);r*=Math.sqrt(e.distance||100)*t}return r}addDirectionalLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n;if(e.target){e.target.updateMatrixWorld();let i=e.target.getWorldPosition(new r.Vector3);n=t.sub(i).normalize()}else n=t.normalize();let i=this.calculateLightImportance(e,`directional`),a=e.userData.angle||e.angle||0,o=cc(e),s=e.userData?.gobo,c=s&&Number.isInteger(s.index)?s.index:-1,l=s&&typeof s.intensity==`number`?s.intensity:1,u=s&&s.inverted?-Math.abs(l):Math.abs(l),d=s&&typeof s.scale==`number`?s.scale:5;this.directionalLightCache.push({data:[n.x,n.y,n.z,o.r,o.g,o.b,o.intensity,a,c,u,d,0],importance:i,light:e})}addRectAreaLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=e.getWorldQuaternion(new r.Quaternion),i=e.getWorldScale(new r.Vector3),a=e.width*i.x*.5,o=e.height*i.y*.5,s=new r.Vector3(a,0,0).applyQuaternion(n),c=new r.Vector3(0,-o,0).applyQuaternion(n),l=this.calculateLightImportance(e,`area`),u=e.userData?.normalize??!0?1:0,d=Number.isFinite(e.userData?.spread)?e.userData.spread:Math.PI,f=+(e.userData?.shape===`ellipse`||e.userData?.shape===`disk`||e.userData?.shape===1),p=cc(e);this.areaLightCache.push({data:[t.x,t.y,t.z,s.x,s.y,s.z,c.x,c.y,c.z,p.r,p.g,p.b,p.intensity,u,d,f],importance:l,light:e})}addPointLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=this.calculateLightImportance(e,`point`),i=cc(e);this.pointLightCache.push({data:[t.x,t.y,t.z,i.r,i.g,i.b,i.intensity*sc,e.distance||0,e.decay===void 0?2:e.decay],importance:n,light:e})}addSpotLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=(e.target?e.target.getWorldPosition(new r.Vector3):new r.Vector3(0,0,-1)).sub(t).normalize(),i=this.calculateLightImportance(e,`spot`),a=e.userData?.gobo,o=a&&Number.isInteger(a.index)?a.index:-1,s=a&&typeof a.intensity==`number`?a.intensity:1,c=a&&a.inverted?-Math.abs(s):Math.abs(s),l=e.userData?.ies,u=l&&Number.isInteger(l.index)?l.index:-1,d=l&&typeof l.intensity==`number`?l.intensity:1,f=cc(e);this.spotLightCache.push({data:[t.x,t.y,t.z,n.x,n.y,n.z,f.r,f.g,f.b,f.intensity*sc,e.angle||Math.PI/4,e.penumbra||0,e.distance||0,e.decay===void 0?2:e.decay,o,c,u,d,0,0],importance:i,light:e})}preprocessLights(){this.directionalLightCache.sort((e,t)=>t.importance-e.importance),this.areaLightCache.sort((e,t)=>t.importance-e.importance),this.pointLightCache.sort((e,t)=>t.importance-e.importance),this.spotLightCache.sort((e,t)=>t.importance-e.importance),this.lightData.directional=[],this.lightData.rectArea=[],this.lightData.point=[],this.lightData.spot=[],this.directionalLightCache.forEach(e=>{this.lightData.directional.push(...e.data)}),this.areaLightCache.forEach(e=>{this.lightData.rectArea.push(...e.data)}),this.pointLightCache.forEach(e=>{this.lightData.point.push(...e.data)}),this.spotLightCache.forEach(e=>{this.lightData.spot.push(...e.data)}),this.areaLightCache.length>0&&console.log(`Preprocessed ${this.areaLightCache.length} area lights by importance`),this.pointLightCache.length>0&&console.log(`Preprocessed ${this.pointLightCache.length} point lights by importance`),this.spotLightCache.length>0&&console.log(`Preprocessed ${this.spotLightCache.length} spot lights by importance`)}updateShaderUniforms(e){let t=Math.floor(this.lightData.directional.length/12),n=Math.floor(this.lightData.rectArea.length/16),r=Math.floor(this.lightData.point.length/9),i=Math.floor(this.lightData.spot.length/20);e.defines.MAX_DIRECTIONAL_LIGHTS=t,e.defines.MAX_AREA_LIGHTS=n,e.defines.MAX_POINT_LIGHTS=r,e.defines.MAX_SPOT_LIGHTS=i,e.uniforms.directionalLights.value=new Float32Array(this.lightData.directional),e.uniforms.areaLights.value=new Float32Array(this.lightData.rectArea),e.uniforms.pointLights.value=new Float32Array(this.lightData.point),e.uniforms.spotLights.value=new Float32Array(this.lightData.spot),e.needsUpdate=!0}processSceneLights(e,t){this.clear(),e.traverse(e=>{e.isDirectionalLight?this.addDirectionalLight(e):e.isRectAreaLight?this.addRectAreaLight(e):e.isPointLight?this.addPointLight(e):e.isSpotLight&&this.addSpotLight(e)}),this.preprocessLights(),this.updateShaderUniforms(t)}getLightStatistics(){return{directionalLights:this.directionalLightCache.map(e=>({intensity:e.light.intensity,importance:e.importance,color:e.light.color})),areaLights:this.areaLightCache.map(e=>({intensity:e.light.intensity,importance:e.importance,color:e.light.color,size:e.light.width*e.light.height}))}}},uc,dc,fc,pc,mc,hc,gc,_c,vc,yc,bc,xc,Sc,Cc,wc,Tc,Ec=g((()=>{uc=C({origin:`vec3`,direction:`vec3`}),dc=C({color:`vec4`,emissive:`vec3`,emissiveIntensity:`float`,roughness:`float`,metalness:`float`,ior:`float`,transmission:`float`,thickness:`float`,clearcoat:`float`,clearcoatRoughness:`float`,opacity:`float`,transparent:`bool`,attenuationColor:`vec3`,attenuationDistance:`float`,dispersion:`float`,sheen:`float`,sheenRoughness:`float`,sheenColor:`vec3`,specularIntensity:`float`,specularColor:`vec3`,alphaTest:`float`,alphaMode:`int`,side:`int`,depthWrite:`int`,albedoMapIndex:`int`,emissiveMapIndex:`int`,normalMapIndex:`int`,bumpMapIndex:`int`,bumpScale:`float`,displacementScale:`float`,metalnessMapIndex:`int`,roughnessMapIndex:`int`,displacementMapIndex:`int`,normalScale:`vec2`,albedoTransform:`mat3`,emissiveTransform:`mat3`,normalTransform:`mat3`,bumpTransform:`mat3`,metalnessTransform:`mat3`,roughnessTransform:`mat3`,displacementTransform:`mat3`,iridescence:`float`,iridescenceIOR:`float`,iridescenceThicknessRange:`vec2`,subsurface:`float`,subsurfaceColor:`vec3`,subsurfaceRadius:`vec3`,subsurfaceRadiusScale:`float`,subsurfaceAnisotropy:`float`,anisotropy:`float`,anisotropyRotation:`float`,anisotropyMapIndex:`int`,transmissionMapIndex:`int`,clearcoatMapIndex:`int`,clearcoatRoughnessMapIndex:`int`,sheenColorMapIndex:`int`,sheenRoughnessMapIndex:`int`,iridescenceMapIndex:`int`,iridescenceThicknessMapIndex:`int`,specularIntensityMapIndex:`int`,specularColorMapIndex:`int`,diffuseTransmission:`float`,diffuseTransmissionColor:`vec3`,diffuseTransmissionMapIndex:`int`,diffuseTransmissionColorMapIndex:`int`}),fc=C({transmission:`float`,clearcoat:`float`,clearcoatRoughness:`float`,sheenColor:`vec3`,sheenRoughness:`float`,iridescence:`float`,iridescenceThickness:`float`,specularIntensity:`float`,specularColor:`vec3`,diffuseTransmission:`float`,diffuseTransmissionColor:`vec3`}),pc=C({color:`vec4`,ior:`float`,transmission:`float`,attenuationColor:`vec3`,attenuationDistance:`float`,albedoMapIndex:`int`,opacity:`float`,transparent:`bool`,alphaTest:`float`,alphaMode:`int`,albedoTransform:`mat3`}),mc=C({shadowed:`vec3`,unoccluded:`vec3`}),C({position:`vec3`,radius:`float`,material:dc}),hc=C({didHit:`bool`,dst:`float`,hitPoint:`vec3`,normal:`vec3`,uv:`vec2`,materialIndex:`int`,meshIndex:`int`,instanceLeaf:`int`,triangleIndex:`int`,boxTests:`int`,triTests:`int`}),C({posA:`vec3`,posB:`vec3`,posC:`vec3`,uvA:`vec2`,uvB:`vec2`,uvC:`vec2`,normalA:`vec3`,normalB:`vec3`,normalC:`vec3`,material:dc,materialIndex:`int`,meshIndex:`int`}),C({color:`vec4`,samples:`int`}),gc=C({direction:`vec3`,value:`vec3`,pdf:`float`,isTransmission:`bool`,colorWeight:`vec3`,isDiffuseTransmission:`bool`}),_c=C({specular:`float`,diffuse:`float`,sheen:`float`,clearcoat:`float`,transmission:`float`,iridescence:`float`,diffuseTransmission:`float`}),vc=C({Ta:`vec3`,Ba:`vec3`}),yc=C({NoL:`float`,NoV:`float`,NoH:`float`,VoH:`float`,LoH:`float`,ToH:`float`,BoH:`float`,ToV:`float`,BoV:`float`,ToL:`float`,BoL:`float`}),bc=C({compensation:`vec3`,E_total:`vec3`}),xc=C({f0:`vec3`,f90:`float`,eta:`float`,F0m:`vec3`,F0:`vec3`}),Sc=C({albedo:`vec4`,emissive:`vec3`,metalness:`float`,roughness:`float`,normal:`vec3`,hasTextures:`bool`}),Cc=C({isMetallic:`bool`,isRough:`bool`,isSmooth:`bool`,isTransmissive:`bool`,hasClearcoat:`bool`,isEmissive:`bool`,complexityScore:`float`}),wc=C({albedoUV:`vec2`,normalUV:`vec2`,metalnessUV:`vec2`,emissiveUV:`vec2`,bumpUV:`vec2`,roughnessUV:`vec2`,normalBumpSameUV:`bool`,metalRoughSameUV:`bool`,albedoEmissiveSameUV:`bool`,allSameUV:`bool`}),Tc=C({invRoughness:`float`,metalFactor:`float`,iorFactor:`float`,maxSheenColor:`float`}),C({traversals:`int`,transmissiveTraversals:`int`,rayType:`int`,isPrimaryRay:`bool`,actualBounceDepth:`int`})})),Dc,Oc,kc,Ac,jc,Mc,Nc,Pc,Fc,Ic,Lc,Rc,zc,Bc,Vc,Hc,Uc,Wc,Gc,Kc,qc,Jc,Yc,Xc,Zc,Qc,$c,el,Z,tl,nl,rl,il,al,ol,sl,cl,ll,ul,dl,fl,pl,ml=g((()=>{Ec(),wt(),Dc=(0,n.wgslFn)(`
247
+ `,bindings:n}}function yo(){So.length=0,So.push(...io),Co.clear();for(let e of So)Co.set(e.id,e);oo()}var bo,xo,So,Co,wo,To,Eo,Do,Oo,ko=g((()=>{ao(),bo=200,xo=12,So=[...io],Co=new Map(So.map(e=>[e.id,e])),wo=1,To=new Set,Eo=Co,Do=r.NoToneMapping,Oo=r.AgXToneMapping}));ko();var Ao=e=>(t,n,r,i,a)=>e(t>0?t:0,n>0?n:0,r>0?r:0,i,a),jo=new Map;function Mo(){jo.clear();for(let e of Eo.values())jo.set(e.id,Ao(e.cpu))}Mo(),co(Mo);function No(e){return lo(e)?.outputEncoded===!0}function Po(e){return e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055}function Fo(e,t){let n=lo(t);return n?n.appliesExposure?e:1:t===r.NoToneMapping?1:e}var Io=.2126,Lo=.7152,Ro=.0722;function zo(e,t){if(t===1)return;let n=e[0]*Io+e[1]*Lo+e[2]*Ro;e[0]=n+(e[0]-n)*t,e[1]=n+(e[1]-n)*t,e[2]=n+(e[2]-n)*t}function Bo(e,{exposure:t,toneMapping:n,saturation:i=1,preserveAlpha:a=!1}){let o=jo.get(n)??jo.get(r.NoToneMapping),s=Fo(t,n),c=No(n),l=new Uint8ClampedArray(e.length),u=[0,0,0];for(let t=0;t<e.length;t+=4)u[0]=e[t]*s,u[1]=e[t+1]*s,u[2]=e[t+2]*s,zo(u,i),o(u[0],u[1],u[2],1,u),c?(l[t]=u[0]*255+.5,l[t+1]=u[1]*255+.5,l[t+2]=u[2]*255+.5):(l[t]=Po(u[0])*255+.5,l[t+1]=Po(u[1])*255+.5,l[t+2]=Po(u[2])*255+.5),l[t+3]=a?e[t+3]*255+.5:255;return l}wt(),X(),Ae();var Vo=ye(`textures`),Ho={MAX_BUFFER_MEMORY:1024*1024*1024,MAX_TEXTURE_MEMORY:2048*1024*1024,CLEANUP_THRESHOLD:.8,STREAM_BATCH_SIZE:4},Uo=8*2**20,Wo=16,Go=4,Ko=8192*8192,qo={busy:0,waiting:[]};async function Jo(){return qo.busy<Math.max(1,ar()-1)?qo.busy++:await new Promise(e=>qo.waiting.push(e)),()=>{let e=qo.waiting.shift();e?e():qo.busy--}}var Yo={toSRGB:null,toLinear:null};function Xo(e){if(!Yo[e]){let t=new Uint8Array(256);for(let n=0;n<256;n++){let r=n/255,i=e===`toSRGB`?Po(r):r<=.04045?r/12.92:((r+.055)/1.055)**2.4;t[n]=Math.max(0,Math.min(255,Math.round(i*255)))}Yo[e]=t}return Yo[e]}var Zo=class{constructor(){this.canvasContextPairs=[],this.maxPoolSize=Nt.CANVAS_POOL_SIZE}getCanvasWithContext(e,t,n=!1,r={}){let i={willReadFrequently:!0,alpha:!0,desynchronized:!0,...r},a=this.canvasContextPairs.pop();if(!a){let r;r=n&&typeof OffscreenCanvas<`u`?new OffscreenCanvas(e,t):document.createElement(`canvas`);let o=r.getContext(`2d`,i);a={canvas:r,context:o}}return a.canvas.width=e,a.canvas.height=t,a}releaseCanvasWithContext(e){this.canvasContextPairs.length<this.maxPoolSize&&(e.context.globalAlpha=1,e.context.globalCompositeOperation=`source-over`,e.context.imageSmoothingEnabled=!0,e.context.clearRect(0,0,e.canvas.width,e.canvas.height),e.canvas.width=1,e.canvas.height=1,this.canvasContextPairs.push(e))}getCanvas(e,t,n=!1){return this.getCanvasWithContext(e,t,n).canvas}getContext(e,t={}){let n=this.canvasContextPairs.find(t=>t.canvas===e);return n?n.context:e.getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0,...t})}dispose(){this.canvasContextPairs=[]}},Qo=class{constructor(e={}){this.pools=new Map,this.memoryUsage=0,this.maxMemoryUsage=e.maxMemory||Ho.MAX_BUFFER_MEMORY,this.allocatedBuffers=new WeakMap,this.sizeStrategy=e.sizeStrategy||`adaptive`}getOptimalSize(e){switch(this.sizeStrategy){case`exact`:return e;case`power2`:return 2**Math.ceil(Math.log2(e));default:return e<1024?e:e<1024*1024?Math.ceil(e/1024)*1024:2**Math.ceil(Math.log2(e))}}getBuffer(e,t=Float32Array){let n=this.getOptimalSize(e),r=`${t.name}-${n}`,i=(this.pools.get(r)||[]).pop();if(!i)try{i=new t(n),this.memoryUsage+=i.byteLength,this.allocatedBuffers.set(i,!0)}catch{this.cleanup();try{i=new t(n),this.memoryUsage+=i.byteLength,this.allocatedBuffers.set(i,!0)}catch(e){let r=n*t.BYTES_PER_ELEMENT/(1024*1024),i=this.memoryUsage/(1024*1024);throw Error(`Buffer allocation failed: requested ${r.toFixed(1)}MB, current usage: ${i.toFixed(1)}MB, max: ${(this.maxMemoryUsage/(1024*1024)).toFixed(1)}MB. Original error: ${e.message}`)}}return this.memoryUsage>this.maxMemoryUsage*Ho.CLEANUP_THRESHOLD&&this.cleanup(),this.checkMemoryHealth(),i.byteOffset+e*t.BYTES_PER_ELEMENT>i.buffer.byteLength&&(i=new t(e),this.memoryUsage+=i.byteLength),new t(i.buffer,i.byteOffset,e)}forget(e){this.memoryUsage=Math.max(0,this.memoryUsage-e.buffer.byteLength)}releaseBuffer(e,t=Float32Array){let n=(e.buffer.byteLength-e.byteOffset)/t.BYTES_PER_ELEMENT,r=this.getOptimalSize(n),i=`${t.name}-${r}`,a=this.pools.get(i)||[];a.length<Nt.BUFFER_POOL_SIZE?(a.push(new t(e.buffer,e.byteOffset,n)),this.pools.set(i,a)):this.allocatedBuffers.has(e)&&(this.memoryUsage-=e.byteLength,this.allocatedBuffers.delete(e))}cleanup(){let e=Array.from(this.pools.entries());e.slice(0,Math.floor(e.length/2)).forEach(([e,t])=>{t.forEach(e=>{this.allocatedBuffers.has(e)&&(this.memoryUsage-=e.byteLength,this.allocatedBuffers.delete(e))}),this.pools.delete(e)})}dispose(){this.pools.forEach(e=>{e.forEach(e=>{this.allocatedBuffers.has(e)&&this.allocatedBuffers.delete(e)})}),this.pools.clear(),this.memoryUsage=0}getMemoryStats(){return{currentUsage:this.memoryUsage,maxUsage:this.maxMemoryUsage,utilizationPercentage:this.memoryUsage/this.maxMemoryUsage*100,poolCount:this.pools.size,allocatedBufferCount:this.allocatedBuffers&&this.allocatedBuffers.size||0}}checkMemoryHealth(){let e=this.getMemoryStats();return e.utilizationPercentage>90?(console.warn(`Memory pool critical: ${e.utilizationPercentage.toFixed(1)}% used (${(e.currentUsage/(1024*1024)).toFixed(1)}MB / ${(e.maxUsage/(1024*1024)).toFixed(1)}MB)`),`critical`):e.utilizationPercentage>70?(console.warn(`Memory pool high: ${e.utilizationPercentage.toFixed(1)}% used (${(e.currentUsage/(1024*1024)).toFixed(1)}MB / ${(e.maxUsage/(1024*1024)).toFixed(1)}MB)`),`high`):`normal`}},$o=class{constructor(e=Nt.CACHE_SIZE_LIMIT){this.cache=new Map,this.accessOrder=[],this.maxSize=e}generateHash(e){let t=``;for(let n of e)if(n?.image){let e=n.image.width||0,r=n.image.height||0,i=n.image.src||n.uuid||``,a=n.flipY===!1?`n`:`f`,o=`${n.colorSpace??``}|${n.userData?.ocioColorSpace??``}`;t+=`${e}x${r}_${i.slice(-8)}_${a}_${o}_`}return t+e.length}get(e){if(this.cache.has(e)){let t=this.cache.get(e);if(t?.userData&&t.userData.buffer===null){this.cache.delete(e);let t=this.accessOrder.indexOf(e);return t>-1&&this.accessOrder.splice(t,1),null}let n=this.accessOrder.indexOf(e);return n>-1&&this.accessOrder.splice(n,1),this.accessOrder.push(e),t}return null}set(e,t){if(this.cache.has(e)){let t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1)}else this.cache.size>=this.maxSize&&this.evictLRU();this.cache.set(e,t),this.accessOrder.push(e)}evictLRU(){if(this.accessOrder.length>0){let e=this.accessOrder.shift(),t=this.cache.get(e);t&&t.dispose&&t.dispose(),this.cache.delete(e)}}dispose(){this.cache.forEach(e=>{e&&e.dispose&&e.dispose()}),this.cache.clear(),this.accessOrder=[]}},es=class{constructor(e={}){this.useWorkers=typeof Worker<`u`,this.maxConcurrentWorkers=Nt.MAX_CONCURRENT_WORKERS,this.activeWorkers=0,this._issues=e.issues??null,this.maxTextureSize=this._clampTextureSize(e.maxTextureSize??Nt.DEFAULT_MAX_TEXTURE_SIZE),this.canvasPool=new Zo,this.bufferPool=new Qo({maxMemory:e.maxBufferMemory||Ho.MAX_BUFFER_MEMORY,sizeStrategy:e.bufferSizeStrategy||`adaptive`}),this.textureCache=new $o,this.capabilities=this.detectCapabilities(),this.optimalMethod=this.selectOptimalMethod()}_reportTextureFailure(e,t){if(t instanceof Gt)throw t;this._issues?.record(Y.TEXTURE_BUILD_FAILED,`${e} texture array failed to build — those surfaces render untextured`,{map:e,cause:String(t?.message??t)})}_reportTextureLayer(e,t){this._issues?.record(Y.TEXTURE_BUILD_FAILED,`texture ${e} could not be read — its surfaces show a white placeholder`,{layer:e,cause:String(t?.message??t)})}_clampTextureSize(e){let t=Math.floor(Number(e)||Nt.DEFAULT_MAX_TEXTURE_SIZE);return Math.max(Nt.MIN_TEXTURE_WIDTH,Math.min(t,Nt.MAX_TEXTURE_SIZE))}setMaxTextureSize(e){let t=this._clampTextureSize(e);return t===this.maxTextureSize?t:(this.maxTextureSize=t,this.textureCache?.dispose(),this.textureCache=new $o,this.maxTextureSize)}detectCapabilities(){return{offscreenCanvas:typeof OffscreenCanvas<`u`,imageBitmap:typeof createImageBitmap<`u`,workers:typeof Worker<`u`,hardwareConcurrency:ar()}}selectOptimalMethod(){return this.capabilities.workers&&this.capabilities.offscreenCanvas?`worker-offscreen`:this.capabilities.imageBitmap?`imageBitmap`:`canvas`}_applyColorManagement(e,t,n,i=new Set){let a=Or();if(!a?.hasConfig)return;let o=e?.image?.data;if(!o||!n)return;let s=t.filter(e=>e?.image),c=e.image.width*e.image.height*4,l=0,u=0,d=[];for(let e=0;e<s.length;e++){let t=e*c,n=Math.min(t+c,o.length);if(t>=o.length)break;let f=s[e],p=o.subarray(t,n),m=null;try{m=a.resolveTexture(f)}catch(t){Vo.warn(`could not resolve the colour space of layer ${e}: ${t.message}`)}let h=m&&m.via!==`three`?m.colorSpace:null,g=f.type===r.FloatType||f.type===r.HalfFloatType;h&&(i.has(e)||g)&&(d.push(`${f.name||`layer ${e}`} (${h})`),h=null);try{a.convertTextureBytes(p,{space:h,encoding:`srgb`})&&(h?l++:u++)}catch(t){this._issues?.warn(Y.TEXTURE_PROCESSING_FALLBACK,`colour conversion failed for layer ${e} — left in its original space`,{cause:String(t?.message??t),space:h})}}d.length&&this._issues?.warn(Y.TEXTURE_PROCESSING_FALLBACK,`${d.length} colour map(s) name a colour space their stored bytes are no longer in (re-encoded or quantized on the way in); converted by primaries only`,{textures:d.slice(0,8)}),l+u!==0&&(e.needsUpdate=!0,Vo.info(`colour maps into ${a.workingSpace}: ${l} by named space, ${u} by primaries, of ${s.length}`))}_harmonizeTransfer(e,t,n){let i=new Set,a=e?.image?.data;if(!a)return i;let o=t.filter(e=>e?.image),s=n?r.SRGBColorSpace:r.LinearSRGBColorSpace,c=e.image.width*e.image.height*4,l=[];for(let e=0;e<o.length;e++){let t=o[e].colorSpace;if(t!==r.SRGBColorSpace&&t!==r.LinearSRGBColorSpace||t===s)continue;let u=Xo(n?`toSRGB`:`toLinear`),d=e*c,f=Math.min(d+c,a.length);for(let e=d;e<f;e+=4)a[e]=u[a[e]],a[e+1]=u[a[e+1]],a[e+2]=u[a[e+2]];l.push(o[e].name||o[e].source?.uuid?.slice(0,8)||`layer ${e}`),i.add(e)}if(l.length===0)return i;e.needsUpdate=!0;let u=l.slice(0,4).join(`, `)+(l.length>4?`, +${l.length-4} more`:``);return n?Vo.info(`re-encoded ${l.length}/${o.length} linear-declared colour map(s) to sRGB so the GPU decode round-trips: ${u}`):Vo.warn(`decoded ${l.length}/${o.length} sRGB-declared data map(s) to linear — precision is lost in the darks, check the asset: ${u}`),i}async createTexturesToDataTexture(e,{srgbPool:t=!1}={}){if(!e||e.length===0)return null;let n=Or()?.inputKey??`-`,r=`${t?`s`:`l`}:${n}:${this.textureCache.generateHash(e)}`,i=this.textureCache.get(r);if(i)return i;if(typeof createImageBitmap>`u`){let n=await this.processOnCPU(e),i=this._harmonizeTransfer(n,e,t);return this._applyColorManagement(n,e,t,i),this.textureCache.set(r,n),n}let{normalized:a,bitmapsToClose:o}=await this._normalizeTexturesForProcessing(e),s=this.selectProcessingStrategy(a),c;try{switch(s.method){case`worker-direct`:c=await this.processWithWorkerDirect(a);break;case`worker-streaming`:c=await this.processInWorkerStreaming(a);break;case`main-batch`:c=await this.processOnMainThreadBatch(a,s.batchSize);break;case`main-streaming`:c=await this.processOnMainThreadStreaming(a);break;default:c=await this.processOnMainThreadSync(a)}if(c){let n=this._harmonizeTransfer(c,e,t);this._applyColorManagement(c,e,t,n),this.textureCache.set(r,c)}return c}catch(n){if(n instanceof Gt)throw n;this._issues?.warn(Y.TEXTURE_PROCESSING_FALLBACK,`worker texture processing failed — retrying on the main thread`,{cause:String(n?.message??n)});let r=await this.processOnMainThreadSync(a),i=this._harmonizeTransfer(r,e,t);return this._applyColorManagement(r,e,t,i),r}finally{for(let e of o)e.close()}}selectProcessingStrategy(e){let t=e.reduce((e,t)=>e+(t.image?.width||0)*(t.image?.height||0),0),n=t*4;return this.capabilities.workers&&n>Ho.MAX_TEXTURE_MEMORY?{method:`worker-streaming`}:this.capabilities.workers&&t>2097152?{method:`worker-direct`}:t>524288?{method:`main-batch`,batchSize:Math.min(4,e.length)}:e.length>8?{method:`main-streaming`}:{method:`main-sync`}}async processWithWorkerDirect(e){for(;this.activeWorkers>=this.maxConcurrentWorkers;)await new Promise(e=>setTimeout(e,10));this.activeWorkers++;let t=1,n=null;try{let r=await this.prepareTexturesForWorkerDirect(e),i=this._sharedPackSlots(r);if(i>0)return t+=i,this.activeWorkers+=i,this.createDataArrayTextureFromResult(await this._packAcrossWorkers(r,t));n=new Ba;let a=await new Promise((e,t)=>{n.onmessage=n=>{n.data.error?t(Error(n.data.error)):e(n.data)},n.onerror=t;let i=[];r.forEach(e=>{e.data instanceof ArrayBuffer?i.push(e.data):e.bitmap&&i.push(e.bitmap)}),n.postMessage({textures:r,maxTextureSize:this.maxTextureSize,method:`direct-transfer`},i)});return this.createDataArrayTextureFromResult(a)}finally{n?.terminate(),this.activeWorkers-=t}}_sharedPackSlots(e){if(typeof SharedArrayBuffer>`u`||!globalThis.crossOriginIsolated||e.reduce((e,t)=>e+t.width*t.height,0)<Ko)return 0;let t=this.maxConcurrentWorkers-this.activeWorkers;return Math.max(0,Math.min(e.length,Go,t+1)-1)}async _packAcrossWorkers(e,t){let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(e.map(e=>({image:e}))),i=e.length,a=new SharedArrayBuffer(n*r*i*4),o=Array.from({length:t},()=>({cost:0,layers:[],transfer:[]})),s=e.map((e,t)=>t),c=t=>e[t].width*e[t].height;s.sort((e,t)=>c(t)-c(e));for(let t of s){let n=o.reduce((e,t)=>t.cost<e.cost?t:e),r=e[t];n.layers.push({index:t,texture:r}),n.cost+=c(t),r.data instanceof ArrayBuffer?n.transfer.push(r.data):r.bitmap&&n.transfer.push(r.bitmap)}let l=[];try{await Promise.all(o.filter(e=>e.layers.length).map(e=>new Promise((t,i)=>{let o=ur(Ba);l.push(o),o.onmessage=({data:e})=>e.error?i(Error(e.error)):t(),o.onerror=e=>i(Error(e.message||`texture worker failed`)),o.postMessage({shared:a,width:n,height:r,layers:e.layers,maxTextureSize:this.maxTextureSize},e.transfer)})))}finally{for(let e of l)e.terminate()}return{data:a,width:n,height:r,depth:i}}async processInWorkerStreaming(e){let t=e.filter(e=>e?.image);if(t.length===0)return this.createFallbackTexture();let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t),i=t.length;for(;this.activeWorkers>=this.maxConcurrentWorkers;)await new Promise(e=>setTimeout(e,10));this.activeWorkers++;let a=ur(Ba);try{let e=0,o=null,s,c=new Promise((e,t)=>s={resolve:e,reject:t});c.catch(()=>{}),a.onmessage=({data:t})=>{t.error?s.reject(Error(t.error)):t.stream===`ack`?e++:s.resolve(t),o?.()},a.onerror=e=>{s.reject(Error(e.message||`texture worker failed`)),o?.()},a.postMessage({stream:`begin`,width:n,height:r,depth:i});let l=performance.now();for(let s=0;s<i;s++){for(;s-e>=Ho.STREAM_BATCH_SIZE;)await Promise.race([new Promise(e=>o=e),c]),l=performance.now();let i=t[s],u=await createImageBitmap(i.image,{resizeWidth:n,resizeHeight:r,resizeQuality:`high`,imageOrientation:i.flipY===!1?`none`:`flipY`});a.postMessage({stream:`layer`,index:s,bitmap:u},[u]),performance.now()-l>Wo&&(await new Promise(e=>setTimeout(e,0)),l=performance.now())}return a.postMessage({stream:`end`}),this.createDataArrayTextureFromResult(await c)}finally{a.terminate(),this.activeWorkers--}}async prepareTexturesForWorkerDirect(e){let t=[],n=()=>({data:new Uint8ClampedArray([255,255,255,255]).buffer,width:1,height:1,isImageData:!0});for(let r=0;r<e.length;r++){let i=e[r];if(!i?.image){this._reportTextureLayer(r,`no image`),t.push(n());continue}let a=i.flipY!==!1;try{let e=i.image;if(typeof createImageBitmap<`u`&&(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&e instanceof OffscreenCanvas)){let e=await createImageBitmap(i.image,{imageOrientation:a?`flipY`:`none`});t.push({bitmap:e,width:i.image.width,height:i.image.height,isDirect:!0})}else{let e=i.image.width,n=i.image.height,r=await createImageBitmap(i.image,{imageOrientation:a?`flipY`:`none`}),o=this.canvasPool.getCanvasWithContext(e,n);o.context.drawImage(r,0,0),r.close();let s=o.context.getImageData(0,0,e,n);t.push({data:s.data.buffer,width:e,height:n,isImageData:!0}),this.canvasPool.releaseCanvasWithContext(o)}}catch(e){this._reportTextureLayer(r,e),t.push(n())}}return t}async processOnCPU(e){let t=e.map((e,t)=>{let n=e?.image,r=e?.isCompressedTexture?e.mipmaps?.[0]:n,i=r?.data;return i&&r.width>0&&r.height>0&&i.byteLength>=r.width*r.height*4?{data:new Uint8Array(i.buffer,i.byteOffset,r.width*r.height*4),width:r.width,height:r.height,flipY:e.flipY!==!1}:(this._reportTextureLayer(t,n?`not decoded to pixels, and there is no browser to decode it`:`no image`),{data:new Uint8Array([255,255,255,255]),width:1,height:1,flipY:!1})}),{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t.map(e=>({image:e}))),i=n*r*4,a=sr()&&i*t.length>=Uo?await this._packInWorker(t,n,r):null;if(a)return this.createDataArrayTextureFromBuffer(a,n,r,t.length);let o=this.bufferPool.getBuffer(i*t.length,Uint8Array);return t.forEach((e,t)=>Wa(e,o,t*i,n,r)),this.createDataArrayTextureFromBuffer(o,n,r,t.length)}async _packInWorker(e,t,n){let r=await Jo(),i=null;try{let r=[],a=e.map(e=>{if(typeof SharedArrayBuffer<`u`&&e.data.buffer instanceof SharedArrayBuffer)return e;let t=e.data.slice();return r.push(t.buffer),{...e,data:t}});return i=ur(Ua),await new Promise((e,o)=>{i.onmessage=t=>t.data.error?o(Error(t.data.error)):e(t.data.data),i.onerror=e=>o(e.error??Error(e.message??`texture pack worker failed`)),i.postMessage({layers:a,width:t,height:n},r)})}catch(e){return this._issues?.warn(Y.TEXTURE_PROCESSING_FALLBACK,`worker texture packing failed — packing on the main thread`,{cause:String(e?.message??e)}),null}finally{i?.terminate(),r()}}async processOnMainThreadBatch(e,t){let n=e.filter(e=>e?.image);if(n.length===0)return this.createFallbackTexture();let{maxWidth:r,maxHeight:i}=this.calculateOptimalDimensions(n),a=n.length,o=this.bufferPool.getBuffer(r*i*a*4,Uint8Array);for(let e=0;e<n.length;e+=t){let a=Math.min(e+t,n.length),s=[];for(let t=e;t<a;t++){let e=n[t],a=e.flipY!==!1,o=createImageBitmap(e.image,{resizeWidth:r,resizeHeight:i,resizeQuality:`high`,imageOrientation:a?`flipY`:`none`});s.push(o.then(e=>({bitmap:e,index:t})))}let c=await Promise.all(s),l=this.canvasPool.getCanvasWithContext(r,i);l.context.imageSmoothingEnabled=!1;for(let{bitmap:e,index:t}of c){l.context.clearRect(0,0,r,i),l.context.drawImage(e,0,0);let n=l.context.getImageData(0,0,r,i),a=r*i*4*t;o.set(n.data,a),e.close()}this.canvasPool.releaseCanvasWithContext(l)}return this.createDataArrayTextureFromBuffer(o,r,i,a)}async processOnMainThreadStreaming(e){let t=e.filter(e=>e?.image);if(t.length===0)return this.createFallbackTexture();let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t),i=t.length,a=this.bufferPool.getBuffer(n*r*i*4,Uint8Array),o=this.canvasPool.getCanvasWithContext(n,r);o.context.imageSmoothingEnabled=!0,o.context.imageSmoothingQuality=`high`;for(let e=0;e<t.length;e++){let i=t[e],s=await createImageBitmap(i.image,{resizeWidth:n,resizeHeight:r,resizeQuality:`high`,imageOrientation:i.flipY===!1?`none`:`flipY`});o.context.clearRect(0,0,n,r),o.context.drawImage(s,0,0),s.close();let c=o.context.getImageData(0,0,n,r),l=n*r*4*e;a.set(c.data,l),e%Ho.STREAM_BATCH_SIZE===0&&await new Promise(e=>setTimeout(e,0))}return this.canvasPool.releaseCanvasWithContext(o),this.createDataArrayTextureFromBuffer(a,n,r,i)}async processOnMainThreadSync(e){let t=e.filter(e=>e?.image);if(t.length===0)return this.createFallbackTexture();let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t),i=t.length,a=this.bufferPool.getBuffer(n*r*i*4,Uint8Array),o=this.canvasPool.getCanvasWithContext(n,r);o.context.imageSmoothingEnabled=!0,o.context.imageSmoothingQuality=`high`;for(let e=0;e<t.length;e++){let i=t[e],s=await createImageBitmap(i.image,{resizeWidth:n,resizeHeight:r,resizeQuality:`high`,imageOrientation:i.flipY===!1?`none`:`flipY`});o.context.clearRect(0,0,n,r),o.context.drawImage(s,0,0),s.close();let c=o.context.getImageData(0,0,n,r),l=n*r*4*e;a.set(c.data,l)}return this.canvasPool.releaseCanvasWithContext(o),this.createDataArrayTextureFromBuffer(a,n,r,i)}createMaterialRawData(e){let t=q.FLOATS_PER_MATERIAL,n=new Float32Array(e.length*t);for(let r=0;r<e.length;r++)Mt(n,r*t,e[r]);return n}createBVHRawData(e){let t=[],n=e=>{let r=t.length;if(t.push(e),e.leftChild){let t=n(e.leftChild),r=n(e.rightChild);e.leftChild=t,e.rightChild=r}return r};n(e);let r=Nt.VEC4_PER_BVH_NODE*Nt.FLOATS_PER_VEC4;gt(t.length,`BVH node count`);let i=t.length*r,a=new Float32Array(i),o=ht(a);for(let e=0;e<t.length;e++){let n=e*r,i=t[e];if(i.leftChild!==null){let e=i.leftChild,r=i.rightChild,s=t[e],c=t[r];a[n]=s.boundsMin.x,a[n+1]=s.boundsMin.y,a[n+2]=s.boundsMin.z,o[n+3]=e,a[n+4]=s.boundsMax.x,a[n+5]=s.boundsMax.y,a[n+6]=s.boundsMax.z,o[n+7]=r,a[n+8]=c.boundsMin.x,a[n+9]=c.boundsMin.y,a[n+10]=c.boundsMin.z,a[n+12]=c.boundsMax.x,a[n+13]=c.boundsMax.y,a[n+14]=c.boundsMax.z}else o[n]=i.triangleOffset,o[n+1]=i.triangleCount,o[n+3]=St.TRIANGLE_LEAF}return a}async createMaterialTextures(e){let{materials:t,maps:n,normalMaps:i,bumpMaps:a,roughnessMaps:o,metalnessMaps:s,emissiveMaps:c,displacementMaps:l}=e;console.log(`[TextureCreator] Creating material textures only`);let u=performance.now();try{if(!t||t.length===0)throw Error(`No materials provided for texture creation`);this.textureCache.dispose(),this.textureCache=new $o;let e=[];for(let[t,r]of[[`albedo`,n],[`normal`,i],[`bump`,a],[`roughness`,o],[`metalness`,s],[`emissive`,c],[`displacement`,l]])!r||r.length===0||e.push(this.createTexturesToDataTexture(r).then(e=>({type:t,texture:e})).catch(e=>(this._reportTextureFailure(t,e),{type:t,texture:null})));let d=await Promise.allSettled(e),f=d.find(e=>e.status===`rejected`);if(f)throw f.reason;let p={};d.forEach(e=>{if(e.status===`fulfilled`&&e.value){let{type:t,texture:n}=e.value;if(n)switch(t){case`albedo`:n.colorSpace=r.SRGBColorSpace,p.albedoTexture=n;break;case`normal`:p.normalTexture=n;break;case`bump`:p.bumpTexture=n;break;case`roughness`:p.roughnessTexture=n;break;case`metalness`:p.metalnessTexture=n;break;case`emissive`:n.colorSpace=r.SRGBColorSpace,p.emissiveTexture=n;break;case`displacement`:p.displacementTexture=n;break}}});let m=performance.now()-u;return console.log(`[TextureCreator] Material texture creation complete (${m.toFixed(2)}ms)`),p}catch(e){throw console.error(`[TextureCreator] Material texture creation error:`,e),Error(`Material texture creation failed: ${e.message}`)}}calculateOptimalDimensions(e){let t=0,n=0;for(let r of e)t=Math.max(t,r.image.width),n=Math.max(n,r.image.height);let r=Math.max(t,n);if(r>this.maxTextureSize){let e=this.maxTextureSize/r;t=Math.round(t*e),n=Math.round(n*e)}return{maxWidth:Ft(t,this.maxTextureSize),maxHeight:Math.max(1,n)}}createDataArrayTextureFromResult(e){let t=(e.data instanceof ArrayBuffer,new Uint8Array(e.data));return this.createDataArrayTextureFromBuffer(t,e.width,e.height,e.depth)}createDataArrayTextureFromBuffer(e,t,n,i){let a=new r.DataArrayTexture(e,t,n,i);a.minFilter=r.LinearFilter,a.magFilter=r.LinearFilter,a.wrapS=r.RepeatWrapping,a.wrapT=r.RepeatWrapping,a.format=r.RGBAFormat,a.type=r.UnsignedByteType,a.needsUpdate=!0,a.generateMipmaps=!1,a.userData={buffer:e,bufferType:Uint8Array},a.onUpdate=()=>{let e=a.userData.buffer;e&&(this.bufferPool.forget(e),a.userData.buffer=null,a.image.data=null)};let o=a.dispose.bind(a);return a.dispose=()=>{a.userData.buffer&&(this.bufferPool.releaseBuffer(a.userData.buffer,a.userData.bufferType),a.userData.buffer=null),o()},a}async _normalizeTexturesForProcessing(e){let t=[],n=[],i=[];for(let n of e){if(!n?.image){this._reportTextureLayer(t.length,`no image`),t.push(null);continue}if(n.isCompressedTexture&&n.format===r.RGBAFormat&&n.mipmaps?.[0]?.data){let e=n.mipmaps[0],r=t.length;t.push(null),i.push({index:r,flipY:n.flipY,promise:ts(e.data,e.width,e.height)});continue}if(n.isCompressedTexture){console.warn(`[TextureCreator] GPU-compressed texture in mixed group — using placeholder`),t.push(null);continue}if(n.image.data&&!(typeof HTMLImageElement<`u`&&n.image instanceof HTMLImageElement)&&!(typeof HTMLCanvasElement<`u`&&n.image instanceof HTMLCanvasElement)&&!(typeof ImageBitmap<`u`&&n.image instanceof ImageBitmap)){let e=t.length;t.push(null),i.push({index:e,flipY:n.flipY,promise:ts(n.image.data,n.image.width,n.image.height)});continue}t.push(n)}if(i.length>0){let e=await Promise.allSettled(i.map(e=>e.promise));for(let r=0;r<i.length;r++){let{index:a,flipY:o}=i[r],s=e[r];if(s.status===`fulfilled`){let e=s.value;n.push(e),t[a]={image:e,flipY:o}}else this._reportTextureLayer(a,s.reason)}}for(let e=0;e<t.length;e++)if(t[e]===null){let r=new Uint8ClampedArray([255,255,255,255]),i=await createImageBitmap(new ImageData(r,1,1));n.push(i),t[e]={image:i,flipY:!1}}return{normalized:t,bitmapsToClose:n}}createFallbackTexture(){let e=new r.DataArrayTexture(new Uint8Array([255,255,255,255]),1,1,1);return e.minFilter=r.LinearFilter,e.magFilter=r.LinearFilter,e.format=r.RGBAFormat,e.type=r.UnsignedByteType,e.needsUpdate=!0,e.generateMipmaps=!1,e}dispose(){this.canvasPool.dispose(),this.bufferPool.dispose(),this.textureCache.dispose()}};function ts(e,t,n){let r=new Uint8ClampedArray(e.buffer,e.byteOffset,e.byteLength);return createImageBitmap(new ImageData(r,t,n))}var ns=class{constructor(){this.maxLeafSize=8}build(e){let t=e.length;if(t===0){let e=new Float32Array(16);return e[7]=1,e[14]=1,e[15]=-1,{nodeData:e,nodeCount:1,sortedPerm:new Int32Array,bitTrails:new Float32Array}}let n=new Int32Array(t);for(let e=0;e<t;e++)n[e]=e;let r=2*t+4,i=new Float32Array(r*16),a=0,o=new Float32Array(t),s=(t,r,c,l)=>{let u=a++,d=u*16,f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,_=-1/0,v=0,y=1/0,b=1/0,x=1/0,S=-1/0,C=-1/0,w=-1/0;for(let i=t;i<r;i++){let t=e[n[i]];f=Math.min(f,t.bMinX),p=Math.min(p,t.bMinY),m=Math.min(m,t.bMinZ),h=Math.max(h,t.bMaxX),g=Math.max(g,t.bMaxY),_=Math.max(_,t.bMaxZ),v+=t.power,y=Math.min(y,t.cx),b=Math.min(b,t.cy),x=Math.min(x,t.cz),S=Math.max(S,t.cx),C=Math.max(C,t.cy),w=Math.max(w,t.cz)}i[d+0]=f,i[d+1]=p,i[d+2]=m,i[d+3]=v,i[d+4]=h,i[d+5]=g,i[d+6]=_;let T=r-t,E;if(T<=this.maxLeafSize){i[d+7]=1,i[d+8]=t,i[d+9]=T,i[d+10]=0,i[d+11]=0,E=null;for(let i=t;i<r;i++){let t=e[n[i]];E=is(E,rs(t)),o[i]=c}E||={ax:0,ay:0,az:1,cosO:-1}}else{let a=S-y,o=C-b,u=w-x,f;f=a>=o&&a>=u?0:o>=u?1:2;let p=[`cx`,`cy`,`cz`][f],m=t+r>>1;this._nthElement(n,e,t,r,m,p),i[d+7]=0;let h=s(t,m,c,l+1),g=s(m,r,c+2**l,l+1);i[d+8]=h.nodeIndex,i[d+9]=g.nodeIndex,i[d+10]=0,i[d+11]=0,E=is(h.cone,g.cone)}return i[d+12]=E.ax,i[d+13]=E.ay,i[d+14]=E.az,i[d+15]=E.cosO,{nodeIndex:u,cone:E}};s(0,t,0,0);let c=new Int32Array(t);for(let e=0;e<t;e++)c[e]=n[e];let l=new Float32Array(a*16);return l.set(i.subarray(0,a*16)),console.log(`[LightBVHBuilder] Built BVH: ${a} nodes for ${t} emissive triangles`),{nodeData:l,nodeCount:a,sortedPerm:c,bitTrails:o}}_nthElement(e,t,n,r,i,a){for(;n<r-1;){let o=n+r>>1,s=t[e[o]][a],c=e[o];e[o]=e[r-1],e[r-1]=c;let l=n;for(let i=n;i<r-1;i++)t[e[i]][a]<s&&(c=e[i],e[i]=e[l],e[l]=c,l++);if(c=e[l],e[l]=e[r-1],e[r-1]=c,l===i)return;l<i?n=l+1:r=l}}};function rs(e){return e.twoSided?{ax:e.nx,ay:e.ny,az:e.nz,cosO:-1}:{ax:e.nx,ay:e.ny,az:e.nz,cosO:1}}function is(e,t){if(!e)return t;if(!t||e.cosO<=-1)return e;if(t.cosO<=-1)return t;let n=Math.min(Math.max(e.cosO,-1),1),r=Math.min(Math.max(t.cosO,-1),1),i=Math.acos(n),a=Math.acos(r),o=Math.min(Math.max(e.ax*t.ax+e.ay*t.ay+e.az*t.az,-1),1),s=Math.acos(o);if(Math.min(s+a,Math.PI)<=i)return e;if(Math.min(s+i,Math.PI)<=a)return t;let c=(i+a+s)*.5;if(c>=Math.PI)return{ax:e.ax,ay:e.ay,az:e.az,cosO:-1};let l=c-i,u=e.ay*t.az-e.az*t.ay,d=e.az*t.ax-e.ax*t.az,f=e.ax*t.ay-e.ay*t.ax,p=Math.sqrt(u*u+d*d+f*f);if(p<1e-8)return{ax:e.ax,ay:e.ay,az:e.az,cosO:-1};u/=p,d/=p,f/=p;let m=Math.cos(l),h=Math.sin(l),g=u*e.ax+d*e.ay+f*e.az,_=d*e.az-f*e.ay,v=f*e.ax-u*e.az,y=u*e.ay-d*e.ax,b=e.ax*m+_*h+u*g*(1-m),x=e.ay*m+v*h+d*g*(1-m),S=e.az*m+y*h+f*g*(1-m),C=Math.sqrt(b*b+x*x+S*S)||1;return{ax:b/C,ay:x/C,az:S/C,cosO:Math.cos(c)}}wt(),Ae(),Fn();var as=Object.freeze({r:0,g:0,b:0});function os(e){if(!e)return as;if(!kn())return e;let t=[e.r,e.g,e.b];return jn(t),{r:t[0],g:t[1],b:t[2]}}var ss=ye(`emissive`),cs=class{constructor(){this.emissiveTriangles=[],this.emissiveCount=0,this.totalEmissivePower=0,this.emissiveIndicesArray=null,this.emissivePowerArray=null,this.cdfArray=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._totalTriangleCount=0,this._hiddenMeshes=new Set}extractEmissiveTriangles(e,t,n,r=null){this.emissiveTriangles=[],this._emissiveMeshes=null,this.totalEmissivePower=0,this._totalTriangleCount=n;let i=K.FLOATS_PER_TRIANGLE,a=K.MATERIAL_FLAGS_OFFSET,o=K.MESH_INDEX_OFFSET,s=e&&e.chunks?e:null,c=s?s.viewAs(Float32Array):null,l=s?null:e,u=s?null:new Float32Array(e.buffer,e.byteOffset,e.length),d=new Map;for(let e=0;e<n;e++){if(s?.spilledChunks&&!s.isResident(e,1)){e=((e/s.recordsPerChunk|0)+1)*s.recordsPerChunk-1;continue}let n=s?s.chunkFor(e):l,f=s?c.chunkFor(e):u,p=s?s.baseOf(e):e*i,m=n[p+a]&_t,h=n[p+o],g=t[m];if(!g)continue;let _=d.get(g);_===void 0&&(_=os(g.emissive),d.set(g,_));let v=g.emissiveIntensity||0;if(v>0&&(_.r>0||_.g>0||_.b>0)){let t=r?.placementRunOf?.(h)?.start??-1,n=t>=0&&r.isSet[t],i=n?r.world:null,a=n?t*16:0,o=(e,t,n)=>i?i[a]*e+i[a+4]*t+i[a+8]*n+i[a+12]:e,s=(e,t,n)=>i?i[a+1]*e+i[a+5]*t+i[a+9]*n+i[a+13]:t,c=(e,t,n)=>i?i[a+2]*e+i[a+6]*t+i[a+10]*n+i[a+14]:n,l=f[p+0],u=f[p+1],d=f[p+2],y=f[p+4],b=f[p+5],x=f[p+6],S=f[p+8],C=f[p+9],w=f[p+10],T=o(l,u,d),E=s(l,u,d),D=c(l,u,d),O=o(y,b,x),k=s(y,b,x),A=c(y,b,x),j=o(S,C,w),M=s(S,C,w),N=c(S,C,w),P=this._calculateTriangleArea(T,E,D,O,k,A,j,M,N),F=(.2126*_.r+.7152*_.g+.0722*_.b)*v*P,I=(k-E)*(N-D)-(A-D)*(M-E),L=(A-D)*(j-T)-(O-T)*(N-D),ee=(O-T)*(M-E)-(k-E)*(j-T),te=Math.sqrt(I*I+L*L+ee*ee)||1,R=g.side===1?-1:1;I=I/te*R,L=L/te*R,ee=ee/te*R;let ne=g.side===2,re=(T+O+j)/3,ie=(E+k+M)/3,ae=(D+A+N)/3,oe=Math.min(T,O,j),se=Math.min(E,k,M),ce=Math.min(D,A,N),le=Math.max(T,O,j),ue=Math.max(E,k,M),z=Math.max(D,A,N);this.emissiveTriangles.push({triangleIndex:e,materialIndex:m,meshIndex:h,sideSign:R,instanceLeaf:n?r.tlasLeafIndex[t]:-1,power:F,area:P,emissive:{r:_.r,g:_.g,b:_.b},emissiveIntensity:v,cx:re,cy:ie,cz:ae,bMinX:oe,bMinY:se,bMinZ:ce,bMaxX:le,bMaxY:ue,bMaxZ:z,nx:I,ny:L,nz:ee,twoSided:ne}),this.totalEmissivePower+=F}}return this.emissiveCount=this.emissiveTriangles.length,this.emissiveCount>0&&ss.debug(`${H.n(this.emissiveCount)} emissive tris (${(this.emissiveCount/n*100).toFixed(2)}%) · total power ${this.totalEmissivePower.toFixed(2)}`),this._buildDataArrays(),this.emissiveCount}get emissiveMeshes(){return this._emissiveMeshes??=new Set(this.emissiveTriangles.map(e=>e.meshIndex))}refreshTransforms(e,t){let n=e&&e.chunks?e:null,r=n?n.viewAs(Float32Array):null,i=n?null:new Float32Array(e.buffer,e.byteOffset,e.length),a=K.FLOATS_PER_TRIANGLE,o=t.world;this.totalEmissivePower=0;for(let e of this.emissiveTriangles){let s=n?r.chunkFor(e.triangleIndex):i,c=n?n.baseOf(e.triangleIndex):e.triangleIndex*a,l=[s[c],s[c+1],s[c+2],s[c+4],s[c+5],s[c+6],s[c+8],s[c+9],s[c+10]],u=t.placementRunOf?.(e.meshIndex)?.start??-1;if(u>=0&&t.isSet[u]){let e=u*16;for(let t=0;t<9;t+=3){let n=l[t],r=l[t+1],i=l[t+2];l[t]=o[e]*n+o[e+4]*r+o[e+8]*i+o[e+12],l[t+1]=o[e+1]*n+o[e+5]*r+o[e+9]*i+o[e+13],l[t+2]=o[e+2]*n+o[e+6]*r+o[e+10]*i+o[e+14]}}let[d,f,p,m,h,g,_,v,y]=l,b=this._calculateTriangleArea(d,f,p,m,h,g,_,v,y),x=e.emissive;e.power=(.2126*x.r+.7152*x.g+.0722*x.b)*e.emissiveIntensity*b,e.area=b;let S=(h-f)*(y-p)-(g-p)*(v-f),C=(g-p)*(_-d)-(m-d)*(y-p),w=(m-d)*(v-f)-(h-f)*(_-d),T=(Math.sqrt(S*S+C*C+w*w)||1)/e.sideSign;e.nx=S/T,e.ny=C/T,e.nz=w/T,e.cx=(d+m+_)/3,e.cy=(f+h+v)/3,e.cz=(p+g+y)/3,e.bMinX=Math.min(d,m,_),e.bMinY=Math.min(f,h,v),e.bMinZ=Math.min(p,g,y),e.bMaxX=Math.max(d,m,_),e.bMaxY=Math.max(f,h,v),e.bMaxZ=Math.max(p,g,y),this.totalEmissivePower+=e.power}this._buildDataArrays()}_calculateTriangleArea(e,t,n,r,i,a,o,s,c){let l=r-e,u=i-t,d=a-n,f=o-e,p=s-t,m=c-n,h=u*m-d*p,g=d*f-l*m,_=l*p-u*f;return Math.sqrt(h*h+g*g+_*_)*.5}_buildDataArrays(){this.emissiveIndicesArray=new Int32Array(this.emissiveCount),this.emissivePowerArray=new Float32Array(this.emissiveCount);for(let e=0;e<this.emissiveCount;e++)this.emissiveIndicesArray[e]=this.emissiveTriangles[e].triangleIndex,this.emissivePowerArray[e]=this.emissiveTriangles[e].power;this._buildCDF()}_buildCDF(){if(this.emissiveCount===0){this.cdfArray=new Float32Array(1),this.cdfArray[0]=0;return}this.cdfArray=new Float32Array(this.emissiveCount);let e=0;for(let t=0;t<this.emissiveCount;t++)e+=this.emissivePowerArray[t],this.cdfArray[t]=e;if(e>0)for(let t=0;t<this.emissiveCount;t++)this.cdfArray[t]/=e}sampleCDF(e){if(this.emissiveCount===0)return-1;if(this.emissiveCount===1)return 0;let t=0,n=this.emissiveCount-1;for(;t<n;){let r=Math.floor((t+n)/2);this.cdfArray[r]<e?t=r+1:n=r}return t}getGPUData(){return{emissiveIndices:this.emissiveIndicesArray,emissivePower:this.emissivePowerArray,emissiveCDF:this.cdfArray,emissiveCount:this.emissiveCount,totalPower:this.totalEmissivePower}}createEmissiveTexture(){if(this.emissiveCount===0)return new r.DataTexture(new Float32Array(4),1,1,r.RGBAFormat,r.FloatType);let e=new Float32Array(this.emissiveCount*4);for(let t=0;t<this.emissiveCount;t++){let n=t*4;e[n+0]=this.emissiveIndicesArray[t],e[n+1]=this.emissivePowerArray[t],e[n+2]=this.cdfArray[t],e[n+3]=0}let t=Math.ceil(Math.sqrt(this.emissiveCount)),n=Math.ceil(this.emissiveCount/t),i=t*n*4,a=new Float32Array(i);a.set(e);let o=new r.DataTexture(a,t,n,r.RGBAFormat,r.FloatType);return o.needsUpdate=!0,o.generateMipmaps=!1,o.minFilter=r.NearestFilter,o.magFilter=r.NearestFilter,ss.debug(`emissive texture ${H.px(t,n)} · ${H.n(this.emissiveCount)} entries`),o}createEmissiveRawData(){if(this.emissiveCount===0)return new Float32Array(8);let e=new Float32Array(this.emissiveCount*8);for(let t=0;t<this.emissiveCount;t++){let n=this.emissiveTriangles[t],r=t*8;e[r+0]=n.triangleIndex,e[r+1]=n.power,e[r+2]=this.cdfArray[t],e[r+3]=n.instanceLeaf,e[r+4]=n.emissive.r*n.emissiveIntensity,e[r+5]=n.emissive.g*n.emissiveIntensity,e[r+6]=n.emissive.b*n.emissiveIntensity,e[r+7]=n.area}return ss.debug(`emissive raw data ${H.n(this.emissiveCount)} entries (${H.mb(e.byteLength)})`),e}getStats(){if(this.emissiveCount===0)return{count:0,totalPower:0,averagePower:0,minPower:0,maxPower:0};let e=1/0,t=-1/0;for(let n=0;n<this.emissiveCount;n++){let r=this.emissivePowerArray[n];e=Math.min(e,r),t=Math.max(t,r)}return{count:this.emissiveCount,totalPower:this.totalEmissivePower,averagePower:this.totalEmissivePower/this.emissiveCount,minPower:e,maxPower:t}}updateMaterialEmissive(e,t,n,r,i){let a=os(t.emissive),o=t.emissiveIntensity||0,s=o>0&&(a.r>0||a.g>0||a.b>0);if(s!==this.emissiveTriangles.some(t=>t.materialIndex===e))return this.extractEmissiveTriangles(n,r,i),!0;if(!s)return!1;let c=.2126*a.r+.7152*a.g+.0722*a.b;for(let t of this.emissiveTriangles)t.materialIndex===e&&(t.power=c*o*t.area,t.emissive={r:a.r,g:a.g,b:a.b},t.emissiveIntensity=o);return!0}setHiddenMeshes(e){let t=new Set;for(let e of this.emissiveTriangles)t.add(e.meshIndex);let n=new Set;for(let r of e)t.has(r)&&n.add(r);let r=this._hiddenMeshes,i=n.size!==r.size;if(!i){for(let e of n)if(!r.has(e)){i=!0;break}}return this._hiddenMeshes=n,i}buildLightBVH(){let e=this._hiddenMeshes.size===0?this.emissiveTriangles:this.emissiveTriangles.filter(e=>!this._hiddenMeshes.has(e.meshIndex));this.emissiveCount=e.length,this.totalEmissivePower=0;for(let t of e)this.totalEmissivePower+=t.power;if(e.length===0)return this.lightBVHNodeData=new Float32Array(16),this.lightBVHNodeData[7]=1,this.lightBVHNodeData[14]=1,this.lightBVHNodeData[15]=-1,this.lightBVHNodeCount=1,this.emissiveBitTrailMap=new Float32Array(Math.max(this._totalTriangleCount,1)).fill(-1),this.emissiveIndicesArray=new Int32Array,this.emissivePowerArray=new Float32Array,this._buildCDF(),this.emissiveTriangleData=new Float32Array(8),1;let{nodeData:t,nodeCount:n,sortedPerm:r,bitTrails:i}=new ns().build(e);this.lightBVHNodeData=t,this.lightBVHNodeCount=n,this._rebuildSortedEmissiveData(r,e),this.emissiveBitTrailMap=new Float32Array(Math.max(this._totalTriangleCount,1)).fill(-1);for(let t=0;t<r.length;t++){let n=e[r[t]].triangleIndex;this.emissiveBitTrailMap[n]=i[t]}return n}_rebuildSortedEmissiveData(e,t){let n=e.length;this.emissiveIndicesArray=new Int32Array(n),this.emissivePowerArray=new Float32Array(n);for(let r=0;r<n;r++){let n=e[r];this.emissiveIndicesArray[r]=t[n].triangleIndex,this.emissivePowerArray[r]=t[n].power}this._buildCDF();let r=new Float32Array(n*8);for(let i=0;i<n;i++){let n=t[e[i]],a=i*8;r[a+0]=n.triangleIndex,r[a+1]=n.power,r[a+2]=this.cdfArray[i],r[a+3]=n.instanceLeaf,r[a+4]=n.emissive.r*n.emissiveIntensity,r[a+5]=n.emissive.g*n.emissiveIntensity,r[a+6]=n.emissive.b*n.emissiveIntensity,r[a+7]=n.area}this.emissiveTriangleData=r,ss.debug(`rebuilt sorted emissive data · ${H.n(n)} entries`)}clear(){this.emissiveTriangles=[],this.emissiveCount=0,this.totalEmissivePower=0,this.emissiveIndicesArray=null,this.emissivePowerArray=null,this.cdfArray=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._totalTriangleCount=0,this._hiddenMeshes=new Set}};Ae();var ls=class{constructor(e=`Build`,{namespace:t=`build`,level:n=`debug`}={}){this.label=e,this.level=n,this.logger=ye(t),this.entries=new Map,this.order=[],this.totalStart=performance.now()}start(e){return this.entries.set(e,{start:performance.now(),end:null}),this.order.includes(e)||this.order.push(e),this}end(e){let t=this.entries.get(e);return t&&(t.end=performance.now(),t.duration=t.end-t.start),this}getDuration(e){return this.entries.get(e)?.duration??0}print(e=[]){let t=performance.now()-this.totalStart,n=this.order.map(e=>{let t=this.entries.get(e)?.duration??0;return t>=1?`${e} ${Math.round(t)}ms`:null}).filter(Boolean),r=H.list([this.label,...e,H.ms(t)]);return this.level===`info`?this.logger.summary(r,n):this.logger.debug(H.list([r,n.join(` · `)])),{steps:Object.fromEntries(this.order.map(e=>[e,Math.round(this.entries.get(e)?.duration??0)])),total:Math.round(t)}}};nn();var us=1<<20,ds=1<<21,fs=()=>new Promise(e=>setTimeout(e,0)),ps=[0,1,2,4,5,6,8,9,10];function ms(e,t,n,r=ps){let i=e.lanesPerRecord,a=r.length,o=0,s=0,c=0;for(;c<n;){let l=t+c,u=e.chunkFor(l),d=Math.min(e.recordsPerChunk-l%e.recordsPerChunk,n-c),f=e.baseOf(l);for(let e=0;e<d;e++,f+=i){let e=2166136261,t=2654435769;for(let n=0;n<a;n++){let i=u[f+r[n]];e=Math.imul(e^i,16777619),t=Math.imul(t+i|0,2246822507)^t>>>13}o=o+e>>>0,s=s+t>>>0}c+=d}return`${o.toString(16)}.${s.toString(16)}`}async function hs(e,t){let n=[],r=0;for(let{triOffset:i,triCount:a}of t)n.push(ms(e,i,a)),r+=a,r>=ds&&(r=0,await fs());return n}async function gs(e,t){let n=await e?.area(tn.SCENES).open(t);if(!n)return null;try{let e=await n.json(`index.json`),t=await n.file(`nodes.f32`),r=await n.file(`order.u32`);return e?.v!==2||!t||!r?(n.release(),null):{index:e,nodes:t,order:r,release:()=>n.release()}}catch{return n.release(),null}}async function _s(e,t,{index:n,bvh:r,orders:i,isStale:a,label:o=``}){let s=e?.area(tn.SCENES);if(!s)return!1;let c=n.totalNodes-n.tlasNodeCount,l=i.reduce((e,t)=>e+(t?.byteLength??0),0),u=await s.create(t,{label:`${o} (BVH)`,expectedBytes:c*64+l});if(!u)return!1;try{for(let e=n.tlasNodeCount;e<n.totalNodes;){if(a())throw Error(`scene changed while it was being stored`);let t=r.chunkFor(e),i=r.recordsPerChunk-e%r.recordsPerChunk,o=Math.min(i,n.totalNodes-e,us),s=r.baseOf(e);await u.write(`nodes.f32`,t.subarray(s,s+o*16)),e+=o}for(let e of i)if(e)for(let t=0;t<e.length;t+=us*4)await u.write(`order.u32`,e.subarray(t,Math.min(e.length,t+us*4)));if(l===0&&await u.write(`order.u32`,new Uint8Array),a())throw Error(`scene changed while it was being stored`);return await u.writeJSON(`index.json`,n),await u.commit(),!0}catch{return await u.abort(),!1}}async function vs(e,t,n,r){for(let i=0;i<r;i+=us){let a=Math.min(us,r-i),o=await e.slice(i*64,(i+a)*64).arrayBuffer();t.setRecords(n+i,new Float32Array(o))}}async function ys(e,t,n){return new Uint32Array(await e.slice(t*4,(t+n)*4).arrayBuffer())}wt();var bs=16,xs=K.POSITION_A_OFFSET,Ss=K.POSITION_B_OFFSET,Cs=K.POSITION_C_OFFSET;async function ws(e,t,n,r,{pause:i=null}={}){let a=e.lanesPerRecord,o=[new Float32Array(n),new Float32Array(n),new Float32Array(n)],[s,c,l]=o;for(let r=0;r<n;){let i=e.chunkFor(t+r),o=new Float32Array(i.buffer,i.byteOffset,i.length),u=Math.min(n,(((t+r)/e.recordsPerChunk|0)+1)*e.recordsPerChunk-t);for(let n=e.baseOf(t+r);r<u;r++,n+=a)s[r]=o[n+xs]+o[n+Ss]+o[n+Cs],c[r]=o[n+xs+1]+o[n+Ss+1]+o[n+Cs+1],l[r]=o[n+xs+2]+o[n+Ss+2]+o[n+Cs+2]}let u=new Uint32Array(n);for(let e=0;e<n;e++)u[e]=e;let d=[],f=(e,t)=>{if(t-e<=r)return d.push({start:e,count:t-e}),{piece:d.length-1};let n=e+(t-e>>1);return Es(u,o,Ts(o,e,t),e,t,n),{left:f(e,n),right:f(n,t)}},p=f(0,n);return await i?.(),await Ds(e,t,n,u,i),{order:u,pieces:d,tree:p}}function Ts(e,t,n){let r=0,i=-1;for(let a=0;a<3;a++){let o=e[a],s=1/0,c=-1/0;for(let e=t;e<n;e++){let t=o[e];t<s&&(s=t),t>c&&(c=t)}c-s>i&&(i=c-s,r=a)}return r}function Es(e,t,n,r,i,a){let o=t[n],[s,c,l]=t,u=(t,n)=>{let r=e[t];e[t]=e[n],e[n]=r,r=s[t],s[t]=s[n],s[n]=r,r=c[t],c[t]=c[n],c[n]=r,r=l[t],l[t]=l[n],l[n]=r},d=2654435769,f=()=>(d^=d<<13,d^=d>>>17,d^=d<<5,o[r+(d>>>0)%(i-r)]);for(;i-r>1;){let e=f(),t=f(),n=f(),s=e<t?t<n?t:e<n?n:e:e<n?e:t<n?n:t,c=r,l=r,d=i;for(;l<d;){let e=o[l];e<s?u(c++,l++):e>s?u(l,--d):l++}if(a<c)i=c;else if(a>=d)r=d;else return}}async function Ds(e,t,n,r,i){let a=e.lanesPerRecord,o=new Uint32Array(a),s=new Uint8Array(n),c=0;for(let l=0;l<n;l++){if(s[l]||(s[l]=1,r[l]===l))continue;let n=e.chunkFor(t+l),u=e.baseOf(t+l);for(let e=0;e<a;e++)o[e]=n[u+e];for(let d=l;;){let f=r[d],p=n,m=u;if(f===l){for(let e=0;e<a;e++)p[m+e]=o[e];break}n=e.chunkFor(t+f),u=e.baseOf(t+f);for(let e=0;e<a;e++)p[m+e]=n[u+e];s[f]=1,d=f,i&&!(++c&1048575)&&await i()}}}function Os(e,t,n,r){let i=t.length-1,a=[],o=i;for(let{bvhData:e}of n)a.push(o),o+=e.length/bs;let s=new Float32Array(i*bs),c=new Uint32Array(s.buffer),l=[s],u=new Uint32Array(r.length);for(let e=0;e<t.length;e++){let{bvhData:i,originalToBvh:o}=n[e];n[e].bvhData=n[e].originalToBvh=null;let s=a[e],{start:c,count:d}=t[e];vi(new Uint32Array(i.buffer,i.byteOffset,i.length),s,c),l.push(i);for(let e=0;e<d;e++)u[r[c+e]]=c+(o?o[e]:e)}let d=0,f=e=>{if(e.piece!==void 0)return{index:a[e.piece],box:n[e.piece].aabb};let t=d++,r=f(e.left),i=f(e.right),o=t*bs;return s[o]=r.box[0],s[o+1]=r.box[1],s[o+2]=r.box[2],c[o+3]=r.index,s[o+4]=r.box[3],s[o+5]=r.box[4],s[o+6]=r.box[5],c[o+7]=i.index,s[o+8]=i.box[0],s[o+9]=i.box[1],s[o+10]=i.box[2],s[o+12]=i.box[3],s[o+13]=i.box[4],s[o+14]=i.box[5],{index:t,box:[0,1,2].map(e=>Math.min(r.box[e],i.box[e])).concat([3,4,5].map(e=>Math.max(r.box[e],i.box[e])))}};return f(e),{bvhData:l,nodeCount:o,originalToBvh:u}}var ks,As=g((()=>{ks=`11.1.1`})),js,Ms=g((()=>{As(),js=ks}));function Ns(e,t,n=Ps){return e>=n&&t/Fs<e/3}var Ps,Fs,Is=g((()=>{Ps=1e4,Fs=15e5}));Ms(),Is();var Ls="const e={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_PACKED_OFFSET:3,NORMAL_B_PACKED_OFFSET:7,NORMAL_C_PACKED_OFFSET:11,UV_AB_OFFSET:12,UV_C_OFFSET:16,MATERIAL_FLAGS_OFFSET:18,MESH_INDEX_OFFSET:19};function t(e,t,n){let r=Math.sqrt(e*e+t*t+n*n);r>0?(e/=r,t/=r,n/=r):(e=0,t=0,n=1);let i=Math.abs(e)+Math.abs(t)+Math.abs(n),a=e/i,o=t/i;if(n<0){let e=a,t=o;a=(1-Math.abs(t))*(e>=0?1:-1),o=(1-Math.abs(e))*(t>=0?1:-1)}let s=Math.round(Math.min(1,Math.max(-1,a))*32767)&65535;return((Math.round(Math.min(1,Math.max(-1,o))*32767)&65535)<<16|s)>>>0}const n={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826};n.TRIANGLE_LEAF;const r=e=>e>=2147483648,i=e=>~e>>>0>>>4,a=e=>~e&15,o=e.FLOATS_PER_TRIANGLE,s=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),c=e=>e instanceof Uint32Array?e:new Uint32Array(e.buffer,e.byteOffset,e.length),l=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:e,idx:t?e.viewAs(Uint32Array):c(e)}},u=(e,t)=>e.chunked?e.f.chunkFor(t):e.f,d=(e,t)=>e.chunked?e.idx.chunkFor(t):e.idx,f=(e,t)=>e.chunked?e.chunked.baseOf(t):t*m,p=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:t?t.viewAs(Float32Array):s(e),u:t?e:c(e)}},m=16,h=n.TRIANGLE_LEAF,g=n.BLAS_POINTER_LEAF;function _(e,t,n,r,i,a){let o=e[t+4],s=e[t+5],c=e[t+6],l=e[t+7],u=e[t+8],d=e[t+9],f=e[t+10],p=e[t+11],m=e[t+12],h=e[t+13],g=e[t+14],_=e[t+15],v=d*g-f*h,y=f*m-u*g,b=u*h-d*m,x=o*v+s*y+c*b,S=o===1&&d===1&&g===1&&s===0&&c===0&&u===0&&f===0&&m===0&&h===0&&l===0&&p===0&&_===0,C=(Math.abs(o)+Math.abs(s)+Math.abs(c))*(Math.abs(u)+Math.abs(d)+Math.abs(f))*(Math.abs(m)+Math.abs(h)+Math.abs(g));if(S||!Number.isFinite(x)||Math.abs(x)<=1e-12*C){for(let e=0;e<6;e++)i[a+e]=n[r+e];return}let w=1/x,T=v*w,E=y*w,D=b*w,O=(c*h-s*g)*w,k=(o*g-c*m)*w,A=(s*m-o*h)*w,j=(s*f-c*d)*w,M=(c*u-o*f)*w,N=(o*d-s*u)*w,P=1/0,F=1/0,I=1/0,L=-1/0,R=-1/0,z=-1/0;for(let e=0;e<8;e++){let t=(e&1?n[r+3]:n[r])-l,i=(e&2?n[r+4]:n[r+1])-p,a=(e&4?n[r+5]:n[r+2])-_,o=T*t+O*i+j*a,s=E*t+k*i+M*a,c=D*t+A*i+N*a;o<P&&(P=o),o>L&&(L=o),s<F&&(F=s),s>R&&(R=s),c<I&&(I=c),c>z&&(z=c)}i[a]=P,i[a+1]=F,i[a+2]=I,i[a+3]=L,i[a+4]=R,i[a+5]=z}function v(t,n,r,i,a){let s=e.POSITION_A_OFFSET,c=e.POSITION_B_OFFSET,l=e.POSITION_C_OFFSET,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0;for(let e=0;e<r;e++){let r=n+e,i=t.chunked?t.f.chunkFor(r):t.f,a=t.chunked?t.chunked.baseOf(r):r*o;u=Math.min(u,i[a+s],i[a+c],i[a+l]),d=Math.min(d,i[a+s+1],i[a+c+1],i[a+l+1]),f=Math.min(f,i[a+s+2],i[a+c+2],i[a+l+2]),p=Math.max(p,i[a+s],i[a+c],i[a+l]),m=Math.max(m,i[a+s+1],i[a+c+1],i[a+l+1]),h=Math.max(h,i[a+s+2],i[a+c+2],i[a+l+2])}i[a]=u,i[a+1]=d,i[a+2]=f,i[a+3]=p,i[a+4]=m,i[a+5]=h}const y=new Float32Array(12);function b(e,t,n,r){let i=u(e,t),a=d(e,t),o=f(e,t);if(a[o+3]===h){v(n,a[o],a[o+1],r,0);return}for(let e=0;e<3;e++)r[e]=Math.min(i[o+e],i[o+8+e]),r[3+e]=Math.max(i[o+4+e],i[o+12+e])}function x(e,t,n,o,s){let c=u(e,t),l=d(e,t),p=f(e,t),m=(t-s)*6,b=l[p+3];if(b===h){v(n,l[p],l[p+1],o,m);return}if(b===g){_(c,p,o,(l[p]-s)*6,o,m);return}let x=l[p+7],S=o,C=(b-s)*6;r(b)&&(v(n,i(b),a(b),y,0),S=y,C=0);let w=o,T=(x-s)*6;r(x)&&(v(n,i(x),a(x),y,6),w=y,T=6),c[p]=S[C],c[p+1]=S[C+1],c[p+2]=S[C+2],c[p+4]=S[C+3],c[p+5]=S[C+4],c[p+6]=S[C+5],c[p+8]=w[T],c[p+9]=w[T+1],c[p+10]=w[T+2],c[p+12]=w[T+3],c[p+13]=w[T+4],c[p+14]=w[T+5];for(let e=0;e<3;e++)o[m+e]=Math.min(S[C+e],w[T+e]),o[m+3+e]=Math.max(S[C+3+e],w[T+3+e])}var S=class{constructor(){this._bounds=null,this._boundsNodeCount=0,this._tlasBounds=null,this._rootBox=null}updateTrianglePositions(n,r,i){let a=i.length,s=p(n);for(let n=0;n<a;n++){let a=i[n],c=s.chunked?s.f.chunkFor(n):s.f,l=s.chunked?s.u.chunkFor(n):s.u,u=s.chunked?s.chunked.baseOf(n):n*o,d=a*9,f=r[d],p=r[d+1],m=r[d+2],h=r[d+3],g=r[d+4],_=r[d+5],v=r[d+6],y=r[d+7],b=r[d+8];c[u+e.POSITION_A_OFFSET]=f,c[u+e.POSITION_A_OFFSET+1]=p,c[u+e.POSITION_A_OFFSET+2]=m,c[u+e.POSITION_B_OFFSET]=h,c[u+e.POSITION_B_OFFSET+1]=g,c[u+e.POSITION_B_OFFSET+2]=_,c[u+e.POSITION_C_OFFSET]=v,c[u+e.POSITION_C_OFFSET+1]=y,c[u+e.POSITION_C_OFFSET+2]=b;let x=h-f,S=g-p,C=_-m,w=v-f,T=y-p,E=b-m,D=t(S*E-C*T,C*w-x*E,x*T-S*w);l[u+e.NORMAL_A_PACKED_OFFSET]=D,l[u+e.NORMAL_B_PACKED_OFFSET]=D,l[u+e.NORMAL_C_PACKED_OFFSET]=D}}refitRange(e,t,n,r){let i=p(t);r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let a=l(e);for(let e=n+r-1;e>=n;e--)x(a,e,i,this._bounds,n)}refitPartial(e,t,n,r){for(let r=0;r<n.length;r+=2)this.refitRange(e,t,n[r],n[r+1]);let i=p(t),a=l(e);(!this._tlasBounds||this._tlasBounds.length<r*6)&&(this._tlasBounds=new Float32Array(r*6));let o=this._tlasBounds,s=this._rootBox||=new Float32Array(6);for(let e=r-1;e>=0;e--){let t=d(a,e),n=f(a,e);t[n+3]===g?(b(a,t[n],i,s),_(u(a,e),n,s,0,o,e*6)):x(a,e,i,o,0)}}refit(e,t,n){let r=p(t);n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let i=l(e);for(let e=n-1;e>=0;e--)x(i,e,r,this._bounds,0)}};const C=64*1024*1024;function w(e,t,n){return n?new e(new SharedArrayBuffer(t*e.BYTES_PER_ELEMENT)):new e(t)}var T=class e{constructor(e,t,n,r=C,i=!1){let a=t*n.BYTES_PER_ELEMENT,o=Math.max(1,Math.floor(r/a));this.recordCount=e,this.lanesPerRecord=t,this.LaneType=n,this.recordsPerChunk=e<=o?Math.max(e,1):o,this.shared=i,this.chunks=[];let s=e;for(;s>0;){let e=Math.min(s,this.recordsPerChunk);this.chunks.push(w(n,e*t,i)),s-=e}this.chunks.length===0&&this.chunks.push(w(n,0,i))}static adopt(t,n,r,i){let a=Object.create(e.prototype);return a.recordCount=n,a.lanesPerRecord=r,a.LaneType=t[0]?.constructor??null,a.recordsPerChunk=i,a.chunks=t,a.shared=typeof SharedArrayBuffer<`u`&&t[0]?.buffer instanceof SharedArrayBuffer,a}static lazy(t,n,r,i=C,a=!1){let o=Math.max(1,Math.floor(i/(n*r.BYTES_PER_ELEMENT))),s=Object.create(e.prototype);return s.recordCount=t,s.lanesPerRecord=n,s.LaneType=r,s.recordsPerChunk=t<=o?Math.max(t,1):o,s.shared=a,s.chunks=Array(Math.max(1,Math.ceil(t/s.recordsPerChunk))),s._views=[],s}_materialize(e){if(this._owner)return this._owner._materialize(e),this.chunks[e];let t=e*this.recordsPerChunk,n=Math.min(this.recordsPerChunk,this.recordCount-t)*this.lanesPerRecord,r=this.chunks[e]=w(this.LaneType,n,this.shared);for(let t of this._liveViews())t.chunks[e]=new t.LaneType(r.buffer,r.byteOffset,r.byteLength/t.LaneType.BYTES_PER_ELEMENT);return r}materializeAll(){for(let e=0;e<this.chunks.length;e++)!this.chunks[e]&&!this._spilled?.has(e)&&this._materialize(e);return this}get chunkCount(){return this.chunks.length}get single(){return this.chunks.length===1?this.chunks[0]:null}get byteLength(){let e=0;for(let t of this.chunks)t&&(e+=t.byteLength);return e}chunkFor(e){let t=e/this.recordsPerChunk|0,n=this.chunks[t];if(n)return n;if(this._spilled?.has(t))throw Error(`ChunkedRecords: chunk ${t} is on disk — await ensureResident() before touching record ${e}`);return this._materialize(t)}async spill(e,{keep:t=()=>!1}={}){if(this._owner)throw Error(`ChunkedRecords: spill the storage, not a view of it`);this._store=e,this._spilled??=new Set;let n=0;for(let r=0;r<this.chunks.length;r++){let i=this.chunks[r];if(!(!i||t(r))){await e.write(r,i),this.chunks[r]=null;for(let e of this._liveViews())e.chunks[r]=null;this._spilled.add(r),n+=i.byteLength}}return n}async spillChunk(e,t){let n=this.chunks[e];if(!n)return 0;this._store=t,this._spilled??=new Set,await t.write(e,n),this.chunks[e]=null;for(let t of this._liveViews())t.chunks[e]=null;return this._spilled.add(e),n.byteLength}async ensureResident(e=0,t=this.recordCount){if(!this._spilled?.size||t<=0)return;let n=e/this.recordsPerChunk|0,r=(e+t-1)/this.recordsPerChunk|0;for(let e=n;e<=r;e++){if(!this._spilled.has(e))continue;let t=Math.min(this.recordsPerChunk,this.recordCount-e*this.recordsPerChunk)*this.lanesPerRecord,n=await this._store.read(e,t*this.LaneType.BYTES_PER_ELEMENT),r=w(this.LaneType,t,this.shared);new Uint8Array(r.buffer,r.byteOffset,r.byteLength).set(new Uint8Array(n)),this.chunks[e]=r;for(let t of this._liveViews())t.chunks[e]=new t.LaneType(r.buffer,r.byteOffset,r.byteLength/t.LaneType.BYTES_PER_ELEMENT);this._spilled.delete(e)}}_liveViews(){return this._weakViews&&=this._weakViews.filter(e=>e.deref()),[...this._views??[],...(this._weakViews??[]).map(e=>e.deref())]}isResident(e=0,t=this.recordCount){if(!this._spilled?.size||t<=0)return!0;let n=e/this.recordsPerChunk|0,r=(e+t-1)/this.recordsPerChunk|0;for(let e=n;e<=r;e++)if(this._spilled.has(e))return!1;return!0}get spilledChunks(){return this._spilled?.size??0}baseOf(e){return e%this.recordsPerChunk*this.lanesPerRecord}isContiguous(e,t){return t<=0?!0:(e/this.recordsPerChunk|0)==((e+t-1)/this.recordsPerChunk|0)}slice(e,t){let n=this.baseOf(e),r=t*this.lanesPerRecord;if(this.isContiguous(e,t))return this.chunkFor(e).subarray(n,n+r);let i=new this.LaneType(r);return this.readRecords(e,t,i),i}readRecords(e,t,n){let r=0;for(;r<t;){let i=e+r,a=this.chunkFor(i),o=this.baseOf(i),s=this.recordsPerChunk-i%this.recordsPerChunk,c=Math.min(s,t-r);n.set(a.subarray(o,o+c*this.lanesPerRecord),r*this.lanesPerRecord),r+=c}return n}setRecords(e,t){let n=t.length/this.lanesPerRecord,r=0;for(;r<n;){let i=e+r,a=this.chunkFor(i),o=this.baseOf(i),s=this.recordsPerChunk-i%this.recordsPerChunk,c=Math.min(s,n-r);a.set(t.subarray(r*this.lanesPerRecord,(r+c)*this.lanesPerRecord),o),r+=c}}copyOf(e,t){return this.readRecords(e,t,new this.LaneType(t*this.lanesPerRecord))}trimTo(t){let n=Math.max(1,Math.ceil(t/this.recordsPerChunk)),r=this.chunks.slice(0,n),i=(t-(n-1)*this.recordsPerChunk)*this.lanesPerRecord,a=r[n-1];return a.length>i&&(r[n-1]=a.subarray(0,Math.max(0,i))),e.adopt(r,t,this.lanesPerRecord,this.recordsPerChunk)}grow(e){if(e<=this.recordCount)return;let t=this.chunks.length-1,n=(e,t)=>Math.min(this.recordsPerChunk,t-e*this.recordsPerChunk)*this.lanesPerRecord,r=this.chunks[t];this.recordCount=e;for(let t of this._liveViews())t.recordCount=e;if(this.chunks.length*this.recordsPerChunk<e){this.chunks.length=Math.ceil(e/this.recordsPerChunk);for(let e of this._liveViews())e.chunks.length=this.chunks.length}if(r&&r.length<n(t,e)){let i=w(this.LaneType,n(t,e),this.shared);i.set(r),this.chunks[t]=i;for(let e of this._liveViews())e.chunks[t]=new e.LaneType(i.buffer,i.byteOffset,i.byteLength/e.LaneType.BYTES_PER_ELEMENT)}else if(!r&&this._spilled?.has(t))throw Error(`ChunkedRecords: cannot grow past chunk ${t}, which is on disk`)}release(e,t){let n=this.recordsPerChunk,r=Math.ceil(e/n),i=Math.floor((e+t)/n),a=0;for(let e=r;e<i;e++){let t=this.chunks[e];if(t){a+=t.byteLength,this.chunks[e]=void 0;for(let t of this._liveViews())t.chunks[e]=void 0}}return a}trimInPlace(e){let t=Math.max(1,Math.ceil(e/this.recordsPerChunk)),n=Math.max(0,(e-(t-1)*this.recordsPerChunk)*this.lanesPerRecord),r=[this,...this._liveViews()];for(let i of r){i.chunks.length=t;let r=i.chunks[t-1];r&&r.length>n&&(i.chunks[t-1]=r.subarray(0,n)),i.recordCount=e}if(this._spilled)for(let e of this._spilled)e>=t&&this._spilled.delete(e);return this}viewAs(t){let n=e=>new t(e.buffer,e.byteOffset,e.byteLength/t.BYTES_PER_ELEMENT),r=e.adopt(this.chunks.map(e=>e?n(e):void 0),this.recordCount,this.lanesPerRecord,this.recordsPerChunk);return r.LaneType=t,r._owner=this,this._views?this._views.push(r):(this._weakViews??=[]).push(new WeakRef(r)),r._spilled=this._spilled??=new Set,r}};const E=new S;let D=null,O=null,k=0;self.onmessage=function(e){let{type:t}=e.data;if(t===`init`){D=T.adopt(e.data.sharedBvhBufs.map(e=>new Float32Array(e)),e.data.bvhRecordCount,16,e.data.bvhRecordsPerChunk),O=T.adopt(e.data.sharedTriBufs.map(e=>new Uint32Array(e)),e.data.triRecordCount,e.data.triLanesPerRecord,e.data.triRecordsPerChunk),k=D.recordCount;return}if(t===`refit`)try{let t=performance.now(),{blasRanges:n,tlasNodeCount:r}=e.data;n?E.refitPartial(D,O,n,r):E.refit(D,O,k),self.postMessage({type:`refitComplete`,refitTimeMs:performance.now()-t})}catch(e){console.error(`[BVHRefitWorker] Refit error:`,e),self.postMessage({type:`error`,error:e.message})}};",Rs=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Ls],{type:`text/javascript;charset=utf-8`});function zs(e){let t;try{if(t=Rs&&(self.URL||self.webkitURL).createObjectURL(Rs),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Ls),{type:`module`,name:e?.name})}}var Bs="const e={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826};function t(e){return new Uint32Array(e.buffer,e.byteOffset,e.length)}function n(e,t){if(e>=1073741824)throw RangeError(`${t} is ${e.toLocaleString()}, at or past the BVH index limit of ${1073741824 .toLocaleString()}. Node indices are stored as u32 bit patterns and the leaf tags occupy everything above that.`);return e}const r=Float64Array.from([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function i(e,t){return e[t]*(e[t+5]*e[t+10]-e[t+6]*e[t+9])-e[t+4]*(e[t+1]*e[t+10]-e[t+2]*e[t+9])+e[t+8]*(e[t+1]*e[t+6]-e[t+2]*e[t+5])}function a(e,t,n){let a=i(e,t);if(!Number.isFinite(a)||Math.abs(a)<1e-20)return n.set(r),n;let o=1/a;return n[0]=(e[t+5]*e[t+10]-e[t+6]*e[t+9])*o,n[1]=(e[t+2]*e[t+9]-e[t+1]*e[t+10])*o,n[2]=(e[t+1]*e[t+6]-e[t+2]*e[t+5])*o,n[3]=0,n[4]=(e[t+6]*e[t+8]-e[t+4]*e[t+10])*o,n[5]=(e[t]*e[t+10]-e[t+2]*e[t+8])*o,n[6]=(e[t+2]*e[t+4]-e[t]*e[t+6])*o,n[7]=0,n[8]=(e[t+4]*e[t+9]-e[t+5]*e[t+8])*o,n[9]=(e[t+1]*e[t+8]-e[t]*e[t+9])*o,n[10]=(e[t]*e[t+5]-e[t+1]*e[t+4])*o,n[11]=0,n[12]=-(n[0]*e[t+12]+n[4]*e[t+13]+n[8]*e[t+14]),n[13]=-(n[1]*e[t+12]+n[5]*e[t+13]+n[9]*e[t+14]),n[14]=-(n[2]*e[t+12]+n[6]*e[t+13]+n[10]*e[t+14]),n[15]=1,n}function o(e,t){for(let n=0;n<16;n++)if(e[t+n]!==r[n])return!1;return!0}const s=e=>e<32?e:32,c=new Float64Array(16);var l=class r{constructor(){this._flatBuffer=null,this._flatBufferCapacity=0,this._binCounts=new Int32Array(96),this._binBounds=new Float64Array(576),this._binSuffix=new Float64Array(32),this._binSuffixCount=new Int32Array(32),this._order=null,this._stackI=null,this._stackB=null,this._stackFrames=0,this._sortScratch=[],this._suffix=null,this._bounds=new Float64Array(12),this._extent=new Float64Array(3),this._cMin=new Float64Array(3)}static nodeCountFor(e){return e>0?e*2-1:0}releaseFlattenBuffer(){this._flatBuffer=null,this._flatBufferCapacity=0}build(e){let t=new Float64Array(e.count*6);e.writeWorldAABBs(t);let n=this.buildStructure(t,e.count);return r.fillLeaves(n.data,n.nodeCount,e),n}buildStructure(i,a){let o=r.nodeCountFor(a);if(a===0)return{data:new Float32Array,nodeCount:0};n(o,`TLAS node count`);let s=o*16;s>this._flatBufferCapacity&&(this._flatBuffer=new Float32Array(s),this._flatBufferCapacity=s);let c=this._flatBuffer,l=t(c);(!this._order||this._order.length<a)&&(this._order=new Int32Array(a));let u=this._order;for(let e=0;e<a;e++)u[e]=e;this._ensureStack(64);let d=0,f=0,p=0,m=a,h=this._bounds;this._rangeBounds(i,u,p,m,h,0);let g=h[0],_=h[1],v=h[2],y=h[3],b=h[4],x=h[5];for(;;){if(m-p===1){let t=f*16;l[t]=0,l[t+1]=u[p],c[t+2]=0,l[t+3]=e.BLAS_POINTER_LEAF}else{let e=this._partition(i,u,p,m,g,_,v,y,b,x),t=e-p,n=f+1,r=n+(t*2-1),a=f*16;c[a]=h[0],c[a+1]=h[1],c[a+2]=h[2],l[a+3]=n,c[a+4]=h[3],c[a+5]=h[4],c[a+6]=h[5],l[a+7]=r,c[a+8]=h[6],c[a+9]=h[7],c[a+10]=h[8],c[a+11]=0,c[a+12]=h[9],c[a+13]=h[10],c[a+14]=h[11],c[a+15]=0;let o=t<=m-e,s=o?0:6,S=o?6:0;d=this._push(d,o?r:n,o?e:p,o?m:e,h,S),f=o?n:r,o?m=e:p=e,g=h[s],_=h[s+1],v=h[s+2],y=h[s+3],b=h[s+4],x=h[s+5];continue}if(d===0)break;d--;let t=d*3,n=d*6;f=this._stackI[t],p=this._stackI[t+1],m=this._stackI[t+2],g=this._stackB[n],_=this._stackB[n+1],v=this._stackB[n+2],y=this._stackB[n+3],b=this._stackB[n+4],x=this._stackB[n+5]}return{data:c.subarray(0,s),nodeCount:o}}_push(e,t,n,r,i,a){e>=this._stackFrames&&this._ensureStack(this._stackFrames*2);let o=e*3,s=e*6;this._stackI[o]=t,this._stackI[o+1]=n,this._stackI[o+2]=r;for(let e=0;e<6;e++)this._stackB[s+e]=i[a+e];return e+1}_ensureStack(e){if(this._stackFrames>=e)return;let t=new Int32Array(e*3),n=new Float64Array(e*6);this._stackI&&(t.set(this._stackI),n.set(this._stackB)),this._stackI=t,this._stackB=n,this._stackFrames=e}static fillLeaves(n,i,a){let o=a.world,s=a.sourceMesh,c=a.tplBlasOffset,l=a.visible,u=a.tlasLeafIndex,d=t(n);for(let t=0;t<i;t++){let i=t*16;if(d[i+3]!==e.BLAS_POINTER_LEAF)continue;let a=d[i+1]&1073741823;d[i]=c[s[a]],n[i+2]=+!!l[a],r.writeLeafMatrix(n,d,i,o,a),u[a]=t}}static writeLeafMatrix(e,t,n,r,i){let s=c;a(r,i*16,s),e[n+4]=s[0],e[n+5]=s[4],e[n+6]=s[8],e[n+7]=s[12],e[n+8]=s[1],e[n+9]=s[5],e[n+10]=s[9],e[n+11]=s[13],e[n+12]=s[2],e[n+13]=s[6],e[n+14]=s[10],e[n+15]=s[14],t[n+1]=(i|(o(r,i*16)?1073741824:0))>>>0}_partition(e,t,n,r,i,a,o,s,c,l){let u=r-n,d=0;if(u===2)d=n+1;else if(u<=8)d=n+(u>>1),this._insertionSortRange(e,t,n,r,this._widestCentroidAxis(e,t,n,r));else{if(d=this._binnedSplit(e,t,n,r,i,a,o,s,c,l),d>n&&d<r)return d;if(d=this._sweepSplit(e,t,n,r,i,a,o,s,c,l),!(d>n&&d<r)){let f=s-i,p=c-a,m=l-o,h=p>f&&p>m?1:m>f?2:0;this._sortRange(e,t,n,r,h),d=n+(u>>1)}}let f=this._bounds;return this._rangeBounds(e,t,n,d,f,0),this._rangeBounds(e,t,d,r,f,6),d}_binnedSplit(e,t,n,r,i,a,o,c,l,u){let d=this._surfaceArea(i,a,o,c,l,u);if(!(d>0)||!isFinite(d))return n;let f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,_=-1/0;for(let i=n;i<r;i++){let n=t[i]*6,r=(e[n]+e[n+3])*.5,a=(e[n+1]+e[n+4])*.5,o=(e[n+2]+e[n+5])*.5;r<f&&(f=r),r>h&&(h=r),a<p&&(p=a),a>g&&(g=a),o<m&&(m=o),o>_&&(_=o)}let v=this._extent,y=this._cMin;v[0]=h-f,v[1]=g-p,v[2]=_-m,y[0]=f,y[1]=p,y[2]=m;let b=1/0,x=-1,S=-1,C=this._binCounts,w=this._binBounds,T=v[0]>1e-12,E=v[1]>1e-12,D=v[2]>1e-12;if(!T&&!E&&!D)return n;let O=s(r-n),k=T?O/v[0]:0,A=E?O/v[1]:0,j=D?O/v[2]:0;C.fill(0,0,O*3);for(let e=0;e<O*3;e++){let t=e*6;w[t]=w[t+1]=w[t+2]=1/0,w[t+3]=w[t+4]=w[t+5]=-1/0}for(let i=n;i<r;i++){let n=t[i]*6,r=e[n],a=e[n+1],o=e[n+2],s=e[n+3],c=e[n+4],l=e[n+5];for(let e=0;e<3;e++){let t=e===0?k:e===1?A:j;if(t===0)continue;let n=((e===0?(r+s)*.5:e===1?(a+c)*.5:(o+l)*.5)-y[e])*t|0;n<0?n=0:n>=O&&(n=O-1),n+=e*O,C[n]++;let i=n*6;r<w[i]&&(w[i]=r),a<w[i+1]&&(w[i+1]=a),o<w[i+2]&&(w[i+2]=o),s>w[i+3]&&(w[i+3]=s),c>w[i+4]&&(w[i+4]=c),l>w[i+5]&&(w[i+5]=l)}}for(let e=0;e<3;e++){if(!(v[e]>1e-12))continue;let t=e*O,n=this._binSuffix,r=this._binSuffixCount,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0,u=0;for(let e=O-1;e>=1;e--){let d=(t+e)*6;w[d]<i&&(i=w[d]),w[d+1]<a&&(a=w[d+1]),w[d+2]<o&&(o=w[d+2]),w[d+3]>s&&(s=w[d+3]),w[d+4]>c&&(c=w[d+4]),w[d+5]>l&&(l=w[d+5]),u+=C[t+e],n[e]=u?this._surfaceArea(i,a,o,s,c,l):0,r[e]=u}let f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,_=-1/0,y=0;for(let i=1;i<O;i++){let a=(t+i-1)*6;if(w[a]<f&&(f=w[a]),w[a+1]<p&&(p=w[a+1]),w[a+2]<m&&(m=w[a+2]),w[a+3]>h&&(h=w[a+3]),w[a+4]>g&&(g=w[a+4]),w[a+5]>_&&(_=w[a+5]),y+=C[t+i-1],y===0||r[i]===0)continue;let o=1+(this._surfaceArea(f,p,m,h,g,_)*y+n[i]*r[i])/d;o<b&&(b=o,x=e,S=i)}}if(x<0)return n;let M=O/v[x],N=y[x],P=this._bounds;P[0]=P[1]=P[2]=P[6]=P[7]=P[8]=1/0,P[3]=P[4]=P[5]=P[9]=P[10]=P[11]=-1/0;let F=n,I=r-1;for(;F<=I;){let n=t[F]*6,r=((e[n+x]+e[n+3+x])*.5-N)*M|0;r<0?r=0:r>=O&&(r=O-1);let i=r<S?0:6;if(e[n]<P[i]&&(P[i]=e[n]),e[n+1]<P[i+1]&&(P[i+1]=e[n+1]),e[n+2]<P[i+2]&&(P[i+2]=e[n+2]),e[n+3]>P[i+3]&&(P[i+3]=e[n+3]),e[n+4]>P[i+4]&&(P[i+4]=e[n+4]),e[n+5]>P[i+5]&&(P[i+5]=e[n+5]),i===0)F++;else{let e=t[F];t[F]=t[I],t[I]=e,I--}}return F}_sweepSplit(e,t,n,r,i,a,o,s,c,l){let u=r-n,d=this._surfaceArea(i,a,o,s,c,l);if(!(d>0)||!isFinite(d))return n;let f=this._suffixBuffer(u),p=1/0,m=-1,h=-1;for(let i=0;i<3;i++){this._sortRange(e,t,n,r,i);let a=1/0,o=1/0,s=1/0,c=-1/0,l=-1/0,g=-1/0;for(let r=u-1;r>=1;r--){let i=t[n+r]*6;e[i]<a&&(a=e[i]),e[i+1]<o&&(o=e[i+1]),e[i+2]<s&&(s=e[i+2]),e[i+3]>c&&(c=e[i+3]),e[i+4]>l&&(l=e[i+4]),e[i+5]>g&&(g=e[i+5]);let u=r*6;f[u]=a,f[u+1]=o,f[u+2]=s,f[u+3]=c,f[u+4]=l,f[u+5]=g}let _=1/0,v=1/0,y=1/0,b=-1/0,x=-1/0,S=-1/0;for(let r=1;r<u;r++){let a=t[n+r-1]*6;e[a]<_&&(_=e[a]),e[a+1]<v&&(v=e[a+1]),e[a+2]<y&&(y=e[a+2]),e[a+3]>b&&(b=e[a+3]),e[a+4]>x&&(x=e[a+4]),e[a+5]>S&&(S=e[a+5]);let o=r*6,s=this._surfaceArea(_,v,y,b,x,S),c=this._surfaceArea(f[o],f[o+1],f[o+2],f[o+3],f[o+4],f[o+5]),l=1+(s*r+c*(u-r))/d;l<p&&(p=l,m=i,h=r)}}return m<0||h<=0?n:(m!==2&&this._sortRange(e,t,n,r,m),n+h)}_widestCentroidAxis(e,t,n,r){let i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let u=n;u<r;u++){let n=t[u]*6,r=(e[n]+e[n+3])*.5,d=(e[n+1]+e[n+4])*.5,f=(e[n+2]+e[n+5])*.5;r<i&&(i=r),r>s&&(s=r),d<a&&(a=d),d>c&&(c=d),f<o&&(o=f),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o;return d>u&&d>f?1:f>u?2:0}_insertionSortRange(e,t,n,r,i){let a=i,o=3+i;for(let i=n+1;i<r;i++){let r=t[i],s=e[r*6+a]+e[r*6+o],c=i-1;for(;c>=n&&e[t[c]*6+a]+e[t[c]*6+o]>s;)t[c+1]=t[c],c--;t[c+1]=r}}_sortRange(e,t,n,r,i){let a=r-n,o=this._sortScratch;o.length=a;for(let e=0;e<a;e++)o[e]=t[n+e];let s=i,c=3+i;o.sort((t,n)=>e[t*6+s]+e[t*6+c]-(e[n*6+s]+e[n*6+c]));for(let e=0;e<a;e++)t[n+e]=o[e]}_suffixBuffer(e){let t=e*6;return(!this._suffix||this._suffix.length<t)&&(this._suffix=new Float64Array(t)),this._suffix}_rangeBounds(e,t,n,r,i,a){let o=1/0,s=1/0,c=1/0,l=-1/0,u=-1/0,d=-1/0;for(let i=n;i<r;i++){let n=t[i]*6;e[n]<o&&(o=e[n]),e[n+1]<s&&(s=e[n+1]),e[n+2]<c&&(c=e[n+2]),e[n+3]>l&&(l=e[n+3]),e[n+4]>u&&(u=e[n+4]),e[n+5]>d&&(d=e[n+5])}i[a]=o,i[a+1]=s,i[a+2]=c,i[a+3]=l,i[a+4]=u,i[a+5]=d}_surfaceArea(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}};const u={silent:0,error:1,warn:2,info:3,debug:4},d=`info`,f=`rayzeeLogLevel`,p=`rayzeeLogNamespaces`,m=`color:#7c8494`,h=`color:inherit`;let g=null,_=null;function v(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function y(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function b(){if(g!==null)return g;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in u?(g=u[e],g):(g=u[v(f)]??u[d],g)}function x(){if(_!==null)return _;let e=globalThis.__RAYZEE_LOG_NS__??v(p);return _=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],_}function S(e,t){if(t<u.debug)return!0;let n=x();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function C(e,t,n){if(e>b()||!S(t,e))return;let r=e===u.error?console.error:e===u.warn?console.warn:console.log,i=`[${t}]`;typeof n[0]==`string`?r(`%c${i}%c ${n[0]}`,m,h,...n.slice(1)):r(`%c${i}`,m,...n)}const w={n:e=>Number(e).toLocaleString(`en-US`),ms:e=>e<10?`${Number(e).toFixed(1)} ms`:`${Math.round(e)} ms`,mb:e=>{let t=e/(1024*1024);return t<10?`${t.toFixed(1)} MB`:`${Math.round(t)} MB`},px:(e,t)=>`${e}×${t}`,count:(e,t,n=`${t}s`)=>`${w.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},T={levels:u,setLevel(e){return e in u?(globalThis.__RAYZEE_LOG_LEVEL__=e,g=u[e],y(f,e===d?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(u).join(`, `)}`),this.getLevel())},getLevel(){let e=b();return Object.keys(u).find(t=>u[t]===e)},isEnabled(e){return(u[e]??u.debug)<=b()},only(...e){let t=e.flat().filter(Boolean);return _=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),y(p,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return g=null,_=null,this.getLevel()}};function E(e){return{namespace:e,error:(...t)=>C(u.error,e,t),warn:(...t)=>C(u.warn,e,t),info:(...t)=>C(u.info,e,t),debug:(...t)=>C(u.debug,e,t),isEnabled:e=>T.isEnabled(e),summary(t,n=[]){let r=n.filter(Boolean);if(r.length===0||!console.groupCollapsed){C(u.info,e,[t]),r.forEach(t=>C(u.debug,e,[t]));return}u.info>b()||((b()>=u.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,m,h),r.forEach(e=>console.log(e)),console.groupEnd())}}}function D(e){e&&e in u&&(globalThis.__RAYZEE_LOG_LEVEL__=e,g=u[e])}const O=E(`bvh`);self.onmessage=function(e){let{aabbs:t,count:n,logLevel:r}=e.data;D(r);try{let e=performance.now(),{data:r,nodeCount:i}=new l().buildStructure(new Float64Array(t),n);O.debug(`TLAS ${w.n(i)} nodes in ${w.ms(performance.now()-e)}`),self.postMessage({tlasData:r,nodeCount:i},[r.buffer])}catch(e){O.error(`TLAS build failed:`,e),self.postMessage({error:e.message})}};",Vs=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Bs],{type:`text/javascript;charset=utf-8`});function Hs(e){let t;try{if(t=Vs&&(self.URL||self.webkitURL).createObjectURL(Vs),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Bs),{type:`module`,name:e?.name})}}$t(),Ae(),wt(),X(),Nr(),zr();var Us=5e4,Ws=2e5,Gs=2e6,Ks=1<<19,qs=4e7,Js=1.5*1024**3,Ys=256*1024*1024,Xs=ye(`scene`),Zs=e=>Array.isArray(e)?e:[e],Qs=e=>Zs(e).reduce((e,t)=>e+t.byteLength,0),$s=64*1024*1024;async function ec(e,t,n){for(let r of Zs(n))await e.writeAt(t,r),t+=r.byteLength}function tc(e){let t=0;return e.traverse(e=>{let n=e.isMesh?e.geometry:null;n&&(t=Math.max(t,Math.ceil((n.index?n.index.count:n.attributes.position?.count??0)/3)))}),t}var nc=class{constructor(e={}){this.config={useWorkers:!0,bvhDepth:30,maxLeafSize:4,verbose:!1,useFloat32Array:!0,textureQuality:`adaptive`,maxTextureSize:Nt.DEFAULT_MAX_TEXTURE_SIZE,enableTextureCache:!0,maxConcurrentTextureTasks:Math.min(ar(),6),maxSceneBytes:ja,sceneCache:!0,sceneCacheMinBuildMs:Ps,...e},this.triangleData=null,this.triangleFloats=null,this.triangleCount=0,this.materials=[],this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.roughnessMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.displacementMaps=[],this.anisotropyMaps=[],this.transmissionMaps=[],this.clearcoatMaps=[],this.clearcoatRoughnessMaps=[],this.sheenColorMaps=[],this.sheenRoughnessMaps=[],this.iridescenceMaps=[],this.iridescenceThicknessMaps=[],this.specularIntensityMaps=[],this.specularColorMaps=[],this.diffuseTransmissionMaps=[],this.diffuseTransmissionColorMaps=[],this.directionalLights=[],this.cameras=[],this.spheres=[],this.bvhRoot=null,this.bvh=null,this.bvhData=null,this.bvhIndexChunks=null,this.bvhIndex=null,this.materialData=null,this.instanceTable=null,this._refitWorker=null,this._refitSharedBuffers=null,this._rebuildGeneration=0,this._pendingRebuilds=new Map,this.srgbBucketTextures=null,this.linearBucketTextures=null,this.emissiveTriangleData=null,this.emissiveTriangleCount=0,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._initProcessors(),this.isProcessing=!1,this.processingStage=null,this.memory=new Ia,this.memoryPreflight=null,this.performanceMetrics={textureCreationTime:0,geometryExtractionTime:0,bvhBuildTime:0,blasBuildTime:0,blasWorkerTime:0,tlasBuildTime:0,bvhAssembleTime:0,totalProcessingTime:0}}setMaxTextureSize(e){return this.config.maxTextureSize=e,this.textureCreator?.setMaxTextureSize(e)}_initProcessors(){this.geometryExtractor=new Dn({issues:this.config.issues}),this.bvhBuilder=new Di,this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.textureCreator=new es({maxTextureSize:this.config.maxTextureSize,issues:this.config.issues}),this.emissiveTriangleBuilder=new cs,this.tlasBuilder=new xa,this._tlasWorker=null,this._tlasWorkerFailed=!1}_log(e,t){t===void 0?Xs.debug(e):Xs.debug(e,t)}_preflightMemory(e){let t=this.config.maxSceneBytes??9663676416,n=this.geometryExtractor.surveyScene(e),r=Ca(n);if(this._progressive&&(r.total-=r.bvh),this._streaming){let t=Js+tc(e)*(K.FLOATS_PER_TRIANGLE*4+44);r.total-=Math.max(0,r.triangles-t)}let i={...n,estimate:r,safeBytes:Aa,maxBytes:t,fits:r.total<=Aa};if(this.memoryPreflight=i,r.total<1610612736)return i;if(Xs.debug(H.list([`memory preflight: ${H.mb(r.total)} estimated`,`triangles ${H.mb(r.triangles)} · bvh ${H.mb(r.bvh)} · geometry ${H.mb(r.geometry)}`,`${H.n(n.triangles)} tris · ${H.n(n.placements)} placements`])),r.total>t){let e=`Scene needs about ${H.mb(r.total)} of CPU memory, past the ${H.mb(t)} a browser tab can hold — loading it would crash the tab rather than fail. Reduce the scene (it has ${H.n(n.triangles)} triangles), or raise maxSceneBytes to try anyway.`;throw this.config.issues?.record(Y.SCENE_MEMORY_BUDGET,e,{...n,estimate:r,maxBytes:t}),Error(e)}return i.fits||this.config.issues?.warn(Y.SCENE_MEMORY_BUDGET,`Scene needs about ${H.mb(r.total)} of CPU memory, above the ${H.mb(Aa)} a fresh browser session can usually place. It may still load, but a long-running session will probably fail during BVH assembly; restarting the browser recovers the address space.`,{...n,estimate:r,safeBytes:Aa}),i}_checkAssemblyHeadroom(e){let t=e*64;if(t<1610612736)return!0;let n=wa(Math.ceil(t*Pa),{shared:Xt});return this.memoryPreflight&&(this.memoryPreflight.assemblyProbed=n.placed),n.exhausted&&this.config.issues?.warn(Y.SCENE_MEMORY_BUDGET,`BVH assembly needs ${H.mb(t)} but only ${H.mb(n.placed)} could be allocated. Restarting the browser usually recovers the address space.`,{totalNodes:e,need:t,placeable:n.placed}),!n.exhausted}_liveMemoryParts(){let e=this.instanceTable,t={triangles:this.triangles?.byteLength??0,bvh:this.bvh?.byteLength??0,geometry:this._geometryBytes??this.memoryPreflight?.geometryBytes??0,placements:e?.world?.byteLength??0,blasScratch:0,orderMaps:0};if(e){for(let n of e.blasData.values())t.blasScratch+=n?Qs(n):0;for(let n of e.bvhToOriginal.values())t.orderMaps+=n?.byteLength??0;for(let n of e.originalToBvhMap.values())t.orderMaps+=n?.byteLength??0}return t}sceneBounds(){if(!this.bvh||this.bvh.recordCount===0)return null;let e=this.bvh.chunkFor(0),t=this.bvh.baseOf(0),n=[],r=[];for(let i=0;i<3;i++)n.push(Math.min(e[t+i],e[t+8+i])),r.push(Math.max(e[t+4+i],e[t+12+i]));return{min:n,max:r}}_sampleMemory(e){this.memory.sample(e,this._liveMemoryParts())}_logMemoryReport(){let{allocatedBytes:e,peakLiveBytes:t,byPhase:n}=this.memory;if(e===0)return;let r=Object.keys(n).filter(e=>n[e].allocated>0).map(e=>`${e} ${H.mb(n[e].allocated)}`),i=this.memoryPreflight?.estimate?.total;Xs.debug(H.list([`memory: peak live ${H.mb(t)}`,`allocated ${H.mb(e)}`,i?`predicted ${H.mb(i)}`:null,r.join(` · `)]))}async buildBVH(e,{sceneKey:t=null,progressive:n=null}={}){if(this.isProcessing)throw Error(`Already processing a scene. Call dispose() first.`);this.isProcessing=!0,this.processingStage=`init`,this.memory.reset(),this._geometryBytes=0,qt(e=>this.memory.alloc(e));let r=new ls(e.name??``,{namespace:`scene`});try{this._reset(),this._sceneKey=t,this._blasKey=null,this._blasRestored=!1,this._progressive=n?.storage&&n.uploader?n:null;let i=this.geometryExtractor._countStoredTriangles(e);this._streaming=!!this._progressive&&i>Math.floor(67108864/(K.FLOATS_PER_TRIANGLE*4)),this._foldLeaves=i>qs,this.bvhBuilder.foldLeaves=this._foldLeaves,this._log(`Starting scene processing`),this.memory.mark(`preflight`),this._preflightMemory(e),this.processingStage=`extraction`,this.memory.mark(`extraction`),r.start(`Geometry extraction`),this._streaming?await this._extractStreaming(e):await this._extractGeometry(e),r.end(`Geometry extraction`),this.performanceMetrics.geometryExtractionTime=r.getDuration(`Geometry extraction`),this._geometryBytes=xn(e),this._sampleMemory(`after extraction`),this.processingStage=`bvh`,r.start(`BVH construction (worker)`),r.start(`Material textures (parallel)`);let a=!1,o=this._buildBVH().then(()=>r.end(`BVH construction (worker)`)),s=this._createMaterialTextures().then(()=>{r.end(`Material textures (parallel)`),a=!0});return await o,z({status:`Building light data...`,progress:77}),r.start(`Emissive extraction + Light BVH`),this._buildEmissiveData(),r.end(`Emissive extraction + Light BVH`),a||z({status:`Processing material textures...`,progress:80}),await s,this.performanceMetrics.bvhBuildTime=r.getDuration(`BVH construction (worker)`),this.performanceMetrics.textureCreationTime=r.getDuration(`Material textures (parallel)`),this.processingStage=`finalize`,r.start(`BVH data packing`),this.bvhRoot&&!this.bvh&&this._setBVHData(this.textureCreator.createBVHRawData(this.bvhRoot)),r.end(`BVH data packing`),this.spheres=this._createSpheres(),this.performanceMetrics.totalProcessingTime=performance.now()-r.totalStart,r.print(),this.processingStage=`complete`,await this._restoreGeometry(e),z({status:`Scene data ready`,progress:85}),this._blasKey&&!this._blasRestored&&this.performanceMetrics.totalProcessingTime>=this.config.sceneCacheMinBuildMs&&(this._blasStoring=this._storeBLASes(e.name??``).catch(e=>Xs.debug(`storing BLASes failed:`,e))),this}catch(e){throw this.processingStage=`error`,Xs.error(`processing failed:`,e),z({status:`Error: ${e.message}`,failed:!0,progress:100}),e}finally{this._disposeGeometrySpill(),qt(null),this._sampleMemory(`at ${this.processingStage}`),this._logMemoryReport(),this.isProcessing=!1}}async _extractGeometry(e){z({isLoading:!0,title:`Processing`,status:`Extracting geometry...`,progress:15}),await new Promise(e=>setTimeout(e,0)),this._log(`Extracting geometry`);let t=performance.now();try{this._adoptExtraction(this.geometryExtractor.extract(e));let n=performance.now()-t;this._log(`Geometry extraction complete (${n.toFixed(2)}ms)`,{triangleCount:this.triangleCount,materials:this.materials.length}),z({status:`Extracted ${this.triangleCount.toLocaleString()} triangles`,progress:25})}catch(e){throw Xs.error(`geometry extraction failed:`,e),z({status:`Extraction error: ${e.message}`,failed:!0,progress:25}),e}}async _extractStreaming(e){z({isLoading:!0,title:`Processing`,status:`Extracting geometry and building BVHs...`,progress:15}),await new Promise(e=>setTimeout(e,0));let t=performance.now(),n=this.geometryExtractor,{storage:r,uploader:i}=this._progressive,a=`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`,o=n._countStoredTriangles(e),s=Qt.lazy(o,K.FLOATS_PER_TRIANGLE,Uint32Array),c=s.recordsPerChunk*s.lanesPerRecord*4,l=await on.create(r,`${a}:tri`,c,{label:`Triangle records`,expectedBytes:o*c/s.recordsPerChunk}),u=l&&await on.create(r,`${a}:blas`,0,{label:`BLAS nodes (while building)`});if(!u)return await l?.dispose(),this._streaming=!1,this._extractGeometry(e);let d=await fn.create(r,`${a}:geo`,this.memoryPreflight?.geometryBytes??0);this._geometrySpill=d;let f={key:a,triStore:l,blasStore:u,bvhStore:null,blasBytes:0,blasAt:new Map,pending:[],extractedChunks:0,emitterChunks:new Set,isEmitter:e=>n._emissiveMaterial(e),uploadTriangles:null,chain:Promise.resolve(),error:null};this._spillStores=[l],this._blasKey=null;let p=new Map,m=this._blasWorkerOpts(),h=[],g=()=>new Promise(e=>h.push(e)),_=()=>{let e=h;h=[];for(let t of e)t()},v=null,y=(e,t,n)=>{let r=n.bvhData,i=new Float32Array(6);pa.rootAABB(Zs(r)[0],v,t.start,t.count,i,0),p.set(e,{result:n,aabb:i});let a=f.blasBytes;f.blasBytes+=Qs(r),f.blasAt.set(e,a),n.nodeCount=Qs(r)/64,n.bvhData=null,this._queueSpill(f,()=>ec(u,a,r)),this._forEachChunk(v,t.start,t.count,e=>{--f.pending[e]===0&&e<f.extractedChunks&&this._finishTriangleChunk(f,e)}),_()},b=0,x=this._blasPool(m,()=>b++,(e,t,n)=>y(e,t,n)),S=Promise.resolve(),C=0,w=e=>{let t=e>=v.recordCount?v.chunks.length:Math.floor(e/v.recordsPerChunk);for(let e=f.extractedChunks;e<t;e++)f.pending[e]||this._finishTriangleChunk(f,e);f.extractedChunks=Math.max(f.extractedChunks,t)},T;try{if(T=await n.extractStreaming(e,{onStore:e=>{v=e,this._setTriangleData(e),f.uploadTriangles=i(e,`triangles`)},onRange:(e,t)=>{this._forEachChunk(v,t.start,t.count,e=>f.pending[e]=(f.pending[e]??0)+1),this._isLargeMesh(t)?(C++,S=S.then(async()=>{y(e,t,await this._buildLargeBLAS(t,m)),C--}),S.catch(e=>{f.error??=e,_()})):x.submit({m:e,range:t})},releaseGeometry:d?e=>d.add(e):null,pause:async e=>{for(w(e),d?.queuedBytes>Ys&&await d.written(),z({status:`Extracted ${e.toLocaleString()} triangles, ${b.toLocaleString()} BVHs built...`,progress:15+Math.floor(20*e/Math.max(1,o))}),await new Promise(e=>setTimeout(e,0));v.byteLength>Js&&(x.pending>0||C>0)&&!f.error&&!x.error;)await Promise.race([g(),new Promise(e=>setTimeout(e,50))]);if(f.error||x.error)throw f.error??x.error}}),w(1/0),await Promise.all([x.close(),S]),await f.chain,f.error)throw f.error}catch(e){throw x.abort(e),Xs.error(`streamed extraction failed:`,e),z({status:`Extraction error: ${e.message}`,failed:!0,progress:25}),e}this._adoptExtraction(T),this._streamed={state:f,templates:p},this._log(`Geometry extracted and ${p.size} BLASes built together (${(performance.now()-t).toFixed(0)}ms)`)}_adoptExtraction(e){if(this._setTriangleData(e.triangleData),this.geometryExtractor.releaseTriangles(),this.triangleCount=gt(e.triangleCount,`triangle count`),this._foldLeaves&&this.triangleCount>134217728)throw RangeError(`${this.triangleCount.toLocaleString()} triangles is past the ${Ct.toLocaleString()} a folded BVH leaf can address`);this.expandedTriangleCount=e.expandedTriangleCount??e.triangleCount,this.instanceSource=e.instanceSource||null,this.instanceMatrices=e.instanceMatrices||null,this.instanceCount=e.instanceCount||0,this.bakeInverse=e.bakeInverse||null,this._log(`Using Float32Array format: ${this.triangleCount} triangles, ${(this.triangles.byteLength/(1024*1024)).toFixed(2)}MB`),this.materials=e.materials,this.materialTriangleCounts=e.materialTriangleCounts,this.meshes=e.meshes,this.meshTriangleRanges=e.meshTriangleRanges,this.maps=e.maps,this.normalMaps=e.normalMaps,this.bumpMaps=e.bumpMaps,this.roughnessMaps=e.roughnessMaps,this.metalnessMaps=e.metalnessMaps,this.emissiveMaps=e.emissiveMaps,this.displacementMaps=e.displacementMaps,this.anisotropyMaps=e.anisotropyMaps,this.transmissionMaps=e.transmissionMaps,this.clearcoatMaps=e.clearcoatMaps,this.clearcoatRoughnessMaps=e.clearcoatRoughnessMaps,this.sheenColorMaps=e.sheenColorMaps,this.sheenRoughnessMaps=e.sheenRoughnessMaps,this.iridescenceMaps=e.iridescenceMaps,this.iridescenceThicknessMaps=e.iridescenceThicknessMaps,this.specularIntensityMaps=e.specularIntensityMaps,this.specularColorMaps=e.specularColorMaps,this.diffuseTransmissionMaps=e.diffuseTransmissionMaps??[],this.diffuseTransmissionColorMaps=e.diffuseTransmissionColorMaps??[],this.directionalLights=e.directionalLights,this.cameras=e.cameras}async _buildBVH(){if(z({status:`Building BVH...`,progress:25}),this.triangleCount===0)throw Error(`No triangles to build BVH from`);this._log(`Building two-level BVH (TLAS/BLAS)`),this.memory.mark(`blas`);let e=performance.now();try{let t=this.meshTriangleRanges;if(!t||t.length===0)throw Error(`No mesh triangle ranges available for TLAS/BLAS build`);let n=this.instanceCount>0,r=n?this.instanceCount:t.length,i=this.instanceSource,a=n?this.instanceMatrices:null,o=e=>n?i[e]:e;this.instanceTable=new pa,this.instanceTable.allocate(r,t.length,a,n?i:null),this.instanceTable.tplBakeInverse=this.bakeInverse;let s=this._streamed;this._streamed=null;let c=[],l=[],u=[],d=new Map,f=new Map;for(let e=0;e<r;e++){let n=t[o(e)];if(!n||n.count===0)continue;let r=f.get(n.start);if(r!==void 0){d.set(e,r);continue}f.set(n.start,e),s?u.push({m:e,range:n}):this._isLargeMesh(n)?l.push({m:e,range:n}):c.push({m:e,range:n})}let p=this._blasWorkerOpts(),m=c.length+l.length,h=0,g=()=>{h++,z({status:`Building BLAS ${h}/${m}...`,progress:25+Math.floor(h/m*45)})},_=[...c,...l].map(({m:e,range:t})=>({m:e,range:t,t:o(e),triOffset:t.start,triCount:t.count})).sort((e,t)=>e.t-t.t),v=s?null:await this._restoreBLASes(_,xa.nodeCountFor(r),p),y=s?s.state:!v&&this._progressive&&this.triangles.chunks.length>1?await this._beginProgressiveSpill(_):null,b=y&&!s?(e,t,n)=>this._onBLASBuilt(y,o(e),t,n):null;if(s)for(let[e,t]of s.templates)this.instanceTable.tplObjectAABB.set(t.aabb,e*6);v&&(c.length=0,l.length=0,z({status:`Restored stored BVHs`,progress:68}));let x=v?Promise.resolve(v.results):s?Promise.resolve(u.map(({m:e,range:t})=>({m:e,range:t,result:s.templates.get(o(e)).result}))):this._buildBLASesWithPool(c,p,g,b),S=[],C=(async()=>{for(let{m:e,range:t}of l){let n=await this._buildLargeBLAS(t,p);b?.(e,t,n),S.push({m:e,range:t,result:n}),g()}})(),[w]=await Promise.all([x,C]);if(y&&(await y.chain,y.error))throw y.error;let T={sah:0,objMed:0,spatMed:0,failed:0};for(let{m:e,range:t,result:r}of[...w,...S]){let i=r.splitStats;i&&(T.sah+=i.sahSplits??0,T.objMed+=i.objectMedianSplits??0,T.spatMed+=i.spatialMedianSplits??0,T.failed+=i.failedSplits??0,this.performanceMetrics.blasWorkerTime+=i.totalBuildTime??0),this.instanceTable.setEntry({meshIndex:e,blasNodeCount:r.nodeCount??Qs(r.bvhData)/64,triOffset:t.start,triCount:t.count,originalToBvhMap:r.originalToBvh||null,bvhData:r.bvhData,matrixWorld:n?a:this.meshes?.[e]?.matrixWorld?.elements??null,matrixOffset:n?e*16:0,expandedStart:t.expandedStart,sourceMesh:o(e)})}for(let[e,r]of d)this.instanceTable.setAlias(e,r,n?a:this.meshes?.[e]?.matrixWorld?.elements??null,t[o(e)].expandedStart,o(e),n?e*16:0);z({status:`Built all BLASes`,progress:70}),this.performanceMetrics.blasBuildTime=performance.now()-e,z({status:`Building TLAS...`,progress:72}),this._sampleMemory(`BLASes built`),this.memory.mark(`tlas`);let E=performance.now(),D=this.instanceTable;this.instanceTable.computeAABBs(this.triangles,{owners:!y}),this.instanceTable.assignOffsets(xa.nodeCountFor(D.count));let O=this.instanceTable.totalNodeCount,k=await this._buildTLAS(D);this.performanceMetrics.tlasBuildTime=performance.now()-E,this.memory.mark(`assemble`);let A=performance.now();y||this._checkAssemblyHeadroom(O),this._setBVHData(Qt.lazy(O,16,Float32Array,void 0,Xt));let j=y?await this._beginBVHSpill(y,D.tlasNodeCount):null;this.bvh.setRecords(0,k),k=null,this.tlasBuilder.releaseFlattenBuffer();let M=Math.max(1,Math.ceil(D.templateCount/32));if(v){try{let e=performance.now();await vs(v.nodes,this.bvh,D.tlasNodeCount,O-D.tlasNodeCount),this.performanceMetrics.blasRestore.readMs=performance.now()-e}finally{v.release()}D.blasData.clear()}else{for(let e=0;e<D.templateCount;e++){let t=y?await this._readSpilledBLAS(y,e):D.blasData.get(e);if(!t)continue;let n=D.tplBlasOffset[e],r=n;for(let e of Zs(t))this.bvh.setRecords(r,e),r+=e.length/16;this._offsetBLASInPlace(n,r-n,n,D.tplTriOffset[e]),D.blasData.delete(e),await j?.(r),e%M===0&&this._sampleMemory(`assembling ${e}/${D.templateCount}`)}await j?.(O,!0),y&&await y.blasStore.dispose()}if(this._setBVHData(this.bvh.materializeAll()),v)for(let[e,t]of v.orders)D.bvhToOriginal.set(e,t);else this._buildBvhToOriginalMaps();this.performanceMetrics.bvhAssembleTime=performance.now()-A,D.originalToBvhMap.clear(),D.blasData.clear(),this.bvhRoot=!0,this._disposeRefitWorker();let N=performance.now()-e;Xs.debug(H.list([`${H.n(D.setCount)} BLASes + TLAS`,`${H.n(this.bvh.recordCount)} nodes`,`SAH ${H.n(T.sah)} · objMed ${T.objMed} · spatMed ${T.spatMed} · failed ${T.failed}`,H.ms(N)])),z({status:`BVH construction complete`,progress:75})}catch(e){throw Xs.error(`BVH build failed:`,e),z({status:`BVH error: ${e.message}`,failed:!0,progress:75}),e}}_blasWorkerOpts(){return{depth:this.config.bvhDepth,reinsertionOptimization:{enabled:this.bvhBuilder.enableReinsertionOptimization,batchSizeRatio:this.bvhBuilder.reinsertionBatchSizeRatio,maxIterations:this.bvhBuilder.reinsertionMaxIterations},maxLeafSize:this.bvhBuilder.maxLeafSize,foldLeaves:this._foldLeaves===!0,numBins:this.bvhBuilder.numBins,maxBins:this.bvhBuilder.maxBins,minBins:this.bvhBuilder.minBins,logLevel:be()}}_isLargeMesh(e){return e.count>=Ws&&aa(e.count)}async _buildLargeBLAS(e,t){if(e.count>Gs)return this._buildSplitBLAS(e,t);let n=new Uint32Array(new SharedArrayBuffer(e.count*this.triangles.lanesPerRecord*4));this.triangles.readRecords(e.start,e.count,n),this.triangles.release(e.start,e.count);let r=await na(n,this.config.bvhDepth,null,t);return r.reorderedTriangles?(this.triangles.setRecords(e.start,r.reorderedTriangles),delete r.reorderedTriangles):r.order&&(this._writeInOrder(e.start,r.triangles,r.order),delete r.order,delete r.triangles),r}async _buildSplitBLAS(e,t){let n=this.triangles,{order:r,pieces:i,tree:a}=await ws(n,e.start,e.count,Ks,{pause:()=>new Promise(e=>setTimeout(e,0))}),o=this._blasPool(t,null,null,Math.min(ar(),8));i.forEach((t,n)=>o.submit({m:n,range:{start:e.start+t.start,count:t.count}}));let s=[],c={};for(let{m:e,range:t,result:r}of await o.close()){r.aabb=new Float32Array(6),pa.rootAABB(r.bvhData,n,t.start,t.count,r.aabb,0),s[e]=r;for(let[e,t]of Object.entries(r.splitStats??{}))typeof t==`number`&&(c[e]=(c[e]??0)+t)}return{...Os(a,i,s,r),splitStats:c}}_blasCacheKey(e){let t={...e};delete t.logLevel;let n=typeof navigator<`u`?navigator.hardwareConcurrency:0;return`blas:2:${js}:${JSON.stringify(t)}:${n}:${this._sceneKey}`}async _restoreBLASes(e,t,n){if(!this._sceneKey||this.config.sceneCache===!1)return null;let r=jr(Ir().cacheNamespace);if(!r)return null;this._blasKey=this._blasCacheKey(n);let i=await gs(r,this._blasKey);if(!i)return null;let a=e=>(Xs.debug(`stored BLASes not used: ${e}`),i.release(),null),{index:o}=i;if(o.tlasNodeCount!==t||o.templates.length!==e.length)return a(`layout changed`);let s=t;for(let t=0;t<e.length;t++){let[n,r,i,c,l]=o.templates[t],u=e[t];if(u.t!==n||u.triOffset!==r||u.triCount!==i||l!==s)return a(`layout changed`);s+=c}if(s!==o.totalNodes)return a(`layout changed`);let c=performance.now(),l=await hs(this.triangles,e);for(let t=0;t<e.length;t++)if(l[t]!==o.templates[t][6])return a(`triangles changed`);let u=performance.now();try{let t=new Map,n=[];for(let r=0;r<e.length;r++){let[a,s,c,l,,u,,d]=o.templates[r],f=await ys(i.order,u,c);this._permuteRange(s,c,f),t.set(a,f),n.push({m:e[r].m,range:e[r].range,result:{bvhData:new Float32Array(Uint32Array.from(d).buffer),originalToBvh:null,nodeCount:l}})}return this._blasRestored=!0,this.performanceMetrics.blasRestore={checksumMs:u-c,permuteMs:performance.now()-u},Xs.debug(`restored ${H.n(e.length)} stored BLASes`),{results:n,orders:t,nodes:i.nodes,release:i.release}}catch(e){throw i.release(),e}}_writeInOrder(e,t,n){let r=this.triangles,i=r.lanesPerRecord;for(let a=0,o=n.length;a<o;){let s=r.chunkFor(e+a),c=Math.min(o,(((e+a)/r.recordsPerChunk|0)+1)*r.recordsPerChunk-e);for(let o=r.baseOf(e+a);a<c;a++,o+=i){let e=n[a]*i;for(let n=0;n<i;n++)s[o+n]=t[e+n]}}}_permuteRange(e,t,n){let r=!0;for(let e=0;e<t&&r;e++)r=n[e]===e;if(r)return;let i=this.triangles.lanesPerRecord,a=this.triangles.slice(e,t),o=new a.constructor(a.length);if(i===20)for(let e=0,r=0;e<t;e++,r+=20){let t=n[e]*20;o[r]=a[t],o[r+1]=a[t+1],o[r+2]=a[t+2],o[r+3]=a[t+3],o[r+4]=a[t+4],o[r+5]=a[t+5],o[r+6]=a[t+6],o[r+7]=a[t+7],o[r+8]=a[t+8],o[r+9]=a[t+9],o[r+10]=a[t+10],o[r+11]=a[t+11],o[r+12]=a[t+12],o[r+13]=a[t+13],o[r+14]=a[t+14],o[r+15]=a[t+15],o[r+16]=a[t+16],o[r+17]=a[t+17],o[r+18]=a[t+18],o[r+19]=a[t+19]}else for(let e=0;e<t;e++){let t=n[e]*i,r=e*i;for(let e=0;e<i;e++)o[r+e]=a[t+e]}this.triangles.setRecords(e,o)}async _storeBLASes(e){let t=jr(Ir().cacheNamespace),n=this.instanceTable;if(!t||!n||!this.bvh)return!1;let r=this._blasKey,i=this._geometryVersion,a=()=>this._geometryVersion!==i||this._blasKey!==r,o=[];for(let e=0;e<n.templateCount;e++){let t=n.tplOwner[e];t<0||n.sourceMesh[t]!==e||o.push({t:e,triOffset:n.tplTriOffset[e],triCount:n.tplTriCount[e],nodeCount:n.tplNodeCount[e],blasOffset:n.tplBlasOffset[e]})}let s=await hs(this.triangles,o);if(a())return!1;let c=e=>{let t=this.bvhIndexChunks.chunkFor(e),n=this.bvhIndexChunks.baseOf(e);return Array.from(t.subarray(n,n+16))},l=0,u=[],d=o.map((e,t)=>{u.push(n.bvhToOriginal.get(e.t)??Uint32Array.from({length:e.triCount},(e,t)=>t));let r=[e.t,e.triOffset,e.triCount,e.nodeCount,e.blasOffset,l,s[t],c(e.blasOffset)];return l+=e.triCount,r}),f=await _s(t,r,{index:{v:2,tlasNodeCount:n.tlasNodeCount,totalNodes:n.totalNodeCount,templates:d},bvh:this.bvh,orders:u,isStale:a,label:e});return f&&Xs.debug(`stored ${H.n(o.length)} BLASes for the next load`),f}async _beginProgressiveSpill(e){let{storage:t,uploader:n}=this._progressive,r=this.triangles,i=`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`,a=r.recordsPerChunk*r.lanesPerRecord*r.LaneType.BYTES_PER_ELEMENT,o=await on.create(t,`${i}:tri`,a,{label:`Triangle records`,expectedBytes:r.byteLength}),s=o&&await on.create(t,`${i}:blas`,0,{label:`BLAS nodes (while building)`});if(!s)return await o?.dispose(),null;let c={key:i,triStore:o,blasStore:s,bvhStore:null,blasBytes:0,blasAt:new Map,pending:new Int32Array(r.chunks.length),emitterChunks:new Set,isEmitter:e=>{let t=this.materials[e];return(t?.emissiveIntensity??0)>0&&!!t.emissive&&(t.emissive.r>0||t.emissive.g>0||t.emissive.b>0)},uploadTriangles:n(r,`triangles`),chain:Promise.resolve(),error:null};this._spillStores=[o],this._blasKey=null;for(let{triOffset:t,triCount:n}of e)this._forEachChunk(r,t,n,e=>c.pending[e]++);for(let e=0;e<r.chunks.length;e++)c.pending[e]===0&&this._finishTriangleChunk(c,e);return c}_forEachChunk(e,t,n,r){if(n<=0)return;let i=(t+n-1)/e.recordsPerChunk|0;for(let n=t/e.recordsPerChunk|0;n<=i;n++)r(n)}_onBLASBuilt(e,t,n,r){let i=this.instanceTable,a=r.bvhData;i.tplTriOffset[t]=n.start,i.tplTriCount[t]=n.count,i._readRootAABB(Zs(a)[0],t,this.triangles,i.tplObjectAABB,t*6);let o=e.blasBytes;e.blasBytes+=Qs(a),e.blasAt.set(t,o),r.nodeCount=Qs(a)/64,r.bvhData=null,this._queueSpill(e,()=>ec(e.blasStore,o,a)),this._forEachChunk(this.triangles,n.start,n.count,t=>{--e.pending[t]===0&&this._finishTriangleChunk(e,t)})}_queueSpill(e,t){e.chain=e.chain.then(t).catch(t=>{e.error??=t})}_finishTriangleChunk(e,t){this._queueSpill(e,async()=>{let n=this.triangles,r=n.chunks[t];if(!r)return;e.uploadTriangles(t);let i=n.lanesPerRecord;for(let n=K.MATERIAL_FLAGS_OFFSET;n<r.length;n+=i)if(e.isEmitter(r[n]&16777215)){e.emitterChunks.add(t);return}await n.spillChunk(t,e.triStore)})}async _readSpilledBLAS(e,t){let n=e.blasAt.get(t);if(n===void 0)return null;let r=this.instanceTable.tplNodeCount[t]*64,i=[];for(let t=0;t<r;t+=$s)i.push(new Float32Array(await e.blasStore.readAt(n+t,Math.min($s,r-t))));return i}async _beginBVHSpill(e,t){let{storage:n,uploader:r}=this._progressive,i=this.bvh,a=i.recordsPerChunk*i.lanesPerRecord*i.LaneType.BYTES_PER_ELEMENT,o=await on.create(n,`${e.key}:bvh`,a,{label:`BLAS nodes`,expectedBytes:i.recordCount*64}),s=r(i),c=Math.ceil(t/i.recordsPerChunk);o&&this._spillStores.push(o);let l=c;return async(e,t=!1)=>{for(;l<i.chunks.length&&(t||(l+1)*i.recordsPerChunk<=e);)i.chunks[l]||i._materialize(l),s(l),o&&await i.spillChunk(l,o),l++;if(t)for(let e=0;e<Math.min(c,i.chunks.length);e++)i.chunks[e]||i._materialize(e),s(e)}}_offsetBLASInPlace(e,t,n,r){let i=this.bvhIndexChunks;for(let a=e,o=e+t;a<o;){let e=i.chunkFor(a),t=Math.min(o,((a/i.recordsPerChunk|0)+1)*i.recordsPerChunk),s=i.baseOf(a);vi(e,n,r,s,s+(t-a)*16),a=t}}_buildBLASesWithPool(e,t,n,r=null){let i=this._blasPool(t,n,r);for(let t of e)i.submit(t);return i.close()}_blasPool(e,t,n=null,r=this.config.maxConcurrentTextureTasks||4){let i=[],a=[],o=[],s=[],c=!1,l=0,u=0,d=null,f,p=new Promise((e,t)=>f={resolve:e,reject:t});p.catch(()=>{});let m=e=>{d||(d=e,o.forEach(e=>e.terminate()),f.reject(e))},h=()=>{d||!c||i.length>0||l>0||(o.forEach(e=>e.terminate()),f.resolve(a))},g=t=>{let n=i.shift();if(!n){s.push(t),h();return}let{m:r,range:a}=n;l++;try{let n=this.triangles.copyOf(a.start,a.count),i=a.count;t._currentTask={m:r,range:a},t.postMessage({triangleData:n.buffer,triangleByteOffset:n.byteOffset,triangleByteLength:n.byteLength,triangleCount:i,depth:e.depth,reportProgress:!1,sharedReorderBuffer:null,reinsertionOptimization:e.reinsertionOptimization,maxLeafSize:e.maxLeafSize,foldLeaves:e.foldLeaves,numBins:e.numBins,maxBins:e.maxBins,minBins:e.minBins,logLevel:e.logLevel},[n.buffer])}catch(e){m(e)}},_=(e,r)=>{let i=r.data;if(i.error){m(Error(i.error));return}if(i.progress!==void 0)return;let{m:o,range:s}=e._currentTask;l--;try{i.triangles&&this.triangles.setRecords(s.start,i.triangles);let e={bvhData:i.bvhData,originalToBvh:i.originalToBvh||null,splitStats:i.splitStats||null};n?.(o,s,e),a.push({m:o,range:s,result:e})}catch(e){m(e);return}u++,t?.(u),g(e)},v=()=>{let e=ur(Ji);return e.onmessage=t=>_(e,t),e.onerror=e=>m(e),o.push(e),e};return{submit(e){if(!d){i.push(e);try{let e=s.pop()??(o.length<r?v():null);e&&g(e)}catch(e){m(e)}}},close(){return c=!0,h(),p},abort(e){m(e??Error(`BLAS pool aborted`))},get pending(){return i.length+l},get error(){return d}}}_buildBvhToOriginalMaps(){let e=this.instanceTable;for(let t=0;t<e.count;t++){if(!e.isSet[t]||!e.isOwner(t))continue;let n=e.sourceMesh[t],r=e.tplTriCount[n],i=e.originalToBvhMap.get(n),a=new Uint32Array(r);if(i)for(let e=0;e<r;e++)a[i[e]]=e;else for(let e=0;e<r;e++)a[e]=e;e.bvhToOriginal.set(n,a),e.originalToBvhMap.delete(n)}}async _createMaterialTextures(){this._log(`Creating material textures (parallel with BVH)`);try{let{srgbLists:e,linearLists:t,remap:n}=this._bucketTextures();this._remapMaterialTextureIndices(n),this.materials?.length&&(this.materialData=this.textureCreator.createMaterialRawData(this.materials));let i=(e,t)=>e.length===0?Promise.resolve(null):this.textureCreator.createTexturesToDataTexture(e,{srgbPool:t}).then(e=>(e&&t&&(e.colorSpace=r.SRGBColorSpace),e)),[a,o]=await Promise.all([Promise.all(e.map(e=>i(e,!0))),Promise.all(t.map(e=>i(e,!1)))]);this.srgbBucketTextures=a,this.linearBucketTextures=o,this._log(`Material textures complete`,{materialData:!!this.materialData,srgbBuckets:a.map(e=>e?`${e.image.width}x${e.image.height}x${e.image.depth}`:`-`).join(`,`),linearBuckets:o.map(e=>e?`${e.image.width}x${e.image.height}x${e.image.depth}`:`-`).join(`,`)})}catch(e){throw Xs.error(`texture creation failed:`,e),e}}_bucketTextures(){let e=this.config.maxTextureSize,t=Nt.MATERIAL_BUCKET_COUNT,n=Nt.BUCKET_LAYER_STRIDE,r=e=>{let t=new Set,n=[];for(let r of e)for(let e of r||[]){if(!e?.image)continue;let r=e.source?.uuid??e.uuid;t.has(r)||(t.add(r),n.push({width:e.image.width,height:e.image.height}))}return n},i=[this.maps,this.emissiveMaps,this.sheenColorMaps,this.specularColorMaps,this.diffuseTransmissionColorMaps],a=[this.normalMaps,this.bumpMaps,this.roughnessMaps,this.metalnessMaps,this.displacementMaps,this.anisotropyMaps,this.transmissionMaps,this.clearcoatMaps,this.clearcoatRoughnessMaps,this.sheenRoughnessMaps,this.iridescenceMaps,this.iridescenceThicknessMaps,this.specularIntensityMaps,this.diffuseTransmissionMaps],o=Vt(r(i),e,t),s=Vt(r(a),e,t);this._srgbBucketShapes=o,this._linearBucketShapes=s;let c=Array.from({length:t},()=>[]),l=Array.from({length:t},()=>[]),u=Array.from({length:t},()=>new Map),d=Array.from({length:t},()=>new Map);this._srgbTexPacked=new Map,this._linearTexPacked=new Map;let f=!1,p=!1,m=(e,t,r,i,a)=>{if(!e)return-1;if(!e.image)return p||this.config.issues?.record(Y.TEXTURE_BUILD_FAILED,`a material map had not finished decoding when the scene was packed; it renders untextured`,{texture:e.name||e.source?.uuid||e.uuid}),p=!0,-1;let o=Ht(e.image.width,e.image.height,a),s=e.source?.uuid??e.uuid,c=r[o].get(s);if(c!==void 0)return Ut(o,c);if(t[o].length>=n)return Xs.warn(`texture bucket ${o} full (${n}); dropping a map`),f||this.config.issues?.record(Y.TEXTURE_LIMIT_EXCEEDED,`texture bucket ${o} full (${n} layers); the rest render untextured`,{bucket:o,limit:n}),f=!0,-1;t[o].push(e);let l=t[o].length-1;r[o].set(s,l);let u=Ut(o,l);return i.set(s,u),u},h=(e,t,n,r,i)=>(e||[]).map(e=>m(e,t,n,r,i));return{srgbLists:c,linearLists:l,remap:{albedo:h(this.maps,c,u,this._srgbTexPacked,o),emissive:h(this.emissiveMaps,c,u,this._srgbTexPacked,o),normal:h(this.normalMaps,l,d,this._linearTexPacked,s),bump:h(this.bumpMaps,l,d,this._linearTexPacked,s),roughness:h(this.roughnessMaps,l,d,this._linearTexPacked,s),metalness:h(this.metalnessMaps,l,d,this._linearTexPacked,s),displacement:h(this.displacementMaps,l,d,this._linearTexPacked,s),anisotropy:h(this.anisotropyMaps,l,d,this._linearTexPacked,s),transmission:h(this.transmissionMaps,l,d,this._linearTexPacked,s),clearcoat:h(this.clearcoatMaps,l,d,this._linearTexPacked,s),clearcoatRoughness:h(this.clearcoatRoughnessMaps,l,d,this._linearTexPacked,s),sheenColor:h(this.sheenColorMaps,c,u,this._srgbTexPacked,o),sheenRoughness:h(this.sheenRoughnessMaps,l,d,this._linearTexPacked,s),iridescence:h(this.iridescenceMaps,l,d,this._linearTexPacked,s),iridescenceThickness:h(this.iridescenceThicknessMaps,l,d,this._linearTexPacked,s),specularIntensity:h(this.specularIntensityMaps,l,d,this._linearTexPacked,s),specularColor:h(this.specularColorMaps,c,u,this._srgbTexPacked,o),diffuseTransmission:h(this.diffuseTransmissionMaps,l,d,this._linearTexPacked,s),diffuseTransmissionColor:h(this.diffuseTransmissionColorMaps,c,u,this._srgbTexPacked,o)}}}_remapMaterialTextureIndices(e){let t=(e,t)=>e>=0&&e<t.length?t[e]:-1;for(let n of this.materials)n.map=t(n.map,e.albedo),n.emissiveMap=t(n.emissiveMap,e.emissive),n.normalMap=t(n.normalMap,e.normal),n.bumpMap=t(n.bumpMap,e.bump),n.roughnessMap=t(n.roughnessMap,e.roughness),n.metalnessMap=t(n.metalnessMap,e.metalness),n.displacementMap=t(n.displacementMap,e.displacement),n.anisotropyMap=t(n.anisotropyMap,e.anisotropy),n.transmissionMap=t(n.transmissionMap,e.transmission),n.clearcoatMap=t(n.clearcoatMap,e.clearcoat),n.clearcoatRoughnessMap=t(n.clearcoatRoughnessMap,e.clearcoatRoughness),n.sheenColorMap=t(n.sheenColorMap,e.sheenColor),n.sheenRoughnessMap=t(n.sheenRoughnessMap,e.sheenRoughness),n.iridescenceMap=t(n.iridescenceMap,e.iridescence),n.iridescenceThicknessMap=t(n.iridescenceThicknessMap,e.iridescenceThickness),n.specularIntensityMap=t(n.specularIntensityMap,e.specularIntensity),n.specularColorMap=t(n.specularColorMap,e.specularColor),n.diffuseTransmissionMap=t(n.diffuseTransmissionMap,e.diffuseTransmission),n.diffuseTransmissionColorMap=t(n.diffuseTransmissionColorMap,e.diffuseTransmissionColor)}_buildEmissiveData(){this.emissiveTriangleCount=this.emissiveTriangleBuilder.extractEmissiveTriangles(this.triangles,this.materials,this.triangleCount,this.instanceTable??null),this.emissiveTriangleData=this.emissiveTriangleBuilder.createEmissiveRawData(),this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower,this._log(`Emissive triangle extraction complete`,this.emissiveTriangleBuilder.getStats()),this.emissiveTriangleBuilder.buildLightBVH(),this.lightBVHNodeData=this.emissiveTriangleBuilder.lightBVHNodeData,this.lightBVHNodeCount=this.emissiveTriangleBuilder.lightBVHNodeCount,this.emissiveTriangleData=this.emissiveTriangleBuilder.emissiveTriangleData||this.emissiveTriangleData,this.emissiveBitTrailMap=this.emissiveTriangleBuilder.emissiveBitTrailMap,this.emissiveTriangleCount=this.emissiveTriangleBuilder.emissiveCount,this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower}_createSpheres(){return[]}_reset(){this._geometryVersion=(this._geometryVersion??0)+1,this._disposeSpill(),this._disposeGeometrySpill(),this._disposeTextures(),this.triangles=[],this._setTriangleData(null),this.triangleCount=0,this.materials=[],this.meshTriangleRanges=null,this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.roughnessMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.displacementMaps=[],this.anisotropyMaps=[],this.transmissionMaps=[],this.clearcoatMaps=[],this.clearcoatRoughnessMaps=[],this.sheenColorMaps=[],this.sheenRoughnessMaps=[],this.iridescenceMaps=[],this.iridescenceThicknessMaps=[],this.specularIntensityMaps=[],this.specularColorMaps=[],this.diffuseTransmissionMaps=[],this.diffuseTransmissionColorMaps=[],this.directionalLights=[],this.cameras=[],this.spheres=[],this.bvhRoot=null,this.bvh=null,this.bvhData=null,this.bvhIndexChunks=null,this.bvhIndex=null,this.instanceTable=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this.performanceMetrics={textureCreationTime:0,geometryExtractionTime:0,bvhBuildTime:0,blasBuildTime:0,blasWorkerTime:0,tlasBuildTime:0,bvhAssembleTime:0,totalProcessingTime:0}}_disposeTextures(){this._disposeBucketTextures()}_disposeBucketTextures(){for(let e of[`srgbBucketTextures`,`linearBucketTextures`]){let t=this[e];if(t){for(let n of t)if(n&&typeof n.dispose==`function`)try{n.dispose()}catch(t){Xs.warn(`error disposing ${e}:`,t)}this[e]=null}}}async rebuildMaterials(e){if(this.isProcessing)throw Error(`Already processing. Cannot rebuild materials during processing.`);this._log(`Rebuilding materials and textures`);let t=performance.now();try{this.isProcessing=!0;let n=this.geometryExtractor.extractMaterialsOnly(e);this._disposeMaterialTextures(),this.materials=n.materials,this.meshes=n.meshes,this.maps=n.maps,this.normalMaps=n.normalMaps,this.bumpMaps=n.bumpMaps,this.roughnessMaps=n.roughnessMaps,this.metalnessMaps=n.metalnessMaps,this.emissiveMaps=n.emissiveMaps,this.displacementMaps=n.displacementMaps,await this._createMaterialTextures();let r=performance.now()-t;return this._log(`Material rebuild complete (${r.toFixed(2)}ms)`,{materials:this.materials.length,textures:this.maps.length}),this}catch(e){throw Xs.error(`material rebuild failed:`,e),e}finally{this.isProcessing=!1}}_disposeMaterialTextures(){this._disposeBucketTextures(),this.textureCreator&&this.textureCreator.textureCache&&(this.textureCreator.textureCache.dispose(),this.textureCreator.textureCache=new this.textureCreator.textureCache.constructor)}getStatistics(){let e={triangleCount:this.triangleCount,materialCount:this.materials.length,textureCount:this.maps.length,lightCount:this.directionalLights.length,cameraCount:this.cameras.length,processingComplete:this.processingStage===`complete`,hasBVH:!!this.bvhRoot,hasTextures:!!this.materialData&&!!this.bvh,useFloat32Array:this.config.useFloat32Array,triangleDataSize:this.triangles?(this.triangles.byteLength/(1024*1024)).toFixed(2)+`MB`:`0MB`};return this.performanceMetrics.totalProcessingTime>0&&(e.performance={totalTime:this.performanceMetrics.totalProcessingTime,textureTime:this.performanceMetrics.textureCreationTime,bvhTime:this.performanceMetrics.bvhBuildTime,extractionTime:this.performanceMetrics.geometryExtractionTime,texturePercentage:(this.performanceMetrics.textureCreationTime/this.performanceMetrics.totalProcessingTime*100).toFixed(1)+`%`}),this.textureCreator&&this.textureCreator.capabilities&&(e.textureCapabilities=this.textureCreator.capabilities),e}updateConfig(e){Object.assign(this.config,e),this.bvhBuilder&&(this.bvhBuilder.maxLeafSize=this.config.maxLeafSize),this._log(`Configuration updated`,this.config)}_adoptSharedChunks(e,t){let n=this[e];if(n.shared)return;let r=n.chunks.map(e=>{let n=new t(new SharedArrayBuffer(e.byteLength));return n.set(e),n}),i=Qt.adopt(r,n.recordCount,n.lanesPerRecord,n.recordsPerChunk);e===`bvh`?this._setBVHData(i):this._setTriangleData(i)}_meshSource(e,t){if(e==null)return null;let n=this.instanceTable;if(typeof e==`function`)return r=>{let i=n.sourceMesh[r],a=e(i,n.triCountOf(r)),o=n.triCountOf(r)*9;if(a&&a.length!==o)throw Error(`SceneProcessor: ${t}s for mesh ${i} must be ${o} floats (${n.triCountOf(r)} triangles × 9), got ${a.length}.`);return a??null};let r=(this.expandedTriangleCount??this.triangleCount)*9;if(e.length!==r)throw Error(`SceneProcessor: expected ${r} ${t} floats (${r/9} triangles × 9, full scene), got ${e.length}. Pass a per-mesh callback instead to avoid building one array for the whole scene.`);return t=>{let r=n.expandedStartOf(t)*9;return e.subarray(r,r+n.triCountOf(t)*9)}}async refitBVH(e,t){if(this._geometryVersion=(this._geometryVersion??0)+1,this._tlasLeafBoxesOf=null,!this.bvh||!this.triangles||!this.instanceTable)throw Error(`No BVH data available for refit. Run buildBVH() first.`);let n=this._meshSource(e,`position`),r=this._meshSource(t,`normal`);if(!n)throw Error(`SceneProcessor.refitBVH: positions are required.`);if(this._refitWorker||=ur(zs),!this._refitSharedBuffers){this._adoptSharedChunks(`bvh`,Float32Array),this._adoptSharedChunks(`triangles`,Uint32Array);let e=this.bvh.chunks.map(e=>e.buffer),t=this.triangles.chunks.map(e=>e.buffer);this._refitSharedBuffers={bvhBufs:e,triBufs:t},this._refitWorker.postMessage({type:`init`,sharedBvhBufs:e,bvhRecordCount:this.bvh.recordCount,bvhRecordsPerChunk:this.bvh.recordsPerChunk,sharedTriBufs:t,triRecordCount:this.triangles.recordCount,triLanesPerRecord:this.triangles.lanesPerRecord,triRecordsPerChunk:this.triangles.recordsPerChunk})}let i=this.instanceTable,a=K.FLOATS_PER_TRIANGLE,o=[],s=[],c=0;for(let e=0;e<i.count;e++){if(!i.isSet[e]||!i.isOwner(e))continue;c++;let t=n(e);if(!t)continue;if(this._updateMeshTrianglePositions(e,t),s.push(i.blasOffsetOf(e),i.blasNodeCountOf(e)),r){let t=r(e);t&&this._patchMeshSmoothNormals(e,t)}let l=i.triOffsetOf(e)*a,u=i.triCountOf(e)*a,d=o.at(-1);d&&d.offset+d.count===l?d.count+=u:o.push({offset:l,count:u})}let l=i.tlasNodeCount,u=l>0&&s.length/2<c,d=u?[this.computeTLASDirtyRange()]:null;for(let e=0;u&&e<s.length;e+=2)d.push({offset:s[e]*16,count:s[e+1]*16});return new Promise((e,t)=>{this._refitWorker.onmessage=n=>{let r=n.data;r.type===`refitComplete`?e({refitTimeMs:r.refitTimeMs,triRanges:o,bvhRanges:d}):r.type===`error`&&t(Error(r.error))},this._refitWorker.postMessage({type:`refit`,blasRanges:u?s:null,tlasNodeCount:l})})}_patchSmoothNormals(e){let t=this.instanceTable;if(t)for(let n=0;n<t.count;n++){if(!t.isSet[n]||!t.isOwner(n))continue;let r=e(n);r&&this._patchMeshSmoothNormals(n,r)}}_placementOf(e){return this.instanceTable?.placementRunOf(e)?.start??-1}refitBLASes(e,t,n){if(this._geometryVersion=(this._geometryVersion??0)+1,!this.instanceTable||!this.bvh||!this.triangles)throw Error(`No TLAS/BLAS data available. Run buildBVH() first.`);let r=this._meshSource(t,`position`),i=this._meshSource(n,`normal`);if(!r)throw Error(`SceneProcessor.refitBLASes: positions are required.`);let a=performance.now();this._blasRefitter||=new Gi;let o=this.instanceTable;for(let t of e){let e=this._placementOf(t);if(e<0||!o.isSet[e])continue;if(!o.isOwner(e)){let n=o.tplOwner[o.sourceMesh[e]];this.config.issues?.record(Y.REFIT_SHARED_GEOMETRY,`mesh ${t} shares its triangles with another placement; deforming it would move every copy, so it was skipped`,{meshIndex:t,owner:o.sourceMesh[n]??n});continue}let n=r(e);if(n){if(this._updateMeshTrianglePositions(e,n),i){let t=i(e);t&&this._patchMeshSmoothNormals(e,t)}this._blasRefitter.refitRange(this.bvh,this.triangles,o.blasOffsetOf(e),o.blasNodeCountOf(e)),this.instanceTable.recomputeAABB(e,this.bvh,this.triangles)}}return this._refitTLAS(),{refitTimeMs:performance.now()-a}}updateMeshTransforms(e){if(!this.instanceTable||!this.bvh)throw Error(`No TLAS/BLAS data available. Run buildBVH() first.`);let t=performance.now(),n=this.instanceTable,r=this._transformScratch??=new Float32Array(16);this._movedPlacements?.length!==n.count&&(this._movedPlacements=new Uint8Array(n.count));let i=this._movedPlacements,a=0;for(let t of e){let e=this.meshes?.[t],o=n.placementRunOf(t);if(!e||!o)continue;e.updateMatrixWorld(!0);let s=e.matrixWorld.elements,c=e.isInstancedMesh?this._ownInstanceMatrices(e):null,l=n.tplBakeInverse?.get(n.sourceMesh[o.start])??null;for(let e=0;e<o.count;e++){let t=o.start+e;n.isSet[t]&&(c?(la(s,c,e*16,r),n.setPlacementMatrix(t,r)):l?(la(s,l,0,r),n.setPlacementMatrix(t,r)):n.setPlacementMatrix(t,s),this._writeLeafMatrix(t),i[t]=1,a++)}}return this._refitTLAS(i),i.fill(0),{refitTimeMs:performance.now()-t,placements:a}}_ownInstanceMatrices(e){let t=e.instanceMatrix;return t?.array?(t.array.buffer===this.instanceTable.world.buffer&&(t.array=t.array.slice(),t.needsUpdate=!0),t.array):null}_writeLeafMatrix(e){let t=this.instanceTable.tlasLeafIndex[e];t<0||xa.writeLeafMatrix(this.bvh.chunkFor(t),this.bvhIndexChunks.chunkFor(t),this.bvh.baseOf(t),this.instanceTable.world,e)}computeTLASDirtyRange(){return{offset:0,count:this.instanceTable.tlasNodeCount*16}}computeBLASDirtyRanges(e){let t=K.FLOATS_PER_TRIANGLE,n=[],r=[];for(let i of e){let e=this.instanceTable,a=this._placementOf(i);a<0||!e.isSet[a]||(n.push({offset:e.triOffsetOf(a)*t,count:e.triCountOf(a)*t}),r.push({offset:e.blasOffsetOf(a)*16,count:e.blasNodeCountOf(a)*16}))}return r.push({offset:0,count:this.instanceTable.tlasNodeCount*16}),{triRanges:n,bvhRanges:r}}uploadToPathTracer(e,t,n,r,{keepUserLights:i=!1}={}){return this.triangles?(e.setTriangleData(this.triangles,this.triangleCount),this.bvh?(e.setBVHData(this.bvh),e.setInstanceTable(this.instanceTable),this.materialData?e.materialData.setMaterialData(this.materialData,this.materials.map(e=>e.sources)):Xs.warn(`no material data, using defaults`),r&&e.environment.setEnvironmentTexture(r),e.materialData.setMaterialTextures({srgbBuckets:this.srgbBucketTextures,linearBuckets:this.linearBucketTextures}),e.materialData.setTexturePackMaps?.(this._srgbTexPacked,this._linearTexPacked),this.emissiveTriangleData&&(e.setEmissiveTriangleData(this.emissiveTriangleData,this.emissiveTriangleCount,this.emissiveTotalPower,this.emissiveBitTrailMap),this._releaseBitTrailMap()),this.lightBVHNodeData&&e.setLightBVHData(this.lightBVHNodeData,this.lightBVHNodeCount),t.transferSceneLights(n,{keepUserLights:i}),!0):(Xs.error(`failed to get BVH data`),!1)):(Xs.error(`failed to get triangle data`),!1)}updateMaterialEmissive(e,t,n){if(!this.emissiveTriangleBuilder)return null;let r=this.materials[e];return!r||(t===`emissive`?r.emissive=n:t===`emissiveIntensity`&&(r.emissiveIntensity=n),!this.emissiveTriangleBuilder.updateMaterialEmissive(e,r,this.triangles,this.materials,this.triangleCount))?null:this._collectEmissivePayload()}rebuildEmissiveColors(){return!this.emissiveTriangleBuilder||!this.triangleCount?null:(this.emissiveTriangleBuilder.extractEmissiveTriangles(this.triangles,this.materials,this.triangleCount,this.instanceTable??null),this.emissiveTriangleBuilder.createEmissiveRawData(),this._collectEmissivePayload())}rebuildEmissiveForVisibility(e,t=!1){return!this.emissiveTriangleBuilder||!this.emissiveTriangleBuilder.setHiddenMeshes(e)&&!t?null:this._collectEmissivePayload()}movesEmitters(e){let t=this.emissiveTriangleBuilder?.emissiveMeshes;return!!t?.size&&e.some(e=>t.has(e))}refreshEmissiveTransforms(){let e=this.emissiveTriangleBuilder;return!e?.emissiveTriangles.length||!this.instanceTable||!this.triangles?null:(e.refreshTransforms(this.triangles,this.instanceTable),this._collectEmissivePayload())}_collectEmissivePayload(){this.emissiveTriangleBuilder.buildLightBVH(),this.lightBVHNodeData=this.emissiveTriangleBuilder.lightBVHNodeData,this.lightBVHNodeCount=this.emissiveTriangleBuilder.lightBVHNodeCount,this.emissiveTriangleData=this.emissiveTriangleBuilder.emissiveTriangleData,this.emissiveBitTrailMap=this.emissiveTriangleBuilder.emissiveBitTrailMap,this.emissiveTriangleCount=this.emissiveTriangleBuilder.emissiveCount,this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower;let e=this.emissiveBitTrailMap;return this._releaseBitTrailMap(),{rawData:this.emissiveTriangleData,emissiveCount:this.emissiveTriangleCount,totalPower:this.emissiveTotalPower,bitTrailMap:e,lightBVHNodeData:this.lightBVHNodeData,lightBVHNodeCount:this.lightBVHNodeCount}}get spilled(){return!!(this.triangles?.spilledChunks||this.bvh?.spilledChunks)}async spillToDisk(e){let t=this.triangles,n=this.bvh;if(!e||this.spilled||this._spillStores||!t?.chunks||t.chunks.length<2||!n?.chunks)return null;await this._blasStoring;let r=this._geometryVersion,i=performance.now(),a=`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`,o=e=>e.recordsPerChunk*e.lanesPerRecord*e.LaneType.BYTES_PER_ELEMENT,s=await on.create(e,`${a}:tri`,o(t),{label:`Triangle records`,expectedBytes:t.byteLength}),c=s&&await on.create(e,`${a}:bvh`,o(n),{label:`BLAS nodes`,expectedBytes:n.byteLength});if(!s||!c)return await s?.dispose(),null;this._spillStores=[s,c];let l=Math.ceil((this.instanceTable?.tlasNodeCount??1)/n.recordsPerChunk),u=await t.spill(s);if(u+=await n.spill(c,{keep:e=>e<l}),await s.flush(),await c.flush(),r!==this._geometryVersion)return null;let d=performance.now()-i;return Xs.info(`spilled ${(u/1048576).toFixed(0)} MB of triangles and BLAS nodes to disk in ${d.toFixed(0)} ms`),{bytes:u,ms:d}}ensureResident(){return this._paging??=(async()=>{await this.triangles?.ensureResident?.(),await this.bvh?.ensureResident?.(),this.spilled||this._disposeSpill()})().finally(()=>{this._paging=null}),this._paging}async _restoreGeometry(e){let t=this._geometrySpill;if(!t?.bytes)return;z({status:`Reading scene geometry back...`,progress:84});let n=performance.now(),r=t.bytes;await t.restore(),this._disposeGeometrySpill(),this._geometryBytes=xn(e),Xs.info(`read ${H.mb(r)} of scene geometry back from disk in ${H.ms(performance.now()-n)}`),t.error&&Xs.warn(`some scene geometry stayed in memory, its spill write failed:`,t.error)}_disposeGeometrySpill(){let e=this._geometrySpill;this._geometrySpill=null,e?.dispose().catch(()=>{})}_disposeSpill(){let e=this._spillStores;this._spillStores=null;for(let t of e??[])t.dispose().catch(()=>{})}_releaseBitTrailMap(){this.emissiveBitTrailMap=null,this.emissiveTriangleBuilder&&(this.emissiveTriangleBuilder.emissiveBitTrailMap=null)}async _buildTLAS(e){let t=e.count;if(t>=Us&&!this._tlasWorkerFailed)try{let n=new Float64Array(t*6);e.writeWorldAABBs(n);let{tlasData:r,nodeCount:i}=await this._runTLASWorker(n,t);return xa.fillLeaves(r,i,e),r}catch(e){this._tlasWorkerFailed=!0,Xs.warn(`TLAS worker unavailable (${e.message}); building on the main thread`)}return this.tlasBuilder.build(e).data}_runTLASWorker(e,t){this._tlasWorker||=ur(Hs);let n=this._tlasWorker;return new Promise((r,i)=>{let a=e=>{n.removeEventListener(`message`,a),n.removeEventListener(`error`,o),e.data?.error?i(Error(e.data.error)):r(e.data)},o=e=>{n.removeEventListener(`message`,a),n.removeEventListener(`error`,o),i(Error(e.message||`worker error`))};n.addEventListener(`message`,a),n.addEventListener(`error`,o),n.postMessage({aabbs:e.buffer,count:t,logLevel:be()},[e.buffer])})}_setBVHData(e){this._tlasLeafBoxesOf=null;let t=e?e instanceof Qt?e:Qt.adopt([e],e.length/16,16,e.length/16):null;this.bvh=t,t&&this._foldLeaves&&(t.foldedLeaves=!0),this.bvhIndexChunks=t?t.viewAs(Uint32Array):null,this.bvhData=t?t.single:null,this.bvhIndex=this.bvhIndexChunks?this.bvhIndexChunks.single:null}_setTriangleData(e){let t=K.FLOATS_PER_TRIANGLE,n=e?e instanceof Qt?e:Qt.adopt([e],e.length/t,t,e.length/t):null;this.triangles=n,this.triangleFloatChunks=n?n.viewAs(Float32Array):null,this.triangleData=n?n.single:null,this.triangleFloats=this.triangleFloatChunks?this.triangleFloatChunks.single:null}_updateMeshTrianglePositions(e,t){let n=K.POSITION_A_OFFSET,r=K.POSITION_B_OFFSET,i=K.POSITION_C_OFFSET,a=K.NORMAL_A_PACKED_OFFSET,o=K.NORMAL_B_PACKED_OFFSET,s=K.NORMAL_C_PACKED_OFFSET,c=this.triangles,l=this.triangleFloatChunks,u=this.instanceTable,d=u.bvhToOriginalOf(e),f=u.triOffsetOf(e),p=u.triCountOf(e),m=u.matrixInverseOf(e),h=ua(m);for(let e=0;e<p;e++){let u=d?d[e]:e,p=f+e,g=l.chunkFor(p),_=c.chunkFor(p),v=c.baseOf(p),y=u*9,b=t[y],x=t[y+1],S=t[y+2],C=t[y+3],w=t[y+4],T=t[y+5],E=t[y+6],D=t[y+7],O=t[y+8];if(!h){let e=(e,t,n)=>m[0]*e+m[4]*t+m[8]*n+m[12],t=(e,t,n)=>m[1]*e+m[5]*t+m[9]*n+m[13],n=(e,t,n)=>m[2]*e+m[6]*t+m[10]*n+m[14],r=[e(b,x,S),t(b,x,S),n(b,x,S)],i=[e(C,w,T),t(C,w,T),n(C,w,T)],a=[e(E,D,O),t(E,D,O),n(E,D,O)];b=r[0],x=r[1],S=r[2],C=i[0],w=i[1],T=i[2],E=a[0],D=a[1],O=a[2]}g[v+n]=b,g[v+n+1]=x,g[v+n+2]=S,g[v+r]=C,g[v+r+1]=w,g[v+r+2]=T,g[v+i]=E,g[v+i+1]=D,g[v+i+2]=O;let k=C-b,A=w-x,j=T-S,M=E-b,N=D-x,P=O-S,F=mt(A*P-j*N,j*M-k*P,k*N-A*M);_[v+a]=F,_[v+o]=F,_[v+s]=F}}_patchMeshSmoothNormals(e,t){let n=this.instanceTable;this._patchNormalsRange(t,n.triOffsetOf(e),n.triCountOf(e),n.matrixWorldOf(e),n.bvhToOriginalOf(e))}_patchNormalsRange(e,t,n,r,i){let a=K.NORMAL_A_PACKED_OFFSET,o=K.NORMAL_B_PACKED_OFFSET,s=K.NORMAL_C_PACKED_OFFSET,c=r,l=!c||ua(c),u=[a,o,s];for(let r=0;r<n;r++){let n=t+r,a=this.triangles.chunkFor(n),o=this.triangles.baseOf(n),s=(i?i[r]:r)*9;for(let t=0;t<3;t++){let n=s+t*3,r=e[n],i=e[n+1],d=e[n+2],f=r,p=i,m=d;if(!l){f=c[0]*r+c[1]*i+c[2]*d,p=c[4]*r+c[5]*i+c[6]*d,m=c[8]*r+c[9]*i+c[10]*d;let e=Math.hypot(f,p,m)||1;f/=e,p/=e,m/=e}a[o+u[t]]=mt(f,p,m)}}}_refitTLAS(e=null){let t=this.instanceTable.tlasNodeCount;(!this._tlasBounds||this._tlasBounds.length<t*6)&&(this._tlasBounds=new Float32Array(t*6),this._tlasLeafBoxesOf=null);let n=this.instanceTable,r=e&&this._tlasLeafBoxesOf===n;for(let i=t-1;i>=0;i--){let t=this.bvhIndexChunks.chunkFor(i),a=this.bvh.chunkFor(i),o=this.bvh.baseOf(i),s=t[o+3];if(s===St.BLAS_POINTER_LEAF){let a=t[o+1]&xt;a<n.count&&!(r&&!e[a])&&n.writeWorldAABB(a,this._tlasBounds,i*6)}else if(s<St.TRIANGLE_LEAF){let e=s,n=t[o+7],r=e*6,c=n*6,l=this._tlasBounds;a[o]=l[r],a[o+1]=l[r+1],a[o+2]=l[r+2],a[o+4]=l[r+3],a[o+5]=l[r+4],a[o+6]=l[r+5],a[o+8]=l[c],a[o+9]=l[c+1],a[o+10]=l[c+2],a[o+12]=l[c+3],a[o+13]=l[c+4],a[o+14]=l[c+5];let u=i*6;l[u]=Math.min(l[r],l[c]),l[u+1]=Math.min(l[r+1],l[c+1]),l[u+2]=Math.min(l[r+2],l[c+2]),l[u+3]=Math.max(l[r+3],l[c+3]),l[u+4]=Math.max(l[r+4],l[c+4]),l[u+5]=Math.max(l[r+5],l[c+5])}}this._tlasLeafBoxesOf=n}scheduleBackgroundRebuild(e,t){if(!this.instanceTable||!this.triangles)return;this._rebuildGeneration++;let n=this._rebuildGeneration,r=(e,r,i)=>{let a=this.triangles.copyOf(r.triOffset,r.triCount);this._pendingRebuilds.set(e,i),i.onmessage=a=>{let o=a.data;if(i.terminate(),this._pendingRebuilds.delete(e),o.error){Xs.error(`background BLAS rebuild failed (mesh ${e}):`,o.error);return}n===this._rebuildGeneration&&this._swapBLAS(e,r,o,t)},i.onerror=t=>{Xs.error(`background BLAS rebuild worker failed (mesh ${e}):`,t),i.terminate(),this._pendingRebuilds.delete(e)},i.postMessage({triangleData:a.buffer,triangleByteOffset:a.byteOffset,triangleByteLength:a.byteLength,triangleCount:r.triCount,depth:this.config.bvhDepth,maxLeafSize:this.bvhBuilder.maxLeafSize,numBins:this.bvhBuilder.numBins,maxBins:this.bvhBuilder.maxBins,minBins:this.bvhBuilder.minBins,reportProgress:!1,sharedReorderBuffer:null,reinsertionOptimization:{enabled:this.bvhBuilder.enableReinsertionOptimization,batchSizeRatio:this.bvhBuilder.reinsertionBatchSizeRatio,maxIterations:this.bvhBuilder.reinsertionMaxIterations}},[a.buffer])};for(let t of e){let e=this._placementOf(t);if(e<0)continue;let n=this.instanceTable.entryAt(e);if(!n||!this.instanceTable.isOwner(e))continue;let i=this._pendingRebuilds.get(e);i&&i.terminate(),r(e,n,ur(Ji))}}_swapBLAS(e,t,n,r){this._geometryVersion=(this._geometryVersion??0)+1;let i=n.bvhData,a=i.length/16;if(a>t.blasNodeCount){Xs.warn(`background rebuild does not fit for mesh ${e} (${a} nodes vs ${t.blasNodeCount} reserved), skipping swap`);return}this.bvh.setRecords(t.blasOffset,i),this._offsetBLASInPlace(t.blasOffset,a,t.blasOffset,t.triOffset);let o=n.triangles;o&&this.triangles.setRecords(t.triOffset,o),this.instanceTable.setBlasNodeCount(e,a);let s=n.originalToBvh;if(s){let n=this.instanceTable.bvhToOriginalOf(e),r=new Uint32Array(t.triCount);for(let e=0;e<t.triCount;e++)r[s[e]]=n?n[e]:e;this.instanceTable.setBvhToOriginal(e,r)}this.instanceTable.recomputeAABB(e,this.bvh,this.triangles),this._refitTLAS(),this._log(`Background BLAS rebuild complete for mesh ${e}`),r?.(this.instanceTable.sourceMesh[e]??e)}cancelBackgroundRebuilds(){for(let e of this._pendingRebuilds.values())e.terminate();this._pendingRebuilds.clear()}_disposeRefitWorker(){this._refitWorker&&=(this._refitWorker.terminate(),null),this._refitSharedBuffers=null,this.cancelBackgroundRebuilds()}_disposeTLASWorker(){this._tlasWorker&&=(this._tlasWorker.terminate(),null)}dispose(){this._geometryVersion=(this._geometryVersion??0)+1,this._log(`Disposing resources`),this._disposeRefitWorker(),this._disposeTLASWorker(),this._disposeTextures(),this._reset(),this.textureCreator&&=(this.textureCreator.dispose(),null),this.geometryExtractor=null,this.bvhBuilder=null,this.tlasBuilder=null,this._blasRefitter=null}},rc=[[1619.19106,-.00205010916,5.02995757],[2488.45471,-.00111330907,3.22621544],[3341.43193,-.000486551192,1.76486769],[4094.61742,-.000127446582,.725731635],[4670.28036,291258199e-13,.126703442],[4595.09185,287495649e-13,.15034502],[3787.1745,935907826e-14,.399075871]],ic=[[-488.999748,.000604330754,-.0755807526],[-755.994277,.000316730098,.478306139],[-1023.63977,.00012022347,.936662319],[-1265.71316,487340896e-14,1.27054498],[-1425.29332,-401150431e-13,1.43972784],[-1175.54822,-216378048e-13,1.30408023],[-500.799571,-459832026e-14,1.09098763]],ac=[[596945309e-19,-4.85742887e-8,-970622247e-13,-.00407936148],[240430366e-19,5.55021075e-8,-.000198503712,.0289312858],[-140949732e-19,1.89878968e-7,-.000356632824,.0910767778],[-361460868e-19,2.84822009e-7,-.000493211319,.15672344],[-197075738e-19,1.75359352e-7,-.000250542825,-.0222783266],[-161997957e-21,-1.64216008e-8,.000386216271,-.738077418],[672650283e-21,-2.73078809e-8,.000424098264,-.752335691]];function oc(e){let t,n,r;if(e>=12e3)t=.8262954810464208,n=.9945080501520986,r=1.566307710274283;else if(e<800)t=5.413294490189271,n=-.20319390035873933,r=-.0822535242887164;else{let i=e>=6365?6:e>=3315?5:e>=1902?4:e>=1449?3:e>=1167?2:+(e>=965),a=rc[i],o=ic[i],s=ac[i],c=1/e;t=a[0]*c+a[1]*e+a[2],n=o[0]*c+o[1]*e+o[2],r=((s[0]*e+s[1])*e+s[2])*e+s[3]}return[Math.max(0,t),Math.max(0,n),Math.max(0,r)]}Fn();var sc=1/(4*Math.PI);function cc(e){let t=e.userData||{},n=Number.isFinite(t.exposure)?t.exposure:0,r=e.intensity*2**n,i=[e.color.r,e.color.g,e.color.b];if(t.useTemperature){let[e,n,r]=oc(t.temperature??6500);i[0]*=e,i[1]*=n,i[2]*=r}return jn(i),{r:i[0],g:i[1],b:i[2],intensity:r}}var lc=class{constructor(){this.lightData={directional:[],rectArea:[],point:[],spot:[]},this.directionalLightCache=[],this.areaLightCache=[],this.pointLightCache=[],this.spotLightCache=[]}clear(){this.lightData.directional=[],this.lightData.rectArea=[],this.lightData.point=[],this.lightData.spot=[],this.directionalLightCache=[],this.areaLightCache=[],this.pointLightCache=[],this.spotLightCache=[]}calculateLightImportance(e,t=`directional`){let n=.2126*e.color.r+.7152*e.color.g+.0722*e.color.b,r=e.intensity*n;if(t===`area`){let t=e.width*e.height;r*=Math.sqrt(t)}else if(t===`point`)r*=Math.sqrt(e.distance||100);else if(t===`spot`){let t=Math.sin(e.angle||Math.PI/4);r*=Math.sqrt(e.distance||100)*t}return r}addDirectionalLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n;if(e.target){e.target.updateMatrixWorld();let i=e.target.getWorldPosition(new r.Vector3);n=t.sub(i).normalize()}else n=t.normalize();let i=this.calculateLightImportance(e,`directional`),a=e.userData.angle||e.angle||0,o=cc(e),s=e.userData?.gobo,c=s&&Number.isInteger(s.index)?s.index:-1,l=s&&typeof s.intensity==`number`?s.intensity:1,u=s&&s.inverted?-Math.abs(l):Math.abs(l),d=s&&typeof s.scale==`number`?s.scale:5;this.directionalLightCache.push({data:[n.x,n.y,n.z,o.r,o.g,o.b,o.intensity,a,c,u,d,0],importance:i,light:e})}addRectAreaLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=e.getWorldQuaternion(new r.Quaternion),i=e.getWorldScale(new r.Vector3),a=e.width*i.x*.5,o=e.height*i.y*.5,s=new r.Vector3(a,0,0).applyQuaternion(n),c=new r.Vector3(0,-o,0).applyQuaternion(n),l=this.calculateLightImportance(e,`area`),u=e.userData?.normalize??!0?1:0,d=Number.isFinite(e.userData?.spread)?e.userData.spread:Math.PI,f=+(e.userData?.shape===`ellipse`||e.userData?.shape===`disk`||e.userData?.shape===1),p=cc(e);this.areaLightCache.push({data:[t.x,t.y,t.z,s.x,s.y,s.z,c.x,c.y,c.z,p.r,p.g,p.b,p.intensity,u,d,f],importance:l,light:e})}addPointLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=this.calculateLightImportance(e,`point`),i=cc(e);this.pointLightCache.push({data:[t.x,t.y,t.z,i.r,i.g,i.b,i.intensity*sc,e.distance||0,e.decay===void 0?2:e.decay],importance:n,light:e})}addSpotLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=(e.target?e.target.getWorldPosition(new r.Vector3):new r.Vector3(0,0,-1)).sub(t).normalize(),i=this.calculateLightImportance(e,`spot`),a=e.userData?.gobo,o=a&&Number.isInteger(a.index)?a.index:-1,s=a&&typeof a.intensity==`number`?a.intensity:1,c=a&&a.inverted?-Math.abs(s):Math.abs(s),l=e.userData?.ies,u=l&&Number.isInteger(l.index)?l.index:-1,d=l&&typeof l.intensity==`number`?l.intensity:1,f=cc(e);this.spotLightCache.push({data:[t.x,t.y,t.z,n.x,n.y,n.z,f.r,f.g,f.b,f.intensity*sc,e.angle||Math.PI/4,e.penumbra||0,e.distance||0,e.decay===void 0?2:e.decay,o,c,u,d,0,0],importance:i,light:e})}preprocessLights(){this.directionalLightCache.sort((e,t)=>t.importance-e.importance),this.areaLightCache.sort((e,t)=>t.importance-e.importance),this.pointLightCache.sort((e,t)=>t.importance-e.importance),this.spotLightCache.sort((e,t)=>t.importance-e.importance),this.lightData.directional=[],this.lightData.rectArea=[],this.lightData.point=[],this.lightData.spot=[],this.directionalLightCache.forEach(e=>{this.lightData.directional.push(...e.data)}),this.areaLightCache.forEach(e=>{this.lightData.rectArea.push(...e.data)}),this.pointLightCache.forEach(e=>{this.lightData.point.push(...e.data)}),this.spotLightCache.forEach(e=>{this.lightData.spot.push(...e.data)}),this.areaLightCache.length>0&&console.log(`Preprocessed ${this.areaLightCache.length} area lights by importance`),this.pointLightCache.length>0&&console.log(`Preprocessed ${this.pointLightCache.length} point lights by importance`),this.spotLightCache.length>0&&console.log(`Preprocessed ${this.spotLightCache.length} spot lights by importance`)}updateShaderUniforms(e){let t=Math.floor(this.lightData.directional.length/12),n=Math.floor(this.lightData.rectArea.length/16),r=Math.floor(this.lightData.point.length/9),i=Math.floor(this.lightData.spot.length/20);e.defines.MAX_DIRECTIONAL_LIGHTS=t,e.defines.MAX_AREA_LIGHTS=n,e.defines.MAX_POINT_LIGHTS=r,e.defines.MAX_SPOT_LIGHTS=i,e.uniforms.directionalLights.value=new Float32Array(this.lightData.directional),e.uniforms.areaLights.value=new Float32Array(this.lightData.rectArea),e.uniforms.pointLights.value=new Float32Array(this.lightData.point),e.uniforms.spotLights.value=new Float32Array(this.lightData.spot),e.needsUpdate=!0}processSceneLights(e,t){this.clear(),e.traverse(e=>{e.isDirectionalLight?this.addDirectionalLight(e):e.isRectAreaLight?this.addRectAreaLight(e):e.isPointLight?this.addPointLight(e):e.isSpotLight&&this.addSpotLight(e)}),this.preprocessLights(),this.updateShaderUniforms(t)}getLightStatistics(){return{directionalLights:this.directionalLightCache.map(e=>({intensity:e.light.intensity,importance:e.importance,color:e.light.color})),areaLights:this.areaLightCache.map(e=>({intensity:e.light.intensity,importance:e.importance,color:e.light.color,size:e.light.width*e.light.height}))}}},uc,dc,fc,pc,mc,hc,gc,_c,vc,yc,bc,xc,Sc,Cc,wc,Tc,Ec=g((()=>{uc=C({origin:`vec3`,direction:`vec3`}),dc=C({color:`vec4`,emissive:`vec3`,emissiveIntensity:`float`,roughness:`float`,metalness:`float`,ior:`float`,transmission:`float`,thickness:`float`,clearcoat:`float`,clearcoatRoughness:`float`,opacity:`float`,transparent:`bool`,attenuationColor:`vec3`,attenuationDistance:`float`,dispersion:`float`,sheen:`float`,sheenRoughness:`float`,sheenColor:`vec3`,specularIntensity:`float`,specularColor:`vec3`,alphaTest:`float`,alphaMode:`int`,side:`int`,depthWrite:`int`,albedoMapIndex:`int`,emissiveMapIndex:`int`,normalMapIndex:`int`,bumpMapIndex:`int`,bumpScale:`float`,displacementScale:`float`,metalnessMapIndex:`int`,roughnessMapIndex:`int`,displacementMapIndex:`int`,normalScale:`vec2`,albedoTransform:`mat3`,emissiveTransform:`mat3`,normalTransform:`mat3`,bumpTransform:`mat3`,metalnessTransform:`mat3`,roughnessTransform:`mat3`,displacementTransform:`mat3`,iridescence:`float`,iridescenceIOR:`float`,iridescenceThicknessRange:`vec2`,subsurface:`float`,subsurfaceColor:`vec3`,subsurfaceRadius:`vec3`,subsurfaceRadiusScale:`float`,subsurfaceAnisotropy:`float`,anisotropy:`float`,anisotropyRotation:`float`,anisotropyMapIndex:`int`,transmissionMapIndex:`int`,clearcoatMapIndex:`int`,clearcoatRoughnessMapIndex:`int`,sheenColorMapIndex:`int`,sheenRoughnessMapIndex:`int`,iridescenceMapIndex:`int`,iridescenceThicknessMapIndex:`int`,specularIntensityMapIndex:`int`,specularColorMapIndex:`int`,diffuseTransmission:`float`,diffuseTransmissionColor:`vec3`,diffuseTransmissionMapIndex:`int`,diffuseTransmissionColorMapIndex:`int`}),fc=C({transmission:`float`,clearcoat:`float`,clearcoatRoughness:`float`,sheenColor:`vec3`,sheenRoughness:`float`,iridescence:`float`,iridescenceThickness:`float`,specularIntensity:`float`,specularColor:`vec3`,diffuseTransmission:`float`,diffuseTransmissionColor:`vec3`}),pc=C({color:`vec4`,ior:`float`,transmission:`float`,attenuationColor:`vec3`,attenuationDistance:`float`,albedoMapIndex:`int`,opacity:`float`,transparent:`bool`,alphaTest:`float`,alphaMode:`int`,albedoTransform:`mat3`}),mc=C({shadowed:`vec3`,unoccluded:`vec3`}),C({position:`vec3`,radius:`float`,material:dc}),hc=C({didHit:`bool`,dst:`float`,hitPoint:`vec3`,normal:`vec3`,uv:`vec2`,materialIndex:`int`,meshIndex:`int`,instanceLeaf:`int`,triangleIndex:`int`,boxTests:`int`,triTests:`int`}),C({posA:`vec3`,posB:`vec3`,posC:`vec3`,uvA:`vec2`,uvB:`vec2`,uvC:`vec2`,normalA:`vec3`,normalB:`vec3`,normalC:`vec3`,material:dc,materialIndex:`int`,meshIndex:`int`}),C({color:`vec4`,samples:`int`}),gc=C({direction:`vec3`,value:`vec3`,pdf:`float`,isTransmission:`bool`,colorWeight:`vec3`,isDiffuseTransmission:`bool`}),_c=C({specular:`float`,diffuse:`float`,sheen:`float`,clearcoat:`float`,transmission:`float`,iridescence:`float`,diffuseTransmission:`float`}),vc=C({Ta:`vec3`,Ba:`vec3`}),yc=C({NoL:`float`,NoV:`float`,NoH:`float`,VoH:`float`,LoH:`float`,ToH:`float`,BoH:`float`,ToV:`float`,BoV:`float`,ToL:`float`,BoL:`float`}),bc=C({compensation:`vec3`,E_total:`vec3`}),xc=C({f0:`vec3`,f90:`float`,eta:`float`,F0m:`vec3`,F0:`vec3`}),Sc=C({albedo:`vec4`,emissive:`vec3`,metalness:`float`,roughness:`float`,normal:`vec3`,hasTextures:`bool`}),Cc=C({isMetallic:`bool`,isRough:`bool`,isSmooth:`bool`,isTransmissive:`bool`,hasClearcoat:`bool`,isEmissive:`bool`,complexityScore:`float`}),wc=C({albedoUV:`vec2`,normalUV:`vec2`,metalnessUV:`vec2`,emissiveUV:`vec2`,bumpUV:`vec2`,roughnessUV:`vec2`,normalBumpSameUV:`bool`,metalRoughSameUV:`bool`,albedoEmissiveSameUV:`bool`,allSameUV:`bool`}),Tc=C({invRoughness:`float`,metalFactor:`float`,iorFactor:`float`,maxSheenColor:`float`}),C({traversals:`int`,transmissiveTraversals:`int`,rayType:`int`,isPrimaryRay:`bool`,actualBounceDepth:`int`})})),Dc,Oc,kc,Ac,jc,Mc,Nc,Pc,Fc,Ic,Lc,Rc,zc,Bc,Vc,Hc,Uc,Wc,Gc,Kc,qc,Jc,Yc,Xc,Zc,Qc,$c,el,Z,tl,nl,rl,il,al,ol,sl,cl,ll,ul,dl,fl,pl,ml=g((()=>{Ec(),wt(),Dc=(0,n.wgslFn)(`
248
248
  fn offsetRayOrigin( p: vec3f, n: vec3f ) -> vec3f {
249
249
  let step = select( vec3<i32>( 32 ), vec3<i32>( -32 ), ( p < vec3f( 0.0 ) ) != ( n < vec3f( 0.0 ) ) );
250
250
  let far = bitcast<vec3f>( bitcast<vec3<i32>>( p ) + step );
@@ -1444,4 +1444,4 @@ fn ${e}( c: vec3<f32> ) -> vec3<f32> {
1444
1444
  return c000 + ( v1 - c000 ) * w.x + ( v2 - v1 ) * w.y + ( v3 - v2 ) * w.z;
1445
1445
  }
1446
1446
  `}function hT({sampler:e,apply:t,count:n=4e3,seed:r=31337}){let i=r>>>0,a=()=>(i=i*1664525+1013904223>>>0)/4294967296,o=[];for(let e=0;e<n;e++){let e=.18*2**(-7+a()*13),t=a()**1.2,n=a()*6,r=[0,1,2].map(e=>1-t*Math.min(1,Math.abs((n+e*2)%6-3))),i=Math.max(...r)||1;o.push(r.map(t=>Math.max(t,0)/i*e))}let s=new Float32Array(o.length*4);o.forEach((e,t)=>{s[t*4]=e[0],s[t*4+1]=e[1],s[t*4+2]=e[2],s[t*4+3]=1}),t(s);let c=[0,0,0],l=[];for(let t=0;t<o.length;t++){e(o[t][0],o[t][1],o[t][2],c);for(let e=0;e<3;e++)l.push(Math.abs(c[e]-s[t*4+e])*255)}return l.sort((e,t)=>e-t),{mean:l.reduce((e,t)=>e+t,0)/l.length,p95:l[Math.floor(l.length*.95)],max:l[l.length-1],samples:l.length}}X(),ko();var gT=-12.47393,_T=12.5260688117,vT=65,yT=null,bT=new Map;function xT(e){yT=e}function ST(){let e=Sw();if(!e)throw Error(`load an OCIO config first`);if(!e.config)throw Error(`OCIO runtime exposes no Config handle`);return e.config}function CT({source:e,display:t,view:n,look:r,context:i}){let a=ST(),o=i?{context:i}:void 0;return r?a.createGroupTransformProcessor([{type:`look`,source:e,destination:e,looks:r},{type:`displayView`,source:e,display:t,view:n}],o):a.createDisplayViewProcessor({source:e,display:t,view:n,...i?{context:i}:{}})}function wT({texture:e,size:t,minEv:r,maxEv:i}){let a=t-1,o=i-r,s=t=>(0,n.texture3DLoad)(e,(0,n.clamp)(t,(0,n.ivec3)(0),(0,n.ivec3)(a))).rgb;return(0,n.Fn)(([e,i])=>{let c=(0,n.clamp)((0,n.log2)((0,n.max)((0,n.max)(e.mul(i),(0,n.vec3)(0)),(0,n.vec3)(1e-10))).sub((0,n.float)(r)).div((0,n.float)(o)),(0,n.vec3)(0),(0,n.vec3)(1)).mul((0,n.float)(a)).toVar(),l=(0,n.clamp)((0,n.ivec3)((0,n.floor)(c)),(0,n.ivec3)(0),(0,n.ivec3)(t-2)).toVar(),u=(0,n.clamp)(c.sub((0,n.vec3)(l)),(0,n.vec3)(0),(0,n.vec3)(1)).toVar(),d=(0,n.vec3)(0).toVar(),f=(0,n.ivec3)(0).toVar(),p=(0,n.ivec3)(0).toVar(),m=(0,n.ivec3)(1).toVar();(0,n.If)(u.x.greaterThan(u.y),()=>{(0,n.If)(u.y.greaterThan(u.z),()=>{d.assign((0,n.vec3)(u.x,u.y,u.z)),f.assign((0,n.ivec3)(1,0,0)),p.assign((0,n.ivec3)(1,1,0)),m.assign((0,n.ivec3)(1,1,1))}).ElseIf(u.x.greaterThan(u.z),()=>{d.assign((0,n.vec3)(u.x,u.z,u.y)),f.assign((0,n.ivec3)(1,0,0)),p.assign((0,n.ivec3)(1,0,1)),m.assign((0,n.ivec3)(1,1,1))}).Else(()=>{d.assign((0,n.vec3)(u.z,u.x,u.y)),f.assign((0,n.ivec3)(0,0,1)),p.assign((0,n.ivec3)(1,0,1)),m.assign((0,n.ivec3)(1,1,1))})}).Else(()=>{(0,n.If)(u.z.greaterThan(u.y),()=>{d.assign((0,n.vec3)(u.z,u.y,u.x)),f.assign((0,n.ivec3)(0,0,1)),p.assign((0,n.ivec3)(0,1,1)),m.assign((0,n.ivec3)(1,1,1))}).ElseIf(u.z.greaterThan(u.x),()=>{d.assign((0,n.vec3)(u.y,u.z,u.x)),f.assign((0,n.ivec3)(0,1,0)),p.assign((0,n.ivec3)(0,1,1)),m.assign((0,n.ivec3)(1,1,1))}).Else(()=>{d.assign((0,n.vec3)(u.y,u.x,u.z)),f.assign((0,n.ivec3)(0,1,0)),p.assign((0,n.ivec3)(1,1,0)),m.assign((0,n.ivec3)(1,1,1))})});let h=s(l).toVar(),g=s(l.add(f)).toVar(),_=s(l.add(p)).toVar(),v=s(l.add(m)).toVar();return h.add(g.sub(h).mul(d.x)).add(_.sub(g).mul(d.y)).add(v.sub(_).mul(d.z))})}function TT({display:e,view:t,look:n=null,context:r=null,source:i=null,size:a=65,minEv:o=gT,maxEv:s=_T,id:c=null,name:l=null}={}){let u=Cw();if(!u)throw Error(`load an OCIO config first`);let d=u.roles.find(e=>e.name===`scene_linear`)?.colorSpace,f=i??d;if(!f)throw Error(`config has no scene_linear role — pass an explicit source space`);if(!u.displays.includes(e))throw Error(`config has no display "${e}" — has ${u.displays.join(`, `)}`);let p=(u.viewsByDisplay[e]??[]).map(e=>e.name);if(!p.includes(t))throw Error(`display "${e}" has no view "${t}" — has ${p.join(`, `)}`);if(n&&!u.looks.some(e=>e.name===n))throw Error(`config has no look "${n}" — has ${u.looks.map(e=>e.name).join(`, `)}`);cw(e)===null&&yT?.warn(Y.VIEW_TRANSFORM_DISPLAY_MISMATCH,`"${e}" is not an sRGB-class SDR display, which is all the canvas is configured for — its view will be shown clipped or in the wrong gamut on screen, though a saved buffer is right`,{display:e,view:t});let m=CT({source:f,display:e,view:t,look:n,context:r}),h=e=>m.applyRGBAF32(e),g,_;try{g=cT(sT({size:a,minEv:o,maxEv:s,apply:h})),_=hT({sampler:pT({data:g,size:a,minEv:o,maxEv:s}),apply:h})}finally{m.dispose()}return DT({id:c,half:g,error:_,name:l??(n?`${t} + ${n} (${e})`:`${t} (${e})`),ocio:{display:e,view:t,look:n,context:r,source:f,configId:u.id,size:a,minEv:o,maxEv:s}})}function ET(e,t=null){let{name:n,data:r,error:i,configId:a,display:o,view:s,look:c,context:l,source:u,size:d,minEv:f,maxEv:p,fingerprint:m,ocioVersion:h}=e;return DT({id:t,name:n,error:i,half:r,ocio:{display:o,view:s,look:c??null,context:l??null,source:u,configId:a,size:d,minEv:f,maxEv:p,baked:{fingerprint:m??null,ocioVersion:h??null}}})}function DT({id:e,name:t,half:n,error:i,ocio:a}){let{size:o,minEv:s,maxEv:c}=a,l=pT({data:n,size:o,minEv:s,maxEv:c}),u=e??po(),d=`TM_OCIO_${u}`,f=`tm_ocio_${u}`,p=bT.get(u),m=p&&p.size===o&&p.minEv===s&&p.maxEv===c,h,g;return m?(h=p.texture,h.image.data=n,h.needsUpdate=!0,g=p.tsl):(p?.texture.dispose(),h=new r.Data3DTexture(n,o,o,o),h.format=r.RGBAFormat,h.type=r.HalfFloatType,h.minFilter=r.NearestFilter,h.magFilter=r.NearestFilter,h.wrapS=h.wrapT=h.wrapR=r.ClampToEdgeWrapping,h.needsUpdate=!0,g=wT({texture:h,size:o,minEv:s,maxEv:c})),bT.set(u,{texture:h,tsl:g,size:o,minEv:s,maxEv:c}),{id:u,name:t,wgslConst:d,source:`ocio`,outputEncoded:!0,appliesExposure:!0,cpu:(e,t,n,r,i)=>l(e*r,t*r,n*r,i),wgsl:mT({fnName:f,texName:`${d.toLowerCase()}_tex`,size:o,minEv:s,maxEv:c}),call:`${f}( c )`,tsl:g,table:{data:n,size:o,texture:h},error:i,ocio:a}}function OT(e){return mo(TT(e))}function kT({display:e=null,look:t=null,context:n=null,source:r=null,size:i=65}={}){let a=Cw();if(!a)throw Error(`load an OCIO config first`);let o=e??a.defaultDisplay,s=a.viewsByDisplay[o]??[],c=[],l=[];for(let e of s){if(e.colorSpace&&e.colorSpace!==`<USE_DISPLAY_NAME>`&&a.colorSpaces.find(t=>t.name===e.colorSpace)?.isData){l.push({view:e.name,reason:`data view`});continue}try{c.push(OT({display:o,view:e.name,look:t,context:n,source:r,size:i}))}catch(t){l.push({view:e.name,reason:t.message}),yT?.warn(Y.VIEW_TRANSFORM_BAKE_FAILED,`could not bake "${e.name}" (${o}): ${t.message}`,{display:o,view:e.name})}}return{added:c,skipped:l}}function AT(e){let t=bT.get(e);t&&(t.texture.dispose(),bT.delete(e))}function jT(e=null){for(let t of Eo.values())t.source===`ocio`&&!e?.has(t.id)&&t.table?.texture?.dispose?.();for(let[t,n]of bT)e?.has(t)||(n.texture.dispose(),bT.delete(t))}var MT=[82,90,86,84],NT=`rayzee-baked-view`,PT=15360;async function FT(e,t){return new Uint8Array(await new Response(new Blob([e]).stream().pipeThrough(t)).arrayBuffer())}async function IT(e,t={}){let n=e?.table?.data;if(e?.source!==`ocio`||!(n instanceof Uint16Array))throw Error(`only a baked OCIO view can be saved`);let{size:r,minEv:i,maxEv:a}=e.ocio,o=r*r*r;if(n.length!==o*4)throw Error(`table holds ${n.length} values, expected ${o*4}`);let s=new Uint8Array(o*6);for(let e=0;e<3;e++)for(let t=0;t<o;t++){if(e===0&&n[t*4+3]!==PT)throw Error(`table alpha is not 1`);let i=n[t*4+e]-(t%r?n[(t-1)*4+e]:0)&65535;s[e*o+t]=i>>8,s[3*o+e*o+t]=i&255}let{display:c,view:l,look:u,context:d,source:f,configId:p}=e.ocio,m=new TextEncoder().encode(JSON.stringify({format:NT,version:1,name:e.name,configId:p,display:c,view:l,look:u??null,context:d??null,source:f,size:r,minEv:i,maxEv:a,error:e.error??null,...t})),h=new Uint8Array(8+m.length+s.length);return h.set(MT,0),new DataView(h.buffer).setUint32(4,m.length,!0),h.set(m,8),h.set(s,8+m.length),await FT(h,new CompressionStream(`gzip`))}async function LT(e){let t=await FT(e,new DecompressionStream(`gzip`));if(t.length<8||MT.some((e,n)=>t[n]!==e))throw Error(`not a baked view file`);let n=new DataView(t.buffer,t.byteOffset).getUint32(4,!0),r=JSON.parse(new TextDecoder().decode(t.subarray(8,8+n)));if(r.format!==NT||r.version!==1)throw Error(`unsupported baked view ${r.format} v${r.version}`);let{size:i,minEv:a,maxEv:o}=r;if(!Number.isInteger(i)||i<2||i>129||!(a<o))throw Error(`baked view has a bad table shape`);let s=i*i*i,c=t.subarray(8+n);if(c.length!==s*6)throw Error(`baked view holds ${c.length} bytes of table, expected ${s*6}`);let l=new Uint16Array(s*4);for(let e=0;e<3;e++){let t=0;for(let n=0;n<s;n++)n%i===0&&(t=0),t=t+(c[e*s+n]<<8|c[3*s+e*s+n])&65535,l[n*4+e]=t}for(let e=0;e<s;e++)l[e*4+3]=PT;return{...r,data:l}}async function RT({builtin:e,text:t,files:n=[],configPath:r=`config.ocio`}={}){if(e)return`builtin:${e}`;let i=globalThis.crypto?.subtle;if(!i)return null;let a=e=>Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``),o=async e=>a(await i.digest(`SHA-256`,e)),s=await Promise.all(n.map(async e=>`${e.relativePath??e.path??e.name}:${await o(e.data)}`));return t!==void 0&&s.push(`text:${await o(new TextEncoder().encode(t))}`),s.sort(),s.unshift(`config:${r}`),`sha256:${await o(new TextEncoder().encode(s.join(`
1447
- `)))}`}var zT=[],BT=0;function VT(){return BT}function HT(){BT++}function UT(e,t){zT.unshift({match:e,colorSpace:t}),BT++}function WT(){zT.length!==0&&(zT.length=0,BT++)}function GT(){return zT.map(e=>({match:String(e.match),colorSpace:e.colorSpace}))}function KT(e){if(!e)return null;for(let t of zT)if(t.match instanceof RegExp?t.match.test(e):e.includes(t.match))return t.colorSpace;return null}function qT(){return Cw()?.fileRules.map(e=>({index:e.index,name:e.name,colorSpace:e.colorSpace,pattern:e.pattern,extension:e.extension,regex:e.regex}))??[]}function JT(e){let t=Cw();if(!t)return null;let n=e=>t.roles.find(t=>t.name===e)?.colorSpace??null;return e===r.NoColorSpace?n(`data`):e===r.SRGBColorSpace?n(`texture_paint`)??n(`color_picking`)??t.colorSpaces.find(e=>/^srgb\b/i.test(e.name)&&!/display/i.test(e.name))?.name??null:e===r.LinearSRGBColorSpace?t.colorSpaces.find(e=>/^lin(ear)?[\s_-]*(rec\.?\s*)?709/i.test(e.name))?.name??t.colorSpaces.find(e=>/^linear.*srgb/i.test(e.name))?.name??n(`scene_linear`):null}function YT(e,{threeColorSpace:t=null}={}){if(!Cw())return null;let n=KT(e);if(n)return{colorSpace:n,via:`override`,rule:null};let r=Sw();if(r&&e){let t=r.matchFileRule(e);if(t&&!t.isDefaultRule&&rT(t.colorSpace))return{colorSpace:t.colorSpace,via:`rule`,rule:{index:t.ruleIndex,name:t.ruleName}}}let i=JT(t);if(i)return{colorSpace:i,via:`three`,rule:null};let a=Sw();if(a&&e){let t=a.matchFileRule(e);if(t&&rT(t.colorSpace))return{colorSpace:t.colorSpace,via:`rule`,rule:{index:t.ruleIndex,name:t.ruleName,isDefault:t.isDefaultRule}}}return null}function XT(e){if(!e)return!1;if(e.colorSpace===r.NoColorSpace)return!0;let t=e.userData?.ocioColorSpace;return!!(t&&nT(t))}function ZT(e,t){return t??e.userData?.sourcePath??(e.name||null)??e.image?.src??null}function QT(e,t=null){if(!Cw()||!e)return null;let n=e.userData?.ocioColorSpace;return n?rT(n)?{colorSpace:n,via:`tag`,rule:null}:null:XT(e)?null:YT(ZT(e,t),{threeColorSpace:e.colorSpace})}function $T(e,t=null){return QT(e,t)?.colorSpace??null}X(),ko(),Fn();function eE(e){return cw(e)??`srgb`}var tE=[`Linear Rec.709 (sRGB)`,`lin_rec709_srgb`,`lin_rec709`,`lin_srgb`,`Linear Rec.709`,`Utility - Linear - sRGB`,`Utility - Linear - Rec.709`,`Linear BT.709`,`linrec709`],nE=/^(lin(ear)?[\s_-]*(rec\.?\s*|bt\.?\s*)?709|linear[\s_-]*\(?srgb\)?$|utility - linear - (srgb|rec\.?709))/i;function rE(e){if(!e)return null;let t=e.colorSpaces.filter(e=>!e.isData),n=e=>[e.name,...e.aliases??[]];for(let e of tE){let r=t.find(t=>n(t).some(t=>t.toLowerCase()===e.toLowerCase()));if(r)return r.name}return t.find(e=>n(e).some(e=>nE.test(e)))?.name??null}var iE=class{constructor({issues:e=null,renderer:t=null}={}){this._issues=e,this._renderer=t,this._listeners=new Map,this._workingSpace=null,this._activeView=null,this._exportSpace=null,this._context=null,this._lastUsed=new Map,this._useClock=0,this._lastBuiltin=Do,this._fingerprint=null,xT(e),this._offRegistry=co(()=>{this._renderer&&_o(this._renderer),this._emit(`transforms`)}),Ar(this)}on(e,t){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(t),()=>this._listeners.get(e)?.delete(t)}_emit(e,t=null){for(let n of this._listeners.get(e)??[])n(t);if(e!==`change`)for(let n of this._listeners.get(`change`)??[])n({event:e,detail:t})}static async listBuiltinConfigs(){return await vw()}async loadConfig({adoptWorkingSpace:e=!1,registerViews:t=!0,display:n=null,lutSize:r,...i}={}){await _w();let a=RT(i).catch(()=>null),o=await this._bakedViewsFrom(i.builtin??i.id??null,a),s;try{s=await yw(i)}catch(e){throw this._issues?.warn(Y.COLOR_CONFIG_LOAD_FAILED,`colour config failed to load; the previous one stays in effect: ${e.message}`,{builtin:i.builtin??null,configPath:i.configPath??null}),e}this._releaseViews(new Set(o.filter(e=>e.ocio.baked.ocioVersion===s.ocioVersion).map(e=>e.id))),this._fingerprint=a,HT(),Bw(),this._context=null;let c=this._workingSpace;if(e?this._workingSpace=s.sceneLinear:c&&!rT(c)&&(this._workingSpace=null),rE(Cw())||this._issues?.warn(Y.COLOR_CONFIG_LOAD_FAILED,`"${s.id}" names no linear Rec.709 space, so until a working space is adopted its views treat the render as ${s.sceneLinear} — colours will be off by that primaries change`,{sceneLinear:s.sceneLinear}),this._publishWorkingMatrix(),this._emit(`config`,s),t){let e=n??s.defaultDisplay,{added:t,skipped:i}=kT({display:e,context:this._context,source:this.workingSpace,...r?{size:r}:{}});if(t.length){let n=s.defaultViews[e],r=t.find(e=>e.ocio.view===n)??t[0];this.setActiveView(r.id)}this._emit(`transforms`,{added:t,skipped:i})}return(this._workingSpace??null)!==(c??null)&&this._emit(`workingSpace`,this.workingSpace),s}unloadConfig(){this.workingSpaceAdopted&&this._issues?.warn(Y.COLOR_CONFIG_LOAD_FAILED,`unloaded while rendering in ${this._workingSpace}; the environment stays converted into it — use app.unloadColorConfig(), which reverts the scene first`,{workingSpace:this._workingSpace}),this._releaseViews(),bw(),Bw(),WT(),HT(),this._fingerprint=null,this._workingSpace=null,this._activeView=null,this._exportSpace=null,this._context=null,On(null),this._applyRendererOutputColorSpace(),this._emit(`config`,null),this._emit(`workingSpace`,this.workingSpace)}_releaseViews(e=null){jT(e),go(e);for(let t of this._lastUsed.keys())e?.has(t)||this._lastUsed.delete(t);this._renderer&&lo(this._renderer.toneMapping)===null&&(this._renderer.toneMapping=lo(this._lastBuiltin)?this._lastBuiltin:Do,this._activeView=null,this._applyRendererOutputColorSpace())}async _bakedViewsFrom(e,t){let n=[...Eo.values()].filter(t=>t.ocio?.baked&&e!==null&&t.ocio.configId===e);if(n.length===0)return[];let r=await t;return r?n.filter(e=>e.ocio.baked.fingerprint===r):[]}async loadBakedView(e,{expect:t=null}={}){let n=await LT(e);for(let[e,r]of Object.entries(t??{}))if((n[e]??null)!==(r??null))throw Error(`baked view has ${e} "${n[e]}", expected "${r}"`);let r=ww();if(r&&(r.id!==n.configId||await this._fingerprint!==n.fingerprint))throw Error(`baked view is from "${n.configId}", not the loaded "${r.id}"`);let i=[...Eo.values()].find(e=>e.source===`ocio`&&e.ocio.display===n.display&&e.ocio.view===n.view&&(e.ocio.look??null)===(n.look??null));return i||this._makeRoomForTable(),mo(ET(n,i?.id??null))}async saveBakedView(e){let t=lo(e);if(t?.source!==`ocio`)throw Error(`no OCIO view with id ${e}`);let n=ww();return await IT(t,{configId:n?.id??t.ocio.configId,fingerprint:(n?await this._fingerprint:null)??t.ocio.baked?.fingerprint??null,ocioVersion:n?.ocioVersion??t.ocio.baked?.ocioVersion??null})}get hasConfig(){return xw()}describe(){return ww()}get workingSpace(){return this._workingSpace?this._workingSpace:xw()?this.nativeLinearSpace??ww()?.sceneLinear??`Linear Rec.709 (sRGB)`:Er}get workingSpaceAdopted(){return this._workingSpace!==null}setWorkingSpace(e){if(e!==null){if(!xw())throw Error(`load an OCIO config before choosing a working space`);if(!rT(e))throw Error(`config has no colour space "${e}"`)}(this._workingSpace??null)!==(e??null)&&(this._workingSpace=e,Pw(),this._publishWorkingMatrix(),this._rebakeViews(),this._emit(`workingSpace`,this.workingSpace))}matrixToWorking(e){return xw()?tT(e,this.workingSpace,{context:this._context}):null}listViews(){return uo()}get activeView(){return this._activeView}setActiveView(e){let t=lo(e);if(!t)throw Error(`no view transform with id ${e}`);return this._isStale(t)&&(t=this._rebakeView(t)??t),this._activeView=t.source===`ocio`?{...t.ocio,id:t.id,name:t.name}:null,this._lastUsed.set(e,++this._useClock),t.source===`builtin`&&(this._lastBuiltin=e),this._renderer&&(this._renderer.toneMapping=e),this._applyRendererOutputColorSpace(),this._emit(`view`,t),t}setView({display:e,view:t,look:n=null,size:r}={}){if(!xw())throw Error(`load an OCIO config first`);let i=[...Eo.values()].find(i=>i.source===`ocio`&&i.ocio.display===e&&i.ocio.view===t&&(i.ocio.look??null)===(n??null)&&(!r||i.ocio.size===r));i||this._makeRoomForTable();let a=i??OT({display:e,view:t,look:n,context:this._context,source:this.workingSpace,...r?{size:r}:{}});return this.setActiveView(a.id),lo(a.id)}_makeRoomForTable(){if(fo()<12)return;let e=this._renderer?.toneMapping??this._activeView?.id??null,t=[...Eo.values()].filter(t=>t.source===`ocio`&&t.id!==e).sort((e,t)=>(this._lastUsed.get(e.id)??0)-(this._lastUsed.get(t.id)??0))[0];t&&(AT(t.id),ho(t.id),this._lastUsed.delete(t.id))}setLook(e){if(!this._activeView)throw Error(`no OCIO view is active`);return this.setView({...this._activeView,look:e})}setContext(e){let t=e&&Object.keys(e).length?{...e}:null;JSON.stringify(t)!==JSON.stringify(this._context)&&(this._context=t,xw()&&(this._context&&Sw()?.invalidateContext(this._context),Pw(),this._rebakeViews()),this._emit(`context`,this._context))}get context(){return this._context}_isStale(e){return e.source!==`ocio`||!xw()?!1:e.ocio.source!==this.workingSpace||JSON.stringify(e.ocio.context??null)!==JSON.stringify(this._context??null)}_rebakeView(e){try{let t=OT({id:e.id,display:e.ocio.display,view:e.ocio.view,look:e.ocio.look,context:this._context,source:this.workingSpace,size:e.ocio.size,minEv:e.ocio.minEv,maxEv:e.ocio.maxEv}),n=e.table?.texture;return n&&n!==t.table?.texture&&n.dispose?.(),t}catch(t){return this._issues?.warn(Y.VIEW_TRANSFORM_BAKE_FAILED,`could not rebake "${e.name}": ${t.message}`,{id:e.id}),null}}_rebakeViews(){let e=this._renderer?.toneMapping??this._activeView?.id??null,t=e===null?null:lo(e);if(!t||!this._isStale(t))return;let n=this._rebakeView(t);n&&(this._activeView={...n.ocio,id:n.id,name:n.name})}attachRenderer(e){this._renderer=e,lo(e.toneMapping)?.source===`builtin`&&(this._lastBuiltin=e.toneMapping);let t=_o(e);return this._applyRendererOutputColorSpace(),t}_applyRendererOutputColorSpace(){if(!this._renderer)return;let e=lo(this._renderer.toneMapping);this._renderer.outputColorSpace=e?.outputEncoded?r.LinearSRGBColorSpace:r.SRGBColorSpace,this._applyCanvasColorSpace(e?.source===`ocio`?eE(e.ocio.display):`srgb`)}_applyCanvasColorSpace(e){let t=(this._renderer?.domElement)?.getContext?.(`webgpu`),n=t?.getConfiguration?.();if(n){if(!t.__rayzeeConfigure){let e=t.configure.bind(t);t.__rayzeeConfigure=e,t.configure=n=>e({...n,colorSpace:t.__rayzeeColorSpace??n.colorSpace})}if(t.__rayzeeColorSpace=e,n.colorSpace!==e)try{t.configure({...n,colorSpace:e})}catch(t){this._issues?.warn(Y.VIEW_TRANSFORM_DISPLAY_MISMATCH,`the canvas could not be set to ${e}: ${t.message}`,{colorSpace:e})}}}resolveInput(e,t){return YT(e,t)}textureSpace(e,t){return $T(e,t)}resolveTexture(e,t){return QT(e,t)}describeTextureSpace(e){let t=e?.userData??{},n=t.ocioColorSpace??t.__rayzeeColorSpaceChoice??null,i=null,a=t.__rayzeeOriginalColorSpace??e?.colorSpace;return xw()&&(i=QT({...e,name:e?.name,image:e?.image,colorSpace:a,userData:{}})),i||={colorSpace:a===r.SRGBColorSpace?`sRGB`:`Linear`,via:`three`},{choice:n,auto:i}}get inputKey(){return xw()?`${ww()?.id}|${this.workingSpace}|${VT()}|${JSON.stringify(this._context)}`:`-`}overrideInput(e,t){UT(e,t)}fileRules(){return qT()}toWorkingPixels(e,t){return!xw()||!t?e:Hw(e,t,this.workingSpace,{context:this._context})}get nativeLinearSpace(){return rE(Cw())}_publishWorkingMatrix(){let e=Or();e!==null&&e!==this||On(xw()?this.primariesMatrixToWorking():null,this.workingSpace)}primariesMatrixToWorking(){if(!xw()||!this.workingSpaceAdopted)return null;let e=this.nativeLinearSpace;if(!e||e===this.workingSpace)return null;let t=tT(e,this.workingSpace,{context:this._context});return t?[1,0,0,0,1,0,0,0,1].every((e,n)=>Math.abs(t[n]-e)<1e-6)?null:t:null}convertLinearTriple(e){return jn(e)}convertLinearTriples(e,t,n){return Mn(e,t,n)}convertTexturePixels(e,{space:t=null}={}){if(!xw())return!1;let n=e?.image?.data;if(!n)return!1;let r=this.nativeLinearSpace,i=e.userData?.__rayzeeColorSpace??t??r,a=this.workingSpaceAdopted?this.workingSpace:r;if(!i||!a||i===a)return!1;let o=!1;if(n instanceof Float32Array)Hw(n,i,a,{context:this._context}),o=!0;else if(n instanceof Uint16Array){let e=lT(n);Hw(e,i,a,{context:this._context}),n.set(cT(e)),o=!0}else if(n instanceof Uint8Array||n instanceof Uint8ClampedArray)Yw(n,i,a,{context:this._context,inputEncoding:`srgb`,outputEncoding:`srgb`}),o=!0;else return this._issues?.warn(Y.VIEW_TRANSFORM_BAKE_FAILED,`texture data is ${n.constructor?.name??typeof n}, which cannot be colour-converted`,{from:i,to:a}),!1;return e.userData=e.userData??{},e.userData.__rayzeeColorSpace=a,e.needsUpdate=!0,o}convertTextureBytes(e,{space:t=null,encoding:n=`srgb`}={}){if(!xw())return!1;if(t)return t===this.workingSpace?!1:(Yw(e,t,this.workingSpace,{context:this._context,inputEncoding:`raw`,outputEncoding:n}),!0);let r=this.primariesMatrixToWorking();return r?(eT(e,r,n),!0):!1}toWorkingColor(e,t){return!xw()||!t?[e[0],e[1],e[2]]:Vw(e,t,this.workingSpace,{context:this._context})}convert(e,t,n){return Vw(e,t,n,{context:this._context})}get exportSpace(){return this._exportSpace}setExportSpace(e){if(e!=null){if(!xw())throw Error(`load an OCIO config before choosing an export space`);if(!rT(e))throw Error(`config has no colour space "${e}"`)}this._exportSpace=e??null,this._emit(`export`,this._exportSpace)}exportPixels(e,t=void 0){let n=t===void 0?this._exportSpace:t;return!n||!xw()?{rgba:e,colorSpace:this.workingSpace}:(Hw(e,this.workingSpace,n,{context:this._context}),{rgba:e,colorSpace:n})}status(){let e=ww(),t=this._renderer?lo(this._renderer.toneMapping):null;return{config:e,workingSpace:this.workingSpace,workingSpaceAdopted:this.workingSpaceAdopted,activeTransform:t?{id:t.id,name:t.name,source:t.source}:null,activeView:this._activeView,context:this._context,exportSpace:this._exportSpace,views:uo(),registryVersion:so(),bakeError:t?.error??null}}dispose(){this._offRegistry?.(),this._listeners.clear(),this._releaseViews(),xT(null),this._renderer=null,this._issues=null,Or()===this&&(On(null),kr(null))}static resetAll(){kr(null),On(null),jT(),yo(),Bw(),WT(),Dw()}};function aE(){return xw()}var oE=new Map;function sE(e,t){return e.exclusive||t===`exclusive`&&e.shared>0?!1:(t===`exclusive`?e.exclusive=!0:e.shared++,!0)}function cE(e,t,n){let r=oE.get(e);r||(r={shared:0,exclusive:!1,queue:[]},oE.set(e,r));let i=lE(()=>{for(t===`exclusive`?r.exclusive=!1:r.shared--;r.queue.length&&sE(r,r.queue[0].mode);)r.queue.shift().grant();!r.exclusive&&r.shared===0&&r.queue.length===0&&oE.delete(e)});return r.queue.length===0&&sE(r,t)?Promise.resolve(i):n?(!r.exclusive&&r.shared===0&&r.queue.length===0&&oE.delete(e),Promise.resolve(null)):new Promise(e=>r.queue.push({mode:t,grant:()=>e(i)}))}function lE(e){let t=!1;return()=>{t||(t=!0,e())}}var uE=()=>typeof navigator<`u`&&navigator.locks?.request?navigator.locks:null;function dE(e,{mode:t=`exclusive`,ifAvailable:n=!1}={}){let r=uE();return r?new Promise((i,a)=>{r.request(e,{mode:t,ifAvailable:n},e=>{if(!e){i(null);return}return new Promise(e=>i(lE(e)))}).catch(a)}):cE(e,t,n)}async function fE(){let e=uE();if(!e)return new Set(oE.keys());let{held:t=[]}=await e.query();return new Set(t.map(e=>e.name))}var pE=class{constructor(){this._handlers=new Map}addEventListener(e,t){this._handlers.has(e)||this._handlers.set(e,new Set),this._handlers.get(e).add(t)}removeEventListener(e,t){this._handlers.get(e)?.delete(t)}dispatchEvent(e){for(let t of[...this._handlers.get(e.type)??[]])t.call(this,e)}},mE=class{constructor(e){this._root=e,this._writers=new Map,this._nextId=1}async _dir(e,t){let n=await this._root;for(let r of e)n=await n.getDirectoryHandle(r,{create:t});return n}async openWriter({path:e,name:t,truncate:n=!0,length:r}){let i=await(await(await this._dir(e,!0)).getFileHandle(t,{create:!0})).createSyncAccessHandle();n?i.truncate(0):r!==void 0&&i.getSize()>r&&i.truncate(r);let a=this._nextId++;return this._writers.set(a,{handle:i,end:i.getSize()}),{id:a}}write({id:e,buffer:t,byteOffset:n=0,byteLength:r,at:i}){let a=this._writers.get(e);if(!a)throw Error(`storage: writer ${e} is not open`);let o=new Uint8Array(t,n,r??t.byteLength-n),s=i??a.end,c=0;for(;c<o.length;){let e=a.handle.write(o.subarray(c),{at:s+c});if(e<=0)throw Error(`storage: write made no progress`);c+=e}return a.end=Math.max(a.end,s+o.length),{bytes:o.length}}closeWriter({id:e,abort:t=!1}){let n=this._writers.get(e);if(!n)return{size:0};this._writers.delete(e);try{return t||n.handle.flush(),{size:n.handle.getSize()}}finally{n.handle.close()}}async writeFile({path:e,name:t,buffer:n,byteOffset:r=0,byteLength:i}){let{id:a}=await this.openWriter({path:e,name:t});try{return this.write({id:a,buffer:n,byteOffset:r,byteLength:i}),this.closeWriter({id:a})}catch(e){throw this.closeWriter({id:a,abort:!0}),e}}async readRange({path:e,name:t,offset:n=0,length:r}){let i=await(await this._dir(e,!1)).getFileHandle(t),a=null;try{a=await i.createSyncAccessHandle()}catch(e){if(e.name!==`NoModificationAllowedError`)throw e}if(!a){let e=await i.getFile(),t=r===void 0?e.size:n+r;return{buffer:await e.slice(n,t).arrayBuffer()}}try{let e=a.getSize(),t=Math.max(0,Math.min(r??e-n,e-n)),i=new ArrayBuffer(t);return a.read(i,{at:n}),{buffer:i}}finally{a.close()}}dispose(){for(let e of[...this._writers.keys()])this.closeWriter({id:e,abort:!0})}},hE=class{constructor(e){this._ops=new mE(e)}async call(e,t){return this._ops[e](t)}dispose(){this._ops.dispose()}};X(),Jg(),nn();var gE=`meta.json`,_E=1,vE=36e5,yE=.3,bE=100*1024**3,xE=64*1024**2,SE=8*1024**2,CE=4,wE=3e4,TE=new TextEncoder;function EE(e,{copy:t,transfer:n}){if(typeof e==`string`&&(e=TE.encode(e)),e instanceof ArrayBuffer){if(!t||n)return{args:{buffer:e},list:[e]};let r=e.slice(0);return{args:{buffer:r},list:[r]}}if(!ArrayBuffer.isView(e))throw TypeError(`storage: write expects an ArrayBuffer, a typed array, a Blob or a string`);let{buffer:r,byteOffset:i,byteLength:a}=e,o=typeof SharedArrayBuffer<`u`&&r instanceof SharedArrayBuffer;if(!t)return{args:{buffer:r,byteOffset:i,byteLength:a},list:[]};if(o){let e=new Uint8Array(a);return e.set(new Uint8Array(r,i,a)),{args:{buffer:e.buffer},list:[e.buffer]}}if(n&&i===0&&a===r.byteLength)return{args:{buffer:r},list:[r]};let s=r.slice(i,i+a);return{args:{buffer:s},list:[s]}}async function DE(e,t){try{let n=await(await e.getFileHandle(t)).getFile();return JSON.parse(await n.text())}catch{return null}}async function*OE(e){for await(let[t,n]of e.entries())n.kind===`directory`&&(yield[t,n])}var kE=class{constructor(e,t,n,r,i){this.area=e,this.id=t,this.key=n.key,this.meta=n,this._dir=r,this._release=i}get bytes(){return this.meta.bytes}get extra(){return this.meta.extra??{}}async file(e){try{return await(await this._dir.getFileHandle(e)).getFile()}catch(t){return this.area.manager._issue(Y.STORAGE_READ_FAILED,`could not read ${this.area.name}/${this.id}/${e}`,{error:t.message}),null}}async json(e){let t=await this.file(e);return t?JSON.parse(await t.text()):null}release(){this._release?.(),this._release=null}},AE=class{constructor(e,t,n,r,i,{sizes:a={},append:o=!1}={}){this.area=e,this.id=t,this.key=n,this._info=r,this._release=i,this._writers=new Map,this._sizes={...a},this._append=o,this._done=!1,this._committedBytes=o?Object.values(a).reduce((e,t)=>e+t,0):0}get _transport(){return this.area.manager._transport}get _path(){return[this.area.name,this.id]}async _writer(e){let t=this._writers.get(e);if(!t){let n=this._append&&e in this._sizes,r=n&&(this._info.growable??[]).includes(e)?this._sizes[e]:void 0;t=this._transport.call(`openWriter`,{path:this._path,name:e,truncate:!n,length:r}),this._writers.set(e,t)}return(await t).id}async write(e,t,{at:n,transfer:r=!1}={}){this._assertOpen();let{args:i,list:a}=(typeof Blob<`u`&&t instanceof Blob?null:EE(t,{copy:!0,transfer:r}))??EE(await t.arrayBuffer(),{copy:!0,transfer:!0}),o=await this._writer(e);return this._transport.call(`write`,{id:o,at:n,...i},a)}async writeFile(e,t){this._assertOpen(),typeof Blob<`u`&&t instanceof Blob&&(t=await t.arrayBuffer());let{args:n,list:r}=EE(t,{copy:!0,transfer:!0}),{size:i}=await this._transport.call(`writeFile`,{path:this._path,name:e,...n},r);return this._sizes[e]=i,i}writeJSON(e,t){return this.writeFile(e,JSON.stringify(t))}async writeStream(e,t,{onProgress:n=null,signal:r=null,batchBytes:i=SE}={}){let a=t.getReader(),o=[],s=new Uint8Array(i),c=0,l=0,u=async()=>{if(c===0)return;let t=c===i?s:s.slice(0,c);s=new Uint8Array(i),c=0,o.push(this.write(e,t,{transfer:!0})),o.length>=CE&&await o.shift()};try{for(;;){if(r?.aborted)throw r.reason??new DOMException(`aborted`,`AbortError`);let{done:e,value:t}=await a.read();if(e)break;let o=0;for(;o<t.length;){let e=Math.min(t.length-o,i-c);s.set(t.subarray(o,o+e),c),c+=e,o+=e,l+=e,c===i&&await u()}n?.(l)}return await u(),await Promise.all(o),l}catch(e){throw a.cancel().catch(()=>{}),await Promise.allSettled(o),e}}async commit(e={}){this._assertOpen(),this._done=!0;try{for(let[e,t]of this._writers){let{size:n}=await this._transport.call(`closeWriter`,{id:(await t).id});this._sizes[e]=n}this._writers.clear();let t=Date.now(),n={v:_E,key:this.key,label:this._info.label??``,kind:this.area.kind,files:{...this._sizes},bytes:Object.values(this._sizes).reduce((e,t)=>e+t,0),createdAt:this._info.createdAt??t,lastUsed:t,pinned:this._info.pinned===!0,extra:{...this._info.extra,...e}},r=this._info.growable??[];r.length&&(n.growable=r);let{args:i,list:a}=EE(JSON.stringify(n),{copy:!1});return await this._transport.call(`writeFile`,{path:this._path,name:gE,...i},a),this.area.kind===en.CACHE&&this.area.manager._countCacheBytes(n.bytes-this._committedBytes),this.area.manager._changed(this.area.name),n}catch(e){throw await this._discard(),this.area.manager._writeFailed(this.area.name,e),e}finally{this._release?.(),this._release=null}}async abort(){if(!this._done){this._done=!0;try{this._append?await this._closeAll(!0):await this._discard()}finally{this._release?.(),this._release=null}}}async _closeAll(e){for(let t of this._writers.values())try{await this._transport.call(`closeWriter`,{id:(await t).id,abort:e})}catch{}this._writers.clear()}async _discard(){await this._closeAll(!0),await this.area._removeDir(this.id)}_assertOpen(){if(this._done)throw Error(`storage: entry ${this.area.name}/${this.id} is already committed or aborted`)}},jE=class{constructor(e,t,n){this.manager=e,this.name=t,this.kind=n}_lockName(e){return`${this.manager.namespace}:store:${this.name}:${e}`}async _dir(e=!1){try{return await this.manager._root.getDirectoryHandle(this.name,{create:e})}catch(e){if(e.name===`NotFoundError`)return null;throw e}}async _entryDir(e,t=!1){let n=await this._dir(t);if(!n)return null;try{return await n.getDirectoryHandle(e,{create:t})}catch(e){if(e.name===`NotFoundError`)return null;throw e}}async _removeDir(e){let t=await this._dir(!1);if(t)try{await t.removeEntry(e,{recursive:!0})}catch(e){if(e.name!==`NotFoundError`)throw e}}async _validMeta(e,t=null){let n=await DE(e,gE);if(!n||n.v!==_E||typeof n.key!=`string`||t!==null&&n.key!==t)return null;let r=n.growable??[];for(let[t,i]of Object.entries(n.files??{}))try{let n=await(await e.getFileHandle(t)).getFile();if(n.size!==i&&!(r.includes(t)&&n.size>i))return null}catch{return null}return n}async open(e,{wait:t=!1}={}){let n=await Rg(e),r=await dE(this._lockName(n),{mode:`shared`,ifAvailable:!t});if(!r)return null;try{let t=await this._entryDir(n),i=t?await this._validMeta(t,e):null;return i?(Date.now()-i.lastUsed>vE&&this._touch(n,i),new kE(this,n,i,t,r)):(r(),null)}catch(e){return r(),this.manager._issue(Y.STORAGE_READ_FAILED,`could not open ${this.name} entry`,{error:e.message}),null}}async has(e){let t=await this.open(e);return t?.release(),!!t}_touch(e,t){let n={...t,lastUsed:Date.now()},{args:r,list:i}=EE(JSON.stringify(n),{copy:!1});this.manager._transport.call(`writeFile`,{path:[this.name,e],name:gE,...r},i).catch(()=>{}),t.lastUsed=n.lastUsed}async create(e,{label:t=``,pinned:n=!1,expectedBytes:r=0,extra:i={},growable:a=[]}={}){let o=await Rg(e),s=await dE(this._lockName(o),{mode:`exclusive`});try{return r>0&&!await this.manager.ensureSpace(r,this.kind)?(s(),this.manager._issue(Y.STORAGE_QUOTA_EXCEEDED,`no room for ${(r/1048576).toFixed(0)} MB in ${this.name}`,{area:this.name,expectedBytes:r}),null):(await this._removeDir(o),await this._entryDir(o,!0),new AE(this,o,e,{label:t,pinned:n,extra:i,growable:a},s))}catch(e){return s(),this.manager._writeFailed(this.name,e),null}}async patchMeta(e,t){let n=await Rg(e),r=await dE(this._lockName(n),{mode:`shared`,ifAvailable:!0});if(!r)return!1;try{let r=await this._entryDir(n),i=r?await this._validMeta(r,e):null;if(!i)return!1;let{args:a,list:o}=EE(JSON.stringify({...i,...t,v:_E,key:e}),{copy:!1});return await this.manager._transport.call(`writeFile`,{path:[this.name,n],name:gE,...a},o),!0}finally{r()}}async edit(e){let t=await Rg(e),n=await dE(this._lockName(t),{mode:`exclusive`});try{let r=await this._entryDir(t),i=r?await this._validMeta(r,e):null;if(!i)return n(),null;let a={label:i.label,pinned:i.pinned,extra:i.extra,createdAt:i.createdAt,growable:i.growable};return new AE(this,t,e,a,n,{sizes:i.files,append:!0})}catch(e){return n(),this.manager._writeFailed(this.name,e),null}}async remove(e){return this.removeById(await Rg(e))}async removeById(e){let t=await dE(this._lockName(e),{mode:`exclusive`,ifAvailable:!0});if(!t)return!1;try{return await this._removeDir(e),this.manager._changed(this.name),!0}finally{t()}}async list(){let e=await this._dir(!1);if(!e)return[];let t=[];for await(let[n,r]of OE(e)){let e=await DE(r,gE);e?.v===_E&&t.push({...e,id:n})}return t}async clear(){let e=0;for(let{id:t}of await this.list())await this.removeById(t)&&e++;return e}async sweep(){let e=await this._dir(!1);if(!e)return 0;let t=await fE(),n=0;for await(let[r,i]of OE(e))t.has(this._lockName(r))||await this._validMeta(i)||await this.removeById(r)&&n++;return n}},ME=class extends pE{constructor({root:e,transport:t,namespace:n}){super(),this.namespace=n,this._root=e,this._transport=t,this._areas=new Map,this._budget=null,this._cacheTotal=null;for(let e of Object.values(tn))this.defineArea(e,{kind:e===tn.SPILL?en.SCRATCH:en.CACHE})}defineArea(e,{kind:t=en.CACHE}={}){let n=this._areas.get(e);if(n){if(n.kind!==t)throw Error(`storage: area "${e}" is already defined as ${n.kind}`);return n}let r=new jE(this,e,t);return this._areas.set(e,r),r}area(e){let t=this._areas.get(e);if(!t)throw Error(`storage: unknown area "${e}"`);return t}get areaNames(){return[...this._areas.keys()]}async estimate(){let e=typeof navigator<`u`?navigator.storage:null;if(!e?.estimate)return{quota:1/0,usage:0};let{quota:t=1/0,usage:n=0}=await e.estimate();return{quota:t,usage:n}}async persisted(){return await globalThis.navigator?.storage?.persisted?.()===!0}async persist(){let e=await globalThis.navigator?.storage?.persist?.()===!0;return this._changed(null),e}async budget(){if(this._budget!==null)return this._budget;let{quota:e}=await this.estimate();return Math.min(e*yE,bE)}setBudget(e){this._budget=e===null?null:Math.max(0,e),this._changed(null)}async _cacheBytes(){let e=this._cacheTotal;return(!e||Date.now()-e.at>wE)&&(e=this._cacheTotal={at:Date.now(),bytes:0,ready:null},e.ready=this._cacheEntries().then(t=>{e.bytes+=t.reduce((e,t)=>e+(t.meta.bytes??0),0)}),e.ready.catch(()=>{this._cacheTotal===e&&(this._cacheTotal=null)})),await e.ready,e.bytes}_countCacheBytes(e){this._cacheTotal&&(this._cacheTotal.bytes+=e)}async _cacheEntries(){let e=[];for(let t of this._areas.values())if(t.kind===en.CACHE)for(let n of await t.list())e.push({area:t,meta:n});return e}async usage(){let{quota:e,usage:t}=await this.estimate(),n={},r=0;for(let e of this._areas.values()){let t=await e.list(),i=t.reduce((e,t)=>e+(t.bytes??0),0);n[e.name]={kind:e.kind,bytes:i,entries:t.length},e.kind===en.CACHE&&(r+=i)}return{quota:e,usage:t,persisted:await this.persisted(),budget:await this.budget(),cacheBytes:r,areas:n}}async collect({freeBytes:e=null}={}){let t=await this._cacheEntries(),n=await this.budget(),r=this._cacheTotal={at:Date.now(),bytes:t.reduce((e,t)=>e+(t.meta.bytes??0),0),ready:null},i=e??Math.max(0,r.bytes-n);if(i<=0)return 0;let a=await fE(),o=t.filter(({area:e,meta:t})=>!t.pinned&&!a.has(e._lockName(t.id))).sort((e,t)=>e.meta.lastUsed-t.meta.lastUsed),s=0;for(let{area:e,meta:t}of o){if(s>=i)break;await e.removeById(t.id)&&(s+=t.bytes??0,r.bytes-=t.bytes??0)}return s}async ensureSpace(e,t=en.CACHE){let n=async()=>{let{quota:n,usage:r}=await this.estimate(),i=e+xE-(n-r);return t===en.CACHE?{free:i,budget:await this._cacheBytes()+e-await this.budget()}:{free:i,budget:0}},r=await n();return r.free<=0&&r.budget<=0?!0:(await this.collect({freeBytes:Math.max(r.free,r.budget)}),(await n()).free<=0)}async sweep(){let e=0;for(let t of this._areas.values())e+=await t.sweep(),t.kind===en.SCRATCH&&(e+=await t.clear());return e}_changed(e){this.dispatchEvent({type:`change`,area:e})}_issue(e,t,n={}){this.dispatchEvent({type:`issue`,code:e,message:t,detail:n})}_writeFailed(e,t){let n=t?.name===`QuotaExceededError`;this._issue(n?Y.STORAGE_QUOTA_EXCEEDED:Y.STORAGE_WRITE_FAILED,`${e}: ${t?.message??t}`,{area:e,error:t?.name})}dispose(){this._transport?.dispose(),this._transport=null,this._areas.clear()}};function NE({namespace:e,root:t}){let n=new hE(t);n.inline=!0;let r=new ME({root:t,transport:n,namespace:e});return r.sweep().catch(()=>{}),r}var PE="var e=class{constructor(e){this._root=e,this._writers=new Map,this._nextId=1}async _dir(e,t){let n=await this._root;for(let r of e)n=await n.getDirectoryHandle(r,{create:t});return n}async openWriter({path:e,name:t,truncate:n=!0,length:r}){let i=await(await(await this._dir(e,!0)).getFileHandle(t,{create:!0})).createSyncAccessHandle();n?i.truncate(0):r!==void 0&&i.getSize()>r&&i.truncate(r);let a=this._nextId++;return this._writers.set(a,{handle:i,end:i.getSize()}),{id:a}}write({id:e,buffer:t,byteOffset:n=0,byteLength:r,at:i}){let a=this._writers.get(e);if(!a)throw Error(`storage: writer ${e} is not open`);let o=new Uint8Array(t,n,r??t.byteLength-n),s=i??a.end,c=0;for(;c<o.length;){let e=a.handle.write(o.subarray(c),{at:s+c});if(e<=0)throw Error(`storage: write made no progress`);c+=e}return a.end=Math.max(a.end,s+o.length),{bytes:o.length}}closeWriter({id:e,abort:t=!1}){let n=this._writers.get(e);if(!n)return{size:0};this._writers.delete(e);try{return t||n.handle.flush(),{size:n.handle.getSize()}}finally{n.handle.close()}}async writeFile({path:e,name:t,buffer:n,byteOffset:r=0,byteLength:i}){let{id:a}=await this.openWriter({path:e,name:t});try{return this.write({id:a,buffer:n,byteOffset:r,byteLength:i}),this.closeWriter({id:a})}catch(e){throw this.closeWriter({id:a,abort:!0}),e}}async readRange({path:e,name:t,offset:n=0,length:r}){let i=await(await this._dir(e,!1)).getFileHandle(t),a=null;try{a=await i.createSyncAccessHandle()}catch(e){if(e.name!==`NoModificationAllowedError`)throw e}if(!a){let e=await i.getFile(),t=r===void 0?e.size:n+r;return{buffer:await e.slice(n,t).arrayBuffer()}}try{let e=a.getSize(),t=Math.max(0,Math.min(r??e-n,e-n)),i=new ArrayBuffer(t);return a.read(i,{at:n}),{buffer:i}}finally{a.close()}}dispose(){for(let e of[...this._writers.keys()])this.closeWriter({id:e,abort:!0})}};let t=null;async function n(e,t){return t||(await navigator.storage.getDirectory()).getDirectoryHandle(e,{create:!0})}self.onmessage=async({data:r})=>{let{id:i,op:a,args:o}=r;try{if(a===`init`){t=new e(n(o.namespace,o.root)),postMessage({id:i,result:{}});return}let r=await t[a](o),s=r?.buffer instanceof ArrayBuffer?[r.buffer]:[];postMessage({id:i,result:r},s)}catch(e){postMessage({id:i,error:{name:e.name,message:e.message}})}};",FE=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,PE],{type:`text/javascript;charset=utf-8`});function IE(e){let t;try{if(t=FE&&(self.URL||self.webkitURL).createObjectURL(FE),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(PE),{type:`module`,name:e?.name})}}function LE({name:e,message:t}){let n=Error(t);return n.name=e,n}var RE=class{constructor({namespace:e,root:t=null}){this._worker=new IE,this._pending=new Map,this._nextId=0,this._worker.onmessage=({data:e})=>{let t=this._pending.get(e.id);t&&(this._pending.delete(e.id),e.error?t.reject(LE(e.error)):t.resolve(e.result))},this._ready=this.call(`init`,{namespace:e,root:t})}call(e,t,n=[]){return this._worker?new Promise((r,i)=>{let a=this._nextId++;this._pending.set(a,{resolve:r,reject:i}),this._worker.postMessage({id:a,op:e,args:t},n)}):Promise.reject(Error(`storage: transport disposed`))}dispose(){this._worker?.terminate(),this._worker=null;for(let{reject:e}of this._pending.values())e(Error(`storage: transport disposed`));this._pending.clear()}};function zE(){return typeof WorkerGlobalScope<`u`&&globalThis instanceof WorkerGlobalScope}Nr();async function BE(e){let t=typeof navigator<`u`?navigator.storage:null;if(!t?.getDirectory)return{root:null,reason:`this browser has no origin private file system`};try{return{root:await(await t.getDirectory()).getDirectoryHandle(e,{create:!0})}}catch(e){return{root:null,reason:`${e.name}: ${e.message}`}}}async function VE({namespace:e,root:t=null,transport:n=`auto`}={}){let r=t?{root:t}:await BE(e);if(!r.root)return{storage:null,reason:r.reason};if(n===`inline`||n===`auto`&&(zE()||typeof Worker>`u`))return{storage:NE({namespace:e,root:r.root})};let i=new RE({namespace:e,root:t}),a=new ME({root:r.root,transport:i,namespace:e});return a.sweep().catch(()=>{}),{storage:a}}async function HE(e){let t=Mr.get(e);t||(t={refs:0,opened:VE({namespace:e})},Mr.set(e,t)),t.refs++;let{storage:n,reason:r}=await t.opened;t.storage=n;let i=!1,a=()=>{i||(i=!0,t.refs--,!(t.refs>0)&&(Mr.get(e)===t&&Mr.delete(e),n?.dispose()))};return n?{storage:n,release:a}:(a(),{storage:null,reason:r,release:()=>{}})}function UE(e){return e.length>=2&&e[0]===31&&e[1]===139}function WE(e){return e.length>=4&&e[0]===80&&e[1]===75&&(e[2]===3||e[2]===5||e[2]===7)}function GE(e){return e.length>=263&&String.fromCharCode(...e.subarray(257,262))===`ustar`}function KE(e){return UE(e)?`gzip`:WE(e)?`zip`:GE(e)?`tar`:null}function qE(e,t,n){let r=t,i=t+n;for(;r<i&&e[r]!==0;)r++;return dD.decode(e.subarray(t,r))}function JE(e,t,n){if(e[t]&128){let r=e[t]&127;for(let i=t+1;i<t+n;i++)r=r*256+e[i];return r}let r=qE(e,t,n).trim();if(!r)return 0;let i=parseInt(r,8);return Number.isFinite(i)?i:0}function YE(e){let t=[];for(let n of e.replace(/\\/g,`/`).split(`/`))n===``||n===`.`||(n===`..`?t.pop():t.push(n));return t.join(`/`)}function XE(e){let t=dD.decode(e).match(/^\d+ path=(.*)$/m);return t?t[1]:null}function ZE(e){let t=qE(e,345,155),n=qE(e,0,100);return{type:String.fromCharCode(e[156]||48),size:JE(e,124,12),name:t?`${t}/${n}`:n}}function QE(e,t){return e===`5`||e===`g`||e===`K`||t.endsWith(`/`)||e!==`0`&&e!==` `?null:YE(t)||null}function $E(e){for(let t=0;t<cD;t++)if(e[t]!==0)return!1;return!0}async function eD(e,t){if(typeof DecompressionStream<`u`&&typeof e?.stream==`function`){let n=e.stream().pipeThrough(new DecompressionStream(`gzip`)).getReader();for(;;){let{done:e,value:r}=await n.read();if(e)break;t(r)}return}let n=null,r=new m.Gunzip((e,r)=>{e instanceof Error?n=e:e&&e.length&&t(e)});await tD(e,(e,t)=>{if(r.push(e,t),n)throw n})}async function tD(e,t){if(e instanceof Uint8Array){for(let n=0;n<e.length;n+=lD){let r=Math.min(n+lD,e.length);t(e.subarray(n,r),r===e.length)}e.length===0&&t(e,!0);return}let n=e.size;for(let r=0;r<n;r+=lD){let i=Math.min(r+lD,n);t(new Uint8Array(await e.slice(r,i).arrayBuffer()),i===n)}n===0&&t(new Uint8Array,!0)}async function nD(e,t={}){let{onProgress:n,...r}=t,i=new mD(r),a=0,o=0;return await eD(e,e=>{i.push(e),a+=e.length,n&&a>=o&&(o=a+(64<<20),n({entries:i.listing.length,bytes:a}))}),i.end(),i.result()}async function rD(e,{onProgress:t=null}={}){let n=e.size,r=[],i=null,a=0,o=null,s=0,c=0,l=async(t,r)=>{if(i&&t>=a&&t+r<=a+i.length)return i.subarray(t-a,t-a+r);let o=Math.min(n,t+Math.max(r,hD));return i=new Uint8Array(await e.slice(t,o).arrayBuffer()),a=t,i.subarray(0,r)};for(;s+cD<=n;){let e=await l(s,cD);if($E(e))break;let{type:n,size:i,name:a}=ZE(e),u=o??a;o=null;let d=s+cD;if(pD(n)){let e=await l(d,i);o=n===`L`?qE(e,0,e.length):XE(e)}else{let e=QE(n,u);e&&r.push({path:e,size:i,offset:d})}s=d+fD(i),t&&s>=c&&(c=s+(256<<20),t({entries:r.length,bytes:s}))}return r}function iD({filter:e=null,sink:t=null}={}){let n=new mD({retain:()=>!1,filter:e,sink:t});return{push:e=>n.push(e),finish:()=>(n.end(),n.listing.filter(e=>e.offset!==void 0))}}async function aD(e,t={}){let{index:n=null,headersOnly:r=!1,onProgress:i=null,...a}=t,o,s,c,l,u=null;if(n||r){u=n?.listing??await rD(e,{onProgress:i});let{filter:t}=a;s=u.map(e=>!t||t(e.path,e.size)?{...e}:{path:e.path,size:e.size}),o=Object.create(null),c=0,l=!1}else{let t=new mD({...a});await tD(e,e=>t.push(e)),t.end(),{entries:o,listing:s,retainedBytes:c,truncated:l}=t.result()}let d=new Map;for(let e of s)e.offset!==void 0&&d.set(e.path,e);return{entries:o,listing:s,read:async t=>{if(o[t])return o[t];let n=d.get(t);return n?new Uint8Array(await e.slice(n.offset,n.offset+n.size).arrayBuffer()):null},readHead:async(t,n)=>{if(o[t])return o[t].subarray(0,n);let r=d.get(t);return r?new Uint8Array(await e.slice(r.offset,r.offset+Math.min(r.size,n)).arrayBuffer()):null},retainedBytes:c,truncated:l,indexed:d.size,index:u?{v:1,listing:u}:null}}function oD(e){let t=(Array.isArray(e)?e:[e]).filter(Boolean).map(e=>{let t=YE(e);return{p:t,inside:t+`/`}});return t.length===0?()=>!0:e=>{let n=e.lastIndexOf(`/`),r=n<0?``:e.slice(0,n);if(r===``)return!0;let i=r.lastIndexOf(`/textures`),a=i>=0&&i===r.length-9?r.slice(0,i)+`/`:null;for(let{p:n,inside:i}of t)if(e===n||e.startsWith(i)||i.startsWith(r+`/`)||a!==null&&i.startsWith(a))return!0;return!1}}function sD(e){let t=e.filter(e=>e.path.toLowerCase().endsWith(`.pbrt`)).sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.length-t.path.length||(e.path<t.path?-1:1));if(!t.length)return{root:null,elements:[]};let n=t[0].path,r=n.lastIndexOf(`/`),i=r<0?``:n.slice(0,r),a=i?i+`/`:``,o=new Map;for(let t of e){if(!t.path.startsWith(a))continue;let e=t.path.slice(a.length),n=e.indexOf(`/`);if(n<0)continue;let r=e.slice(0,n),i=o.get(r);i||o.set(r,i={name:r,prefix:a+r,files:0,bytes:0,scenes:0}),i.files++,i.bytes+=t.size,t.path.toLowerCase().endsWith(`.pbrt`)&&i.scenes++}return{root:i,elements:[...o.values()].filter(e=>e.scenes>0).sort((e,t)=>e.bytes-t.bytes)}}var cD,lD,uD,dD,fD,pD,mD,hD,gD=g((()=>{cD=512,lD=4<<20,uD=15e8,dD=new TextDecoder,fD=e=>e+(cD-e%cD)%cD,pD=e=>e===`L`||e===`x`||e===`X`,mD=class{constructor({filter:e=null,retain:t=null,byteBudget:n=uD,onEntry:r=null,sink:i=null}={}){this.filter=e,this.sink=i,this._sunk=0,this.retain=t,this.byteBudget=n,this.onEntry=r,this.entries=Object.create(null),this.listing=[],this.retainedBytes=0,this.truncated=!1,this.finished=!1,this._header=new Uint8Array(cD),this._headerLen=0,this._state=`header`,this._remaining=0,this._size=0,this._copied=0,this._dst=null,this._special=null,this._pendingName=null,this._abs=0}push(e){let t=this._abs;this._abs+=e.length;let n=0;for(;n<e.length&&!this.finished;)if(this._state===`header`){let r=Math.min(cD-this._headerLen,e.length-n);this._header.set(e.subarray(n,n+r),this._headerLen),this._headerLen+=r,n+=r,this._headerLen===cD&&(this._headerLen=0,this._bodyStart=t+n,this._readHeader())}else{let t=Math.min(this._remaining,e.length-n);if(this.sink&&this._indexed&&this._sinkLeft>0){let r=Math.min(t,this._sinkLeft);this.sink(e.subarray(n,n+r)),this._sinkLeft-=r}if(this._dst&&this._copied<this._size){let r=Math.min(t,this._size-this._copied);this._dst.set(e.subarray(n,n+r),this._copied),this._copied+=r}this._remaining-=t,n+=t,this._remaining===0&&this._endBody()}}end(){this.finished=!0}result(){return{entries:this.entries,listing:this.listing,retainedBytes:this.retainedBytes,truncated:this.truncated}}_readHeader(){let e=this._header,t=!0;for(let n=0;n<cD;n++)if(e[n]!==0){t=!1;break}if(t){this.finished=!0;return}let{type:n,size:r,name:i}=ZE(e),a=this._pendingName??i;if(this._pendingName=null,this._size=r,this._copied=0,this._remaining=fD(r),this._dst=null,this._special=null,this._indexed=!1,this._state=this._remaining>0?`body`:`header`,pD(n)){this._special=n===`L`?`longname`:`pax`,this._dst=new Uint8Array(r);return}let o=QE(n,a);o&&(this.listing.push({path:o,size:r}),this._indexed=this.filter?this.filter(o,r):!0,this.sink&&this._indexed&&(this._sinkStart=this._sunk,this._sinkLeft=r,this._sunk+=r),this._indexed&&!(this.retain&&!this.retain(o,r))&&(this.retainedBytes+r>this.byteBudget?this.truncated=!0:(this._dst=new Uint8Array(r),this.retainedBytes+=r)),this._remaining===0&&this._endBody())}_endBody(){if(this._state=`header`,this._special===`longname`){this._pendingName=qE(this._dst,0,this._dst.length),this._dst=null;return}if(this._special===`pax`){let e=XE(this._dst);e&&(this._pendingName=e),this._dst=null;return}let e=this.listing[this.listing.length-1];this._indexed&&e&&(e.offset=this.sink?this._sinkStart:this._bodyStart,this._indexed=!1),this._dst&&=(this.entries[e.path]=this._dst,this.onEntry?.(e.path,this._dst),null)}},hD=1<<20}));async function _D(e,t,n){return new Uint8Array(await e.slice(t,n).arrayBuffer())}function vD(e,t){return e.getUint32(t+4,!0)*4294967296+e.getUint32(t,!0)}function yD(e){let t=``;for(let n=0;n<e.length;n+=8192)t+=String.fromCharCode(...e.subarray(n,n+8192));return t}async function bD(e){let t=e.size,n=await _D(e,Math.max(0,t-kD-20),t),r=new DataView(n.buffer),i=-1;for(let e=n.length-22;e>=0;e--)if(r.getUint32(e,!0)===wD){i=e;break}if(i<0)throw Error(`zip: end of central directory not found`);let a=r.getUint16(i+10,!0),o=r.getUint32(i+12,!0),s=r.getUint32(i+16,!0);if(a===65535||o===4294967295||s===4294967295){let t=i-20;if(t<0||r.getUint32(t,!0)!==TD)throw Error(`zip: ZIP64 locator missing`);let n=vD(r,t+8),c=new DataView((await _D(e,n,n+56)).buffer);if(c.getUint32(0,!0)!==ED)throw Error(`zip: ZIP64 end record missing`);a=vD(c,32),o=vD(c,40),s=vD(c,48)}let c=await _D(e,s,s+o),l=new DataView(c.buffer),u=[],d=0;for(let e=0;e<a&&d+46<=c.length;e++){if(l.getUint32(d,!0)!==DD)throw Error(`zip: corrupt central directory`);let e=l.getUint16(d+8,!0),t=l.getUint16(d+10,!0),n=l.getUint32(d+20,!0),r=l.getUint32(d+24,!0),i=l.getUint16(d+28,!0),a=l.getUint16(d+30,!0),o=l.getUint16(d+32,!0),s=l.getUint32(d+42,!0),f=c.subarray(d+46,d+46+i),p=e&2048?AD.decode(f):yD(f);for(let e=d+46+i,t=e+a;e+4<=t;){let t=l.getUint16(e,!0),i=l.getUint16(e+2,!0);if(t===1){let t=e+4;r===4294967295&&(r=vD(l,t),t+=8),n===4294967295&&(n=vD(l,t),t+=8),s===4294967295&&(s=vD(l,t))}e+=4+i}p.endsWith(`/`)||u.push({name:p,size:r,compSize:n,method:t,local:s,encrypted:(e&1)!=0}),d+=46+i+a+o}return u}async function xD(e,t){if(t.encrypted)throw Error(`zip: "${t.name}" is encrypted`);let n=new DataView((await _D(e,t.local,t.local+30)).buffer);if(n.getUint32(0,!0)!==OD)throw Error(`zip: bad local header for "${t.name}"`);return t.local+30+n.getUint16(26,!0)+n.getUint16(28,!0)}async function SD(e,t){let n=await xD(e,t),r=await _D(e,n,n+t.compSize);if(t.method===0)return r;if(t.method===8)return t.size===0?new Uint8Array:(0,m.inflateSync)(r,{out:new Uint8Array(t.size)});throw Error(`zip: "${t.name}" uses compression method ${t.method}, which is not supported`)}async function CD(e,{filter:t=null}={}){let n=await bD(e),r=new Map,i=n.map(e=>t&&!t(e.name,e.size)?{path:e.name,size:e.size}:(r.set(e.name,e),{path:e.name,size:e.size,offset:e.local})),a=async t=>{let n=r.get(t);return n?SD(e,n):null},o=async t=>{let n=r.get(t);if(!n)return null;if(n.method!==0)return new Blob([await SD(e,n)]);let i=await xD(e,n);return e.slice(i,i+n.compSize)};return{entries:Object.create(null),listing:i,read:a,readHead:async(e,t)=>{let n=await o(e);return n?new Uint8Array(await n.slice(0,t).arrayBuffer()):null},slice:o,retainedBytes:0,truncated:!1,indexed:r.size}}var wD,TD,ED,DD,OD,kD,AD,jD=g((()=>{wD=101010256,TD=117853008,ED=101075792,DD=33639248,OD=67324752,kD=65557,AD=new TextDecoder}));async function MD(e,t){return`${e}:${Vg(await Bg(t))}`}async function ND(e,{storage:t,label:n=e.name,onProgress:r=null,filter:i=null,part:a=null}){if(!t||typeof DecompressionStream>`u`)return null;let o=t.area(tn.ARCHIVES),s=await MD(`gunzip`,e),c=s,l=await o.open(s);!l&&i&&(l=await o.open(c=`${s}|${a}`));let u=!!l;if(!l){let s=await o.create(c,i?{label:`${n} (${a})`}:{label:n,expectedBytes:e.size*LD});if(!s)return null;let u=null,d=iD(i?{filter:i,sink:e=>u.enqueue(e)}:{}),f=new TransformStream({start(e){u=e},transform(e,t){d.push(e),i||t.enqueue(e)}});try{let t=e.stream().pipeThrough(new DecompressionStream(`gzip`)).pipeThrough(f),n=await s.writeStream(`data.tar`,t,{onProgress:r});await s.writeJSON(`index.json`,{v:ID,listing:d.finish()}),await s.commit({compressedBytes:e.size,tarBytes:n})}catch(e){if(await s.abort(),e?.name!==`QuotaExceededError`)throw e;return t._issue(Y.STORAGE_QUOTA_EXCEEDED,`ran out of room unpacking ${n}; reading it in memory instead`,{area:tn.ARCHIVES}),null}if(l=await o.open(c,{wait:!0}),!l)return null}let d=await l.file(`data.tar`),f=await l.json(`index.json`);return!d||f?.v!==ID?(l.release(),null):{file:d,index:f,release:()=>l.release(),cached:u}}async function PD(e,t){if(!t)return null;let n=await t.area(tn.ARCHIVES).open(await MD(`tarindex`,e));if(!n)return null;try{let e=await n.json(`index.json`);return e?.v===ID?e:null}finally{n.release()}}async function FD(e,t,n){if(!t||!n)return!1;let r=await t.area(tn.ARCHIVES).create(await MD(`tarindex`,e),{label:`${e.name} (index)`});if(!r)return!1;try{return await r.writeJSON(`index.json`,n),await r.commit(),!0}catch{return await r.abort(),!1}}var ID,LD,RD=g((()=>{gD(),nn(),Jg(),X(),ID=1,LD=3}));function zD(e){return e.isInstancedMesh?`InstancedMesh`:e.isSkinnedMesh||e.isBatchedMesh?null:e.isMesh?`Mesh`:e.isPerspectiveCamera?`PerspectiveCamera`:e.isOrthographicCamera?`OrthographicCamera`:e.isDirectionalLight?`DirectionalLight`:e.isPointLight?`PointLight`:e.isSpotLight?`SpotLight`:e.isLight||e.isPoints||e.isLine||e.isSprite||e.isLOD?null:e.isGroup?`Group`:e.constructor===r.Object3D?`Object3D`:null}function BD(e,t){try{let t=JSON.parse(JSON.stringify(e??{}));return delete t[tO],delete t[nO],t}catch{throw new uO(`${t}: userData is not plain JSON`)}}function VD(e,t,n){if(e.isInterleavedBufferAttribute||!ArrayBuffer.isView(e.array))throw new uO(`${n}: interleaved or non-typed attribute`);return{section:t.add(e.array),itemSize:e.itemSize,normalized:e.normalized===!0,name:e.name??``}}function HD(e,t){let n=`geometry ${e.name||e.uuid}`;if(Object.keys(e.morphAttributes??{}).length)throw new uO(`${n}: morph targets`);let r={};for(let[i,a]of Object.entries(e.attributes))r[i]=VD(a,t,n);return{uuid:e.uuid,name:e.name,attributes:r,index:e.index?VD(e.index,t,n):null,groups:e.groups.map(e=>({...e})),drawRange:{...e.drawRange},userData:BD(e.userData,n)}}function UD(e,t){let n={uuid:e.uuid,userData:BD(e.userData,`texture ${e.uuid}`)};for(let t of sO)n[t]=e[t];for(let t of[`repeat`,`offset`,`center`])n[t]=e[t].toArray();n.rotation=e.rotation;let r=e.userData?.[tO];if(r)n.path=r,n.loader=e.userData.__rayzeeArchiveLoader??`image`;else if(e.isDataTexture&&ArrayBuffer.isView(e.image?.data))n.data={section:t.add(e.image.data),width:e.image.width,height:e.image.height};else throw new uO(`texture ${e.name||e.uuid}: no archive path and no pixel data to keep`);return n}function WD(e,t){let n=e.toJSON(t);n.exactColors={};for(let[t,r]of Object.entries(e))r?.isColor&&(n.exactColors[t]=[r.r,r.g,r.b]);e.ior!==void 0&&(n.exactIor=e.ior),e.diffuseTransmission!==void 0&&(n.diffuseTransmission=e.diffuseTransmission);for(let t of eO)e[t]?.isTexture&&((n.engineTextures??={})[t]=e[t].uuid);return n}function GD(e,t){for(let n of Object.values(e))n?.isTexture&&t.set(n.uuid,n)}function KD(e,{environment:t=null,animations:n=[],stats:i={}}={}){let a=new dO,o=[],s=new Map,c=new Map,l=new Map,u=(e,t)=>{let n=zD(e);if(!n)throw new uO(`${e.type} "${e.name}" cannot be cached`);let r={type:n,uuid:e.uuid,parent:t,userData:BD(e.userData,`${n} "${e.name}"`)};for(let t of lO)r[t]=e[t];if(r.position=e.position.toArray(),r.quaternion=e.quaternion.toArray(),r.scale=e.scale.toArray(),r.layers=e.layers.mask,e.matrixAutoUpdate||(r.matrix=e.matrix.toArray()),e.isMesh){s.set(e.geometry.uuid,e.geometry);let t=Array.isArray(e.material)?e.material:[e.material];for(let e of t)c.set(e.uuid,e),GD(e,l);r.geometry=e.geometry.uuid,r.material=Array.isArray(e.material)?t.map(e=>e.uuid):e.material.uuid}if(e.isInstancedMesh&&(r.count=e.count,r.instanceMatrix=a.add(e.instanceMatrix.array),r.instanceColor=e.instanceColor?a.add(e.instanceColor.array):null),e.isCamera)for(let t of[`fov`,`aspect`,`near`,`far`,`zoom`,`focus`,`filmGauge`,`filmOffset`,`left`,`right`,`top`,`bottom`])e[t]!==void 0&&(r[t]=e[t]);if(e.isLight){r.color=e.color.toArray();for(let t of cO)e[t]!==void 0&&(r[t]=e[t]);e.target&&(r.target=e.target.uuid)}let i=o.push(r)-1;for(let t of e.children)u(t,i)};u(e,-1),t&&l.set(t.uuid,t);let d={textures:{},images:{}};for(let e of l.keys())d.textures[e]={uuid:e};return{manifest:{v:2,nodes:o,geometries:[...s.values()].map(e=>HD(e,a)),textures:[...l.values()].map(e=>UD(e,a)),materials:[...c.values()].map(e=>WD(e,d)),animations:n.map(e=>r.AnimationClip.toJSON(e)),environment:t?t.uuid:null,stats:i},sections:a.sections,byteLength:a.length}}async function qD(e,{manifest:t,sections:n},{release:r=!1}={}){for(let t of n){let{offset:n,array:i}=t,a=new Uint8Array(i.buffer,i.byteOffset,i.byteLength);for(let t=0;t<a.length;t+=iO)await e.write(`data.bin`,a.subarray(t,Math.min(a.length,t+iO)),{at:n+t});r&&(t.array=null)}n.length===0&&await e.write(`data.bin`,new Uint8Array),await e.writeJSON(`graph.json`,t)}function JD(e){let t=oO[e];if(!t)throw Error(`scene graph: unknown array type ${e}`);return t}async function YD(e,t){let n=new Map,r=[...t].sort((e,t)=>e.offset-t.offset),i=null,a=0;for(let t of r){let{offset:r,byteLength:o,type:s}=t,c=JD(s),l=r+o;if(o>aO){n.set(r,new c(await e.slice(r,l).arrayBuffer()));continue}(!i||r<a||l>a+i.byteLength)&&(a=r,i=await e.slice(r,Math.min(e.size,r+aO)).arrayBuffer()),n.set(r,new c(i.slice(r-a,l-a)))}return n}function XD(e){let t=[];for(let n of e.nodes)n.instanceMatrix&&t.push(n.instanceMatrix),n.instanceColor&&t.push(n.instanceColor);for(let n of e.geometries){for(let e of Object.values(n.attributes))t.push(e.section);n.index&&t.push(n.index.section)}for(let n of e.textures)n.data&&t.push(n.data.section);return t}function ZD(e,t){let n=new r.BufferAttribute(e.get(t.section.offset),t.itemSize,t.normalized);return n.name=t.name,n}function QD(e,t){for(let n of sO)t[n]!==void 0&&(e[n]=t[n]);e.repeat.fromArray(t.repeat),e.offset.fromArray(t.offset),e.center.fromArray(t.center),e.rotation=t.rotation,e.uuid=t.uuid,Object.assign(e.userData,t.userData),e.needsUpdate=!0}async function $D(e,t,{loadTexture:n}){if(e?.v!==2)throw Error(`scene graph: unknown format`);let i=await YD(t,XD(e)),a=e=>i.get(e.offset),o={};for(let t of e.textures){let e;if(t.path){if(e=await n(t.path,t.loader),!e)throw Error(`scene graph: "${t.path}" is missing from the archive`);e.userData[tO]=t.path,e.userData[nO]=t.loader}else e=new r.DataTexture(a(t.data.section),t.data.width,t.data.height);QD(e,t),o[t.uuid]=e}let s=new r.MaterialLoader().setTextures(o),c={};for(let t of e.materials){let e=s.parse(t);for(let[n,i]of Object.entries(t.exactColors??{}))n===`diffuseTransmissionColor`&&(e[n]=new r.Color),e[n]?.setRGB(i[0],i[1],i[2]);t.exactIor!==void 0&&(e.ior=t.exactIor),t.diffuseTransmission!==void 0&&(e.diffuseTransmission=t.diffuseTransmission);for(let[n,r]of Object.entries(t.engineTextures??{}))o[r]&&(e[n]=o[r]);c[t.uuid]=e}let l={};for(let t of e.geometries){let e=new r.BufferGeometry;e.uuid=t.uuid,e.name=t.name;for(let[n,r]of Object.entries(t.attributes))e.setAttribute(n,ZD(i,r));t.index&&e.setIndex(ZD(i,t.index));for(let n of t.groups)e.addGroup(n.start,n.count,n.materialIndex);e.setDrawRange(t.drawRange.start,t.drawRange.count),e.userData=t.userData,l[t.uuid]=e}let u=[];for(let t of e.nodes){let e=Array.isArray(t.material)?t.material.map(e=>c[e]):c[t.material],n;switch(t.type){case`InstancedMesh`:n=new r.InstancedMesh(l[t.geometry],e,1),n.instanceMatrix=new r.InstancedBufferAttribute(a(t.instanceMatrix),16),n.count=t.count,t.instanceColor&&(n.instanceColor=new r.InstancedBufferAttribute(a(t.instanceColor),3));break;case`Mesh`:n=new r.Mesh(l[t.geometry],e);break;case`PerspectiveCamera`:n=new r.PerspectiveCamera;break;case`OrthographicCamera`:n=new r.OrthographicCamera;break;case`Group`:n=new r.Group;break;case`DirectionalLight`:n=new r.DirectionalLight;break;case`PointLight`:n=new r.PointLight;break;case`SpotLight`:n=new r.SpotLight;break;default:n=new r.Object3D}n.uuid=t.uuid;for(let e of lO)n[e]=t[e];if(n.position.fromArray(t.position),n.quaternion.fromArray(t.quaternion),n.scale.fromArray(t.scale),n.layers.mask=t.layers,n.userData=t.userData,t.matrix&&n.matrix.fromArray(t.matrix),n.isCamera){for(let e of[`fov`,`aspect`,`near`,`far`,`zoom`,`focus`,`filmGauge`,`filmOffset`,`left`,`right`,`top`,`bottom`])t[e]!==void 0&&(n[e]=t[e]);n.updateProjectionMatrix()}if(n.isLight){n.color.fromArray(t.color);for(let e of cO)t[e]!==void 0&&(n[e]=t[e])}u.push(n),t.parent>=0&&u[t.parent].add(n)}let d=new Map(u.map(e=>[e.uuid,e]));return e.nodes.forEach((e,t)=>{e.target&&d.has(e.target)&&(u[t].target=d.get(e.target))}),{root:u[0],environment:e.environment?o[e.environment]:null,animations:e.animations.map(e=>r.AnimationClip.parse(e)),stats:e.stats}}var eO,tO,nO,rO,iO,aO,oO,sO,cO,lO,uO,dO,fO=g((()=>{eO=[`diffuseTransmissionMap`,`diffuseTransmissionColorMap`],tO=`__rayzeeArchivePath`,nO=`__rayzeeArchiveLoader`,rO=64,iO=32<<20,aO=64<<20,oO={Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Uint8ClampedArray},sO=[`name`,`mapping`,`channel`,`wrapS`,`wrapT`,`magFilter`,`minFilter`,`anisotropy`,`format`,`type`,`flipY`,`generateMipmaps`,`premultiplyAlpha`,`unpackAlignment`,`colorSpace`],cO=[`intensity`,`distance`,`decay`,`angle`,`penumbra`],lO=[`name`,`visible`,`castShadow`,`receiveShadow`,`frustumCulled`,`renderOrder`,`matrixAutoUpdate`],uO=class extends Error{constructor(e){super(e),this.name=`SceneGraphUnsupported`}},dO=class{constructor(){this.sections=[],this.length=0}add(e){let t=Math.ceil(this.length/rO)*rO;return this.sections.push({offset:t,array:e}),this.length=t+e.byteLength,{offset:t,byteLength:e.byteLength,type:e.constructor.name,length:e.length}}}}));function pO(e){e&&hO(e)&&e.buffer.transfer(0)}function mO(e,t){let n=e.constructor;if(hO(e))return new n(e.buffer.transfer(t*n.BYTES_PER_ELEMENT));let r=new n(t);return r.set(t<e.length?e.subarray(0,t):e),r}var hO,gO=g((()=>{hO=e=>e.byteOffset===0&&e.byteLength===e.buffer.byteLength&&typeof e.buffer.transfer==`function`&&!(typeof SharedArrayBuffer<`u`&&e.buffer instanceof SharedArrayBuffer)}));function _O(e,t,n){if(n-t===0)return``;let r=!0;for(let i=t;i<n;i++)if(e[i]>127){r=!1;break}if(!r)return BO.decode(e.subarray(t,n));let i=``;for(let r=t;r<n;r++)i+=String.fromCharCode(e[r]);return i}var vO,yO,bO,xO,SO,CO,wO,TO,EO,DO,OO,kO,AO,jO,MO,NO,PO,FO,IO,LO,RO,zO,BO,VO,HO=g((()=>{vO={STRING:`string`,NUMBER:`number`,WORD:`word`,LBRACKET:`[`,RBRACKET:`]`},yO=9,bO=10,xO=12,SO=13,CO=32,wO=34,TO=35,EO=43,DO=45,OO=46,kO=48,AO=57,jO=91,MO=93,NO=69,PO=101,FO=e=>e===CO||e===yO||e===bO||e===SO||e===xO,IO=e=>e>=kO&&e<=AO,LO=15,RO=22,zO=(()=>{let e=new Float64Array(RO+1);for(let t=0;t<e.length;t++)e[t]=10**t;return e})(),BO=new TextDecoder,VO=class{constructor(e){this.bytes=typeof e==`string`?new TextEncoder().encode(e):e,this.i=0,this.n=this.bytes.length,this._ahead=null}peek(){return this._ahead===null&&(this._ahead=this._scan()),this._ahead}next(){let e=this.peek();return this._ahead=null,e}_scan(){let e=this.bytes,t=this.i,n=this.n;for(;;){for(;t<n&&FO(e[t]);)t++;if(t<n&&e[t]===TO){for(;t<n&&e[t]!==bO;)t++;continue}break}if(t>=n)return this.i=t,null;let r=e[t];if(r===jO)return this.i=t+1,{type:vO.LBRACKET};if(r===MO)return this.i=t+1,{type:vO.RBRACKET};if(r===wO){let r=++t;for(;t<n&&e[t]!==wO;)t++;if(t>=n)throw Error(`PBRT tokenizer: unterminated string literal`);return this.i=t+1,{type:vO.STRING,value:_O(e,r,t)}}if(IO(r)||r===OO&&IO(e[t+1])||(r===DO||r===EO)&&(IO(e[t+1])||e[t+1]===OO&&IO(e[t+2])))return this._scanNumber(t);let i=t;for(;t<n;){let n=e[t];if(FO(n)||n===wO||n===jO||n===MO||n===TO)break;t++}return this.i=t,{type:vO.WORD,value:_O(e,i,t)}}_scanNumber(e){let t=this.bytes,n=this.n,r=e,i=!1;t[r]===DO?(i=!0,r++):t[r]===EO&&r++;let a=0,o=0,s=0;for(;r<n&&IO(t[r]);)a=a*10+(t[r]-kO),o++,r++;if(r<n&&t[r]===OO)for(r++;r<n&&IO(t[r]);)a=a*10+(t[r]-kO),o++,s++,r++;let c=0;if(r<n&&(t[r]===PO||t[r]===NO)){let e=r+1,i=!1;if(e<n&&(t[e]===DO||t[e]===EO)&&(i=t[e]===DO,e++),e<n&&IO(t[e])){let a=0;for(;e<n&&IO(t[e]);)a=a*10+(t[e]-kO),e++;c=i?-a:a,r=e}}if(this.i=r,o===0)throw Error(`PBRT tokenizer: invalid number "${_O(t,e,r)}"`);let l=c-s;if(!(o<=LO&&l>=-RO&&l<=RO)){let n=Number(_O(t,e,r));if(Number.isNaN(n))throw Error(`PBRT tokenizer: invalid number "${_O(t,e,r)}"`);return{type:vO.NUMBER,value:n}}let u=l===0?a:l>0?a*zO[l]:a/zO[-l];return i&&(u=-u),{type:vO.NUMBER,value:u}}}}));function UO(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function WO(e){return e[0]*(e[5]*e[10]-e[6]*e[9])-e[4]*(e[1]*e[10]-e[2]*e[9])+e[8]*(e[1]*e[6]-e[2]*e[5])}function GO(e,t,n,r){for(let i=0;i<4;i++){let a=r[i*4],o=r[i*4+1],s=r[i*4+2],c=r[i*4+3];for(let r=0;r<4;r++)e[i*4+r]=t[n+r]*a+t[n+4+r]*o+t[n+8+r]*s+t[n+12+r]*c}return e}function KO(e,t){let n=e[0],r=e[1],i=e[2],a=e[3],o=e[4],s=e[5],c=e[6],l=e[7],u=e[8],d=e[9],f=e[10],p=e[11],m=e[12],h=e[13],g=e[14],_=e[15],v=t[0],y=t[1],b=t[2],x=t[3],S=t[4],C=t[5],w=t[6],T=t[7],E=t[8],D=t[9],O=t[10],k=t[11],A=t[12],j=t[13],M=t[14],N=t[15];return[n*v+o*y+u*b+m*x,r*v+s*y+d*b+h*x,i*v+c*y+f*b+g*x,a*v+l*y+p*b+_*x,n*S+o*C+u*w+m*T,r*S+s*C+d*w+h*T,i*S+c*C+f*w+g*T,a*S+l*C+p*w+_*T,n*E+o*D+u*O+m*k,r*E+s*D+d*O+h*k,i*E+c*D+f*O+g*k,a*E+l*D+p*O+_*k,n*A+o*j+u*M+m*N,r*A+s*j+d*M+h*N,i*A+c*j+f*M+g*N,a*A+l*j+p*M+_*N]}function qO(e,t,n){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,n,1]}function JO(e,t,n){return[e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1]}function YO(e,t,n,r){let i=Math.hypot(t,n,r)||1;t/=i,n/=i,r/=i;let a=e*Math.PI/180,o=Math.cos(a),s=Math.sin(a),c=1-o,l=c*t*t+o,u=c*t*n-s*r,d=c*t*r+s*n,f=c*t*n+s*r,p=c*n*n+o,m=c*n*r-s*t;return[l,f,c*t*r-s*n,0,u,p,c*n*r+s*t,0,d,m,c*r*r+o,0,0,0,0,1]}function XO(e,t){return[e[0]-t[0],e[1]-t[1],e[2]-t[2]]}function ZO(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function QO(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function $O(e,t,n){let r=QO(XO(t,e)),i=QO(ZO(QO(n),r)),a=ZO(r,i);return[i[0],i[1],i[2],0,a[0],a[1],a[2],0,r[0],r[1],r[2],0,e[0],e[1],e[2],1]}function ek(e){let t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13],h=e[14],g=e[15],_=u*h*c-m*d*c+m*s*f-o*h*f-u*s*g+o*d*g,v=p*d*c-l*h*c-p*s*f+a*h*f+l*s*g-a*d*g,y=l*m*c-p*u*c+p*o*f-a*m*f-l*o*g+a*u*g,b=p*u*s-l*m*s-p*o*d+a*m*d+l*o*h-a*u*h,x=t*_+n*v+r*y+i*b;if(x===0)return UO();let S=1/x;return[_*S,(m*d*i-u*h*i-m*r*f+n*h*f+u*r*g-n*d*g)*S,(o*h*i-m*s*i+m*r*c-n*h*c-o*r*g+n*s*g)*S,(u*s*i-o*d*i-u*r*c+n*d*c+o*r*f-n*s*f)*S,v*S,(l*h*i-p*d*i+p*r*f-t*h*f-l*r*g+t*d*g)*S,(p*s*i-a*h*i-p*r*c+t*h*c+a*r*g-t*s*g)*S,(a*d*i-l*s*i+l*r*c-t*d*c-a*r*f+t*s*f)*S,y*S,(p*u*i-l*m*i-p*n*f+t*m*f+l*n*g-t*u*g)*S,(a*m*i-p*o*i+p*n*c-t*m*c-a*n*g+t*o*g)*S,(l*o*i-a*u*i-l*n*c+t*u*c+a*n*f-t*o*f)*S,b*S,(l*m*r-p*u*r+p*n*d-t*m*d-l*n*h+t*u*h)*S,(p*o*r-a*m*r-p*n*s+t*m*s+a*n*h-t*o*h)*S,(a*u*r-l*o*r+l*n*s-t*u*s-a*n*d+t*o*d)*S]}var tk=g((()=>{}));function nk(e,t){if(e===t)return!0;for(let n=0;n<16;n++)if(e[n]!==t[n])return!1;return!0}var rk,ik,ak,ok,sk,ck,lk,uk=g((()=>{gO(),HO(),tk(),rk=8,ik=1,ak=2,ok=3,sk=new Set([`Identity`,`Transform`,`CoordinateSystem`,`CoordSysTransform`,`ActiveTransform`,`TransformTimes`,`Camera`,`Film`,`WorldBegin`,`MakeNamedMaterial`,`Texture`,`MakeNamedMedium`,`LightSource`,`AreaLightSource`,`ObjectBegin`,`ObjectEnd`,`ObjectInstance`]),ck={integer:Int32Array,point3:Float32Array,point2:Float32Array,vector3:Float32Array,vector2:Float32Array,vector:Float32Array,normal:Float32Array,rgb:Float32Array},lk=class{constructor(e={}){this.releaseInclude=e.releaseInclude||null,this.resolveInclude=e.resolveInclude||(()=>{throw Error(`PBRTParser: Include used but no resolveInclude provided`)}),this.maxPlacements=e.maxPlacements??1/0,this.instanceIncludes=e.instanceIncludes!==!1,this._includes=new Map,this._stateIds=new WeakMap,this._nextStateId=1,this._effects=0,this._movedShapes=!1,this.ir={film:null,camera:null,namedMaterials:new Map,namedTextures:new Map,shapes:[],lights:[],instances:new Map,instanceCount:0,skippedInstances:0,objects:new Map,media:new Map,transformTimes:{start:0,end:1},hasMotion:!1,warnings:[]},this.ctm=UO(),this.ctmEnd=null,this.activeTransform=ok,this._ctmSource=null,this._ctmValue=null,this.state={material:null,areaLight:null,reverseOrientation:!1,interior:null},this.attributeStack=[],this.transformStack=[],this.coordSystems=new Map,this.currentObject=null,this.dirStack=[``],this.stream=null,this._warnedUnknown=new Set}async parse(e,t=``){this.dirStack=[t],await this._run(new VO(e)),this._movedShapes&&(this.ir.shapes=this.ir.shapes.filter(Boolean));for(let e of this.ir.instances.values())e.matrices=mO(e.matrices,e.count*16),e.matricesEnd&&=mO(e.matricesEnd,e.count*16);return this.ir}_addInstance(e,t=this.ctm){if(this.ir.instanceCount>=this.maxPlacements){this.ir.skippedInstances++;return}let n=this.ir.instances.get(e);n||this.ir.instances.set(e,n={name:e,count:0,matrices:new Float32Array(512),matricesEnd:null});let r=(n.count+1)*16;if(r>n.matrices.length){let e=Math.max(r,n.matrices.length*2);n.matrices=mO(n.matrices,e),n.matricesEnd&&=mO(n.matricesEnd,e)}let i=n.count*16;for(let e=0;e<16;e++)n.matrices[i+e]=t[e];let a=this._ctmEndSnapshot();if(a&&!n.matricesEnd&&(n.matricesEnd=n.matrices.slice()),n.matricesEnd){let e=a||t;for(let t=0;t<16;t++)n.matricesEnd[i+t]=e[t]}n.count++,this.ir.instanceCount++}_ctmSnapshot(){return this._ctmSource!==this.ctm&&(this._ctmSource=this.ctm,this._ctmValue=this.ctm.slice()),this._ctmValue}_ctmEndSnapshot(){return this.ctmEnd===null||nk(this.ctmEnd,this.ctm)?null:(this.ir.hasMotion=!0,this.ctmEnd.slice())}_concat(e){if(this.activeTransform===ok&&this.ctmEnd===null){this.ctm=KO(this.ctm,e);return}let t=this.ctmEnd??this.ctm;this.ctmEnd=this.activeTransform&ak?KO(t,e):t,this.activeTransform&ik&&(this.ctm=KO(this.ctm,e))}_setCTM(e){if(this.activeTransform===ok){this.ctm=e,this.ctmEnd=null;return}let t=this.ctmEnd??this.ctm;this.ctmEnd=this.activeTransform&ak?e:t,this.activeTransform&ik&&(this.ctm=e)}_pushGraphicsState(){this.attributeStack.push({ctm:this.ctm,ctmEnd:this.ctmEnd,activeTransform:this.activeTransform,material:this.state.material,areaLight:this.state.areaLight,reverseOrientation:this.state.reverseOrientation,interior:this.state.interior})}_popGraphicsState(){let e=this.attributeStack.pop();e&&(this.ctm=e.ctm,this.ctmEnd=e.ctmEnd,this.activeTransform=e.activeTransform,this.state={material:e.material,areaLight:e.areaLight,reverseOrientation:e.reverseOrientation,interior:e.interior})}_peek(){return this.stream.peek()}_next(){return this.stream.next()}_expectNumber(e){let t=this._next();if(!t||t.type!==vO.NUMBER)throw Error(`PBRT parser: expected number for ${e}, got ${t?t.value:`EOF`}`);return t.value}_expectString(e){let t=this._next();if(!t||t.type!==vO.STRING)throw Error(`PBRT parser: expected string for ${e}, got ${t?t.value:`EOF`}`);return t.value}_readNumbers(e){let t=[];for(let n=0;n<e;n++)t.push(this._expectNumber(`matrix/transform`));return t}_readBracketedOrBareNumbers(e){if(this._peek()&&this._peek().type===vO.LBRACKET){this._next();let e=[];for(;this._peek()&&this._peek().type!==vO.RBRACKET;)e.push(this._expectNumber(`transform element`));return this._next(),e}return this._readNumbers(e)}_parseParams(){let e={};for(;this._peek()&&this._peek().type===vO.STRING;){let t=this._next().value.trim().split(/\s+/),n=t[0],r=t[1]===void 0?t[0]:t[1];e[r]={type:n,value:this._parseParamValue(n)}}return e}_parseParamValue(e){let t=this._peek()&&this._peek().type===vO.LBRACKET;t&&this._next();let n=()=>{let e=this._peek();return t?e&&e.type!==vO.RBRACKET:!1};if(!t)return[this._coerceValueToken(this._next())];if(this._peek()&&this._peek().type===vO.NUMBER){let t=[];for(;n()&&t.length<rk;){let e=this._next();if(e.type!==vO.NUMBER)return this._finishMixedValue(t,t.length,e);t.push(e.value)}if(!n())return this._next(),t;let r=new(ck[e]||Float64Array)(rk*4);r.set(t);let i=t.length;for(;n();){let e=this._next();if(e.type!==vO.NUMBER)return this._finishMixedValue(r,i,e);i===r.length&&(r=mO(r,r.length*2)),r[i++]=e.value}return this._next(),i===r.length?r:mO(r,i)}let r=[];for(;n();)r.push(this._coerceValueToken(this._next()));return this._next(),r}_finishMixedValue(e,t,n){let r=[];for(let n=0;n<t;n++)r.push(e[n]);for(r.push(this._coerceValueToken(n));this._peek()&&this._peek().type!==vO.RBRACKET;)r.push(this._coerceValueToken(this._next()));return this._next(),r}_coerceValueToken(e){if(!e)throw Error(`PBRT parser: unexpected EOF in parameter value`);if(e.type===vO.NUMBER||e.type===vO.STRING)return e.value;if(e.type===vO.WORD)return e.value===`true`?!0:e.value===`false`?!1:e.value;throw Error(`PBRT parser: unexpected token in parameter value: ${e.type}`)}async _run(e){let t=this.stream;this.stream=e;for(let e=this._next();e!==null;e=this._next()){if(e.type!==vO.WORD)throw Error(`PBRT parser: expected directive, got ${e.type} ${e.value??``}`);sk.has(e.value)&&this._effects++;let t=this._directive(e.value);t!==void 0&&await t}this.stream=t}_directive(e){switch(e){case`Identity`:this._setCTM(UO());break;case`Translate`:{let[e,t,n]=this._readNumbers(3);this._concat(qO(e,t,n));break}case`Scale`:{let[e,t,n]=this._readNumbers(3);this._concat(JO(e,t,n));break}case`Rotate`:{let[e,t,n,r]=this._readNumbers(4);this._concat(YO(e,t,n,r));break}case`LookAt`:{let e=this._readNumbers(9),t=$O([e[0],e[1],e[2]],[e[3],e[4],e[5]],[e[6],e[7],e[8]]);this._concat(ek(t));break}case`Transform`:this._setCTM(this._readBracketedOrBareNumbers(16));break;case`ConcatTransform`:this._concat(this._readBracketedOrBareNumbers(16));break;case`CoordinateSystem`:this.coordSystems.set(this._expectString(`CoordinateSystem`),{ctm:this.ctm,ctmEnd:this.ctmEnd});break;case`CoordSysTransform`:{let e=this.coordSystems.get(this._expectString(`CoordSysTransform`));e&&(this.ctm=e.ctm,this.ctmEnd=e.ctmEnd);break}case`Camera`:{let e=this._expectString(`Camera type`),t=this._parseParams();this.ir.camera={type:e,params:t,cameraToWorld:ek(this.ctm)};let n=this._ctmEndSnapshot();n&&(this.ir.camera.cameraToWorldEnd=ek(n));break}case`Film`:{this._expectString(`Film type`);let e=this._parseParams();this.ir.film={xresolution:this._num(e.xresolution,1280),yresolution:this._num(e.yresolution,720),resolutionGiven:!!(e.xresolution||e.yresolution),filename:this._str(e.filename,null)};break}case`Integrator`:{this._expectString(`Integrator type`);let e=this._parseParams();e.maxdepth&&(this.ir.integrator={maxdepth:this._num(e.maxdepth,5)});break}case`Sampler`:{this._expectString(`Sampler type`);let e=this._parseParams();e.pixelsamples&&(this.ir.sampler={pixelsamples:this._num(e.pixelsamples,16)});break}case`PixelFilter`:case`Filter`:case`Accelerator`:case`ColorSpace`:case`Option`:this._skipTypeAndParams();break;case`WorldBegin`:this.ctm=UO(),this.ctmEnd=null,this.activeTransform=ok,this.state={material:null,areaLight:null,reverseOrientation:!1,interior:null};break;case`WorldEnd`:break;case`AttributeBegin`:this._pushGraphicsState();break;case`AttributeEnd`:this._popGraphicsState();break;case`TransformBegin`:this.transformStack.push({ctm:this.ctm,ctmEnd:this.ctmEnd,activeTransform:this.activeTransform});break;case`TransformEnd`:{let e=this.transformStack.pop();e&&(this.ctm=e.ctm,this.ctmEnd=e.ctmEnd,this.activeTransform=e.activeTransform);break}case`ReverseOrientation`:this.state.reverseOrientation=!this.state.reverseOrientation;break;case`Attribute`:this._expectString(`Attribute target`),this._parseParams();break;case`ActiveTransform`:{let e=this._next()?.value;e===`StartTime`?this.activeTransform=ik:e===`EndTime`?this.activeTransform=ak:e===`All`?this.activeTransform=ok:this._warn(`ActiveTransform "${e}" not recognised`);break}case`TransformTimes`:{let[e,t]=this._readNumbers(2);this.ir.transformTimes={start:e,end:t};break}case`MediumInterface`:{let e=this._peek()?.type===vO.STRING?this._next().value:``;this._peek()?.type===vO.STRING&&this._next(),this.state.interior=e||null;break}case`MakeNamedMedium`:{let e=this._expectString(`MakeNamedMedium name`);this.ir.media.set(e,this._parseParams());break}case`Material`:{let e=this._expectString(`Material type`),t=this._parseParams();this.state.material={type:e,params:t};break}case`MakeNamedMaterial`:{let e=this._expectString(`MakeNamedMaterial name`),t=this._parseParams(),n=this._str(t.type,`diffuse`);this.ir.namedMaterials.set(e,{type:n,params:t});break}case`NamedMaterial`:{let e=this._expectString(`NamedMaterial name`),t=this.ir.namedMaterials.get(e);this.state.material=t||{type:`diffuse`,params:{},_missingRef:e},t||this._warn(`NamedMaterial "${e}" referenced before definition`);break}case`Texture`:{let e=this._expectString(`Texture name`),t=this._expectString(`Texture data type`),n=this._expectString(`Texture class`),r=this._parseParams();this.ir.namedTextures.set(e,{dataType:t,class:n,params:r});break}case`AreaLightSource`:{let e=this._expectString(`AreaLightSource type`),t=this._parseParams();this.state.areaLight={type:e,params:t};break}case`LightSource`:{let e=this._expectString(`LightSource type`),t=this._parseParams();this.ctmEnd!==null&&!nk(this.ctmEnd,this.ctm)&&this._warnOnce(`animated-light`,`animated LightSource transforms are not supported — using the start transform`),this.ir.lights.push({type:e,params:t,ctm:this._ctmSnapshot()});break}case`Shape`:{let e=this._expectString(`Shape type`),t=this._parseParams(),n=t.alpha;if(n?.type===`float`&&n.value[0]<=0)break;let r={type:e,params:t,ctm:this._ctmSnapshot(),material:this.state.material,areaLight:this.state.areaLight,reverseOrientation:this.state.reverseOrientation,interior:this.state.interior},i=this.currentObject===null?this._ctmEndSnapshot():null;i?r.ctmEnd=i:this.currentObject!==null&&this.ctmEnd!==null&&!nk(this.ctmEnd,this.ctm)&&this._warnOnce(`animated-template`,`animated transforms inside ObjectBegin are not supported — using the start transform`),this._emitShape(r);break}case`ObjectBegin`:{let e=this._expectString(`ObjectBegin name`);this._pushGraphicsState(),this.currentObject=e,this.ir.objects.has(e)||this.ir.objects.set(e,[]);break}case`ObjectEnd`:this.currentObject=null,this._popGraphicsState();break;case`ObjectInstance`:{let e=this._expectString(`ObjectInstance name`);this._addInstance(e);break}case`Include`:case`Import`:{let t=this._expectString(e);return this._include(t)}default:this._warnUnknown(e),this._parseParams();break}}_emitShape(e){this.currentObject===null?this.ir.shapes.push(e):this.ir.objects.get(this.currentObject).push(e)}async _include(e){let t=this.dirStack[this.dirStack.length-1],n=this._includeKey(e,t);if(n!==null&&this._placeRepeat(n,e))return;let r=await this.resolveInclude(e,t);if(r==null){this._warn(`Include target not found: ${e}`);return}let i=n===null?null:this._includeState(),a=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)):``;this.dirStack.push(a);try{await this._run(new VO(r))}finally{this.dirStack.pop(),this.releaseInclude?.(e,t,r)}i&&this._sameIncludeState(i)&&!this._includes.has(n)&&this._includes.set(n,{start:i.shapes,end:this.ir.shapes.length,ctm:i.ctm.slice(),template:null})}_includeKey(e,t){return!this.instanceIncludes||this.currentObject!==null||this.ctmEnd!==null||this.activeTransform!==ok||this.state.areaLight?null:`${t}\0${e}\0${this._stateId(this.state.material)}\0${this.state.reverseOrientation}\0${this.state.interior}`}_stateId(e){if(!e)return 0;let t=this._stateIds.get(e);return t===void 0&&this._stateIds.set(e,t=this._nextStateId++),t}_includeState(){return{shapes:this.ir.shapes.length,effects:this._effects,ctm:this.ctm,attributes:this.attributeStack.length,transforms:this.transformStack.length,material:this.state.material,reverseOrientation:this.state.reverseOrientation,interior:this.state.interior}}_sameIncludeState(e){return this._effects===e.effects&&this.ctmEnd===null&&this.activeTransform===ok&&nk(this.ctm,e.ctm)&&this.attributeStack.length===e.attributes&&this.transformStack.length===e.transforms&&this.state.material===e.material&&this.state.areaLight===null&&this.state.reverseOrientation===e.reverseOrientation&&this.state.interior===e.interior}_placeRepeat(e,t){let n=this._includes.get(e);if(!n)return!1;if(n.template===null){let{start:r,end:i}=n;if(i===r||this.ir.instanceCount+2>this.maxPlacements)return!1;for(let t=r;t<i;t++)if(!this.ir.shapes[t])return this._includes.delete(e),!1;let a=`${t}#${this.ir.objects.size}`,o=ek(n.ctm),s=[],c=null,l=null;for(let e=r;e<i;e++){let t=this.ir.shapes[e];t.ctm!==c&&(l=KO(o,c=t.ctm)),t.relativeCTM=l,s.push(t),this.ir.shapes[e]=null}this.ir.objects.set(a,s),this._addInstance(a,n.ctm),n.template=a,this._movedShapes=!0}return this._addInstance(n.template),!0}_skipTypeAndParams(){this._peek()&&this._peek().type===vO.STRING&&this._next(),this._parseParams()}_skipNamedAndParams(){this._peek()&&this._peek().type===vO.STRING&&this._next(),this._parseParams()}_num(e,t){return e&&e.value.length?e.value[0]:t}_str(e,t){return e&&e.value.length?e.value[0]:t}_warn(e){this.ir.warnings.push(e)}_warnOnce(e,t){this._warnedUnknown.has(e)||(this._warnedUnknown.add(e),this._warn(t))}_warnUnknown(e){this._warnedUnknown.has(e)||(this._warnedUnknown.add(e),this._warn(`Unsupported directive ignored: ${e}`))}}}));function dk(e){let t=mk[e];return t?{sigmaS:t[0].slice(),sigmaA:t[1].slice()}:null}function fk(e,t){let n=-1.44/(t*t)+.71/t+.668+.0636*t,r=(1+n)/(1-n),i=Math.sqrt(3*(1-e));return e/2*(1+Math.exp(-4/3*r*i))*Math.exp(-i)}function pk(e,t){let n=Math.min(Math.max(e,0),fk(1,t)),r=0,i=1;for(let e=0;e<48;e++){let e=(r+i)/2;fk(e,t)<n?r=e:i=e}return(r+i)/2}var mk,hk=g((()=>{mk={Apple:[[2.29,2.39,1.97],[.003,.0034,.046]],Chicken1:[[.15,.21,.38],[.015,.077,.19]],Chicken2:[[.19,.25,.32],[.018,.088,.2]],Cream:[[7.38,5.47,3.15],[2e-4,.0028,.0163]],Ketchup:[[.18,.07,.03],[.061,.97,1.45]],Marble:[[2.19,2.62,3],[.0021,.0041,.0071]],Potato:[[.68,.7,.55],[.0024,.009,.12]],Skimmilk:[[.7,1.22,1.9],[.0014,.0025,.0142]],Skin1:[[.74,.88,1.01],[.032,.17,.48]],Skin2:[[1.09,1.59,1.79],[.013,.07,.145]],Spectralon:[[11.6,20.4,14.9],[0,0,0]],Wholemilk:[[2.55,3.21,3.77],[.0011,.0024,.014]],"Lowfat Milk":[[.89187,1.5136,2.532],[.002875,.00575,.0115]],"Reduced Milk":[[2.4858,3.1669,4.5214],[.0025556,.0051111,.012778]],"Regular Milk":[[4.5513,5.8294,7.136],[.0015333,.0046,.019933]],Espresso:[[.72378,.84557,1.0247],[4.7984,6.5751,8.8493]],"Mint Mocha Coffee":[[.31602,.38538,.48131],[3.772,5.8228,7.82]],"Lowfat Soy Milk":[[.30576,.34233,.61664],[.0014375,.0071875,.035937]],"Regular Soy Milk":[[.59223,.73866,1.4693],[.0019167,.0095833,.065167]],"Lowfat Chocolate Milk":[[.64925,.83916,1.1057],[.0115,.0368,.1564]],"Regular Chocolate Milk":[[1.4585,2.1289,2.9527],[.010063,.043125,.14375]],Coke:[[89053e-9,8372e-8,0],[.10014,.16503,.2468]],Pepsi:[[61697e-9,42564e-9,0],[.091641,.14158,.20729]],Sprite:[[60306e-10,64139e-10,65504e-10],[.001886,.0018308,.0020025]],Gatorade:[[.0024574,.003007,.0037325],[.024794,.019289,.008878]],Chardonnay:[[17982e-9,13758e-9,12023e-9],[.010782,.011855,.023997]],"White Zinfandel":[[17501e-9,19069e-9,1288e-8],[.012072,.016184,.019843]],Merlot:[[21129e-9,0,0],[.11632,.25191,.29434]],"Budweiser Beer":[[24356e-9,24079e-9,10564e-9],[.011492,.024911,.057786]],"Coors Light Beer":[[50922e-9,4301e-8,0],[.006164,.013984,.034983]],Clorox:[[.0024035,.0031373,.003991],[.0033542,.014892,.026297]],"Apple Juice":[[13612e-8,15836e-8,227e-6],[.012957,.023741,.052184]],"Cranberry Juice":[[10402e-8,11646e-8,78139e-9],[.039437,.094223,.12426]],"Grape Juice":[[5382e-8,0,0],[.10404,.23958,.29325]],"Ruby Grapefruit Juice":[[.011002,.010927,.011036],[.085867,.18314,.25262]],"White Grapefruit Juice":[[.22826,.23998,.32748],[.0138,.018831,.056781]],Shampoo:[[7176e-7,8303e-7,9016e-7],[.014107,.045693,.061717]],"Strawberry Shampoo":[[15671e-8,15947e-8,1518e-8],[.01449,.05796,.075823]],"Head & Shoulders Shampoo":[[.023805,.028804,.034306],[.084621,.15688,.20365]],"Lemon Tea Powder":[[.040224,.045264,.051081],[2.4288,4.5757,7.2127]],"Orange Powder":[[15617e-8,17482e-8,1762e-7],[.001449,.003441,.007863]],"Pink Lemonade Powder":[[12103e-8,13073e-8,12528e-8],[.001165,.002366,.003195]],"Cappuccino Powder":[[1.8436,2.5851,2.1662],[35.844,49.547,61.084]],"Salt Powder":[[.027333,.032451,.031979],[.28415,.3257,.34148]],"Sugar Powder":[[22272e-8,25513e-8,271e-6],[.012638,.031051,.050124]],"Suisse Mocha Powder":[[2.7979,3.5452,4.3365],[17.502,27.004,35.433]],"Pacific Ocean Surface Water":[[1764e-7,32095e-8,19617e-8],[.031845,.031324,.030147]]}}));function gk(e){let t=Math.max(1e3,Math.min(4e4,e))/100,n,r,i;t<=66?(n=255,r=99.47*Math.log(t)-161.12):(n=329.7*(t-60)**-.1332,r=288.12*(t-60)**-.0755),i=t>=66?255:t<=19?0:138.52*Math.log(t-10)-305.04;let a=e=>Math.max(0,Math.min(255,e))/255;return[a(n)**2.2,a(r)**2.2,a(i)**2.2]}function _k(e,t,n){let r=e[t];return r&&typeof r.value[0]==`number`?r.value[0]:n}function vk(e,t,n){let r=e[t];return r&&typeof r.value[0]==`string`?r.value[0]:n}function yk(e,t,n){let r=e[t]?.value?.[0];return r===void 0?n:r===!0||r===`true`}async function bk(e,t,n,r=null){let i=e[t];if(!i)return{rgb:r,texture:null};if(i.type===`texture`){let e=i.value[0],t=await n.resolveNamedTexture(e);return t&&t.texture?{rgb:t.constant??null,texture:t.texture}:t&&t.constant?{rgb:t.constant,texture:null}:(n.warn(`texture "${e}" could not be resolved`),{rgb:r,texture:null})}if(i.type===`rgb`||i.type===`color`)return{rgb:[i.value[0],i.value[1],i.value[2]],texture:null};if(i.type===`float`){let e=i.value[0];return{rgb:[e,e,e],texture:null}}if(i.type===`blackbody`)return{rgb:gk(i.value[0]),texture:null};if(i.type===`spectrum`){if(typeof i.value[0]==`string`){let e=xk(i.value[0]);return e&&kk[e]?{rgb:kk[e].slice(),texture:null}:(n.warn(`named spectrum "${i.value[0]}" approximated to gray`),{rgb:[.5,.5,.5],texture:null})}let e=0,t=0;for(let n=1;n<i.value.length;n+=2)e+=i.value[n],t++;let r=t?e/t:.5;return{rgb:[r,r,r],texture:null}}return{rgb:r,texture:null}}function xk(e){let t=e.toLowerCase().match(/metal-([a-z]+)/);if(t)return t[1];for(let t of Object.keys(kk))if(e.toLowerCase().includes(t))return t;return null}async function Sk(e,t,n){let r=e[t];return r?typeof r.value[0]==`number`?r.value[0]:r.type===`texture`?await n.floatTextureMean?.(r.value[0])??null:null:null}async function Ck(e,t,n,r=``){let i=jk(e),a=e=>i?Math.sqrt(Math.max(e,0)):e,o=null,s=await Sk(e,`${r}roughness`,n);if(s!==null)o=a(s);else{let t=await Sk(e,`${r}uroughness`,n),i=await Sk(e,`${r}vroughness`,n);t!==null&&(o=i===null?a(t):(a(t)+a(i))/2)}return o===null?t:Math.sqrt(Math.max(o,0))}async function wk(e,t,n,r,i,a=``){let o=n[`${a}roughness`]?[`${a}roughness`]:[`${a}uroughness`,`${a}vroughness`].filter(e=>n[e]);if(i.bakeFloatMap&&o.some(e=>n[e].type===`texture`)){let r=jk(n),a=e=>r?Math.sqrt(Math.max(e,0)):Math.max(e,0),s=await i.bakeFloatMap(n,o,e=>Math.sqrt(e.reduce((e,t)=>e+a(t),0)/e.length));if(s){e[`${t}Map`]=s,e[t]=1;return}}e[t]=await Ck(n,r,i,a)}async function Tk(e,t,n,r){let i=e[t];return i?.type===`texture`?await n.textureMeanRGB?.(i.value[0])??r:(await bk(e,t,n,r)).rgb??r}async function Ek(e,t,n){let i=_k(t,`eta`,1.33),a=_k(t,`scale`,1),o=e=>e.map(e=>Math.max(0,e*a)),s=_k(t,`g`,0),c,l,u=vk(t,`name`,``),d=u?dk(u):null;if(u&&!d&&n.warn(`subsurface: no medium named "${u}" — using pbrt's default`),d)c=o(d.sigmaA),l=o(d.sigmaS),s=0;else if(t.sigma_a&&t.sigma_s)c=o(await Tk(t,`sigma_a`,n,Mk)),l=o(await Tk(t,`sigma_s`,n,Nk));else if(t.reflectance&&!u){let e=await Tk(t,`reflectance`,n,[.5,.5,.5]),r=o(t.mfp?await Tk(t,`mfp`,n,[1,1,1]):[1,1,1]);c=[],l=[];for(let t=0;t<3;t++){let n=1/Math.max(r[t],1e-9),a=pk(e[t],i);l[t]=a*n/(1-s+a*s),c[t]=n-l[t]}}else c=o(Mk),l=o(Nk);let f=c.map((e,t)=>e+l[t]);e.subsurface=1,e.subsurfaceColor=new r.Color(...f.map((e,t)=>e>0?l[t]/e:0)),e.subsurfaceRadius=f.map(e=>e>0?1/e:1e6),e.subsurfaceRadiusScale=1,e.subsurfaceAnisotropy=Math.max(-.99,Math.min(.99,s)),e.ior=i,e.metalness=0,e.color.setRGB(...f.map((e,t)=>{let n=(1-s)*l[t];return e>0?fk(n/(c[t]+n),i):0})),await wk(e,`roughness`,t,0,n)}async function Dk(e,t,n,r,i,a){let o=await bk(t,`reflectance`,n,null),s=t[`${r}eta`],c=t[`${r}k`],l=s&&s.type===`spectrum`&&typeof s.value[0]==`string`;if(o.rgb||o.texture)i(o);else if(s&&c&&!l){let e=(await bk(t,`${r}eta`,n,[.2,.92,1.1])).rgb,i=(await bk(t,`${r}k`,n,[3.9,2.45,2.14])).rgb,o=(e,t)=>((e-1)**2+t**2)/((e+1)**2+t**2);a([o(e[0],i[0]),o(e[1],i[1]),o(e[2],i[2])])}else a(s?(await bk(t,`${r}eta`,n,Ak)).rgb||Ak:kk.cu);e.metalness=1}async function Ok(e,t){let n=e?.type||`diffuse`,i=e?.params||{},a=new r.MeshPhysicalMaterial({side:r.DoubleSide,roughness:1,metalness:0}),o=e=>{e&&a.color.setRGB(e[0],e[1],e[2])},s=e=>{o(e.rgb),e.texture&&(a.map=e.texture,e.rgb||a.color.setRGB(1,1,1))};switch(n){case`diffuse`:s(await bk(i,`reflectance`,t,[.5,.5,.5])),a.roughness=1,a.metalness=0,a.specularIntensity=0;break;case`conductor`:case`metal`:await Dk(a,i,t,``,s,o),await wk(a,`roughness`,i,.1,t);break;case`coatedconductor`:await Dk(a,i,t,`conductor.`,s,o),await wk(a,`roughness`,i,0,t,`conductor.`),a.clearcoat=1,await wk(a,`clearcoatRoughness`,i,0,t,`interface.`);break;case`dielectric`:case`thindielectric`:a.transmission=1,a.metalness=0,a.color.setRGB(1,1,1),a.ior=_k(i,`eta`,1.5),await wk(a,`roughness`,i,0,t),a.thickness=n===`thindielectric`?0:_k(i,`thickness`,0);break;case`coateddiffuse`:s(await bk(i,`reflectance`,t,[.5,.5,.5])),a.roughness=.6,a.metalness=0,a.clearcoat=1,await wk(a,`clearcoatRoughness`,i,0,t);break;case`diffusetransmission`:{let e=_k(i,`scale`,1),n=t=>Math.min(1,Math.max(0,e*t)),o=await bk(i,`transmittance`,t,[.25,.25,.25]),c=o.rgb?o.rgb.map(n):[.5,.5,.5],l=Math.min(.99,Math.max(...c)),u=await bk(i,`reflectance`,t,[.25,.25,.25]),d=e=>Math.min(1,n(e)/(1-l));s({texture:u.texture,rgb:u.rgb?u.rgb.map(d):u.texture?[1,1,1].map(d):null}),o.texture&&t.warn(`diffusetransmission: a textured "transmittance" is not supported — using 0.5`),a.diffuseTransmission=l,a.diffuseTransmissionColor=new r.Color().setRGB(...c.map(e=>l>0?Math.min(1,e/l):1)),a.roughness=1,a.metalness=0,a.specularIntensity=0;break}case`interface`:case`none`:case``:a.transmission=1,a.ior=1,a.roughness=0,a.color.setRGB(1,1,1);break;case`mix`:{let e=i.materials?.value||[],n=Math.max(0,Math.min(1,_k(i,`amount`,.5))),o=e[0]?t.namedMaterials?.get(e[0]):null,s=e[1]?t.namedMaterials?.get(e[1]):null;if(o&&s){let[e,c]=await Promise.all([Ok(o,t),Ok(s,t)]),l=i.amount,u=l?.type===`texture`?await t.bakeMaterialMix?.(e,c,l.value[0]):null;u&&(n=u.mean);let d=(e,t)=>e*(1-n)+t*n;a.color.lerpColors(e.color,c.color,n),a.roughness=d(e.roughness,c.roughness),a.metalness=d(e.metalness,c.metalness),a.ior=d(e.ior??1.5,c.ior??1.5),a.transmission=d(e.transmission??0,c.transmission??0),a.thickness=d(e.thickness??0,c.thickness??0),a.clearcoat=d(e.clearcoat??0,c.clearcoat??0),a.clearcoatRoughness=d(e.clearcoatRoughness??0,c.clearcoatRoughness??0),a.emissive.lerpColors(e.emissive,c.emissive,n);let f=e.diffuseTransmission??0,p=c.diffuseTransmission??0;(f>0||p>0)&&(a.diffuseTransmission=d(f,p),a.diffuseTransmissionColor=new r.Color().lerpColors(e.diffuseTransmissionColor??new r.Color(1,1,1),c.diffuseTransmissionColor??new r.Color(1,1,1),n)),a.emissiveIntensity=d(e.emissiveIntensity??0,c.emissiveIntensity??0),a.map=(n<.5?e.map:c.map)||null,a.normalMap=(n<.5?e.normalMap:c.normalMap)||null,u?.texture&&(a.map=u.texture,a.color.setRGB(1,1,1));break}t.warn(`material "mix" — could not resolve inner materials [${e.join(`, `)}], falling back to diffuse`),a.color.set(new r.Color(.6,.6,.6));break}case`subsurface`:await Ek(a,i,t);break;case`hair`:case`measured`:t.warn(`material "${n}" not supported — using diffuse approximation`),o((await bk(i,`reflectance`,t,[.5,.5,.5])).rgb),a.roughness=1;break;default:t.warn(`unknown material "${n}" — using neutral diffuse`),a.color.set(new r.Color(.6,.6,.6));break}let c=vk(i,`normalmap`,null);return c&&t.resolveNormalMap&&(a.normalMap=await t.resolveNormalMap(c)),a.roughness=Math.max(0,Math.min(1,a.roughness)),a}var kk,Ak,jk,Mk,Nk,Pk=g((()=>{hk(),kk={au:[1,.78,.34],gold:[1,.78,.34],cu:[.95,.64,.54],copper:[.95,.64,.54],ag:[.97,.96,.91],silver:[.97,.96,.91],al:[.91,.92,.92],aluminium:[.91,.92,.92],aluminum:[.91,.92,.92],mgo:[.9,.9,.9],tio2:[.9,.9,.9]},Ak=[.92,.92,.92],jk=e=>{let t=e.remaproughness?.value?.[0];return t!==!1&&t!==`false`},Mk=[.0011,.0024,.014],Nk=[2.55,3.21,3.77]}));function Fk(e,{channels:t,decode:n=null,scale:r=1,invert:i=!1,mapping:a=null}){let{width:o,height:s}=e,c=e.channels??4,l=new Float32Array(o*s*t),u=e.topDown!==!1,d=t=>n?n(e.data[t]/255):e.data[t],f=t===1&&c===4&&Ik(e),p=t===1&&c>=3&&!f;for(let e=0;e<s;e++){let n=u?e:s-1-e;for(let a=0;a<o;a++){let s=(n*o+a)*c,u=(e*o+a)*t;for(let e=0;e<t;e++){let t=r*(f?d(s+3):p?(d(s)+d(s+1)+d(s+2))/3:d(s+Math.min(e,c-1)));l[u+e]=i?Math.max(0,1-t):t}}}return{width:o,height:s,channels:t,data:l,su:1,sv:1,du:0,dv:0,...a}}function Ik(e){let{data:t}=e,n=e.float?1:255;for(let e=3;e<t.length;e+=4)if(t[e]!==n)return!0;return!1}function Lk(e){let t=0;for(let n=0;n<e.data.length;n++)t+=e.data[n];return e.data.length?t/e.data.length:0}function Rk(e,t,n,r){let{width:i,height:a,channels:o,data:s}=e,c=t*i-.5,l=(1-n)*a-.5,u=Math.floor(c),d=Math.floor(l),f=c-u,p=l-d,m=(e,t)=>(e%t+t)%t,h=m(u,i),g=m(u+1,i),_=m(d,a),v=m(d+1,a);for(let e=0;e<3;e++){let t=Math.min(e,o-1),n=s[(_*i+h)*o+t]*(1-f)+s[(_*i+g)*o+t]*f,a=s[(v*i+h)*o+t]*(1-f)+s[(v*i+g)*o+t]*f;r[e]=n*(1-p)+a*p}return r}function zk(e,t,{alphaOf:n=null,linear:r=!1}={}){let i=null;for(let t of e)t.layer&&(!i||t.layer.width*t.layer.height>i.width*i.height)&&(i=t.layer);if(!i)return null;let a=Math.min(i.width,Bk),o=Math.min(i.height,Bk),s=new Uint8Array(a*o*4),c=e.map(()=>[0,0,0]);for(let l=0;l<o;l++){let u=(l+.5)/o,d=(u-i.dv)/i.sv;for(let o=0;o<a;o++){let f=(o+.5)/a,p=(f-i.du)/i.su;for(let t=0;t<e.length;t++){let n=e[t],r=c[t];if(n.layer){let e=n.layer;if(Rk(e,e===i?f:e.su*p+e.du,e===i?u:e.sv*d+e.dv,r),n.tint)for(let e=0;e<3;e++)r[e]*=n.tint[e]}else r[0]=n.rgb[0],r[1]=n.rgb[1],r[2]=n.rgb[2];if(n.clamp)for(let e=0;e<3;e++)r[e]=Math.min(1,Math.max(0,r[e]))}let m=t(c),h=(l*a+o)*4;for(let e=0;e<3;e++){let t=Math.min(1,Math.max(0,m[e]));s[h+e]=Math.round(255*(r?t:Hk(t)))}s[h+3]=n?Math.round(255*Math.min(1,Math.max(0,n(c)))):255}}return{data:s,width:a,height:o,mapping:{su:i.su,sv:i.sv,du:i.du,dv:i.dv}}}var Bk,Vk,Hk,Uk,Wk=g((()=>{Bk=4096,Vk=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4,Hk=e=>e<=.0031308?e*12.92:1.055*e**(1/2.4)-.055,Uk=([e,t,n])=>{let r=n[0];return[e[0]+(t[0]-e[0])*r,e[1]+(t[1]-e[1])*r,e[2]+(t[2]-e[2])*r]}}));function Gk(e){return e===3?3/16:3/(8*e)}function Kk(e){return 1/(e+3/(8*Gk(e)))}function qk(e,t){let n=new Map,r=[],i=[],a=[],o=[],s=[],c=t.length/3;for(let l=0;l<c;l++)for(let c=0;c<3;c++){let u=t[l*3+c],d=t[l*3+(c+1)%3],f=t[l*3+(c+2)%3],p=u<d?u:d,m=u<d?d:u,h=p*e+m,g=n.get(h);g===void 0?(n.set(h,r.length),r.push(p),i.push(m),a.push(f),o.push(-1),s.push(1)):(o[g]<0&&(o[g]=f),s[g]++)}let l=Array.from({length:e},()=>[]),u=Array.from({length:e},()=>[]);for(let e=0;e<r.length;e++){let t=r[e],n=i[e];l[t].push(n),l[n].push(t),s[e]===1&&(u[t].push(n),u[n].push(t))}return{edgeIndex:n,edgeV0:r,edgeV1:i,edgeOpp0:a,edgeOpp1:o,edgeFaces:s,ring:l,boundaryRing:u}}function Jk(e,t,n,r,i){let a=new Float64Array(e.length);for(let o=0;o<n;o++){let n=o*3,s=t.boundaryRing[o];if(s.length===2){let t=s[0]*3,r=s[1]*3,o=1-2*i;for(let s=0;s<3;s++)a[n+s]=o*e[n+s]+i*(e[t+s]+e[r+s]);continue}let c=t.ring[o],l=c.length;if(l===0||s.length>0){for(let t=0;t<3;t++)a[n+t]=e[n+t];continue}let u=r(l),d=0,f=0,p=0;for(let t=0;t<l;t++){let n=c[t]*3;d+=e[n],f+=e[n+1],p+=e[n+2]}let m=1-l*u;a[n]=m*e[n]+u*d,a[n+1]=m*e[n+1]+u*f,a[n+2]=m*e[n+2]+u*p}return a}function Yk(e,t){let n=e.length/3,r=qk(n,t),i=r.edgeV0.length,a=Jk(e,r,n,Gk,1/8),o=new Float64Array((n+i)*3);o.set(a);for(let t=0;t<i;t++){let i=r.edgeV0[t]*3,a=r.edgeV1[t]*3,s=(n+t)*3,c=r.edgeOpp1[t];if(c<0)for(let t=0;t<3;t++)o[s+t]=.5*(e[i+t]+e[a+t]);else{let n=r.edgeOpp0[t]*3,l=c*3;for(let t=0;t<3;t++)o[s+t]=.375*(e[i+t]+e[a+t])+.125*(e[n+t]+e[l+t])}}let s=t.length/3,c=new Int32Array(s*12),l=(e,t)=>n+r.edgeIndex.get((e<t?e:t)*n+(e<t?t:e));for(let e=0;e<s;e++){let n=t[e*3],r=t[e*3+1],i=t[e*3+2],a=l(n,r),o=l(r,i),s=l(i,n),u=e*12;c[u]=n,c[u+1]=a,c[u+2]=s,c[u+3]=a,c[u+4]=r,c[u+5]=o,c[u+6]=s,c[u+7]=o,c[u+8]=i,c[u+9]=a,c[u+10]=o,c[u+11]=s}return{positions:o,indices:c}}function Xk(e,t,n,r=2e6){let i=Float64Array.from(e),a=Int32Array.from(t),o=0;for(let e=0;e<n&&!(a.length/3*4>r);e++){let e=Yk(i,a);i=e.positions,a=e.indices,o++}let s=i.length/3,c=Jk(i,qk(s,a),s,Kk,1/5);return{positions:Float32Array.from(c),indices:Uint32Array.from(a),levels:o}}var Zk=g((()=>{}));function Qk(e,t,n){let r=Math.abs(e),i=Math.abs(t),a=Math.sqrt(Math.max(0,1-Math.abs(n))),o=Math.max(r,i),s=o===0?0:Math.min(r,i)/o,c=2/Math.PI*Math.atan(s);r<i&&(c=1-c);let l=c*a,u=a-l;if(n<0){let e=u;u=1-l,l=1-e}return e<0&&(u=-u),t<0&&(l=-l),[.5*(u+1),.5*(l+1)]}function $k(e,t,n,r,i,a,o,s){let c=Math.min(Math.max(i*t-.5,0),t-1),l=Math.min(Math.max(a*n-.5,0),n-1),u=Math.floor(c),d=Math.floor(l),f=Math.min(u+1,t-1),p=Math.min(d+1,n-1),m=c-u,h=l-d,g=(d*t+u)*r,_=(d*t+f)*r,v=(p*t+u)*r,y=(p*t+f)*r;for(let t=0;t<3;t++){let n=s?s[e[g+t]]:e[g+t],r=s?s[e[_+t]]:e[_+t],i=s?s[e[v+t]]:e[v+t],a=s?s[e[y+t]]:e[y+t],c=n*(1-m)+r*m,l=i*(1-m)+a*m;o[t]=c*(1-h)+l*h}}function eA(e,t,n=1,r=0){let i=r||Math.min(e.width,4096),a=Math.max(1,i>>1),o=new Float32Array(i*a*4),s=t?ek(t):null,c=e.srgb?tA:null,l=[0,0,0];for(let t=0;t<a;t++){let r=(1-(t+.5)/a)*Math.PI,u=Math.sin(r),d=Math.cos(r);for(let r=0;r<i;r++){let a=((r+.5)/i-.5)*2*Math.PI,f=u*Math.cos(a),p=d,m=u*Math.sin(a);if(s){let e=s,t=e[0]*f+e[4]*p+e[8]*m,n=e[1]*f+e[5]*p+e[9]*m,r=e[2]*f+e[6]*p+e[10]*m,i=Math.hypot(t,n,r)||1;f=t/i,p=n/i,m=r/i}let[h,g]=Qk(f,p,m);$k(e.data,e.width,e.height,e.channels,h,e.bottomUp?1-g:g,l,c);let _=(t*i+r)*4;o[_]=l[0]*n,o[_+1]=l[1]*n,o[_+2]=l[2]*n,o[_+3]=1}}return{data:o,width:i,height:a}}var tA,nA=g((()=>{tk(),tA=(()=>{let e=new Float32Array(256);for(let t=0;t<256;t++){let n=t/255;e[t]=n<=.04045?n/12.92:((n+.055)/1.055)**2.4}return e})()}));function rA(e,t){let n=e*e,r=n*e;t[0]=(1-3*e+3*n-r)/6,t[1]=(4-6*n+3*r)/6,t[2]=(1+3*e+3*n-3*r)/6,t[3]=r/6}function iA(e,t){let n=1-e;t[0]=n*n*n,t[1]=3*n*n*e,t[2]=3*n*e*e,t[3]=e*e*e}function aA(e){let t=Math.hypot(e[0],e[1],e[2]);return t>0&&(e[0]/=t,e[1]/=t,e[2]/=t),e}function oA(e,t,n){return n[0]=e[1]*t[2]-e[2]*t[1],n[1]=e[2]*t[0]-e[0]*t[2],n[2]=e[0]*t[1]-e[1]*t[0],n}function sA(e,t){let n=e.length/3;return t===`bspline`?n-3:Math.max(1,(n-1)/3)}function cA(e,t,n,r,i,a,o){let s=Math.floor(r);s>=n&&(s=n-1);let c=r-s;t===`bspline`?rA(c,i):iA(c,i);let l=t===`bspline`?s:s*3,u=0,d=0,f=0;for(let t=0;t<4;t++){let n=(l+t)*3;u+=i[t]*e[n],d+=i[t]*e[n+1],f+=i[t]*e[n+2]}a[o]=u,a[o+1]=d,a[o+2]=f}function lA(e,t,n){let r=sA(e,t);if(r<1)return null;let i=Math.max(1,Math.round(n*r)),a=new Float64Array((i+1)*3),o=[0,0,0,0];for(let n=0;n<=i;n++)cA(e,t,r,n/i*r,o,a,n*3);return{points:a,count:i+1,spans:r}}function uA(e,t,n,r,i){let a=e[t*3],o=e[t*3+1],s=e[t*3+2],c=n[r*3],l=n[r*3+1],u=n[r*3+2],d=n[i*3]-c,f=n[i*3+1]-l,p=n[i*3+2]-u,m=d*d+f*f+p*p,h=m>0?((a-c)*d+(o-l)*f+(s-u)*p)/m:0;return h=h<0?0:h>1?1:h,Math.hypot(a-c-h*d,o-l-h*f,s-u-h*p)}function dA(e,t,n,r,i,a){let{points:o,count:s,spans:c}=n;if(s<3)return null;let l=new Float64Array((s-1)*3),u=[0,0,0,0],d=s-1;for(let n=0;n<d;n++)cA(e,t,c,(n+.5)/d*c,u,l,n*3);let f=0;for(let e=0;e<d;e++)f=Math.max(f,uA(l,e,o,e,e+1));let p=e=>Math.max(f,r*.5*(i+(a-i)*(e/d))),m=(e,t)=>{for(let n=e+1;n<t;n++)if(uA(o,n,o,e,t)>p(n))return!1;for(let n=e;n<t;n++)if(uA(l,n,o,e,t)>p(n+.5))return!1;return!0},h=new Int32Array(s),g=0;h[g++]=0;for(let e=0;e<d;){let t=e+1;for(;t<d&&m(e,t+1);)t++;h[g++]=t,e=t}return g===s?null:h.subarray(0,g)}function fA(e){let{P:t,basis:n=`bezier`,width0:r=1,width1:i=1,N:a=null}=e,o=Math.max(1,Math.round(e.steps??pA)),s=Math.max(1,Math.round(e.sides??1));if(!t||t.length<12)return null;let c=lA(t,n,o);if(!c)return null;let{points:l,count:u}=c,d=e.tolerance>0?dA(t,n,c,e.tolerance,r,i):null,f=d?d.length:u,p=s>=3?s:s*2,m=new Float32Array(f*p*3),h=[0,0,0],g=[0,0,0],_=[0,0,0],v=[0,0,0],y=!1,b=0;for(let e=0;e<u;e++){let t=Math.max(0,e-1),n=Math.min(u-1,e+1);if(h[0]=l[n*3]-l[t*3],h[1]=l[n*3+1]-l[t*3+1],h[2]=l[n*3+2]-l[t*3+2],aA(h),y){let e=g[0]*h[0]+g[1]*h[1]+g[2]*h[2];g[0]-=e*h[0],g[1]-=e*h[1],g[2]-=e*h[2],Math.hypot(g[0],g[1],g[2])<1e-9&&oA(h,[0,1,0],g),aA(g)}else{if(a&&a.length>=3)g[0]=a[0],g[1]=a[1],g[2]=a[2],oA(h,g,v),g[0]=v[0],g[1]=v[1],g[2]=v[2];else{let e=Math.abs(h[0]),t=Math.abs(h[1]),n=Math.abs(h[2]);oA(h,e<t&&e<n?[1,0,0]:t<n?[0,1,0]:[0,0,1],g)}Math.hypot(g[0],g[1],g[2])<1e-9&&oA(h,[0,1,0],g),aA(g),y=!0}if(d&&d[b]!==e)continue;oA(h,g,_),aA(_);let o=e/(u-1||1),c=(r+(i-r)*o)*.5,f=l[e*3],x=l[e*3+1],S=l[e*3+2];for(let e=0;e<p;e++){let t,n,r;if(s>=3){let i=e/s*Math.PI*2,a=Math.cos(i),o=Math.sin(i);t=g[0]*a+_[0]*o,n=g[1]*a+_[1]*o,r=g[2]*a+_[2]*o}else{let i=e<2?g:_,a=e%2==0?-1:1;t=i[0]*a,n=i[1]*a,r=i[2]*a}let i=(b*p+e)*3;m[i]=f+t*c,m[i+1]=x+n*c,m[i+2]=S+r*c}b++}let x=s,S=new Uint32Array((f-1)*x*6),C=0;for(let e=0;e<f-1;e++)for(let t=0;t<x;t++){let n=s>=3?t:t*2,r=s>=3?(t+1)%s:t*2+1,i=e*p+n,a=e*p+r,o=(e+1)*p+r,c=(e+1)*p+n;S[C++]=i,S[C++]=a,S[C++]=o,S[C++]=i,S[C++]=o,S[C++]=c}return{positions:m,indices:C===S.length?S:mO(S,C)}}var pA,mA=g((()=>{gO(),pA=2}));async function hA(e,t,n){let r=e[t];if(r?.type===`spectrum`&&typeof r.value[0]==`string`&&r.value[0].startsWith(`stdillum`))return[1,1,1];let i=(await bk(e,t,n,[1,1,1])).rgb||[1,1,1];if(!r||r.type===`rgb`||r.type===`color`||r.type===`float`)return i;let a=.2126*i[0]+.7152*i[1]+.0722*i[2];return a>0?i.map(e=>e/a):i}function gA(e){return e instanceof Uint32Array?new r.Uint32BufferAttribute(e,1):ArrayBuffer.isView(e)&&e.BYTES_PER_ELEMENT===4?new r.Uint32BufferAttribute(new Uint32Array(e.buffer,e.byteOffset,e.length),1):new r.Uint32BufferAttribute(Uint32Array.from(e),1)}function _A(e,t){if(t<=e.length)return e;let n=e.length||1;for(;n<t;)n*=2;return mO(e,n)}function vA(e){return e instanceof Float32Array?e:Float32Array.from(e)}function yA(e,t){if(e.count!==t.count)return!1;for(let n=0,r=e.count*16;n<r;n++)if(e.matrices[n]!==t.matrices[n])return!1;return!0}function bA(e,t){let n=Math.min(e.width,VA),r=null;if(typeof OffscreenCanvas<`u`)r=new OffscreenCanvas(n,n);else if(typeof document<`u`)r=document.createElement(`canvas`),r.width=r.height=n;else return null;try{let i=r.getContext(`2d`,{willReadFrequently:!0});if(!i)return null;i.drawImage(e,0,0,n,n);let{data:a}=i.getImageData(0,0,n,n);return{data:a,width:n,height:n,channels:4,bottomUp:!1,srgb:t}}catch{return null}}function xA(e){let t=e?.image;if(!t)return null;if(ArrayBuffer.isView(t.data))return{data:t.data,width:t.width,height:t.height,channels:4,topDown:e.flipY===!0,float:!(t.data instanceof Uint8Array||t.data instanceof Uint8ClampedArray)};let{width:n,height:r}=t;if(!n||!r)return null;let i=null;if(typeof OffscreenCanvas<`u`)i=new OffscreenCanvas(n,r);else if(typeof document<`u`)i=document.createElement(`canvas`),i.width=n,i.height=r;else return null;try{let e=i.getContext(`2d`,{willReadFrequently:!0});return e?(e.drawImage(t,0,0),{data:e.getImageData(0,0,n,r).data,width:n,height:r,channels:4,topDown:!0,float:!1}):null}catch{return null}}function SA(e){let t=vk(e,`encoding`,`sRGB`);if(t===`linear`)return e=>e;let n=/^gamma\s+([\d.]+)$/.exec(t);return n?e=>e**Number(n[1]):Vk}function CA(e){return{su:_k(e,`uscale`,1),sv:_k(e,`vscale`,1),du:_k(e,`udelta`,0),dv:_k(e,`vdelta`,0)}}function wA(e,{su:t,sv:n,du:r,dv:i}){e.repeat.set(t,n),e.offset.set(r,i)}function TA(e,{srgb:t}){let n=e?.image?.data;if(!ArrayBuffer.isView(n)||n instanceof Uint8Array||n instanceof Uint8ClampedArray)return e;let{width:i,height:a}=e.image,o=new Uint8Array(i*a*4),s=n.length/(i*a);for(let e=0;e<i*a;e++)for(let r=0;r<4;r++){let i=r<s?Math.min(1,Math.max(0,n[e*s+r])):1;o[e*4+r]=Math.round(255*(t&&r<3?Hk(i):i))}let c=new r.DataTexture(o,i,a,r.RGBAFormat);return c.flipY=e.flipY,c.colorSpace=t?r.SRGBColorSpace:r.NoColorSpace,c.wrapS=c.wrapT=r.RepeatWrapping,c.needsUpdate=!0,c}function EA({data:e,width:t,height:n,mapping:i},{srgb:a=!0}={}){let o=new r.DataTexture(e,t,n,r.RGBAFormat);return o.colorSpace=a?r.SRGBColorSpace:r.NoColorSpace,o.wrapS=o.wrapT=r.RepeatWrapping,wA(o,i),o.needsUpdate=!0,o}function DA(e,t,n){let r=e.isOrthographicCamera===!0,i=r?1:Math.tan(e.fov*Math.PI/360),a=r?50:12/i;return{enableDOF:!0,focusDistance:n,aperture:a*.001/(2*t),focalLength:a,apertureScale:1,anamorphicRatio:1,dofBlur:t/(n*i),autoFocusMode:`manual`,afScreenPoint:{x:.5,y:.5},orthoHeight:r?(e.top-e.bottom)/e.zoom:null}}function OA(e){let t={};return e.integrator?.maxdepth>0&&(t.maxBounces=Math.round(e.integrator.maxdepth)),e.sampler?.pixelsamples>0&&(t.samples=Math.round(e.sampler.pixelsamples)),e.film?.resolutionGiven&&(t.width=e.film.xresolution,t.height=e.film.yresolution),Object.keys(t).length?t:null}function kA(e){let t=_k(e,`radius`,1),n=_k(e,`zmin`,-t),r=_k(e,`zmax`,t),i=e=>Math.min(t,Math.max(-t,e));return{radius:t,zMin:i(Math.min(n,r)),zMax:i(Math.max(n,r)),phiMax:QA(e)}}function AA(e){let t=_k(e,`zmin`,-1),n=_k(e,`zmax`,1);return{radius:_k(e,`radius`,1),zMin:Math.min(t,n),zMax:Math.max(t,n),phiMax:QA(e)}}function jA(e){return{radius:_k(e,`radius`,1),inner:_k(e,`innerradius`,0),height:_k(e,`height`,0),phiMax:QA(e)}}function MA(e,t,n){let i=Math.max(3,Math.ceil(ZA*e/(2*Math.PI))),a=i+1,o=new Float32Array(a*(t+1)*3),s=new Float32Array(o.length),c=new Float32Array(a*(t+1)*2),l=new r.Vector3,u=new r.Vector3;for(let e=0;e<=t;e++)for(let r=0;r<=i;r++){let d=e*a+r;n(r/i,e/t,l,u),l.toArray(o,d*3),u.toArray(s,d*3),c[d*2]=r/i,c[d*2+1]=e/t}let d=0;for(let e=0;e<o.length;e++)d=Math.max(d,Math.abs(o[e]));let f=(e,t)=>Math.hypot(o[e*3]-o[t*3],o[e*3+1]-o[t*3+1],o[e*3+2]-o[t*3+2])>d*1e-6,p=[];for(let e=0;e<t;e++)for(let t=0;t<i;t++){let n=e*a+t,r=n+1,i=n+a,o=i+1;f(n,r)&&p.push(n,r,o),f(i,o)&&p.push(n,o,i)}let m=new r.BufferGeometry;return m.setAttribute(`position`,new r.Float32BufferAttribute(o,3)),m.setAttribute(`normal`,new r.Float32BufferAttribute(s,3)),m.setAttribute(`uv`,new r.Float32BufferAttribute(c,2)),m.setIndex(new r.Uint32BufferAttribute(new Uint32Array(p),1)),m}function NA(e,t){let n=e.params;switch(e.type){case`sphere`:{let{radius:e,zMin:t,zMax:r,phiMax:i}=kA(n);return i*e*(r-t)}case`cylinder`:{let{radius:e,zMin:t,zMax:r,phiMax:i}=AA(n);return i*e*(r-t)}case`disk`:{let{radius:e,inner:t,phiMax:r}=jA(n);return r*.5*(e*e-t*t)}}let i=new r.Matrix4().fromArray(e.ctm),a=t.getAttribute(`position`),o=t.index,s=o?o.count:a.count,c=new r.Vector3,l=new r.Vector3,u=new r.Vector3,d=0;for(let e=0;e+2<s;e+=3)c.fromBufferAttribute(a,o?o.getX(e):e).applyMatrix4(i),l.fromBufferAttribute(a,o?o.getX(e+1):e+1).applyMatrix4(i),u.fromBufferAttribute(a,o?o.getX(e+2):e+2).applyMatrix4(i),d+=l.sub(c).cross(u.sub(c)).length()/2;return d}function PA(e,t,n){let r=new Uint8Array(e*t*4);for(let i=0;i<t;i++)for(let a=0;a<e;a++){let o=n((a+.5)/e,(i+.5)/t),s=(i*e+a)*4;for(let e=0;e<3;e++)r[s+e]=Math.round(255*Hk(Math.min(1,Math.max(0,o[e]))));r[s+3]=255}return r}function FA(e){let t=e.clone();for(let n of Object.keys(e))n in t||(t[n]=e[n]);return t}function IA(e,t){let n=FA(e);return n.transparent=!0,n.opacity=e.opacity*t,n}function LA(e,t){if(e.float||!Ik(e))return null;let{data:n,width:i,height:a}=e,o=new Uint8Array(256);for(let e=0;e<256;e++)o[e]=Math.round(255*Math.min(1,Math.max(0,t(e/255))));let s=new Uint8Array(i*a*4),c=i*4;for(let t=0;t<a;t++){let r=(e.topDown?a-1-t:t)*c,i=t*c;for(let e=0;e<c;e+=4)s[i+e]=n[r+e],s[i+e+1]=n[r+e+1],s[i+e+2]=n[r+e+2],s[i+e+3]=o[n[r+e+3]]}let l=new r.DataTexture(s,i,a,r.RGBAFormat);return l.colorSpace=r.SRGBColorSpace,l.wrapS=l.wrapT=r.RepeatWrapping,l.needsUpdate=!0,l}function RA(e){let t=[e],n=e,r=[e=>e.replace(/-renamed-\d+$/,``),e=>e.replace(/\d+$/,``),e=>e.replace(/_Color$/i,``),e=>e.replace(/\d+$/,``)];for(let e of r){let r=e(n);r!==n&&r&&t.push(n=r)}return t}var zA,BA,VA,HA,UA,WA,GA,KA,qA,JA,YA,XA,ZA,QA,$A,ej,tj,nj,rj=g((()=>{gO(),Pk(),Wk(),Zk(),nA(),mA(),tk(),La(),zA=new Set([`distant`,`point`,`spot`]),BA=[1,0,0,0,0,1,0,0,0,0,-1,0,0,0,0,1],VA=4096,HA=1e3,UA=45e6,WA=6e6,GA=256,KA=4096,qA=5e5,JA=2,YA={flat:1,ribbon:1,cylinder:2},XA=.05,ZA=48,QA=e=>Math.min(360,Math.max(0,_k(e,`phimax`,360)))*Math.PI/180,$A=64,ej=64,tj=(e,{su:t,sv:n,du:r,dv:i})=>e.repeat.x===t&&e.repeat.y===n&&e.offset.x===r&&e.offset.y===i,nj=class{constructor(e={}){this.maxTriangles=e.maxTriangles??UA,this.maxPlacements=e.maxPlacements??WA,this.mergeShapesAbove=e.mergeShapesAbove??GA,this.curveSteps=e.curveSteps??JA,this.curveSides=e.curveSides??null,this.curveTolerance=e.curveTolerance??XA,this.resolvePLY=e.resolvePLY||(async()=>null),this.resolveImage=e.resolveImage||(async()=>null),this.resolveEnvironment=e.resolveEnvironment||e.resolveImage||(async()=>null),this.convertHandedness=e.convertHandedness===!0,this.warnings=[],this.report=[],this._materialCache=new Map,this._textureCache=new Map,this._geometryCache=new Map,this._materialBySignature=new Map,this._noUVMaterials=new Map,this._plyCache=new Map,this._imageCache=new Map,this._termCache=new Map,this._mediumMaterials=new Map,this._alphaMaterials=new Map}warn(e){this.warnings.push(e)}async build(e){this.ir=e,this._keepShapes=new Set;for(let{name:t}of e.animatedInstances??[])for(let n of e.objects.get(t)??[])this._keepShapes.add(n);this._plyUsers=new Map,this._plyHeld=new Set;for(let t of e.shapes)if(t?.type===`plymesh`){let e=vk(t.params,`filename`,null);this._plyUsers.set(e,(this._plyUsers.get(e)??0)+1)}for(let t of e.objects.values())for(let e of t)e.type===`plymesh`&&this._plyHeld.add(vk(e.params,`filename`,null));this._recoveredColors=0,this.reportedMeshes=0,this.triangleCount=0,this.placementCount=0,this.skippedForBudget=0,this._countedGeometries=new WeakSet;let t=new r.Group;t.name=`PBRTScene`,this._batches=e.shapes.length>=this.mergeShapesAbove?new Map:null,this._mergedBatches=0,this.mergedShapes=0,this.droppedNoTemplate=0,this._animated=[];for(let n=0;n<e.shapes.length;n++){if(this._overBudget()){this.skippedForBudget+=e.shapes.length-n;break}let r=e.shapes[n],[i,a]=await Promise.all([this._batches?this._createGeometry(r):this._buildGeometry(r),this._getMaterial(r)]);if(!i)continue;let o=r.areaLight?this._poweredMaterial(r,i,a):a;if(this._batches&&!r.motion&&i.getAttribute(`position`).count<=KA){this._mergeShape(r,i,o,t),e.shapes[n]=null;continue}r.type===`plymesh`&&this._plyHeld.add(vk(r.params,`filename`,null));let s=this._meshFromGeometry(r,i,o,r.ctm,`shape_${n}`);s&&(t.add(s),r.motion&&this._animate(s,r.motion))}if(this._batches){for(let e of this._batches.values())this._flushBatch(e[0],t),this._flushBatch(e[1],t);this._batches=null}await this._buildInstances(e,t),await this._buildAnimatedPlacements(e,t),this.skippedForBudget>0&&this.warn(`stopped at ${this.triangleCount.toLocaleString()} stored triangles (budget ${this.maxTriangles.toLocaleString()}) and ${this.placementCount.toLocaleString()} placements (budget ${this.maxPlacements.toLocaleString()}); ${this.skippedForBudget.toLocaleString()} placement(s) skipped`);let n=null;e.camera&&(n=this._buildCamera(e.camera,e.film),n&&t.add(n));let i=e.animation?this._buildClip(e,n):[],a=await this._buildEnvironment(e.lights);return await this._buildLamps(e.lights,t),this._reportUnsupportedLights(e.lights),this._recoveredColors>0&&this.warn(`${this._recoveredColors} unreadable texture(s) fell back to the like-named material's colour`),{group:t,camera:n,environment:a,animations:i,render:OA(e),report:this.report,meshCount:this.reportedMeshes,triangleCount:this.triangleCount,placementCount:this.placementCount,mergedShapes:this.mergedShapes,droppedNoTemplate:this.droppedNoTemplate,skippedForBudget:this.skippedForBudget,warnings:this.warnings.concat(e.warnings||[])}}_overBudget(){return this.triangleCount>=this.maxTriangles||this.placementCount>=this.maxPlacements}_accountGeometry(e){let t=e.index?e.index.count/3:e.getAttribute(`position`).count/3;return this._countedGeometries.has(e)||(this._countedGeometries.add(e),this.triangleCount+=t),t}async _buildInstances(e,t){let n=0;e.skippedInstances>0&&(this.skippedForBudget+=e.skippedInstances);let i=new Float64Array(16),a=new r.Matrix4,o=(e,o,s,c,l,u,d)=>{let f=Math.max(0,this.maxPlacements-this.placementCount),p=Math.min(e.count,f);if(p<e.count&&(this.skippedForBudget+=e.count-p),p===0)return;let m=new r.InstancedMesh(o,s,p);m.name=`instance_${n++}`,m.frustumCulled=!1;for(let t=0;t<p;t++){if(c)GO(i,e.matrices,t*16,c);else for(let n=0;n<16;n++)i[n]=e.matrices[t*16+n];m.setMatrixAt(t,a.fromArray(this.convertHandedness?KO(BA,i):i))}m.instanceMatrix.needsUpdate=!0,t.add(m),this.placementCount+=p,this.reportedMeshes+=p,this.report.length<HA&&this.report.push({mesh:`${m.name} ×${p}`,shape:l,material:u,color:`#`+s.color.getHexString(),map:s.map?`yes`:`-`,uv:o.getAttribute(`uv`)?`yes`:`NO`,normals:o.getAttribute(`normal`)?`yes`:`NO`,emissive:s.emissiveIntensity>0?`#${s.emissive.getHexString()}×${s.emissiveIntensity}`:`-`,size:`instanced`,tris:d})},s=(e,t)=>{t&&t.triangles>0&&o(e,this._batchGeometry(t),t.material,null,`merged`,`-`,t.triangles)};for(let{name:t,list:n,template:r}of this._samePlacementGroups(e)){if(!r){this.droppedNoTemplate+=n.count,this.warn(`ObjectInstance "${t}" has no template — ${n.count.toLocaleString()} placement(s) dropped`);continue}let e=0;for(let t of r)t.type!==`plymesh`&&e++;let i=e>=2?new Map:null;for(let e of r){if(this._overBudget()){this.skippedForBudget+=n.count;continue}let[r,a]=await Promise.all([this._buildGeometry(e),this._getMaterial(e)]);if(!r)continue;if(i&&e.type!==`plymesh`&&r.getAttribute(`position`).count<=KA){this._geometryCache.delete(e);let t=this._appendToBatch(i,e,r,a,e.relativeCTM||e.ctm);this._releaseMerged(e,r),s(n,t);continue}let c=this._accountGeometry(r);o(n,r,this._materialForGeometry(e,r,a,`instances_${t}`),e.relativeCTM||e.ctm,e.type,e.material?.type||`diffuse`,c)}if(i)for(let e of i.values())s(n,e[0]),s(n,e[1]);pO(n.matrices),pO(n.matricesEnd)}}_samePlacementGroups(e){let t=[],n=new Map;for(let[r,i]of e.instances){let a=e.objects.get(r);if(!a||i.matricesEnd){t.push({name:r,list:i,template:a});continue}let o=`${i.count}:${Array.prototype.join.call(i.matrices.subarray(0,16),`,`)}`,s=n.get(o);s||n.set(o,s=[]);let c=s.find(e=>yA(e.list,i));if(c){c.template===e.objects.get(c.name)&&(c.template=c.template.slice());for(let e of a)c.template.push(e);pO(i.matrices);continue}let l={name:r,list:i,template:a};s.push(l),t.push(l)}return t}async _buildAnimatedPlacements(e,t){let n=e.animatedInstances??[];for(let i=0;i<n.length;i++){let{name:a,motion:o}=n[i],s=e.objects.get(a);if(!s){this.droppedNoTemplate++;continue}if(this._overBudget()){this.skippedForBudget+=n.length-i;break}let c=new r.Group;c.name=`placement_${i}`;let l=Array.from(o.matrices.subarray(0,16));new r.Matrix4().fromArray(this.convertHandedness?KO(BA,l):l).decompose(c.position,c.quaternion,c.scale);for(let e=0;e<s.length;e++){let t=s[e],[n,r]=await Promise.all([this._buildGeometry(t),this._getMaterial(t)]);if(!n)continue;let i=this._meshFromGeometry(t,n,r,t.relativeCTM||t.ctm,`${c.name}_${e}`,!0);i&&c.add(i)}c.children.length!==0&&(t.add(c),this._animate(c,o))}}_animate(e,t){t.visible&&(e.visible=t.visible[0]===1),this._animated.push({node:e,motion:t})}_buildClip(e,t){let n=[];for(let{node:e,motion:t}of this._animated)if(this._transformTracks(n,e.name,t,(e,t)=>{let n=Array.from(e.subarray(t,t+16));return this.convertHandedness?KO(BA,n):n}),t.visible){let i=t.times,a=i.map((e,t)=>t===0?0:(i[t-1]+e)/2);n.push(new r.BooleanKeyframeTrack(`${e.name}.visible`,a,Array.from(t.visible,e=>e===1)))}let i=e.camera?.motion;if(t&&i){let e=new r.PerspectiveCamera;if(this._transformTracks(n,t.name,i,(t,n)=>(this._poseCamera(e,t.subarray(n,n+16)),e.updateMatrix(),e.matrix.elements)),i.fov&&t.isPerspectiveCamera){let e=Array.from(i.fov,e=>this._verticalFov({fov:{type:`float`,value:[e]}},t.aspect));n.push(new r.NumberKeyframeTrack(`${t.name}.fov`,i.times.slice(),e))}}for(let e of n)e.optimize();return n.length===0?[]:[new r.AnimationClip(e.animation.name,e.animation.duration,n)]}_transformTracks(e,t,n,i){let a=n.times.length,o=new Float32Array(a*3),s=new Float32Array(a*4),c=new Float32Array(a*3),l=new r.Matrix4,u=new r.Vector3,d=new r.Quaternion,f=new r.Vector3;for(let e=0;e<a;e++)l.fromArray(i(n.matrices,e*16)).decompose(u,d,f),e>0&&d.x*s[e*4-4]+d.y*s[e*4-3]+d.z*s[e*4-2]+d.w*s[e*4-1]<0&&d.set(-d.x,-d.y,-d.z,-d.w),u.toArray(o,e*3),d.toArray(s,e*4),f.toArray(c,e*3);let p=(e,t)=>{for(let n=t;n<e.length;n++)if(e[n]!==e[n%t])return!0;return!1};p(o,3)&&e.push(new r.VectorKeyframeTrack(`${t}.position`,n.times.slice(),o)),p(s,4)&&e.push(new r.QuaternionKeyframeTrack(`${t}.quaternion`,n.times.slice(),s)),p(c,3)&&e.push(new r.VectorKeyframeTrack(`${t}.scale`,n.times.slice(),c))}async _buildShapeMesh(e,t,n){let[r,i]=await Promise.all([this._buildGeometry(e),this._getMaterial(e)]);return r?this._meshFromGeometry(e,r,i,t,n):null}_meshFromGeometry(e,t,n,i,a,o=!1){let s=!!t.getAttribute(`uv`),c=this._materialForGeometry(e,t,n,a),l=new r.Mesh(t,c);l.name=a;let u=this.convertHandedness&&!o?KO(BA,i):i;new r.Matrix4().fromArray(u).decompose(l.position,l.quaternion,l.scale),l.updateMatrix(),t.boundingBox||t.computeBoundingBox();let d=t.boundingBox?t.boundingBox.clone().applyMatrix4(l.matrix).getSize(new r.Vector3):new r.Vector3,f=this._accountGeometry(t);return this.placementCount++,this.reportedMeshes++,this.report.length<HA&&this.report.push({mesh:a,shape:e.type,material:e.material?.type||`diffuse`,color:`#`+c.color.getHexString(),map:c.map?`yes`:`-`,uv:s?`yes`:`NO`,normals:t.getAttribute(`normal`)?`yes`:`NO`,emissive:c.emissiveIntensity>0?`#${c.emissive.getHexString()}×${c.emissiveIntensity}`:`-`,size:`${d.x.toFixed(2)}×${d.y.toFixed(2)}×${d.z.toFixed(2)}`,tris:f}),l}_materialForGeometry(e,t,n,r){if(!n.map||t.getAttribute(`uv`))return n;let i=this._noUVMaterials.get(n);return i||(this.warn(`${r} (${e.type}, "${e.material?.type||`diffuse`}") has a texture map but no UVs — dropping map, using base color`),i=FA(n),i.map=null,this._noUVMaterials.set(n,i)),i}_mergeShape(e,t,n,r){this.reportedMeshes++;let i=this.convertHandedness?KO(BA,e.ctm):e.ctm,a=this._appendToBatch(this._batches,e,t,n,i);this._releaseMerged(e,t),a&&this._flushBatch(a,r)}_releaseMerged(e,t){if(!this._keepShapes?.has(e)&&!(e.type===`plymesh`&&!this._lastPlyUse(vk(e.params,`filename`,null)))){for(let e in t.attributes)pO(t.attributes[e].array);pO(t.index?.array);for(let t in e.params)ArrayBuffer.isView(e.params[t]?.value)&&pO(e.params[t].value)}}_lastPlyUse(e){let t=(this._plyUsers.get(e)??1)-1;return this._plyUsers.set(e,t),t>0||this._plyHeld.has(e)?!1:(this._plyCache.delete(e),!0)}_appendToBatch(e,t,n,r,i){let a=this._materialForGeometry(t,n,r,`merged shape`),o=n.getAttribute(`position`),s=n.getAttribute(`normal`),c=n.getAttribute(`uv`),l=n.index,u=o.count;this.triangleCount+=(l?l.count:u)/3,this.mergedShapes++;let d=e.get(a);d||e.set(a,d=[null,null]);let f=+!!c,p=d[f];p||(d[f]=p={material:a,positions:new Float32Array(3072),normals:new Float32Array(3072),uvs:c?new Float32Array(2048):null,indices:new Uint32Array(3072),vertexCount:0,indexCount:0,triangles:0});let m=i,h=ek(m),g=p.vertexCount;p.positions=_A(p.positions,(g+u)*3),p.normals=_A(p.normals,(g+u)*3),c&&(p.uvs=_A(p.uvs,(g+u)*2));let _=o.array,v=p.positions,y=s?s.array:null,b=p.normals;for(let e=0;e<u;e++){let t=e*3,n=(g+e)*3,r=_[t],i=_[t+1],a=_[t+2];if(v[n]=m[0]*r+m[4]*i+m[8]*a+m[12],v[n+1]=m[1]*r+m[5]*i+m[9]*a+m[13],v[n+2]=m[2]*r+m[6]*i+m[10]*a+m[14],!y)continue;let o=y[t],s=y[t+1],c=y[t+2],l=h[0]*o+h[1]*s+h[2]*c,u=h[4]*o+h[5]*s+h[6]*c,d=h[8]*o+h[9]*s+h[10]*c,f=Math.hypot(l,u,d);f>0&&(l/=f,u/=f,d/=f),b[n]=l,b[n+1]=u,b[n+2]=d}c&&p.uvs.set(c.array.subarray(0,u*2),g*2);let x=l?l.count:u;p.indices=_A(p.indices,p.indexCount+x);let S=p.indices,C=l?l.array:null;for(let e=0;e<x;e++)S[p.indexCount+e]=g+(C?C[e]:e);return p.vertexCount+=u,p.indexCount+=x,p.triangles+=x/3,p.triangles>=qA?(d[f]=null,p):null}_batchGeometry(e){let t=new r.BufferGeometry;return t.setAttribute(`position`,new r.Float32BufferAttribute(mO(e.positions,e.vertexCount*3),3)),t.setAttribute(`normal`,new r.Float32BufferAttribute(mO(e.normals,e.vertexCount*3),3)),e.uvs&&t.setAttribute(`uv`,new r.Float32BufferAttribute(mO(e.uvs,e.vertexCount*2),2)),t.setIndex(new r.Uint32BufferAttribute(mO(e.indices,e.indexCount),1)),e.positions=e.normals=e.uvs=e.indices=null,t}_flushBatch(e,t){if(!e||e.triangles===0)return;let n=new r.Mesh(this._batchGeometry(e),e.material);n.name=`merged_${this._mergedBatches++}`,n.frustumCulled=!1,t.add(n),this.placementCount++,this.report.length<HA&&this.report.push({mesh:n.name,shape:`merged`,material:`-`,color:`#`+e.material.color.getHexString(),map:e.material.map?`yes`:`-`,uv:e.uvs?`yes`:`NO`,normals:`yes`,emissive:e.material.emissiveIntensity>0?`#${e.material.emissive.getHexString()}×${e.material.emissiveIntensity}`:`-`,size:`merged`,tris:e.triangles})}_buildGeometry(e){let t=this._geometryCache.get(e);return t||this._geometryCache.set(e,t=this._createGeometry(e)),t}async _createGeometry(e){let t=await this._shapeGeometry(e);return t&&e.areaLight&&!yk(e.areaLight.params,`twosided`,!1)?this._facingEmission(e,t):t}_facingEmission(e,t){let n=t.userData.pbrtNormals?t.getAttribute(`normal`):null;if(!n&&!e.reverseOrientation)return t;let i=t.getAttribute(`position`).array,a=n?.array,o=t.index?.array??null,s=o?o.length:t.getAttribute(`position`).count,c=new Uint32Array(s),l=0;for(let t=0;t+2<s;t+=3){let n=o?o[t]:t,r=o?o[t+1]:t+1,s=o?o[t+2]:t+2,u=e.reverseOrientation;if(a){let e=i[r*3]-i[n*3],t=i[r*3+1]-i[n*3+1],o=i[r*3+2]-i[n*3+2],c=i[s*3]-i[n*3],l=i[s*3+1]-i[n*3+1],d=i[s*3+2]-i[n*3+2],f=a[n*3]+a[r*3]+a[s*3],p=a[n*3+1]+a[r*3+1]+a[s*3+1],m=a[n*3+2]+a[r*3+2]+a[s*3+2];u=(t*d-o*l)*f+(o*c-e*d)*p+(e*l-t*c)*m<0}c[t]=n,c[t+1]=u?s:r,c[t+2]=u?r:s,u&&l++}if(l===0)return t;let u=new r.BufferGeometry;for(let e in t.attributes)u.setAttribute(e,t.getAttribute(e));return u.setIndex(new r.Uint32BufferAttribute(c,1)),u}_shapeGeometry(e){switch(e.type){case`trianglemesh`:return this._triangleMesh(e.params);case`bilinearmesh`:return this._bilinearMesh(e.params);case`loopsubdiv`:return this._loopSubdiv(e.params);case`curve`:return this._curve(e.params);case`plymesh`:return this._plyMesh(e.params);case`sphere`:return this._sphere(e.params);case`disk`:return this._disk(e.params);case`cylinder`:return this._cylinder(e.params);default:return this.warn(`shape "${e.type}" not supported — skipped`),null}}_triangleMesh(e){let t=e.P?.value;if(!t||t.length<9)return this.warn(`trianglemesh missing P`),null;let n=new r.BufferGeometry;n.setAttribute(`position`,new r.Float32BufferAttribute(vA(t),3));let i=e.N?.value;i&&i.length===t.length&&(n.setAttribute(`normal`,new r.Float32BufferAttribute(vA(i),3)),n.userData.pbrtNormals=!0);let a=(e.uv||e.st)?.value;a&&a.length===t.length/3*2&&n.setAttribute(`uv`,new r.Float32BufferAttribute(vA(a),2));let o=e.indices?.value;return o&&o.length&&n.setIndex(gA(o)),i||n.computeVertexNormals(),n}_curve(e){let t=e.P?.value;if(!t||t.length<12)return this.warn(`curve needs at least 4 control points`),null;let n=Math.round(_k(e,`degree`,3));if(n!==3)return this.warn(`curve degree ${n} not supported — only cubic`),null;let i=vk(e,`type`,`flat`),a=_k(e,`width`,1),o=fA({P:t,basis:vk(e,`basis`,`bezier`),width0:_k(e,`width0`,a),width1:_k(e,`width1`,a),N:e.N?.value||null,steps:this.curveSteps,sides:this.curveSides??YA[i]??1,tolerance:this.curveTolerance});if(!o)return this.warn(`curve could not be tessellated`),null;let s=new r.BufferGeometry;return s.setAttribute(`position`,new r.Float32BufferAttribute(o.positions,3)),s.setIndex(new r.Uint32BufferAttribute(o.indices,1)),s.computeVertexNormals(),s}_loopSubdiv(e){let t=e.P?.value,n=e.indices?.value;if(!t||t.length<9||!n||n.length<3)return this.warn(`loopsubdiv missing P/indices`),null;let i=Math.max(0,Math.min(6,Math.round(_k(e,`levels`,3)))),{positions:a,indices:o,levels:s}=Xk(t,n,i);s<i&&this.warn(`loopsubdiv refined ${s}/${i} levels — the control mesh is too dense for the triangle budget`);let c=new r.BufferGeometry;return c.setAttribute(`position`,new r.Float32BufferAttribute(a,3)),c.setIndex(new r.Uint32BufferAttribute(o,1)),c.computeVertexNormals(),c}_bilinearMesh(e){let t=e.P?.value,n=e.indices?.value??(t?.length===12?[0,1,2,3]:null);if(!t||!n)return this.warn(`bilinearmesh missing P/indices`),null;let i=t.length/3,a=e.uv?.value?.length===i*2?e.uv.value:null,o=e.N?.value?.length===i*3?e.N.value:null,s=new r.BufferGeometry;if(a){let e=[];for(let t=0;t+3<n.length;t+=4){let[r,i,a,o]=[n[t],n[t+1],n[t+2],n[t+3]];e.push(r,i,o,r,o,a)}s.setAttribute(`position`,new r.Float32BufferAttribute(Float32Array.from(t),3)),s.setAttribute(`uv`,new r.Float32BufferAttribute(Float32Array.from(a),2)),o&&s.setAttribute(`normal`,new r.Float32BufferAttribute(Float32Array.from(o),3)),s.setIndex(new r.Uint32BufferAttribute(new Uint32Array(e),1))}else{let e=Math.floor(n.length/4),i=new Float32Array(e*12),a=o?new Float32Array(e*12):null,c=new Float32Array(e*8),l=new Uint32Array(e*6);for(let r=0;r<e;r++){for(let e=0;e<4;e++){let s=n[r*4+e];for(let n=0;n<3;n++)i[r*12+e*3+n]=t[s*3+n],a&&(a[r*12+e*3+n]=o[s*3+n]);c[r*8+e*2]=e&1,c[r*8+e*2+1]=e>>1}l.set([0,1,3,0,3,2].map(e=>r*4+e),r*6)}s.setAttribute(`position`,new r.Float32BufferAttribute(i,3)),s.setAttribute(`uv`,new r.Float32BufferAttribute(c,2)),a&&s.setAttribute(`normal`,new r.Float32BufferAttribute(a,3)),s.setIndex(new r.Uint32BufferAttribute(l,1))}return o?s.userData.pbrtNormals=!0:s.computeVertexNormals(),s}_plyMesh(e){let t=vk(e,`filename`,null);if(!t)return this.warn(`plymesh missing filename`),null;let n=this._plyCache.get(t);return n||this._plyCache.set(t,n=this._decodePly(t)),n}async _decodePly(e){try{let t=await this.resolvePLY(e);return t?(t.getAttribute(`normal`)?t.userData.pbrtNormals=!0:t.computeVertexNormals(),t):(this.warn(`plymesh file not found: ${e}`),null)}catch(t){return this.warn(`failed to load plymesh ${e}: ${t.message}`),null}}_sphere(e){let{radius:t,zMin:n,zMax:r,phiMax:i}=kA(e),a=Math.acos(n/t),o=Math.acos(r/t);return MA(i,Math.max(1,Math.ceil(32*(a-o)/Math.PI)),(e,n,r,s)=>{let c=e*i,l=a+n*(o-a);s.set(Math.sin(l)*Math.cos(c),Math.sin(l)*Math.sin(c),Math.cos(l)),r.copy(s).multiplyScalar(t)})}_cylinder(e){let{radius:t,zMin:n,zMax:r,phiMax:i}=AA(e);return MA(i,1,(e,a,o,s)=>{let c=e*i;s.set(Math.cos(c),Math.sin(c),0),o.set(t*s.x,t*s.y,n+a*(r-n))})}_disk(e){let{radius:t,inner:n,height:r,phiMax:i}=jA(e);return MA(i,1,(e,a,o,s)=>{let c=e*i,l=t-a*(t-n);o.set(l*Math.cos(c),l*Math.sin(c),r),s.set(0,0,1)})}async _getMaterial(e){let t=await this._surfaceMaterial(e);return e.interior&&(t=await this._inMedium(t,e.interior)),e.params.alpha?this._withAlpha(t,e.params.alpha):t}_withAlpha(e,t){let n=t.type===`texture`?t.value[0]:`#${t.value[0]}`,r=this._alphaMaterials.get(e);return r||this._alphaMaterials.set(e,r=new Map),r.has(n)||r.set(n,this._createAlphaMaterial(e,t)),r.get(n)}async _createAlphaMaterial(e,t){if(t.type!==`texture`)return t.value[0]<1?IA(e,t.value[0]):e;let n=t.value[0],r=await this._alphaMap(e.map,n);if(!r)return this.warn(`shape alpha "${n}" could not be read here — drawn opaque`),e;if(r.constant!==void 0)return r.constant<1?IA(e,r.constant):e;let i=FA(e);return i.map=r,i.transparent=!0,i}async _alphaMap(e,t){let n=this.ir.namedTextures.get(t),r=n?.class===`imagemap`?vk(n.params,`filename`,null):null;if(r&&e?.userData.pbrtImage===r&&vk(n.params,`mapping`,`uv`)===`uv`&&_k(n.params,`scale`,1)===1&&!yk(n.params,`invert`,!1)&&tj(e,CA(n.params))){let t=xA(e),r=t&&LA(t,SA(n.params));if(r)return wA(r,CA(n.params)),r}let i=await this._bakeTerm(t,1);if(!i)return null;if(!i.layer)return{constant:i.rgb[0]};let a=e?this._textureLayer(e,3):null;if(e&&!a)return null;let o=zk([a?{layer:a}:{rgb:[1,1,1]},i],([e])=>e,{alphaOf:([,e])=>e[0]});return o&&EA(o)}async _surfaceMaterial(e){let t=this._materialCache.get(e.material);if(t||(t=new Map,this._materialCache.set(e.material,t)),t.has(e.areaLight))return t.get(e.areaLight);let n=this._materialContext(),r=await Ok(e.material,n);e.areaLight&&await this._applyAreaLight(r,e.areaLight,n);let i=this._dedupeMaterial(r);return t.set(e.areaLight,i),i}_materialContext(){return this._ctx??={resolveNamedTexture:e=>this._resolveNamedTexture(e),namedMaterials:this.ir.namedMaterials,warn:e=>this.warn(e),floatTextureMean:async e=>{let t=await this._bakeTerm(e,1);return t?t.layer?Lk(t.layer):t.rgb[0]:null},bakeMaterialMix:(e,t,n)=>this._bakeMaterialMix(e,t,n),bakeFloatMap:(e,t,n)=>this._floatMap(e,t,n),textureMeanRGB:async e=>{let t=await this._bakeTerm(e,3);if(!t?.layer)return t?.rgb??null;let{data:n}=t.layer,r=[0,0,0];for(let e=0;e<n.length;e++)r[e%3]+=n[e];return r.map((e,r)=>e/(n.length/3)*(t.tint?.[r]??1))},resolveNormalMap:async e=>{let t=await this._image(e);if(!t)return null;let n=TA(t,{srgb:!1}),i=n===t?t.clone():n;return i.colorSpace=r.NoColorSpace,i}}}async _inMedium(e,t){if(!(e.transmission>0))return e;let n=this._mediumMaterials.get(e);return n||this._mediumMaterials.set(e,n=new Map),n.has(t)||n.set(t,this._attenuated(e,t)),n.get(t)}async _attenuated(e,t){let n=this.ir.media?.get(t),r=n&&vk(n,`type`,``);if(r!==`homogeneous`)return this.warn(n?`medium "${t}" (${r}) is not supported — "${t}" glass left clear`:`medium "${t}" not defined`),e;n.preset&&this.warn(`medium preset "${vk(n,`preset`,``)}" is not supported — using sigma_a / sigma_s`);let i=this._materialContext(),a=(await bk(n,`sigma_a`,i,[1,1,1])).rgb,o=(await bk(n,`sigma_s`,i,[1,1,1])).rgb,s=_k(n,`scale`,1),c=[0,1,2].map(e=>(a[e]+o[e])*s),l=Math.max(...c);if(!(l>0))return e;let u=FA(e);return u.attenuationDistance=1/l,u.attenuationColor.setRGB(...c.map(e=>Math.exp(-e/l))),this._dedupeMaterial(u)}_dedupeMaterial(e){let t=e.color,n=e.emissive,r=`${t.r},${t.g},${t.b}|${n.r},${n.g},${n.b}|${e.emissiveIntensity}|${e.map?e.map.uuid:`-`}|${e.roughness}|${e.roughnessMap?.uuid??`-`}|${e.metalness}|${e.transmission}|${e.ior}|${e.thickness}|${e.clearcoat}|${e.clearcoatRoughness}|${e.clearcoatRoughnessMap?.uuid??`-`}|${e.opacity}|${e.side}|${e.normalMap?e.normalMap.uuid:`-`}|${e.attenuationDistance}|${e.attenuationColor.toArray()}|${e.specularIntensity}|${e.diffuseTransmission??0}|${e.diffuseTransmissionColor?.toArray()??`-`}|${e.subsurface??0}|${e.subsurfaceColor?.toArray()??`-`}|${e.subsurfaceRadius??`-`}|${e.subsurfaceAnisotropy??0}`;return this._materialBySignature.get(r)||(this._materialBySignature.set(r,e),e)}_poweredMaterial(e,t,n){let r=_k(e.areaLight.params,`power`,-1);if(!(r>0))return n;let i=NA(e,t)*(yk(e.areaLight.params,`twosided`,!1)?2:1);if(!(i>0))return n;let a=FA(n);return a.emissiveIntensity=n.emissiveIntensity*r/(Math.PI*i),a}async _applyAreaLight(e,t,n){let i=await hA(t.params,`L`,n),a=_k(t.params,`scale`,1);e.emissive.setRGB(i[0],i[1],i[2]),e.emissiveIntensity=a,e.side=yk(t.params,`twosided`,!1)?r.DoubleSide:r.FrontSide}async _resolveNamedTexture(e){if(this._textureCache.has(e))return this._textureCache.get(e);let t=this.ir.namedTextures.get(e),n=null;if(!t)this.warn(`named texture "${e}" not defined`);else if(t.class===`imagemap`)n=await this._imageMapTexture(e,t);else if(t.class===`mix`)n=await this._mixTexture(e,t);else if(t.class===`constant`){let e=t.params.value;e&&e.type===`rgb`?n={constant:[e.value[0],e.value[1],e.value[2]]}:e&&(n={constant:[e.value[0],e.value[0],e.value[0]]})}else if(t.class===`checkerboard`||t.class===`bilerp`)n=await this._proceduralTexture(e,t);else if(t.class===`scale`)n=await this._resolveScaleTexture(e,t);else{let r=this._colorFromLikeNamedMaterial(e);r?(n={constant:r.rgb},this._recoveredColors++):this.warn(`texture class "${t.class}" not supported (texture "${e}")`)}return this._textureCache.set(e,n),n}async _proceduralTexture(e,t){let n=t.params,r=this._materialContext(),i=async(e,t)=>{let i=n[e];return i?.type===`texture`?await r.textureMeanRGB(i.value[0])??t:(await bk(n,e,r,t)).rgb??t},a=vk(n,`mapping`,`uv`);a!==`uv`&&this.warn(`texture "${e}": "${a}" mapping is not supported — using the mesh's uv`);let{su:o,sv:s,du:c,dv:l}=CA(n);if(t.class===`checkerboard`){if(_k(n,`dimension`,2)!==2)return this.warn(`texture "${e}": a 3D checkerboard is not supported`),null;let[t,r]=await Promise.all([i(`tex1`,[1,1,1]),i(`tex2`,[0,0,0])]),a=2*$A;return{texture:EA({data:PA(a,a,(e,n)=>(Math.floor(2*e)+Math.floor(2*n))%2?r:t),width:a,height:a,mapping:{su:o/2,sv:s/2,du:c/2,dv:l/2}})}}let[u,d,f,p]=await Promise.all([i(`v00`,[0,0,0]),i(`v01`,[1,1,1]),i(`v10`,[0,0,0]),i(`v11`,[1,1,1])]);return{texture:EA({data:PA(ej,ej,(e,t)=>[0,1,2].map(n=>(1-e)*(1-t)*u[n]+e*(1-t)*f[n]+(1-e)*t*d[n]+e*t*p[n])),width:ej,height:ej,mapping:{su:o,sv:s,du:c,dv:l}})}}_image(e){let t=this._imageCache.get(e);return t||(t=Promise.resolve().then(()=>this.resolveImage(e)).catch(t=>(this.warn(`failed to load image ${e}: ${t.message}`),null)),this._imageCache.set(e,t)),t}async _imageMapTexture(e,t){let n=vk(t.params,`filename`,null);if(!n)return null;let r=await this._image(n);if(!r)return this.warn(`image not found for texture "${e}": ${n}`),null;let i=vk(t.params,`mapping`,`uv`);i!==`uv`&&this.warn(`texture "${e}": "${i}" mapping is not supported — using the mesh's uv`);let a=_k(t.params,`scale`,1);if(a>1||yk(t.params,`invert`,!1)){let t=await this._bakeTerm(e,3),n=t?.layer&&zk([{...t,clamp:!0}],([e])=>e);if(n)return{texture:EA(n)};this.warn(`texture "${e}": its scale or invert could not be baked here — ignored`)}let o=TA(r,{srgb:!0}),s=o===r?r.clone():o;return s.userData.pbrtImage=n,wA(s,CA(t.params)),s.needsUpdate=!0,a<1?{texture:s,constant:[a,a,a]}:{texture:s}}async _floatMap(e,t,n){let r=await Promise.all(t.map(t=>this._paramTerm(e,t,1,[0,0,0])));if(r.some(e=>!e))return null;let i=zk(r,e=>{let t=n(e.map(e=>e[0]));return[t,t,t]},{linear:!0});return i&&EA(i,{srgb:!1})}async _mixTexture(e,t){let[n,r,i]=await Promise.all([this._paramTerm(t.params,`tex1`,3,[0,0,0]),this._paramTerm(t.params,`tex2`,3,[1,1,1]),this._paramTerm(t.params,`amount`,1,[.5,.5,.5])]);if(!n||!r||!i)return this.warn(`texture "${e}": a "mix" input could not be read here`),null;let a=e=>e.map(e=>Math.min(1,Math.max(0,e))),o=zk([{...n,clamp:!0},{...r,clamp:!0},i],Uk);return o?{texture:EA(o)}:{constant:Uk([a(n.rgb),a(r.rgb),i.rgb])}}async _paramTerm(e,t,n,r){let i=e[t];if(!i)return{rgb:r};if(i.type===`texture`)return this._bakeTerm(i.value[0],n);let a=(await bk(e,t,this._materialContext(),r)).rgb;return a?{rgb:a}:null}_bakeTerm(e,t){let n=`${e}\0${t}`,r=this._termCache.get(n);return r||this._termCache.set(n,r=this._createBakeTerm(e,t)),r}async _createBakeTerm(e,t){let n=this.ir.namedTextures.get(e);if(n?.class===`imagemap`){if(vk(n.params,`mapping`,`uv`)!==`uv`)return null;let e=vk(n.params,`filename`,null),r=xA(e&&await this._image(e));return r?{layer:Fk(r,{channels:t,decode:r.float?null:SA(n.params),scale:_k(n.params,`scale`,1),invert:yk(n.params,`invert`,!1),mapping:CA(n.params)})}:null}let r=await this._resolveNamedTexture(e);if(!r)return null;if(!r.texture)return r.constant?{rgb:r.constant}:null;let i=this._textureLayer(r.texture,t);return i?{layer:i,tint:r.constant??null}:null}_textureLayer(e,t){let n=xA(e);if(!n)return null;let i=!n.float&&e.colorSpace===r.SRGBColorSpace;return Fk(n,{channels:t,decode:n.float?null:i?Vk:e=>e,mapping:{su:e.repeat.x,sv:e.repeat.y,du:e.offset.x,dv:e.offset.y}})}async _bakeMaterialMix(e,t,n){let r=await this._bakeTerm(n,1);if(!r)return null;if(!r.layer)return{mean:r.rgb[0],texture:null};let i=Lk(r.layer),a=e=>{if(!e.map)return{rgb:e.color.toArray(),clamp:!0};let t=this._textureLayer(e.map,3);return t&&{layer:t,tint:e.color.toArray(),clamp:!0}},o=a(e),s=a(t);if(!o||!s)return{mean:i,texture:null};let c=zk([o,s,r],Uk);return{mean:i,texture:c?EA(c):null}}_colorFromLikeNamedMaterial(e){for(let t of RA(e)){let e=(this.ir?.namedMaterials?.get(t))?.params?.reflectance;if(e&&(e.type===`rgb`||e.type===`color`))return{name:t,rgb:[e.value[0],e.value[1],e.value[2]]}}return null}async _resolveScaleTexture(e,t){if(t.params.scale?.type===`texture`){let[n,r]=await Promise.all([this._paramTerm(t.params,`tex`,3,[1,1,1]),this._paramTerm(t.params,`scale`,1,[1,1,1])]),i=([e,t])=>[e[0]*t[0],e[1]*t[0],e[2]*t[0]];if(n&&r){let e=zk([{...n,clamp:!0},r],i);return e?{texture:EA(e)}:{constant:i([n.rgb,r.rgb])}}this.warn(`texture "${e}": its "scale" texture could not be read here — ignored`)}let n=t.params.tex,r=null;if(n?.type===`texture`&&typeof n.value[0]==`string`)r=await this._resolveNamedTexture(n.value[0]);else if(n?.type===`rgb`||n?.type===`color`)r={constant:[n.value[0],n.value[1],n.value[2]]};else if(n?.type===`float`){let e=n.value[0];r={constant:[e,e,e]}}let i=t.params.scale,a=[1,1,1];if(i?.type===`rgb`||i?.type===`color`)a=[i.value[0],i.value[1],i.value[2]];else if(i?.type===`float`){let e=i.value[0];a=[e,e,e]}if(r?.texture){let e=r.constant||[1,1,1];return{texture:r.texture,constant:[e[0]*a[0],e[1]*a[1],e[2]*a[2]]}}let o=r?.constant||[1,1,1];return{constant:[o[0]*a[0],o[1]*a[1],o[2]*a[2]]}}_buildCamera(e,t){let n=t&&t.yresolution?t.xresolution/t.yresolution:16/9,i;if(e.type===`orthographic`){let t=e.params?.screenwindow?.value,a=t?.length===4?(t[3]-t[2])/2:Math.max(1,1/n);i=new r.OrthographicCamera(-a*n,a*n,a,-a,.01,1e4)}else i=new r.PerspectiveCamera(this._verticalFov(e.params,n),n,.01,1e4);i.name=`PBRT Camera`,this._poseCamera(i,e.cameraToWorld),i.updateMatrixWorld(!0);let a=_k(e.params,`lensradius`,0);return a>0&&(i.userData.__rayzeeEffects=DA(i,a,_k(e.params,`focaldistance`,1e6))),i}_poseCamera(e,t){let n=t,i=new r.Vector3(n[12],n[13],n[14]),a=new r.Vector3(n[8],n[9],n[10]),o=new r.Vector3(n[4],n[5],n[6]);this.convertHandedness&&(i.z*=-1,a.z*=-1,o.z*=-1),e.up.copy(o.normalize()),e.position.copy(i),e.scale.set(1,1,1),e.lookAt(i.clone().add(a)),WO(t)>0!==this.convertHandedness&&(e.scale.x=-1)}_verticalFov(e,t){let n=_k(e,`fov`,90);if(t>=1)return n;let r=n*Math.PI/180;return 2*Math.atan(Math.tan(r/2)/t)*180/Math.PI}_equirectFromInfiniteLight(e,t,n,i){let a=e.image;if(!a?.width||a.width!==a.height)return a?.width!==a?.height&&this.warn(`infinite-light image "${i}" is ${a?.width}x${a?.height}, not square — read as equirectangular, but pbrt would read it as equal-area octahedral`),null;let o=null;if(a.data){let e=a.data.length/(a.width*a.height);if(!Number.isInteger(e)||e<3)return null;o={data:a.data,width:a.width,height:a.height,channels:e,bottomUp:!0}}else if(o=bA(a,e.colorSpace===r.SRGBColorSpace),!o)return this.warn(`infinite-light image "${i}" could not be read back for octahedral conversion`),null;let{data:s,width:c,height:l}=eA(o,t.ctm,n),u=new r.DataTexture(s,c,l,r.RGBAFormat,r.FloatType);return u.mapping=r.EquirectangularReflectionMapping,u.minFilter=r.LinearFilter,u.magFilter=r.LinearFilter,u.needsUpdate=!0,u}async _buildEnvironment(e){let t=e.find(e=>e.type===`infinite`);if(!t)return null;let n=_k(t.params,`scale`,1),i=vk(t.params,`filename`,null);if(i)try{let e=await this.resolveEnvironment(i);if(e){let a=this._equirectFromInfiniteLight(e,t,n,i);return a?{texture:a}:(e.mapping=r.EquirectangularReflectionMapping,{texture:e})}this.warn(`infinite-light image not found: ${i}`)}catch(e){this.warn(`failed to load infinite-light image ${i}: ${e.message}`)}let a=(await hA(t.params,`L`,{resolveNamedTexture:async()=>null,warn:e=>this.warn(e)})).map(e=>e*n),o=new Float32Array(8);for(let e=0;e<2;e++)o[e*4+0]=a[0],o[e*4+1]=a[1],o[e*4+2]=a[2],o[e*4+3]=1;let s=new r.DataTexture(o,2,1,r.RGBAFormat,r.FloatType);return s.mapping=r.EquirectangularReflectionMapping,s.minFilter=r.LinearFilter,s.magFilter=r.LinearFilter,s.needsUpdate=!0,{texture:s}}async _buildLamps(e,t){let n={resolveNamedTexture:async()=>null,warn:e=>this.warn(e)};for(let i of e){if(!zA.has(i.type))continue;let e=new r.Matrix4().fromArray(this.convertHandedness?KO(BA,i.ctm):i.ctm),a=(t,n)=>{let a=i.params[t]?.value;return new r.Vector3().fromArray(a?.length>=3?a:n).applyMatrix4(e)},o=await hA(i.params,i.type===`distant`?`L`:`I`,n),s=_k(i.params,`scale`,1),c=a(`from`,[0,0,0]),l=a(`to`,[0,0,1]),u;if(i.type===`distant`){let e=_k(i.params,`illuminance`,-1);e>0&&(s*=e),u=new r.DirectionalLight,u.userData.__luxConverted=!0}else if(i.type===`point`){let e=_k(i.params,`power`,-1);s*=e>0?e:4*Math.PI,u=new r.PointLight,u.userData.__candelaConverted=!0}else{let e=Math.min(Math.max(_k(i.params,`coneangle`,30),0),90)*Math.PI/180,t=Math.min(Math.max(_k(i.params,`conedeltaangle`,5)*Math.PI/180,0),e),n=Math.cos(e),a=Math.cos(e-t),o=_k(i.params,`power`,-1);o>0&&(s*=o/(2*Math.PI*(1-a+(a-n)/2))),s*=4*Math.PI,u=new r.SpotLight,u.angle=e,u.penumbra=n<1?Math.min((a-n)/(1-n),1):0,u.userData.__candelaConverted=!0}let d=Math.max(o[0],o[1],o[2]);!(d>0)||!(s>0)||(u.color.setRGB(o[0]/d,o[1]/d,o[2]/d),u.intensity=d*s,u.name=`pbrt ${i.type}`,u.position.copy(c),u.decay=2,u.distance=0,u.target&&(u.target.position.subVectors(l,c),u.add(u.target)),t.add(u))}}_reportUnsupportedLights(e){for(let t of e)t.type!==`infinite`&&!zA.has(t.type)&&this.warn(`light "${t.type}" not supported (only infinite, distant, point and spot lights and emissive area lights are mapped)`)}}}));function ij(e){let t=e[0],n=e=>{let t=e.lastIndexOf(`/`),n=/^(.*?)(\d+)\.pbrt$/i.exec(e.slice(t+1));return n?{group:e.slice(0,t+1)+`\0`+n[1].toLowerCase(),number:parseInt(n[2],10)}:null},r=t?n(t):null;if(!r)return null;let i=new Map;for(let t of e){let e=n(t);e&&e.group===r.group&&!i.has(e.number)&&i.set(e.number,t)}return i.size<2?null:[...i].sort((e,t)=>e[0]-t[0]).slice(0,hj).map(([e,t])=>({path:t,number:e}))}function aj(e){let t=e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint32Array?new Uint32Array(e.buffer,e.byteOffset,e.length):null;t||=new Uint32Array(Float32Array.from(e).buffer);let n=2166136261;for(let e=0;e<t.length;e++)n=Math.imul(n^t[e],16777619),n^=n>>>15;return(n>>>0).toString(36)+`:`+e.length}function oj(e){let t=``;for(let n of Object.keys(e).sort()){let{type:r,value:i}=e[n],a=ArrayBuffer.isView(i)||i.length>16&&typeof i[0]==`number`;t+=`${r} ${n}=${a?`#`+aj(i):i.join(`,`)};`}return t}function sj(e,t){let n=new Int32Array(t.length).fill(-1),r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];)n[r]=r,r++;let i=e.length,a=t.length;for(;i>r&&a>r&&e[i-1]===t[a-1];)n[--a]=--i;return r<i&&r<a&&!cj(e,r,i,t,r,a,n)&&uj(e,r,i,t,r,a,n),n}function cj(e,t,n,r,i,a,o){let s=n-t,c=a-i,l=Math.min(s+c,gj),u=l+1,d=new Int32Array(2*l+3),f=[];for(let n=0;n<=l;n++){for(let a=-n;a<=n;a+=2){let l=a===-n||a!==n&&d[u+a-1]<d[u+a+1]?d[u+a+1]:d[u+a-1]+1,p=l-a;for(;l<s&&p<c&&e[t+l]===r[i+p];)l++,p++;if(d[u+a]=l,l>=s&&p>=c)return f.push(d.slice(u-n,u+n+1)),lj(f,s,c,t,i,o),!0}f.push(d.slice(u-n,u+n+1))}return!1}function lj(e,t,n,r,i,a){let o=t,s=n;for(let t=e.length-1;t>0;t--){let n=e[t-1],c=e=>n[e+t-1],l=o-s,u=l===-t||l!==t&&c(l-1)<c(l+1)?l+1:l-1,d=c(u),f=d-u;for(;o>d&&s>f;)a[i+--s]=r+--o;o=d,s=f}for(;o>0&&s>0;)a[i+--s]=r+--o}function uj(e,t,n,r,i,a,o){let s=new Map;for(let r=t;r<n;r++){let t=s.get(e[r]);t?t.push(r):s.set(e[r],[r])}let c=new Map;for(let e=i;e<a;e++){let t=s.get(r[e]);if(!t)continue;let n=c.get(r[e])??0;n<t.length&&(o[e]=t[n],c.set(r[e],n+1))}}function dj(e,t,n,r){for(let i=0;i<16;i++)if(e[t+i]!==n[r+i])return!1;return!0}function fj(e,t,n){let r=e.length,i=new Float32Array(16*r),a=null,o=-1;for(let e=0;e<r;e++)if(t(e)){if(i.set(n(e),e*16),o<0)for(let t=0;t<e;t++)i.copyWithin(t*16,e*16,e*16+16);o=e}else a??=new Uint8Array(r).fill(1),a[e]=0,o>=0&&i.copyWithin(e*16,o*16,o*16+16);return{times:e,matrices:i,visible:a}}function pj(e){if(e.visible)return!1;let t=e.matrices;for(let e=16;e<t.length;e+=16)if(!dj(t,0,t,e))return!1;return!0}function mj(e){if(!e.hasMotion)return e;let{start:t,end:n}=e.transformTimes,r=n-t;if(!(r>0))return e;let i=Float32Array.of(0,r),a=(e,t,n,r)=>{let a=new Float32Array(32);for(let i=0;i<16;i++)a[i]=e[t+i],a[16+i]=n[r+i];return{times:i,matrices:a,visible:null}};for(let t of e.shapes)t.ctmEnd&&(t.motion=a(t.ctm,0,t.ctmEnd,0));e.animatedInstances=[];for(let t of e.instances.values()){if(!t.matricesEnd)continue;let n=[];for(let r=0;r<t.count;r++){let i=r*16;dj(t.matrices,i,t.matricesEnd,i)||e.animatedInstances.length>=_j?n.push(r):e.animatedInstances.push({name:t.name,motion:a(t.matrices,i,t.matricesEnd,i)})}if(n.length!==t.count){let r=new Float32Array(n.length*16);n.forEach((e,n)=>r.set(t.matrices.subarray(e*16,e*16+16),n*16)),e.instanceCount-=t.count-n.length,t.matrices=r,t.count=n.length}t.matricesEnd=null}return e.camera?.cameraToWorldEnd&&(e.camera.motion={...a(e.camera.cameraToWorld,0,e.camera.cameraToWorldEnd,0),fov:null}),e.animation={name:`Shutter motion`,duration:r,frames:2},e}var hj,gj,_j,vj,yj,bj=g((()=>{hj=1e3,gj=2048,_j=1e5,vj=class{constructor(e){this.materialNames=new Map;for(let[t,n]of e.namedMaterials)this.materialNames.set(n,t);this.cache=new Map}of(e){return`${e.type}|${+!!e.reverseOrientation}|${oj(e.params)}|${this._material(e.material)}|${this._light(e.areaLight)}`}_material(e){if(!e)return`-`;let t=this.cache.get(e);if(t===void 0){let n=this.materialNames.get(e)??e._missingRef;t=n===void 0?`I:`+e.type+`:`+oj(e.params):`N:`+n,this.cache.set(e,t)}return t}_light(e){if(!e)return`-`;let t=this.cache.get(e);return t===void 0&&this.cache.set(e,t=`L:`+e.type+`:`+oj(e.params)),t}},yj=class{constructor(e,t){this.times=Float32Array.from(e),this.name=t,this.base=null,this.frame=-1,this.keyIds=new Map,this.tracks=[],this.prev=null,this.placements=new Map,this.templates=new Map,this.cameras=[],this.warnings=new Set}addFrame(e){let t=++this.frame;t===0?this.base=e:this._adoptDefinitions(e);for(let t of e.warnings)this.warnings.add(t);let n=new vj(e),r=new Int32Array(e.shapes.length);for(let t=0;t<r.length;t++){let i=n.of(e.shapes[t]),a=this.keyIds.get(i);a===void 0&&this.keyIds.set(i,a=this.keyIds.size),r[t]=a}let i=this.prev?sj(this.prev.keys,r):null,a=Array(r.length);for(let o=0;o<r.length;o++){let r=e.shapes[o],s=i&&i[o]>=0?this.prev.tracks[i[o]]:null;s?(s.last=t,s.ctms?s.ctms.push(r.ctm):r.ctm!==s.shape.ctm&&!dj(r.ctm,0,s.shape.ctm,0)&&(s.ctms=Array(t-s.first).fill(s.shape.ctm),s.ctms.push(r.ctm))):(s={shape:r,first:t,last:t,ctms:null},t>0&&this._adoptMaterial(r,n.materialNames),this.tracks.push(s)),a[o]=s}this.prev={keys:r,tracks:a},this._addPlacements(e,t,this._resolveTemplates(e,t,n)),this.cameras.push(e.camera?{cameraToWorld:e.camera.cameraToWorld,fov:e.camera.params?.fov?.value?.[0]}:null)}_adoptDefinitions(e){for(let[t,n]of e.namedMaterials)this.base.namedMaterials.has(t)||this.base.namedMaterials.set(t,n);for(let[t,n]of e.namedTextures)this.base.namedTextures.has(t)||this.base.namedTextures.set(t,n)}_resolveTemplates(e,t,n){let r=new Map;for(let[i,a]of e.objects){let e=``;for(let t of a)e+=n.of(t)+`@`+Array.prototype.join.call(t.relativeCTM||t.ctm,`,`)+`;`;let o=i+`\0`+e,s=this.templates.get(o);if(s===void 0&&(s=t===0||!this.base.objects.has(i)?i:`${i} @${t}`,this.templates.set(o,s),t>0)){for(let e of a)this._adoptMaterial(e,n.materialNames);this.base.objects.set(s,a)}r.set(i,s)}return r}_adoptMaterial(e,t){let n=e.material&&t.get(e.material);n!==void 0&&(e.material=this.base.namedMaterials.get(n)??e.material)}_addPlacements(e,t,n){for(let[r,i]of e.instances){let e=n.get(r)??r,a=this.placements.get(e);if(a||this.placements.set(e,a={counts:new Int32Array(this.times.length),diffs:new Map}),a.counts[t]=i.count,t===0)continue;let o=this.base.instances.get(e),s=o?.count??0;for(let e=0;e<i.count;e++){let n=e*16;if(e<s&&dj(i.matrices,n,o.matrices,n))continue;let r=a.diffs.get(e);r||a.diffs.set(e,r=new Map),r.set(t,i.matrices.slice(n,n+16))}}}finish(){let e=this.base,t=this.times,n=this.frame+1;e.shapes=this.tracks.map(e=>{let{shape:r,first:i,last:a,ctms:o}=e;return(i>0||a<n-1||o)&&(r.motion=fj(t,e=>e>=i&&e<=a,e=>o?o[e-i]:r.ctm)),r}),e.warnings=[...this.warnings],e.animatedInstances=this._finishPlacements(e,t,n);let r=this.cameras;if(r[0]&&r.every(Boolean)){let n=fj(t,()=>!0,e=>r[e].cameraToWorld),i=r.map(e=>e.fov??r[0].fov),a=i.some(e=>e!==i[0]);(!pj(n)||a)&&(e.camera.motion={...n,fov:a?Float32Array.from(i):null})}return e.animation={name:this.name,duration:t[n-1],frames:n},e}_finishPlacements(e,t,n){let r=[],i=0;for(let[a,{counts:o,diffs:s}]of this.placements){let c=e.instances.get(a),l=c?.count??0,u=Math.max(...o.subarray(0,n)),d=[];for(let e=0;e<u;e++){let u=s.get(e),f=!!u;for(let t=0;t<n&&!f;t++)f=e>=o[t];if(f&&r.length<_j){let n=fj(t,t=>e<o[t],t=>u?.get(t)??c.matrices.subarray(e*16,e*16+16));r.push({name:a,motion:n})}else f&&i++,e<l&&d.push(e)}if(c&&d.length!==l){let t=new Float32Array(d.length*16);d.forEach((e,n)=>t.set(c.matrices.subarray(e*16,e*16+16),n*16)),e.instanceCount-=l-d.length,c.matrices=t,c.matricesEnd=null,c.count=d.length}}return i>0&&e.warnings.push(`${i.toLocaleString()} moving placement(s) past ${_j.toLocaleString()} left static`),r}}}));function xj(e){let t=e.replace(/\\/g,`/`).split(`/`),n=[];for(let e of t)e===``||e===`.`||(e===`..`?n.pop():n.push(e));return n.join(`/`)}function Sj(e,t){return!e||t.startsWith(`/`)?xj(t):xj(`${e}/${t}`)}function Cj(e,t,n=0){let r=t[0],i=e.length-t.length;outer:for(let a=n;a<=i;a++)if(e[a]===r){for(let n=1;n<t.length;n++)if(e[a+n]!==t[n])continue outer;return a}return-1}function wj(e,t){for(let n=t-1;n>=0;n--){let t=e[n];if(t===10)return!0;if(t!==32&&t!==9)return!1}return!0}function Tj(e){for(let t=Cj(e,Rj);t>=0;t=Cj(e,Rj,t+1))if(wj(e,t))return!0;return!1}function Ej(e,t){for(let n of zj)for(let r=Cj(e,n);r>=0;r=Cj(e,n,r+1)){if(!wj(e,r))continue;let i=r+n.length;for(;i<e.length&&(e[i]===32||e[i]===9);)i++;if(e[i]!==34)continue;let a=++i;for(;i<e.length&&e[i]!==34&&e[i]!==10;)i++;if(e[i]!==34)continue;let o=Pj.decode(e.subarray(a,i));t.add(xj(o).toLowerCase().split(`/`).pop())}}function Dj(e){let t=Object.keys(e).filter(e=>e.toLowerCase().endsWith(`.pbrt`));if(t.length<=1)return t;let n=new Set,r=new Map;for(let i of t){let t=e[i];r.set(i,Tj(t)),Ej(t,n)}return Oj(t,r,n)}function Oj(e,t,n){let r=(e,t)=>{let n=e.filter(t);return n.length?n:e},i=r(e,e=>t.get(e));return i=r(i,e=>!n.has(e.toLowerCase().split(`/`).pop())),i=r(i,e=>/(^|\/)(scene|main)\.pbrt$/i.test(e)),i.sort((e,t)=>{let n=e.split(`/`).length,r=t.split(`/`).length;return n===r?e.length===t.length?e<t?-1:+(e>t):e.length-t.length:n-r})}function kj(e){return Dj(e)[0]||null}async function Aj(e){let t=e.records.filter(e=>e.norm.endsWith(`.pbrt`));if(t.length===0)return[];if(t.length===1)return[t[0].key];let n=async n=>{let r=new Set,i=new Map,a=!1;for(let o of t){let t=await n(o);t&&(i.set(o.key,Tj(t)),Ej(t,r),t.length>=Lj&&(a=!0),o.lazy&&(e.release(o),pO(t)))}return{included:r,worlds:i,cut:a}},r=await n(t=>e.readHead(t,Lj)),{included:i,worlds:a}=[...r.worlds.values()].filter(Boolean).length===1||!r.cut?r:await n(t=>e.read(t));return Oj(t.map(e=>e.key),a,i)}async function jj(e){let{vfs:t,source:n,plyParser:r,imageFromBytes:i,envFromBytes:a,convertHandedness:o}=e,s=new Fj(t,n),c=[],l=await Aj(s);if(l.length===0)throw Error(`PBRT loader: no .pbrt file found in archive`);let u=e.entryPath&&l.includes(e.entryPath)?e.entryPath:null;e.entryPath&&!u&&c.push(`PBRT entry "${e.entryPath}" is not a scene in this archive — auto-detecting instead`);let d=u||l[0],f=async t=>{let n=await s.readPath(t);if(!n)throw Error(`PBRT loader: entry "${t}" not readable`);let r=await new lk({resolveInclude:(e,t)=>s.readPath(e,t),releaseInclude:(e,t,n)=>s.releasePath(e,t,n),maxPlacements:e.maxPlacements,instanceIncludes:e.instanceIncludes}).parse(n,t.includes(`/`)?t.slice(0,t.lastIndexOf(`/`)):``);return s.releasePath(t,null,n),r},p=performance.now(),m=!u&&e.animation!==!1?ij(l):null,h;if(m){let e=await f(m[0].path);if(e.shapes.length+e.instanceCount>Nj)c.push(`${m.length} animation frames found, but the scene is too large to parse once per frame — loaded "${m[0].path}" only`),m=null,h=mj(e);else{let t=new yj(m.map(e=>(e.number-m[0].number)/30),Mj(m));t.addFrame(e);for(let e=1;e<m.length;e++)t.addFrame(await f(m[e].path));h=t.finish()}}else h=mj(await f(d));let g=performance.now()-p;s.releaseScenes();let _=e=>e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),v=new Map,y=async e=>{let t=await s.read(e);return t?(s.release(e),r(_(t))):null},b=new nj({convertHandedness:o,maxTriangles:e.maxTriangles,maxPlacements:e.maxPlacements,mergeShapesAbove:e.mergeShapesAbove,curveSteps:e.curveSteps,curveSides:e.curveSides,curveTolerance:e.curveTolerance,resolvePLY:async e=>{let t=s.findRecord(e);return t?(v.has(t.norm)||v.set(t.norm,await y(t)),v.get(t.norm)):null},resolveImage:async e=>{let t=await s.readPath(e);return t?i(t,e):null},resolveEnvironment:async e=>{let t=await s.readPath(e);return t?(a||i)(t,e):null}}),x=performance.now(),S=await b.build(h);return{...S,entryPath:m?m[0].path:d,frames:m?m.map(e=>e.path):null,candidates:l,warnings:[...c,...S.warnings??[]],parseMs:g,buildMs:performance.now()-x}}function Mj(e){let t=e[0].path.split(`/`);return`${t.length>1?t[t.length-2]:t[0].replace(/\d+\.pbrt$/i,``)||`frames`} · frames ${e[0].number}–${e[e.length-1].number}`}var Nj,Pj,Fj,Ij,Lj,Rj,zj,Bj=g((()=>{gO(),uk(),rj(),bj(),HO(),Nj=2e6,Pj=new TextDecoder,Fj=class{constructor(e,t=null){this.entries=e,this.source=t,this.records=[],this.byPath=new Map,this.byBase=new Map;let n=(e,t,n)=>{let r=xj(e).toLowerCase();if(this.byPath.has(r))return;let i={key:e,norm:r,bytes:t,lazy:n};this.records.push(i),this.byPath.set(r,i);let a=r.split(`/`).pop(),o=this.byBase.get(a);o?o.push(i):this.byBase.set(a,[i])};for(let t in e)n(t,e[t],!1);for(let e of t?.listing??[])e.offset!==void 0&&n(e.path,null,!0)}async read(e){return e?e.bytes?e.bytes:!e.lazy||!this.source?null:this.source.read(e.key):null}async readHead(e,t){return e?e.bytes?e.bytes.subarray(0,t):!e.lazy||!this.source?null:this.source.readHead?this.source.readHead(e.key,t):this.source.read(e.key):null}async readPath(e,t=null){let n=t!==null&&this.findRecord(Sj(t,e))||this.findRecord(e);return this.read(n)}release(e){e.bytes=null,delete this.entries[e.key]}releasePath(e,t=null,n=null){let r=t!==null&&this.findRecord(Sj(t,e))||this.findRecord(e);r?.lazy&&(this.release(r),pO(n))}releaseScenes(){for(let e of this.records)e.norm.endsWith(`.pbrt`)&&this.release(e)}findRecord(e){let t=xj(e).toLowerCase();if(this.byPath.has(t))return this.byPath.get(t);let n=this.byBase.get(t.split(`/`).pop());return n?n.find(e=>e.norm.endsWith(`/`+t))||(n.length===1?n[0]:null):null}find(e){return this.findRecord(e)?.bytes??null}},Ij=e=>Uint8Array.from(e,e=>e.charCodeAt(0)),Lj=4*1024*1024,Rj=Ij(`WorldBegin`),zj=[Ij(`Include`),Ij(`Import`)]}));function Vj(e){let t=0,n=()=>{for(;t<e.length&&e[t]<=32;)t++;let n=t;for(;t<e.length&&e[t]>32;)t++;return String.fromCharCode(...e.subarray(n,t))},r=n();if(r!==`PF`&&r!==`Pf`)throw Error(`not a PFM image`);let i=parseInt(n(),10),a=parseInt(n(),10),o=parseFloat(n());t++;let s=r===`PF`?3:1,c=i*a;if(!(i>0&&a>0)||!Number.isFinite(o)||o===0)throw Error(`bad PFM header`);if(e.length-t<c*s*4)throw Error(`PFM image is truncated`);let l=new DataView(e.buffer,e.byteOffset+t,c*s*4),u=o<0,d=Math.abs(o),f=new Float32Array(c*4);for(let e=0;e<c;e++){for(let t=0;t<3;t++)f[e*4+t]=l.getFloat32((e*s+(s===3?t:0))*4,u)*d;f[e*4+3]=1}return{data:f,width:i,height:a}}function Hj(e){let{data:t,width:n,height:i}=Vj(e),a=new r.DataTexture(t,n,i,r.RGBAFormat,r.FloatType);return a.minFilter=r.LinearFilter,a.magFilter=r.LinearFilter,a.needsUpdate=!0,a}var Uj=g((()=>{})),Wj=_({ARCHIVE_ELEMENT_PROMPT_BYTES:()=>Jj,ArchiveImporter:()=>Yj}),Gj,Kj,qj,Jj,Yj,Xj=g((()=>{gD(),jD(),RD(),Jr(),Jg(),nn(),fO(),Is(),Ms(),fe(),Bj(),Uj(),z_(),X(),Gj=/\.(usd|usda|usdc)$/i,Kj=/\.(png|jpg|jpeg|avif)$/i,qj=3e4,Jj=4e9,Yj=class e{static FORMATS=OS;constructor(e){this.loader=e,this._pendingGraph=null,this.lastPBRTStats=null}release(){this._pendingGraph=null}async _readHead(e,t=512){return e instanceof Uint8Array?e.subarray(0,t):typeof e.slice==`function`&&typeof e.arrayBuffer==`function`?new Uint8Array(await e.slice(0,t).arrayBuffer()):new Uint8Array((await this.loader.readFileAsArrayBuffer(e)).slice(0,t))}async inspectArchive(e){let t=KE(await this._readHead(e)),n=e=>z({isLoading:!0,status:`Scanning archive… ${(e.bytes/1e9).toFixed(1)} GB`,progress:4}),r;if(t===`gzip`){let t=await this._unpackGzip(e,e.name);t?(r=t.index.listing,t.release()):{listing:r}=await nD(e,{filter:()=>!1,onProgress:n})}else r=t===`tar`?(await PD(e,this.loader.storage))?.listing??await rD(e,{onProgress:n}):(await bD(e)).map(e=>({path:e.name,size:e.size}));let{root:i,elements:a}=sD(r);return{kind:t??`zip`,root:i,elements:a,entryCount:r.length,totalBytes:r.reduce((e,t)=>e+t.size,0)}}async _unpackGzip(e,t,n=null){let r=(Array.isArray(n)?n:[n]).filter(Boolean);try{return await ND(e,{storage:this.loader.storage,label:t,...r.length?{filter:oD(r),part:[...r].sort().join(`,`)}:{},onProgress:e=>z({isLoading:!0,status:`Unpacking archive… ${(e/1e9).toFixed(1)} GB`,progress:4})})}catch(e){return console.warn(`Unpacking "${t}" to storage failed, reading it in memory: ${e.message}`),null}}async loadArchiveFromFile(e,t,{pbrtEntry:n=null,element:r=null,byteBudget:i,promptBytes:a,...o}={}){try{let s=KE(await this._readHead(e)),c=this.loader.storage?Vg(await Bg(e)):null,l={element:r,promptBytes:a,pbrtEntry:n,pbrt:o,archiveId:c};if(s===`tar`)return await this._loadSeekable(e,t,l);if(s===`gzip`){let a=await this._unpackGzip(e,t,r);if(a)try{return await this._loadSeekable(a.file,t,{...l,index:a.index})}finally{a.release()}let u=await this._readStreamedArchive(e,t,s,r,i);if(kj(u))return await this.loadPBRTFromZip(u,t,n,o);let d=await this._loadNonPBRTArchive(u,t);return this.loader._sourceKey=this.loader._keyed(`archive`,c),d}return await this._loadSeekable(e,t,{...l,zip:!0})}catch(e){throw e?.code!==`ARCHIVE_NEEDS_ELEMENT`&&console.error(`Error loading archive:`,e),e}}async _loadNonPBRTArchive(e,t){return await this.processObjMtlPairsInZip(e,t)||await this.findAndLoadModelFromZip(e,t)}async _loadSeekable(e,t,{element:n,promptBytes:r,pbrtEntry:i,pbrt:a,index:o=null,zip:s=!1,archiveId:c=null}){let l=await this._openSeekableArchive(e,t,n,r,{index:o,zip:s});if(l.archiveId=c,l.elements=(Array.isArray(n)?n:[n]).filter(Boolean),l.listing.some(e=>e.path.toLowerCase().endsWith(`.pbrt`)))return await this.loadPBRTFromZip({},t,i,a,l);for(let e of l.listing)e.offset!==void 0&&(l.entries[e.path]??=await l.read(e.path));let u=await this._loadNonPBRTArchive(l.entries,t);return this.loader._sourceKey=this.loader._keyed(`archive`,c),u}async _loadStoredGraph(e,t,{imageFromBytes:n,envFromBytes:r}){let i=this.loader.storage?.area(tn.SCENES),a=i?await i.open(e):null;if(!a)return null;let o=performance.now(),s=null;try{z({isLoading:!0,status:`Opening the stored scene...`,progress:6});let e=await a.json(`graph.json`),i=await a.file(`data.bin`),s=new Fj({},t),c=await $D(e,i,{loadTexture:async(e,t)=>{let i=await s.readPath(e);return i?t===`environment`?r(i,e):n(i,e):null}});return{...c.stats,group:c.root,environment:c.environment?{texture:c.environment}:null,animations:c.animations,report:null,parseMs:0,buildMs:performance.now()-o,fromStorage:!0}}catch(e){return s=e,null}finally{a.release(),s&&(console.warn(`The stored scene could not be used, parsing the archive instead: ${s.message}`),this.loader._issues?.warn(Y.STORAGE_ENTRY_CORRUPT,`stored scene unusable: ${s.message}`,{key:e}),i.remove(e).catch(()=>{}))}}_storeGraph(e,t,n){let r=this.loader.storage?.area(tn.SCENES);if(!r)return;let i;try{i=KD(t.group,{environment:t.environment?.texture??null,animations:t.animations??[],stats:{meshCount:t.meshCount,entryPath:t.entryPath,candidates:t.candidates,frames:t.frames,warnings:t.warnings,triangleCount:t.triangleCount,placementCount:t.placementCount,mergedShapes:t.mergedShapes,skippedForBudget:t.skippedForBudget,droppedNoTemplate:t.droppedNoTemplate,render:t.render??null}})}catch(e){e instanceof uO?console.info(`Scene not stored for next time: ${e.message}`):console.warn(`Scene not stored for next time:`,e);return}let a={key:e,encoded:i,label:n,parseMs:(t.parseMs??0)+(t.buildMs??0),triangles:t.triangleCount??null};Ns(a.parseMs,i.byteLength)?this._writeGraph(r,a):this._pendingGraph=a}flushPendingGraph(e){let t=this._pendingGraph;this._pendingGraph=null;let n=this.loader.storage?.area(tn.SCENES);!t||!n||!Ns(t.parseMs+e,t.encoded.byteLength)||this._writeGraph(n,t)}_writeGraph(e,t){(async()=>{let n=await e.create(t.key,{label:`${t.label} (scene)`,expectedBytes:t.encoded.byteLength});if(n)try{await qD(n,t.encoded,{release:!0}),await n.commit({triangles:t.triangles})}catch(e){await n.abort(),console.warn(`Storing the scene failed:`,e)}})().catch(e=>console.warn(`Storing the scene failed:`,e))}async _openSeekableArchive(e,t,n,r,{index:i=null,zip:a=!1}={}){let o=Array.isArray(n)?n.filter(Boolean):n?[n]:[],s=o.length?oD(o):null,c;if(a)c=await CD(e,{filter:s});else{let t=i??await PD(e,this.loader.storage);c=await aD(e,{index:t,headersOnly:!0,filter:s,onProgress:e=>z({isLoading:!0,status:`Indexing archive… ${(e.bytes/1e9).toFixed(1)} GB`,progress:4})}),t||FD(e,this.loader.storage,c.index).catch(()=>{})}let l=c.listing.reduce((e,t)=>e+t.size,0);return o.length===0&&this._requireElementChoice(t,c.listing,l,r),console.info(`Archive "${t}": indexed ${c.indexed} entries, ${(l/1e9).toFixed(1)} GB, none resident`+(o.length?`, ${o.length} part${o.length>1?`s`:``} selected.`:`.`)),c}_requireElementChoice(e,t,n,r=Jj){if(n<r)return;let{root:i,elements:a}=sD(t);if(a.length<2)return;let o=Error(`"${e}" holds ${(n/1e9).toFixed(1)} GB across ${a.length} parts. Choose which to load — loading all of them at once may exhaust memory.`);throw o.code=`ARCHIVE_NEEDS_ELEMENT`,o.root=i,o.elements=a,o.totalBytes=n,this.loader._issues?.record(Y.ASSET_ARCHIVE_TOO_LARGE,`archive holds ${(n/1e9).toFixed(1)} GB across ${a.length} parts; choose which to load`,{root:i,elements:a.map(e=>e.prefix),totalBytes:n},Wt.WARNING),o}async _readStreamedArchive(e,t,n,r,i){let a=Array.isArray(r)?r.filter(Boolean):r?[r]:[],{entries:o,listing:s,retainedBytes:c,truncated:l}=await nD(e,{filter:a.length?oD(a):null,...i===void 0?{}:{byteBudget:i},onProgress:e=>z({isLoading:!0,status:`Reading archive… ${(e.bytes/1e9).toFixed(1)} GB`,progress:4})});if(l&&a.length===0){let{root:e,elements:n}=sD(s),r=s.reduce((e,t)=>e+t.size,0),i=Error(`"${t}" unpacks to ${(r/1e9).toFixed(1)} GB, past the load budget. Load one of its ${n.length} parts instead.`);throw i.code=`ARCHIVE_NEEDS_ELEMENT`,i.root=e,i.elements=n,i.totalBytes=r,this.loader._issues?.record(Y.ASSET_ARCHIVE_TOO_LARGE,`archive unpacks to ${(r/1e9).toFixed(1)} GB; choose one of ${n.length} parts`,{root:e,elements:n.map(e=>e.prefix),totalBytes:r},Wt.WARNING),i}if(l){let e=oD(a),t=s.filter(t=>e(t.path,t.size)&&!o[t.path]).length;this.loader._issues?.record(Y.ASSET_ARCHIVE_TOO_LARGE,`${t} files of the chosen parts were left out: they did not fit the ${((i??15e8)/1e9).toFixed(1)} GB in-memory read budget`,{elements:a,missing:t,retainedBytes:c},Wt.WARNING)}return a.length&&console.info(`Archive "${t}": loaded ${a.map(e=>`"${e}"`).join(`, `)} — ${Object.keys(o).length} of ${s.length} files, ${(c/1048576).toFixed(1)} MB.`),o}async loadPBRTFromZip(e,t,n=null,i={},a=null){if(z({isLoading:!0,status:`Parsing PBRT scene...`,progress:5}),!this.loader.loaderCache.ply){let{PLYLoader:e}=await import(`three/examples/jsm/loaders/PLYLoader.js`);this.loader.loaderCache.ply=new e}let o=e=>this.loader.loaderCache.ply.parse(e),s=async(e,t)=>{let n=await this._pbrtTextureFromBytes(e,t);return n&&(n.userData[tO]=t),n},c=async(e,t)=>{let n=t.split(`.`).pop().toLowerCase(),i=new Blob([e]),a=n===`pfm`?null:URL.createObjectURL(i);try{let o=a?await this.loader.loadEnvironmentByExtension(a,n,{loader:n===`exr`?this._exrLoader():null}):Hj(e);return o.mapping=r.EquirectangularReflectionMapping,Br(o,`bytes:${await zg(i)}`),o.userData[tO]=t,o.userData[nO]=`environment`,o}finally{a&&URL.revokeObjectURL(a)}},l=performance.now(),u={animation:i.animation,maxTriangles:i.maxTriangles,maxPlacements:i.maxPlacements,mergeShapesAbove:i.mergeShapesAbove,curveSteps:i.curveSteps,curveSides:i.curveSides,curveTolerance:i.curveTolerance,instanceIncludes:i.instanceIncludes},d=a?.archiveId?this.loader._keyed(`pbrt:2.9:${js}`,`${a.archiveId}|${n??``}|${[...a.elements??[]].sort().join(`,`)}|${JSON.stringify(u)}`):null,f=d?await this._loadStoredGraph(d,a,{imageFromBytes:s,envFromBytes:c}):null,p=f??await jj({vfs:e,source:a,entryPath:n,plyParser:o,imageFromBytes:s,envFromBytes:c,...u}),{group:m,environment:h,animations:g,report:_,warnings:v,meshCount:y,entryPath:b,candidates:x,frames:S,parseMs:C,buildMs:w,triangleCount:T,placementCount:E,mergedShapes:D,skippedForBudget:O,droppedNoTemplate:k}=p;f&&console.info(`PBRT scene "${b}" opened from storage in ${(w/1e3).toFixed(1)} s, skipping the parse`),this.lastPBRTStats={parseMs:C,buildMs:w,loaderMs:performance.now()-l,triangleCount:T,placementCount:E,mergedShapes:D,skippedForBudget:O,droppedNoTemplate:k,meshCount:y,frames:S?.length??1};let A=new Set(S??[b]),j=x.filter(e=>!A.has(e));if(j.length>0&&(console.warn(`PBRT archive holds ${x.length} scenes; loaded "${b}". Others: ${j.join(`, `)}`),this.loader._issues?.record(Y.ASSET_AMBIGUOUS_ENTRY,`archive holds ${x.length} pbrt scenes; loaded "${b}"`,{loaded:b,alternatives:j},Wt.WARNING)),_&&_.length&&typeof console.table==`function`){let e=_.length<y?` (first ${_.length} of ${y})`:``;console.groupCollapsed(`PBRT loader: ${y} mesh(es) from "${b}"${e}`),console.table(_),console.groupEnd()}return v&&v.length&&(console.warn(`PBRT loader: ${v.length} warning(s) parsing "${b}"`),v.forEach(e=>console.warn(` •`,e))),h?.texture&&(h.texture.generateMipmaps=!0,this.loader.applyEnvironmentToScene(h.texture)),m.name=b||t,this.loader.releaseTargetModel(),this.loader._sourceKey=d,d&&!f&&this._storeGraph(d,p,t),this.loader.targetModel=m,this.loader.animations=g??[],this.loader.sceneMetadata={environment:h?.texture?{rotation:0,intensity:1}:{enabled:!1},...p.render?{render:{...p.render}}:{}},z({isLoading:!0,status:`Processing PBRT geometry...`,progress:10}),await this.loader.onModelLoad(this.loader.targetModel),this.loader.dispatchEvent({type:`load`,model:m,filename:`${b} (from ZIP)`}),m}_exrLoader(){return this.loader.loaderCache.exr??=new p.EXRLoader().setDataType(r.FloatType)}async _pbrtTextureFromBytes(e,t){let n=t.split(`.`).pop().toLowerCase(),i;if(n===`exr`||n===`hdr`){let t=n===`hdr`?this.loader.loaderCache.hdr||(this.loader.loaderCache.hdr=new s.HDRLoader().setDataType(r.FloatType)):this._exrLoader();i=await this._loadViaObjectURL(t,e)}else if(n===`pfm`)i=Hj(e);else if(n===`tga`){if(!this.loader.loaderCache.tga){let{TGALoader:e}=await import(`three/examples/jsm/loaders/TGALoader.js`);this.loader.loaderCache.tga=new e}i=await this._loadViaObjectURL(this.loader.loaderCache.tga,e),i.colorSpace=r.SRGBColorSpace}else i=new r.Texture(await createImageBitmap(new Blob([e]))),i.colorSpace=r.SRGBColorSpace;return i.wrapS=i.wrapT=r.RepeatWrapping,i.needsUpdate=!0,i}async _loadViaObjectURL(e,t){let n=URL.createObjectURL(new Blob([t]));try{return await e.loadAsync(n)}finally{URL.revokeObjectURL(n)}}async processObjMtlPairsInZip(e,t){let n=[],r=[];for(let t in e){let i=t.toLowerCase();i.endsWith(`.obj`)?n.push({path:t,content:e[t]}):i.endsWith(`.mtl`)&&r.push({path:t,content:e[t]})}if(n.length>0&&r.length>0){console.log(`Found ${n.length} OBJ files and ${r.length} MTL files in ZIP`);let i=this.findMatchingObjMtlPairs(n,r);if(i.length>0)return console.log(`Found ${i.length} matching OBJ+MTL pairs`),await this.loadOBJMTLPairFromZip(i[0].obj,i[0].mtl,e,t);if(i.length===0)return console.log(`No matching pairs by name, using first OBJ and MTL files`),await this.loadOBJMTLPairFromZip(n[0],r[0],e,t)}return null}findMatchingObjMtlPairs(e,t){let n=[];for(let r of e){let e=r.path.split(`/`).pop().replace(/\.obj$/i,``).toLowerCase();for(let i of t){let t=i.path.split(`/`).pop().replace(/\.mtl$/i,``).toLowerCase();if(e===t||e.includes(t)||t.includes(e)){n.push({obj:r,mtl:i});break}}}return n}async findAndLoadModelFromZip(e){for(let t of[`scene.gltf`,`scene.glb`,`model.gltf`,`model.glb`,`main.gltf`,`main.glb`,`asset.gltf`,`asset.glb`])if(e[t]){console.log(`Found main model file: ${t}`);let n=t.split(`.`).pop().toLowerCase();return await this.loadModelFromZipEntry(e[t],t,n,e)}for(let t in e){let n=t.split(`.`).pop().toLowerCase();if(n===`obj`||this.loader.getFileFormat(t)?.type===`model`)return Gj.test(t)?await this.loadUSDHierarchyFromZip(e):(console.log(`Loading model file from ZIP: ${t}`),await this.loadModelFromZipEntry(e[t],t,n,e))}throw Error(`No supported model files found in the ZIP archive`)}async loadUSDHierarchyFromZip(t){let n=Object.keys(t).filter(e=>Gj.test(e));if(n.length===0)throw Error(`No USD layers found in the ZIP archive`);let r=e._pickUSDRootLayer(n);console.log(`Loading USD scene from ZIP: ${r} (${n.length} layers)`);let i={[r]:[t[r],{level:0}]};for(let e of Object.keys(t))e!==r&&(Gj.test(e)||Kj.test(e))&&(i[e]=[t[e],{level:0}]);return await this.loader._loadModelFileByExtension(new File([(0,m.zipSync)(i)],r),r)}static _pickUSDRootLayer(e){let t=e=>e.split(`/`).length,n=Math.min(...e.map(t)),r=e.filter(e=>t(e)===n);return r.find(e=>{let t=e.split(`/`);return t.length>1&&t[t.length-1].replace(Gj,``)===t[t.length-2]})||r[0]}async loadModelFromZipEntry(e,t,n,r){try{z({isLoading:!0,status:`Processing ${n.toUpperCase()} from ZIP...`,progress:5});let i=new Blob([e.buffer],{type:`application/octet-stream`}),a=URL.createObjectURL(i),o;switch(n){case`glb`:case`gltf`:o=await this.handleGltfFromZip(n,e,t,r);break;case`obj`:o=await this.handleObjFromZip(e,t,r);break;default:o=await this.loader._loadModelFileByExtension(new File([e],t),t)}return URL.revokeObjectURL(a),this.loader.dispatchEvent({type:`load`,model:this.loader.targetModel,filename:`${t} (from ZIP)`}),o}catch(e){throw console.error(`Error loading ${n} from ZIP:`,e),this.loader.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async handleGltfFromZip(e,t,n,i){if(e===`gltf`){let e=(0,m.strFromU8)(t),a=new r.LoadingManager,o=n.split(`/`).slice(0,-1).join(`/`);a.setURLModifier(e=>this.resolveZipResource(e,o,i));let s=await this.loader.createGLTFLoader();s.manager=a;try{return await new Promise((t,n)=>{s.parse(e,``,e=>{try{this.loader._throwDeferred()}catch(e){n(e);return}this.loader.releaseTargetModel(),this.loader.targetModel=e.scene,this.loader.sceneMetadata=I_(e),this.loader.onModelLoad(this.loader.targetModel).then(()=>t(e))},e=>n(e))})}finally{this.loader._disposeGLTFLoader(s)}}else return await this.loader.loadGLBFromArrayBuffer(t.buffer,n)}async handleObjFromZip(e,t,n){let r=(0,m.strFromU8)(e),i=r.match(/mtllib\s+([^\s]+)/),a=null;i&&i[1]&&(a=await this.loadMtlFromZip(i[1],t,n));let{OBJLoader:o}=await import(`three/examples/jsm/loaders/OBJLoader.js`),s=new o;a&&s.setMaterials(a);let c=s.parse(r);return c.name=t,this.loader.releaseTargetModel(),this.loader.targetModel=c,await this.loader.onModelLoad(this.loader.targetModel),c}async preloadMtlTextures(e){let t=[],n=e.loadTexture.bind(e);if(e.loadTexture=(e,r,i,a,o)=>{let s;return t.push(new Promise(e=>s=e)),n(e,r,e=>{s(),i?.(e)},a,e=>{s(),o?.(e)})},e.preload(),t.length===0)return e;let r,i=await Promise.race([Promise.all(t).then(()=>!0),new Promise(e=>r=setTimeout(()=>e(!1),qj))]);return clearTimeout(r),i||this.loader._issues?.record(Y.TEXTURE_BUILD_FAILED,`MTL textures did not decode within ${qj}ms; affected materials render untextured`,{pending:t.length}),e}async loadMtlFromZip(e,t,n){let i=t.split(`/`).slice(0,-1).join(`/`),a=[e,`${i}/${e}`,e.split(`/`).pop()];for(let e of a)if(n[e]){let{MTLLoader:t}=await import(`three/examples/jsm/loaders/MTLLoader.js`),a=(0,m.strFromU8)(n[e]),o=new r.LoadingManager;o.setURLModifier(e=>this.resolveZipResource(e,i,n));let s=new t(o).parse(a,i);return await this.preloadMtlTextures(s),s}return null}resolveZipResource(e,t,n){let r=e.replace(/^\.\/|^\//,``),i=[r,`${t}/${r}`,r.split(`/`).pop()];for(let e of i)if(n[e]){let t=new Blob([n[e].buffer],{type:`application/octet-stream`});return URL.createObjectURL(t)}return console.warn(`Resource not found in ZIP: ${e}`),e}async loadOBJMTLPairFromZip(e,t,n,i){let{MTLLoader:a}=await import(`three/examples/jsm/loaders/MTLLoader.js`),{OBJLoader:o}=await import(`three/examples/jsm/loaders/OBJLoader.js`),s=[],c=new r.LoadingManager,l=e.path.split(`/`).slice(0,-1).join(`/`),u=t.path.split(`/`).slice(0,-1).join(`/`);c.setURLModifier(e=>this.resolveTextureInZip(e,l,u,t,n,s));let d=this.prepareFixedMtlContent(t),f=new a(c).parse(d,u);await this.preloadMtlTextures(f);let p=new o(c);p.setMaterials(f);let h=(0,m.strFromU8)(e.content),g=p.parse(h);return this.loader.releaseTargetModel(),this.loader.targetModel=g,await this.loader.onModelLoad(this.loader.targetModel),s.forEach(e=>URL.revokeObjectURL(e)),this.loader.dispatchEvent({type:`load`,model:g,filename:`${e.path} (from ${i})`}),g}prepareFixedMtlContent(e){return(0,m.strFromU8)(e.content).replace(RegExp(`${e.path.split(`/`).pop()}\\s+`,`g`),` `).replace(/([a-zA-Z_]+)([\\/])/g,`$1 $2`)}resolveTextureInZip(e,t,n,r,i,a){let o=e.split(`?`)[0].split(`#`)[0].replace(/^\.\/|^\//,``),s=r.path.split(`/`).pop();o.startsWith(s)&&(o=o.substring(s.length).replace(/^\.\/|^\/|^\./,``));let c=[o,`${t}/${o}`,`${n}/${o}`,`textures/${o}`,`texture/${o}`,`materials/${o}`,o.split(`/`).pop()];for(let e of c)if(i[e]){let t=new Blob([i[e].buffer],{type:`application/octet-stream`}),n=URL.createObjectURL(t);return a.push(n),n}return this.findTextureWithFuzzyMatch(o,i,a)||e}findTextureWithFuzzyMatch(e,t,n){let r=e.split(`/`).pop();for(let e in t)if(e.endsWith(r)){let r=new Blob([t[e].buffer],{type:`application/octet-stream`}),i=URL.createObjectURL(r);return n.push(i),i}if(r&&r.length>5)for(let e in t){let i=e.split(`/`).pop();if(i.includes(r)||r.includes(i)){let r=new Blob([t[e].buffer],{type:`application/octet-stream`}),i=URL.createObjectURL(r);return n.push(i),i}}return null}}}));function Zj(e){let t=(e/1e3)**2;return .002152*(1.0455996-341.29061/t-.9023085*t)/(1+.0027059889/t-85.968563*t)}function Qj(e,t,n,r,i=1,a=0){let o=e.length/i,s=(r-t)/n;if(s<=0)return e[a];if(s>=o-1)return e[(o-1)*i+a];let c=Math.floor(s),l=s-c;return e[c*i+a]*(1-l)+e[(c+1)*i+a]*l}function $j(e,t){let n=0,r=bM+e*xM;for(let e=0;e<xM;e++)n+=t(r+e+.5);return n/xM}function eM(e){let t=new Float64Array(16);for(let n=0;n<16;n++)t[n]=$j(n,e);return t}function tM(e=1){let t=new Float32Array(48);for(let n=0;n<16;n++){let r=NM[n*3],i=NM[n*3+1],a=NM[n*3+2];for(let o=0;o<3;o++){let s=EM;t[o*16+n]=(s[o*3]*r+s[o*3+1]*i+s[o*3+2]*a)*e}}return t}function nM(e){let t=0,n=0,r=0;for(let i=0;i<16;i++)t+=e[i]*NM[i*3],n+=e[i]*NM[i*3+1],r+=e[i]*NM[i*3+2];return[t,n,r]}function rM([e,t,n]){let r=EM;return[r[0]*e+r[1]*t+r[2]*n,r[3]*e+r[4]*t+r[5]*n,r[6]*e+r[7]*t+r[8]*n]}function iM(e){return Math.max(0,.0460836582205*e-.04586025928522)}function aM([e,t,n]){let r=(e,t,n)=>{let r=Math.min(Math.max((n-e)/(t-e),0),1);return r*r*(3-2*r)};return Float64Array.from(OM,i=>{let a=1-r(470,520,i),o=r(560,610,i);return n*a+e*o+t*(1-a-o)})}function oM({airDensity:e=1,turbidity:t=2,ozone:n=300,groundAlbedo:r=[.3,.3,.3]}={}){let i=iM(t)/gM,a=n*DM/(15*1e3)*1e3,o=new Float64Array(16),s=new Float64Array(16),c=new Float64Array(16),l=new Float64Array(16);for(let t=0;t<16;t++)o[t]=AM[t]*e,s[t]=MM[t]*i,c[t]=s[t]*_M,l[t]=jM[t]*a;return{rayleigh:o,mieScattering:c,mieExtinction:s,ozone:l,albedo:aM(r)}}function sM(e){let t=Math.max(e,0);return Math.sqrt(t*(2*mM+t))/(mM+t)}function cM(e,t,n=1024){let r=Math.max(e,0),i=mM+r,a=i*t,o=r*(2*mM+r);if(t<0&&a*a>=o)return null;let s=-a+Math.sqrt(a*a+(hM-i)*(hM+i)),c=0,l=0,u=0;for(let e=0;e<n;e++){let t=s*(e/n)**2,r=s*((e+1)/n)**2,d=.5*(t+r),f=(o+d*(d+2*a))/(Math.sqrt(i*i+d*(d+2*a))+mM),p=r-t;c+=PM(f)*p,l+=FM(f)*p,u+=IM(f)*p}return[c,l,u]}function lM(e,t){let n=new Float64Array(16);if(!t)return n;let[r,i,a]=t;for(let t=0;t<16;t++)n[t]=Math.exp(-(e.rayleigh[t]*r+e.mieExtinction[t]*i+e.ozone[t]*a));return n}function uM(e){let t=Math.sin(e/2);return 4*Math.PI*t*t}function dM({direction:e,altitude:t,angularDiameter:n,strength:r=1,coefficients:i}){let a=n/2,o=uM(a),s=sM(t),[c,l,u]=e,d=Math.sin(a),f=new Float64Array(16),p=0,m=e=>{if(e<-s)return;let n=lM(i,cM(t,e,512));for(let e=0;e<16;e++)f[e]+=n[e];p++};if(l-d>.1)m(l);else{let e=Math.sqrt(Math.max(0,1-l*l));for(let t=0;t<48;t++){let n=(t+.5)/48,r=-1,i=1;for(let e=0;e<30;e++){let e=.5*(r+i);(Math.asin(e)+e*Math.sqrt(1-e*e)+Math.PI/2)/Math.PI<n?r=e:i=e}m(l+.5*(r+i)*d*e)}}let h=new Float64Array(16),g=l-d>.1?1:48;if(p>0)for(let e=0;e<16;e++)h[e]=kM[e]*r/o*f[e]/p;return{radiance:rM(nM(h)).map(e=>Math.max(0,e*SM)),visibleFraction:p/g,solidAngle:o,direction:[c,l,u]}}function fM(e,t=vM){let n=t*t;return 3/(8*Math.PI)*(1-n)/(2+n)*(1+e*e)/(1+n-2*t*e)**1.5}function pM(e,t,n,r,i=8){let a=n*r,o=e*t,s=new Float32Array(2*o*a);return[LM,e=>fM(e)].forEach((c,l)=>{for(let u=0;u<o;u++){let d=-1+2*Math.floor(u/t)/(e-1),f=u%t*Math.PI/(t-1),p=Math.sqrt(Math.max(0,1-d*d)),m=(l*o+u)*a,h=0;for(let e=0;e<a;e++){let t=Math.floor(e/r),a=e%r,o=0;for(let e=0;e<i;e++){let s=-1+2*(t+(e+.5)/i)/n,l=Math.sqrt(Math.max(0,1-s*s));for(let e=0;e<i;e++){let t=Math.PI*(a+(e+.5)/i)/r;o+=c(d*s+p*l*Math.cos(f-t))+c(d*s+p*l*Math.cos(f+t))}}s[m+e]=o,h+=o}for(let e=0;e<a;e++)s[m+e]/=h}}),s}var mM,hM,gM,_M,vM,yM,bM,xM,SM,CM,wM,TM,EM,DM,OM,kM,AM,jM,MM,NM,PM,FM,IM,LM,RM=g((()=>{om(),mM=6360,hM=6420,gM=1.2,_M=.9,vM=.76,yM=1.3,bM=380,xM=25,SM=1/32,CM=[1.11776,1.14259,1.01249,1.14716,1.72765,1.73054,1.6887,1.61253,1.91198,2.03474,2.02042,2.02212,1.93377,1.95809,1.91686,1.8298,1.8685,1.8931,1.85149,1.8504,1.8341,1.8345,1.8147,1.78158,1.7533,1.6965,1.68194,1.64654,1.6048,1.52143,1.55622,1.5113,1.474,1.4482,1.41018,1.36775,1.34188,1.31429,1.28303,1.26758,1.2367,1.2082,1.18737,1.14683,1.12362,1.1058,1.07124,1.04992],wM=[118e-29,2182e-31,2818e-31,6636e-31,1527e-30,2763e-30,552e-29,8451e-30,1582e-29,2316e-29,3669e-29,4924e-29,7752e-29,9016e-29,148e-27,1602e-28,2139e-28,2755e-28,3091e-28,35e-26,4266e-28,4672e-28,4398e-28,4701e-28,5019e-28,4305e-28,374e-27,3215e-28,2662e-28,2238e-28,1852e-28,1473e-28,1209e-28,9423e-29,7455e-29,6566e-29,5105e-29,415e-28,4228e-29,3237e-29,2451e-29,2801e-29,2534e-29,1624e-29,1465e-29,2078e-29,1383e-29,7105e-30],TM=[1299e-7,3917e-9,6061e-7,2321e-7,6965e-9,.001086,4149e-7,1239e-8,.001946,7416e-7,2202e-8,.003486,.001368,39e-6,.006450001,.002236,64e-6,.01054999,.004243,12e-5,.02005001,.00765,217e-6,.03621,.01431,396e-6,.06785001,.02319,64e-5,.1102,.04351,.00121,.2074,.07763,.00218,.3713,.13438,.004,.6456,.21477,.0073,1.0390501,.2839,.0116,1.3856,.3285,.01684,1.62296,.34828,.023,1.74706,.34806,.0298,1.7826,.3362,.038,1.77211,.3187,.048,1.7441,.2908,.06,1.6692,.2511,.0739,1.5281,.19536,.09098,1.28764,.1421,.1126,1.0419,.09564,.13902,.8129501,.05795001,.1693,.6162,.03201,.20802,.46518,.0147,.2586,.3533,.0049,.323,.272,.0024,.4073,.2123,.0093,.503,.1582,.0291,.6082,.1117,.06327,.71,.07824999,.1096,.7932,.05725001,.1655,.862,.04216,.2257499,.9148501,.02984,.2904,.954,.0203,.3597,.9803,.0134,.4334499,.9949501,.008749999,.5120501,1,.005749999,.5945,.995,.0039,.6784,.9786,.002749999,.7621,.952,.0021,.8425,.9154,.0018,.9163,.87,.001650001,.9786,.8163,.0014,1.0263,.757,.0011,1.0567,.6949,.001,1.0622,.631,8e-4,1.0456,.5668,6e-4,1.0026,.503,34e-5,.9384,.4412,24e-5,.8544499,.381,19e-5,.7514,.321,1e-4,.6424,.265,4999999e-11,.5419,.217,3e-5,.4479,.175,2e-5,.3608,.1382,1e-5,.2835,.107,0,.2187,.0816,0,.1649,.061,0,.1212,.04458,0,.0874,.032,0,.0636,.0232,0,.04677,.017,0,.0329,.01192,0,.0227,.00821,0,.01584,.005723,0,.01135916,.004102,0,.008110916,.002929,0,.005790346,.002091,0,.004109457,.001484,0,.002899327,.001047,0,.00204919,74e-5,0,.001439971,52e-5,0,.0009999493,3611e-7,0,.0006900786,2492e-7,0,.0004760213,1719e-7,0,.0003323011,12e-5,0,.0002348261,848e-7,0,.0001661505,6e-5,0,117413e-9,424e-7,0,8307527e-11,3e-5,0,5870652e-11,212e-7,0,4150994e-11,1499e-8,0,2935326e-11,106e-7,0,2067383e-11,74657e-10,0,1455977e-11,52578e-10,0,1025398e-11,37029e-10,0,7221456e-12,26078e-10,0,5085868e-12,18366e-10,0,3581652e-12,12934e-10,0,2522525e-12,9.1093e-7,0,1776509e-12,6.4153e-7,0,1251141e-12,4.5181e-7,0],EM=[3.2406,-1.5372,-.4986,-.9689,1.8758,.0415,.0557,-.204,1.057],DM=0xe90f62a5dcb760000,OM=Float64Array.from({length:16},(e,t)=>bM+(t+.5)*xM),kM=eM(e=>Qj(CM,360,10,e)),AM=eM(e=>Zj(e)/8),jM=eM(e=>Qj(wM,360,10,e)),MM=eM(e=>(e/1e3)**-yM),NM=(()=>{let e=new Float64Array(48);for(let t=0;t<16;t++)for(let n=0;n<3;n++)e[t*3+n]=$j(t,e=>Qj(TM,360,5,e,3,n))*xM;return e})(),PM=e=>Math.exp(-e/8),FM=e=>Math.exp(-e/gM),IM=e=>Math.max(0,1-Math.abs(e-25)/15),LM=e=>3/(16*Math.PI)*(1+e*e)}));function zM(e){return{r:(0,n.exp)(e.mul(-1/8)),m:(0,n.exp)(e.mul(-1/gM)),o:(0,n.max)((0,n.float)(0),(0,n.float)(1).sub((0,n.abs)(e.sub(25)).div(15)))}}function BM(e,t){return cN(n=>e.rayleigh[n].mul(t.r).add(e.mieExtinction[n].mul(t.m)).add(e.ozone[n].mul(t.o)))}function VM(e,t){return cN(r=>{let i=e[r].mul(t),a=(0,n.exp)(i.negate()),o=(0,n.float)(1).sub(a).div((0,n.max)(i,1e-12));return{weight:(0,n.mix)((0,n.float)(1).sub(i.mul(.5)),o,(0,n.step)(.001,i)).mul(t),transmittance:a}})}function HM(e,t,r,i,a,o=1,s=0){let c=(0,n.clamp)(i,0,t-1),l=(0,n.clamp)(a,0,r-1),u=(0,n.floor)(c),d=(0,n.floor)(l),f=c.sub(u),p=l.sub(d),m=(0,n.uint)(u),h=(0,n.uint)(d),g=(0,n.min)(m.add(1),(0,n.uint)(t-1)),_=(0,n.min)(h.add(1),(0,n.uint)(r-1)),v=(n,r)=>e.element(r.mul(t).add(n).mul(o).add(s));return(0,n.mix)((0,n.mix)(v(m,h),v(g,h),f),(0,n.mix)(v(m,_),v(g,_),f),p)}function UM(e,t){let r=e.add(mM),i=(0,n.sqrt)((0,n.max)(e.mul(e.add(2*mM)),0)),a=r.mul(t),o=a.negate().add((0,n.sqrt)((0,n.max)(a.mul(a).add(iN*iN).sub(i.mul(i)),0))),s=(0,n.float)(aN).sub(e),c=i.add(iN);return{x:o.sub(s).div((0,n.max)(c.sub(s),1e-6)).mul(255),y:i.div(iN).mul(63),rho:i,r}}function WM(e,t,r,i,a){let o=UM(r,i),s=HM(e,256,64,o.x,o.y).xyz,c=(0,n.smoothstep)(a.negate(),a,i.add(o.rho.div(o.r)));return cN(e=>(0,n.exp)(t.rayleigh[e].mul(s.x).add(t.mieExtinction[e].mul(s.y)).add(t.ozone[e].mul(s.z)).negate()).mul(c))}function GM(e,t,r,i,a){let o=[[(0,n.clamp)(gN(r,64),0,63),64],[(0,n.clamp)(uN(t),0,15),16],[(0,n.clamp)(i.add(1).mul(.5*15),0,15),16],[(0,n.clamp)((0,n.acos)((0,n.clamp)(a,-1,1)).mul(7/oN),0,7),8]].map(([e,t])=>{let r=(0,n.floor)(e),i=e.sub(r).toVar(),a=(0,n.uint)(r).toVar();return{t:i,i0:a,i1:(0,n.min)(a.add(1),(0,n.uint)(t-1)).toVar()}}),s=[128,8192,8,1],c=[];for(let e=0;e<16;e++){let t=(0,n.uint)(0);o.forEach((n,r)=>{t=t.add((e>>r&1?n.i1:n.i0).mul(s[r]))}),c.push(t.mul(8).toVar())}return Array.from({length:8},(t,r)=>{let i=c.map(t=>e.element(t.add(r)));for(let e=0;e<4;e++){let t=[];for(let r=0;r<i.length;r+=2)t.push((0,n.mix)(i[r],i[r+1],o[e].t));i=t}return(0,n.exp)(i[0])})}function KM(e,t){let r=gN(t,128);return cN(t=>(0,n.exp)(HM(e,128,1,r,(0,n.float)(0),4,t)))}function qM(e,t){let r=e.add(mM).toVar(),i=r.mul(t).toVar(),a=e.mul(e.add(2*mM)).toVar(),o=i.mul(i).sub(a),s=t.lessThan(0).and(o.greaterThanEqual(0)).toVar(),c=a.div((0,n.max)(i.negate().add((0,n.sqrt)((0,n.max)(o,0))),1e-9)),l=i.negate().add((0,n.sqrt)((0,n.max)(i.mul(i).add((0,n.float)(hM).sub(r).mul(r.add(hM))),0)));return{r,b:i,cGround:a,hitsGround:s,tMax:s.select(c,l).toVar()}}function JM(e,t,r,i){let a=t.mul(t.add(e.b.mul(2))),o=(0,n.sqrt)(e.r.mul(e.r).add(a));return{h:(0,n.max)(e.cGround.add(a).div(o.add(mM)),0),muS:(0,n.clamp)(e.r.mul(r).add(t.mul(i)).div(o),-1,1),mu:(0,n.clamp)(e.b.add(t).div(o),-1,1)}}function YM(e,t){let r=t*t,i=3/(8*oN)*(1-r)/(2+r),a=(0,n.max)((0,n.float)(1+r).sub(e.mul(2*t)),1e-6);return e.mul(e).add(1).mul(i).div(a.mul((0,n.sqrt)(a)))}function XM({transmittance:e},t=256){let r=256*64;return(0,n.Fn)(()=>{let i=n.instanceIndex;(0,n.If)(i.greaterThanEqual((0,n.uint)(r)),()=>{(0,n.Return)()});let a=(0,n.float)(i.mod(256)).div(255),o=(0,n.float)(i.div(256)).div(63).mul(iN).toVar(),s=(0,n.sqrt)(o.mul(o).add(mM*mM)).toVar(),c=(0,n.float)(hM).sub(s),l=o.add(iN),u=c.add(a.mul(l.sub(c))).toVar(),d=(0,n.clamp)((0,n.float)(iN*iN).sub(o.mul(o)).sub(u.mul(u)).div((0,n.max)(s.mul(u).mul(2),1e-9)),-1,1).toVar(),f=o.mul(o).toVar(),p=s.mul(d).mul(2).toVar(),m=(0,n.vec3)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(t),type:`int`,condition:`<`},({i:e})=>{let r=(0,n.float)(e).div(t),i=(0,n.float)(e).add(1).div(t),a=u.mul(r.mul(r)),o=u.mul(i.mul(i)),c=a.add(o).mul(.5),l=c.mul(c.add(p)),d=zM((0,n.max)(f.add(l).div((0,n.sqrt)(s.mul(s).add(l)).add(mM)),0));m.addAssign((0,n.vec3)(d.r,d.m,d.o).mul(o.sub(a)))}),e.element(i).assign((0,n.vec4)(m,0))})().compute(r,[64])}function ZM(e,t,r,i){let a=(0,n.float)(e).add((0,n.float)(r.div(i)).add(.5).div(i)).div(16).mul(2).sub(1),o=(0,n.sqrt)((0,n.max)((0,n.float)(1).sub(a.mul(a)),0)),s=(0,n.float)(t).add((0,n.float)(r.mod(i)).add(.5).div(i)).mul(oN/8);return(0,n.vec3)(o.mul((0,n.cos)(s)),a,o.mul((0,n.sin)(s)))}function QM(e,t){let r=gN(t,64);return cN(t=>HM(e,64,1,r,(0,n.float)(0),4,t))}function $M(e,{first:t,out:r,cellSamples:i=2,steps:a=20}){let{transmittance:o,transfer:s,multipleScattering:c,groundE:l,coefficients:u,sunSinRadius:d,mieG:f}=e,p=1024*128,m=i*i;return(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(p)),()=>{(0,n.Return)()});let h=e.mod(128),g=e.div(128),_=hN(g.mod(64),64).toVar(),v=(0,n.max)(lN(g.div(64)),.001).toVar(),y=(0,n.vec3)((0,n.sqrt)((0,n.max)((0,n.float)(1).sub(_.mul(_)),0)),_,0).toVar(),b=cN(()=>(0,n.vec4)(0).toVar()),x=t?cN(()=>(0,n.vec4)(0).toVar()):null;(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(m),type:`int`,condition:`<`,name:`ray`},({ray:e})=>{let r=ZM(h.div(8),h.mod(8),e,i).toVar(),s=(0,n.dot)(r,y).toVar(),p=t?bN(s).toVar():null,m=t?YM(s,f).toVar():null,g=t?null:Array.from({length:8},()=>(0,n.vec4)(0).toVar()),S=qM(v,r.y),C=cN(()=>(0,n.vec4)(1).toVar());(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(a),type:`int`,condition:`<`},({i:e})=>{let r=(0,n.float)(e).div(a),i=(0,n.float)(e).add(1).div(a),l=S.tMax.mul(r.mul(r)),f=S.tMax.mul(i.mul(i)).sub(l),h=JM(S,l.add(f.mul(.5)),_,s),v=zM(h.h),y=cN(e=>u.rayleigh[e].mul(v.r)),w=cN(e=>u.mieScattering[e].mul(v.m)),T=VM(BM(u,v),f),E;if(t){let e=WM(o,u,h.h,h.muS,d);E=cN(t=>e[t].mul(y[t].mul(p).add(w[t].mul(m))))}else (0,n.If)(e.mod(2).equal(0),()=>{let e=GM(c,h.h,h.muS,h.mu,yN(s,h.mu,h.muS));for(let t=0;t<8;t++)g[t].assign(e[t])}),E=cN(e=>y[e].mul(g[e]).add(w[e].mul(g[4+e])));for(let e of sN)b[e].addAssign(C[e].mul(E[e]).mul(T[e].weight)),x&&x[e].addAssign(C[e].mul(y[e].add(w[e])).mul(T[e].weight)),C[e].mulAssign(T[e].transmittance)}),(0,n.If)(S.hitsGround,()=>{let e=(0,n.clamp)(S.r.mul(_).add(S.tMax.mul(s)).div(mM),-1,1),r;if(t){let t=WM(o,u,(0,n.float)(0),e,d);r=cN(r=>t[r].mul((0,n.max)(e,0)))}else r=QM(l,e);for(let e of sN)b[e].addAssign(C[e].mul(r[e]).mul(u.albedo[e]).mul(1/oN))})});for(let t of sN)r.element(e.mul(4).add(t)).assign(b[t].div(m)),x&&s.element(e.mul(4).add(t)).assign(x[t].div(m))})().compute(p,[64])}function eN(e,{incoming:t,stage:r}){let{transfer:i,phaseCells:a,multipleScattering:o,psiSum:s,groundE:c}=e,l=1024*128,u=r===`last`;return(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(l)),()=>{(0,n.Return)()});let d=e.mod(128),f=e.div(128),p=f.mul(128),m=null;if(u){let e=cN(()=>(0,n.vec4)(0).toVar());(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(128),type:`int`,condition:`<`},({i:t})=>{for(let r of sN)e[r].addAssign(i.element(p.add((0,n.uint)(t)).mul(4).add(r)))}),m=cN(t=>{let r=(0,n.min)(e[t].div(128),.95);return r.div((0,n.float)(1).sub(r)).toVar()})}for(let i=0;i<2;i++){let c=cN(()=>(0,n.vec4)(0).toVar());(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(32),type:`int`,condition:`<`},({i:e})=>{let r=a.element((0,n.uint)(i*128).add(d).mul(32).add((0,n.uint)(e))).toVar();for(let i=0;i<4;i++){let a=p.add((0,n.uint)(e).mul(4).add(i)).mul(4),o=r.element((0,n.int)(i));for(let e of sN)c[e].addAssign(t.element(a.add(e)).mul(o))}});for(let t of sN){let n=e.mul(8).add(i*4+t);r===`first`?(s.element(n).assign(c[t]),o.element(n).assign(vN(c[t]))):r===`middle`?(s.element(n).addAssign(c[t]),o.element(n).assign(vN(c[t]))):o.element(n).assign(vN(s.element(n).add(c[t].mul(m[t].add(1)))))}}u||(0,n.If)(f.lessThan((0,n.uint)(64)).and(d.equal((0,n.uint)(0))),()=>{let e=cN(()=>(0,n.vec4)(0).toVar());(0,n.Loop)({start:(0,n.int)(128/2),end:(0,n.int)(128),type:`int`,condition:`<`},({i:r})=>{let i=(0,n.float)((0,n.uint)(r).div(8)).add(.5).div(16).mul(2).sub(1);for(let a of sN)e[a].addAssign(t.element(p.add((0,n.uint)(r)).mul(4).add(a)).mul(i))});for(let t of sN)c.element(f.mul(4).add(t)).assign(e[t].mul(xN))})})().compute(l,[64])}function tN({transmittance:e,multipleScattering:t,coefficients:r,sunSinRadius:i,mieG:a},o,s,c,l){let u=cN(()=>(0,n.vec4)(0).toVar()),d=cN(()=>(0,n.vec4)(1).toVar()),f=t?Array.from({length:8},()=>(0,n.vec4)(0).toVar()):null,p=bN(c).toVar(),m=YM(c,a).toVar(),h=o.tMax;return(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(l),type:`int`,condition:`<`},({i:a})=>{let g=(0,n.float)(a).div(l),_=(0,n.float)(a).add(1).div(l),v=h.mul(g.mul(g)),y=h.mul(_.mul(_)).sub(v),b=JM(o,v.add(y.mul(.5)),s,c),x=zM(b.h),S=cN(e=>r.rayleigh[e].mul(x.r)),C=cN(e=>r.mieScattering[e].mul(x.m)),w=WM(e,r,b.h,b.muS,i),T=VM(BM(r,x),y);f&&(0,n.If)(a.mod(SN).equal(0),()=>{let e=GM(t,b.h,b.muS,b.mu,yN(c,b.mu,b.muS));for(let t=0;t<8;t++)f[t].assign(e[t])});for(let e of sN){let t=w[e].mul(S[e].mul(p).add(C[e].mul(m)));f&&(t=t.add(S[e].mul(f[e])).add(C[e].mul(f[4+e]))),u[e].addAssign(d[e].mul(t).mul(T[e].weight)),d[e].mulAssign(T[e].transmittance)}}),{L:u,throughput:d}}function nN(e,{sqrtDirections:t=12,steps:r=32}={}){let{irradiance:i}=e,a=t*t,o=(0,n.float)(.001);return(0,n.Fn)(()=>{let s=n.instanceIndex;(0,n.If)(s.greaterThanEqual((0,n.uint)(128)),()=>{(0,n.Return)()});let c=hN(s,128).toVar(),l=(0,n.vec3)((0,n.sqrt)((0,n.max)((0,n.float)(1).sub(c.mul(c)),0)),c,0).toVar(),u=cN(()=>(0,n.vec4)(0).toVar());(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(a),type:`int`,condition:`<`,name:`dirIndex`},({dirIndex:i})=>{let a=(0,n.float)(i.div(t)).add(.5).div(t),s=(0,n.float)(i.mod(t)).add(.5).div(t),d=(0,n.sqrt)(a),f=s.mul(2*oN),p=(0,n.vec3)(d.mul((0,n.cos)(f)),(0,n.sqrt)((0,n.max)((0,n.float)(1).sub(a),0)),d.mul((0,n.sin)(f))).toVar(),{L:m}=tN(e,qM(o,p.y),c,(0,n.dot)(p,l),r);for(let e of sN)u[e].addAssign(m[e])});for(let e of sN)i.element(s.mul(4).add(e)).assign(vN(u[e].mul(oN/a)))})().compute(128,[64])}function rN(e,{width:t,height:r,steps:i=40,multipleScattering:a=!0}){let{sky:o,skyRows:s,irradiance:c,coefficients:l,rgb:u,sunDirection:d,altitude:f,sunSinRadius:p,transmittance:m}=e,h=a?e:{...e,multipleScattering:null},g=256*r;return[(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(g)),()=>{(0,n.Return)()});let t=(0,n.float)(1).sub((0,n.float)(e.div(256)).add(.5).div(r)).mul(oN),a=(0,n.cos)(t).toVar(),o=(0,n.max)(f,.001).toVar(),_=d.y.toVar(),v=(0,n.sin)(t).mul((0,n.cos)(CN(e.mod(256)))).mul((0,n.sqrt)((0,n.max)((0,n.float)(1).sub(_.mul(_)),0))).add(a.mul(_)).toVar(),y=qM(o,a),{L:b,throughput:x}=tN(h,y,_,v,i);(0,n.If)(y.hitsGround,()=>{let e=(0,n.clamp)(y.r.mul(_).add(y.tMax.mul(v)).div(mM),-1,1).toVar(),t=WM(m,l,(0,n.float)(0),e,p),r=KM(c,e);for(let i of sN)b[i].addAssign(x[i].mul(l.albedo[i]).mul(1/oN).mul(t[i].mul((0,n.max)(e,0)).add(r[i])))});let S=cN(e=>b[e].mul(l.solar[e])),C=e=>S.reduce((t,r,i)=>t.add((0,n.dot)(r,u[e*4+i])),(0,n.float)(0));s.element(e).assign((0,n.vec4)((0,n.max)((0,n.vec3)(C(0),C(1),C(2)),(0,n.vec3)(0)),1))})().compute(g,[64]),(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(t*r)),()=>{(0,n.Return)()});let i=(0,n.float)(e.mod(t)).add(.5).div(t).sub(.5).mul(2*oN).sub((0,n.atan)(d.z,d.x)),a=(0,n.sqrt)((0,n.abs)((0,n.atan)((0,n.sin)(i),(0,n.cos)(i))).div(oN)).mul(255).toVar(),c=(0,n.min)((0,n.floor)(a),254).toVar(),l=e.div(t).mul(256).add((0,n.uint)(c)).toVar();o.element(e).assign((0,n.mix)(s.element(l),s.element(l.add(1)),a.sub(c)))})().compute(t*r,[64])]}var iN,aN,oN,sN,cN,lN,uN,dN,fN,pN,mN,hN,gN,_N,vN,yN,bN,xN,SN,CN,wN=g((()=>{RM(),iN=Math.sqrt(hM*hM-mM*mM),aN=hM-mM,oN=Math.PI,sN=[0,1,2,3],cN=e=>sN.map(e),lN=e=>(0,n.float)(e).div(15).pow(2).mul(aN),uN=e=>(0,n.sqrt)((0,n.clamp)(e.div(aN),0,1)).mul(15),dN=-3*oN/180,fN=15*oN/180,pN=.5+Math.atan((-oN/2-dN)/fN)/oN,mN=.5+Math.atan((oN/2-dN)/fN)/oN,hN=(e,t)=>(0,n.sin)((0,n.clamp)((0,n.tan)((0,n.float)(e).div(t-1).mul(mN-pN).add(pN-.5).mul(oN)).mul(fN).add(dN),-oN/2,oN/2)),gN=(e,t)=>(0,n.atan)((0,n.asin)((0,n.clamp)(e,-1,1)).sub(dN).div(fN)).div(oN).add(.5-pN).div(mN-pN).mul(t-1),_N=1e-30,vN=e=>(0,n.log)((0,n.max)(e,(0,n.vec4)(_N))),yN=(e,t,r)=>e.sub(t.mul(r)).div((0,n.max)((0,n.sqrt)((0,n.float)(1).sub(t.mul(t)).mul((0,n.float)(1).sub(r.mul(r)))),1e-4)),bN=e=>e.mul(e).add(1).mul(3/(16*oN)),xN=4*oN/128,SN=4,CN=e=>(0,n.float)(e).div(255).pow(2).mul(oN)}));function TN(e,t,r){let i=(0,n.int)(0).toVar(),a=(0,n.int)(e-1).toVar();return(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(Math.ceil(Math.log2(e))+1),type:`int`,condition:`<`,name:`step`},()=>{(0,n.If)(i.lessThan(a),()=>{let e=i.add(a).div(2).toVar();(0,n.If)(t(e).lessThanEqual(r),()=>{i.assign(e.add(1))}).Else(()=>{a.assign(e)})})}),i}function EN({pixels:e,rows:t,prefix:r,stats:i,cdf:a,width:o,height:s}){let c=DN(o),l=(e,t,r)=>(0,n.uint)(t).mul((0,n.uint)(c)).add((0,n.uint)(e).mul((0,n.uint)(4))).add((0,n.uint)(r)),u=e=>(0,n.sin)((0,n.float)(e).add(.5).mul(Math.PI/s)),d=(t,r,i)=>(0,n.dot)(e.element(t.mul(o).add(r)).xyz,Ic).mul(i),f=()=>(0,n.If)(n.instanceIndex.greaterThan((0,n.uint)(0)),()=>{(0,n.Return)()}),p=(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(s)),()=>{(0,n.Return)()});let r=u(e).toVar(),i=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(o),type:`int`,condition:`<`},({i:t})=>{i.addAssign(d(e,(0,n.uint)(t),r))}),t.element(e).assign((0,n.vec4)(i,0,0,0))})().compute(s,[64]),m=(0,n.Fn)(()=>{f();let e=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(s),type:`int`,condition:`<`},({i:n})=>{e.addAssign(t.element(n).x)}),i.element(0).assign((0,n.vec4)(e,e.div(o*s),0,0))})().compute(1,[1]),h=(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(s)),()=>{(0,n.Return)()});let a=u(e).toVar(),c=i.element(0).y.toVar(),l=(0,n.float)(0).toVar(),f=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(o),type:`int`,condition:`<`},({i:t})=>{let i=d(e,(0,n.uint)(t),a).toVar();l.addAssign(i),f.addAssign((0,n.max)(i.sub(c),0)),r.element(e.mul(o).add((0,n.uint)(t))).assign((0,n.vec2)(l,f))}),t.element(e).assign((0,n.vec4)(l,f,0,0))})().compute(s,[64]),g=(0,n.Fn)(()=>{f();let e=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(s),type:`int`,condition:`<`},({i:n})=>{e.addAssign(t.element(n).y)});let r=i.element(0).toVar();i.element(1).assign((0,n.select)(e.greaterThan(0),(0,n.vec4)(e,r.y,1,0),(0,n.vec4)(r.x,0,0,0)))})().compute(1,[1]),_=()=>i.element(0).x.mul(1e-4/(o*s)),v=(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(s)),()=>{(0,n.Return)()});let c=_().toVar(),u=i.element(1).z.greaterThan(0).toVar(),d=t.element(e).toVar(),f=(0,n.select)(u,d.y,d.x).add(c.mul(o)).toVar(),p=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(o),type:`int`,condition:`<`},({i:t})=>{let i=r.element(e.mul(o).add((0,n.uint)(t))).toVar(),s=(0,n.select)(u,i.y,i.x).add(c.mul((0,n.float)(t).add(1))).div((0,n.max)(f,1e-30)),d=(0,n.select)(f.greaterThan(0),(0,n.select)(t.equal((0,n.int)(o-1)),(0,n.float)(1),s),(0,n.float)(0)).toVar();a.element(l(t,e,0)).assign(d),a.element(l(t,e,1)).assign(p),p.assign(d)})})().compute(s,[64]),y=(0,n.Fn)(()=>{f();let e=_().mul(o).toVar(),r=i.element(1).z.greaterThan(0).toVar(),c=i=>{let a=t.element(i);return(0,n.select)(r,a.y,a.x).add(e)},u=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(s),type:`int`,condition:`<`},({i:e})=>{u.addAssign(c(e))});let d=(0,n.float)(0).toVar(),p=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(s),type:`int`,condition:`<`},({i:e})=>{d.addAssign(c(e));let t=(0,n.select)(e.equal((0,n.int)(s-1)),(0,n.float)(1),d.div((0,n.max)(u,1e-30))),r=(0,n.select)(u.greaterThan(0),t,(0,n.float)(0)).toVar();a.element(l(o,e,0)).assign(r),a.element(l(o,e,1)).assign(p),p.assign(r)})})().compute(1,[1]),b=2*o*s;return[p,m,h,g,v,y,(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(b+2*s)),()=>{(0,n.Return)()}),(0,n.If)(e.lessThan((0,n.uint)(b)),()=>{let t=e.mod(2*o).toVar(),r=e.div(2*o).toVar(),i=TN(o,e=>a.element(l(e,r,0)),(0,n.float)(t).div(2*o));a.element(l(t.shiftRight((0,n.uint)(1)),r,(0,n.uint)(2).add(t.bitAnd((0,n.uint)(1))))).assign((0,n.float)(i))}).Else(()=>{let t=e.sub((0,n.uint)(b)).toVar(),r=TN(s,e=>a.element(l(o,e,0)),(0,n.float)(t).div(2*s));a.element(l(o,t.shiftRight((0,n.uint)(1)),(0,n.uint)(2).add(t.bitAnd((0,n.uint)(1))))).assign((0,n.float)(r))})})().compute(b+2*s,[64])]}var DN,ON=g((()=>{ml(),DN=e=>Math.ceil((e+1)*16/256)*64})),kN=_({PhysicalSky:()=>jN});function AN(e,t,n){let i=new r.DataTexture(null,e,t,n,r.FloatType);return i.source.dataReady=!1,i.needsUpdate=!0,i._isPhysicalSky=!0,i}var jN,MN=g((()=>{k(),Au(),wN(),ON(),Fn(),RM(),jN=class{constructor(e=1024,t=512,n={}){this.width=e,this.height=t,this._quality=n,this.lastRenderTime=0,this._texture=AN(e,t,r.RGBAFormat),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1,this._cdfTexture=AN(e+1,t,r.RGBAFormat),this._rec709Weights=tM(SM),this._attrs=null,this._kernels=null,this._airKey=null,this._transmittanceBuilt=!1}_init(){let e=e=>Array.from({length:e},()=>(0,n.uniform)(new r.Vector4)),i=e(24);this._uniforms={coefficient:i,rgb:e(12),sunDirection:(0,n.uniform)(new r.Vector3(0,1,0)),altitude:(0,n.uniform)(.05),sunSinRadius:(0,n.uniform)(.0046)};let a=e=>v(e,4);this._attrs={transmittance:a(256*64),incomingA:a(1024*128*4),incomingB:a(1024*128*4),transfer:a(1024*128*4),multipleScattering:a(1024*128*8),psiSum:a(1024*128*8),groundE:a(256),irradiance:a(512),sky:a(this.width*this.height),skyRows:a(256*this.height),cdfRows:a(this.height),cdfPrefix:v(this.width*this.height,2),cdfStats:a(2),cdf:v(DN(this.width)*this.height,1),phaseCells:new t.StorageInstancedBufferAttribute(pM(16,8,16,8),4)};let o=(e,t=`vec4`)=>(0,n.storage)(this._attrs[e],t,this._attrs[e].count),s=e=>i.slice(e*4,e*4+4),c={transmittance:o(`transmittance`),transfer:o(`transfer`),psiSum:o(`psiSum`),groundE:o(`groundE`),phaseCells:o(`phaseCells`),multipleScattering:o(`multipleScattering`),irradiance:o(`irradiance`),sky:o(`sky`),skyRows:o(`skyRows`),coefficients:{rayleigh:s(0),mieScattering:s(1),mieExtinction:s(2),ozone:s(3),solar:s(4),albedo:s(5)},rgb:this._uniforms.rgb,sunDirection:this._uniforms.sunDirection,altitude:this._uniforms.altitude,sunSinRadius:this._uniforms.sunSinRadius,mieG:vM},l=this._quality,u=o(`incomingA`),d=o(`incomingB`);this._kernels={transmittance:XM(c),air:[$M(c,{first:!0,out:u,...l.incoming}),eN(c,{incoming:u,stage:`first`}),$M(c,{first:!1,out:d,...l.incoming}),eN(c,{incoming:d,stage:`middle`}),$M(c,{first:!1,out:u,...l.incoming}),eN(c,{incoming:u,stage:`last`}),nN(c,l.irradiance)],sky:rN(c,{width:this.width,height:this.height,...l.sky}),cdf:EN({pixels:c.sky,rows:o(`cdfRows`),prefix:o(`cdfPrefix`,`vec2`),stats:o(`cdfStats`),cdf:o(`cdf`,`float`),width:this.width,height:this.height})},this._setSpectrum(4,kM)}_setColorWeights(){let e=this._rec709Weights,t=kn(),n=[0,0,0,0];for(let r=0;r<3;r++)for(let i=0;i<4;i++){for(let a=0;a<4;a++){let o=i*4+a;n[a]=t?t[r*3]*e[o]+t[r*3+1]*e[16+o]+t[r*3+2]*e[32+o]:e[r*16+o]}this._uniforms.rgb[r*4+i].value.fromArray(n)}}_copyToTextures(e){let t=e.backend;e.initTexture(this._texture),e.initTexture(this._cdfTexture);let n=t.device.createCommandEncoder({label:`PhysicalSky`});n.copyBufferToTexture({buffer:t.get(this._attrs.sky).buffer,bytesPerRow:this.width*16,rowsPerImage:this.height},{texture:t.get(this._texture).texture},[this.width,this.height]),n.copyBufferToTexture({buffer:t.get(this._attrs.cdf).buffer,bytesPerRow:DN(this.width)*4,rowsPerImage:this.height},{texture:t.get(this._cdfTexture).texture},[this.width+1,this.height]),t.device.queue.submit([n.finish()])}_setSpectrum(e,t){for(let n=0;n<4;n++)this._uniforms.coefficient[e*4+n].value.set(t[n*4],t[n*4+1],t[n*4+2],t[n*4+3])}bake(e,t){let n=performance.now();this._kernels||this._init();let r={airDensity:t.airDensity,turbidity:t.turbidity,ozone:t.ozone,groundAlbedo:[...t.groundAlbedo]},i=oM(r),a=Math.max(t.altitude,1)/1e3,o=t.sunAngularDiameter/2,s=this._uniforms;s.sunDirection.value.fromArray(t.sunDirection).normalize(),s.altitude.value=a,s.sunSinRadius.value=Math.sin(o),this._setColorWeights();let c=[];this._transmittanceBuilt||=(c.push(this._kernels.transmittance),!0);let l=JSON.stringify([r,s.sunSinRadius.value]);l!==this._airKey&&(this._setSpectrum(0,i.rayleigh),this._setSpectrum(1,i.mieScattering),this._setSpectrum(2,i.mieExtinction),this._setSpectrum(3,i.ozone),this._setSpectrum(5,i.albedo),c.push(...this._kernels.air),this._airKey=l),c.push(...this._kernels.sky,...this._kernels.cdf),e.compute(c),this._copyToTextures(e);let u=e.getArrayBufferAsync(this._attrs.cdfStats).then(e=>{let t=new Float32Array(e);return{totalSum:t[4],radianceIntegral:2*Math.PI*Math.PI*t[0]/(this.width*this.height)}}),d=dM({direction:[s.sunDirection.value.x,s.sunDirection.value.y,s.sunDirection.value.z],altitude:a,angularDiameter:t.sunAngularDiameter,strength:t.sunStrength??1,coefficients:i});return d.cosHalfAngle=Math.cos(o),d.sinHalfAngle=Math.sin(o),d.horizonSin=sM(a),this.lastRenderTime=performance.now()-n,{texture:this._texture,cdfTexture:this._cdfTexture,sun:d,stats:u}}async readBack(e){let[t,n,r]=await Promise.all([`sky`,`cdf`,`cdfStats`].map(t=>e.getArrayBufferAsync(this._attrs[t])));return{pixels:new Float32Array(t),cdf:new Float32Array(n),cdfStride:DN(this.width),stats:new Float32Array(r)}}getLastRenderTime(){return this.lastRenderTime}dispose(e=null){for(let e of Object.values(this._kernels??{}).flat())e.dispose();for(let t of Object.values(this._attrs??{}))bl(e,t);this._kernels=null,this._attrs=null,this._texture.dispose(),this._cdfTexture.dispose()}}}));Ae(),I(),X(),kS();var NN=ye(`engine`),PN=class extends dv{constructor(e,t={}){super(e,t),this.setColorManagement(iE),this.setStorageOpener(HE),this.settings.define(`interactionRenderScale`,{default:.5,apply:()=>{this.stages?.pathTracer?.interactionMode&&this._requestRenderScale(this._interactionRenderScale())},reset:!1}),this._container=t.container||null,this._animRefitInFlight=!1,this._emittersMoved=!1,this._pendingRenderScale=null,this.cameraManager=null,this.timeline=null,this.goboManager=null,this.iesManager=null,this.denoisingManager=null,this.overlayManager=null,this.interactionManager=null,this.transformManager=null,this.animationManager=new dS}_createCamera(){return this.cameraManager=new ib(this.canvas),this.timeline=new ub({cameraManager:this.cameraManager,onReset:()=>this.reset()}),this.cameraManager.camera}_initAssetPipeline(){super._initAssetPipeline(),this.assetLoader.controls=this.cameraManager.controls,this.assetLoader.registerFormat(...AS),this.assetLoader.setArchiveImporterLoader(()=>Promise.resolve().then(()=>(Xj(),Wj)).then(e=>new e.ArchiveImporter(this.assetLoader)),OS);let e=()=>{this.needsReset=!0,this.stages.pathTracer?.enterInteractionMode(),this.wake()};this._addTrackedListener(this.cameraManager.controls,`change`,e),this._addTrackedListener(this.cameraManager.walkControls,`change`,e),this._addTrackedListener(this.cameraManager.walkControls,`start`,()=>this.wake())}_createExtraStages(){let{renderer:e,stages:t}=this;return t.normalDepth=new Cv(e,{pathTracer:t.pathTracer}),t.motionVector=new wv(e,this.camera,{pathTracer:t.pathTracer}),t.asvgf=new Dv(e,{enabled:!1}),t.nrd=new dy(e,{enabled:!1,pathTracer:t.pathTracer}),t.variance=new my(e,{enabled:!1}),t.bilateralFilter=new gy(e,{enabled:!1}),t.edgeFilter=new Sy(e,{enabled:!1}),t.autoExposure=new Ay(e,{enabled:Cy.autoExposure}),[t.normalDepth,t.motionVector,t.nrd,t.asvgf,t.variance,t.bilateralFilter,t.edgeFilter,t.autoExposure]}_initPipeline(){super._initPipeline(),this.pipeline.eventBus.on(`pathtracer:interactionStart`,()=>this._requestRenderScale(this._interactionRenderScale())),this.pipeline.eventBus.on(`pathtracer:interactionEnd`,()=>this._applyRenderScale(1))}async _initManagers(){await super._initManagers(),this.environmentManager.setProceduralSkyLoader(()=>Promise.resolve().then(()=>(MN(),kN)).then(e=>e.PhysicalSky)),this.stages.pathTracer.registerIntegrator([`bidirectional`,`vcm`],e=>new sw(e)),this.stages.pathTracer.requestOutput(`gBuffer`),this.interactionManager=new Fy({scene:this.meshScene,camera:this.camera,canvas:this.canvas,assetLoader:this.assetLoader,pathTracer:null,floorPlane:this.assetLoader.floorPlane}),this.interactionManager.wireAppEvents(this),this.cameraManager.setInteractionManager(this.interactionManager),this.goboManager=new db(this.stages.pathTracer,{onReset:()=>this.reset(),issues:this._issues}),this.iesManager=new Cb(this.stages.pathTracer,{onReset:()=>this.reset(),issues:this._issues}),this._setupDenoisingManager(),this._headless||(await this._setupOverlayManager(),this.transformManager=new mS({camera:this.camera,canvas:this.canvas,orbitControls:this.cameraManager.controls,app:this}),this.overlayManager.register(`transform`,new hS(this.transformManager))),this.interactionManager.setDependencies({overlayManager:this.overlayManager,transformManager:this.transformManager,appDispatch:e=>this.dispatchEvent(e),orbitControls:this.cameraManager.controls,helperScene:this._sceneHelpers.scene}),this.denoisingManager.setOverlayManager(this.overlayManager),this.denoisingManager.setResetCallback(()=>this.reset()),this.denoisingManager.setPostProcessRefreshCallback(()=>this.requestPostProcessRefresh()),this.denoisingManager.setDisplayRefreshCallback(()=>this._presentDisplay()),this.denoisingManager.setSettings(this.settings)}_wireEvents(){this._addTrackedListener(this.cameraManager,P.CAMERA_SWITCHED,e=>this.dispatchEvent(e)),this._addTrackedListener(this.cameraManager,P.AUTO_FOCUS_UPDATED,e=>this.dispatchEvent(e)),this._addTrackedListener(this.cameraManager,P.ORTHO_HEIGHT_UPDATED,e=>this.dispatchEvent(e)),this._addTrackedListener(this.timeline,P.TIMELINE_CHANGED,e=>this.dispatchEvent(e)),this._forwardEvents(this.denoisingManager,[P.DENOISING_START,P.DENOISING_END,P.UPSCALING_START,P.UPSCALING_PROGRESS,P.UPSCALING_END,P.RESOLUTION_CHANGED]),this._setupAutoExposureListener(),this.animationManager.wakeCallback=()=>this.wake(),this.animationManager.applyPoseCallback=e=>this._applyAnimationPose(e),this._forwardEvents(this.animationManager,[P.ANIMATION_STARTED,P.ANIMATION_PAUSED,P.ANIMATION_STOPPED]),this._addTrackedListener(this.animationManager,P.ANIMATION_PAUSED,()=>{this._animRefitInFlight=!1,this._refreshMovedEmitters()}),this._addTrackedListener(this.animationManager,P.ANIMATION_STOPPED,()=>{this._animRefitInFlight=!1}),this.cameraManager.initCallbacks({onResize:()=>this.onResize(),onReset:()=>this.reset(),getSettings:e=>this.settings.get(e),applySettings:e=>this.settings.setMany(e,{silent:!0,reset:!1})}),this.cameraManager.initAutoFocus({assetLoader:this.assetLoader,pathTracer:this.stages.pathTracer,settings:this.settings,softReset:()=>this.reset(!0),hardReset:()=>this.reset()}),super._wireEvents(),this._addTrackedListener(this.assetLoader,`modelProcessed`,e=>{let t=[this.cameraManager.camera,...e.cameras||[]];this.cameraManager.setCameras(t),this.timeline.clear(),this.interactionManager&&(this.interactionManager.floorPlane=this.assetLoader.floorPlane)})}_displaySources(){return[`oidn:output`,`edgeFiltering:output`,`bilateralFiltering:output`,`asvgf:output`,`nrd:output`]}_settingsBindings(){let e=super._settingsBindings();return{...e,applyExposure:t=>{this.stages.autoExposure?.enabled||e.applyExposure(t)},onCameraProjection:e=>{this.cameraManager.applyProjection(e),e===`equirectangular`&&this.denoisingManager?.requiresMotionVectors&&this.denoisingManager.setDenoiserStrategy(`edgeaware`)}}}_beginFrame(){if(this.timeline.update(),this.cameraManager.updateControls(),this._applyPendingRenderScale(),this.animationManager?.isPlaying&&!this._animRefitInFlight){let e=this.animationManager.update();e&&(this._animRefitInFlight=!0,this.refitBVH(e).catch(e=>NN.error(`animation refit error:`,e)).finally(()=>{this._animRefitInFlight=!1}))}}_beforeTrace(){this.cameraManager.updateAutoFocus()}_holdTrace(e){return this.denoisingManager?.skipsTrace()?(e&&this.stages.pathTracer.enterInteractionMode(),!0):!1}_afterTrace(e,t){this.denoisingManager?.afterTrace(),t&&!e.isComplete&&this.denoisingManager?.tickContinuousDenoise(e.frameCount)}_renderCompleted(){this.denoisingManager.onRenderComplete({isStillComplete:()=>this.completion.renderCompleteDispatched,context:this.pipeline?.context})}_renderHelperOverlay(){super._renderHelperOverlay(),this.overlayManager?.render()}_beforeReset(e){this.denoisingManager?.beforeReset({keepHistory:e})}_afterReset(){this.denoisingManager?.afterReset(),this._abortPostProcess({keepDisplay:!0})}_dropDisplay(){this.denoisingManager?.dropDisplay()}_releaseSceneState({keepSelection:e=!1}={}){e||(this.interactionManager?.deselect(),this.transformManager?.detach?.()),this.animationManager?.dispose(),this._animRefitInFlight=!1,this._emittersMoved=!1}_modelReplaced(){this._syncControlsAfterLoad(),this.cameraManager.currentCameraIndex=0}_modelAnnounced(){this._dispatchCamerasUpdated()}_sceneRebuilt(){this._initAnimationAndTransforms()}_sceneBoundsChanged(){this._recalibrateControlLimits()}_lightRemoved(e){this.interactionManager?.selectedObject===e&&this.interactionManager.deselect()}_renderSizeChanged(e,t){this.denoisingManager?.setRenderSize(e,t)}_completionReopened(){this.denoisingManager?.abort(this.canvas)}async _finalDenoise(){return this.denoisingManager?.finalDenoise?await this.runFinalDenoise():!1}_displayCanvas(){let e=this.denoisingManager?.upscalerCanvas;return e&&e.style.display!==`none`?e:null}_registerVRAM(e){e.register(`denoiser`,()=>({bytes:this.denoisingManager?.gpuBytes()??0}))}_canvasResources(){return this.overlayManager?.gpuResources()??[]}_deterministicSnapshot(){return{autoFocusMode:this.cameraManager?.autoFocusMode,autoExposure:this.stages.autoExposure?.enabled,continuousDenoise:this.denoisingManager?.continuousDenoise}}_setDeterministicExtras(e,t){if(e){this.cameraManager?.setAutoFocusMode(`manual`),this.stages.autoExposure&&(this.stages.autoExposure.enabled=!1),this.denoisingManager?.setContinuousDenoise(!1);return}t.autoFocusMode!==void 0&&this.cameraManager?.setAutoFocusMode(t.autoFocusMode),this.stages.autoExposure&&t.autoExposure!==void 0&&(this.stages.autoExposure.enabled=t.autoExposure),t.continuousDenoise!==void 0&&this.denoisingManager?.setContinuousDenoise(t.continuousDenoise)}_disposeExtensions(){this.interactionManager?.deselect?.(),this.transformManager?.detach?.(),this.animationManager?.dispose(),this.transformManager?.dispose(),this.overlayManager?.dispose(),this.goboManager?.dispose(),this.iesManager?.dispose(),this.denoisingManager?.dispose(),this.interactionManager?.dispose(),this.timeline?.dispose(),this.cameraManager?.dispose()}get currentCameraIndex(){return this.cameraManager?.currentCameraIndex??0}addCamera({name:e}={}){let t=this.cameraManager.addCameraFromView(e);return this.cameraManager.switchCamera(t),this._dispatchCamerasUpdated(),t}removeCamera(e){let t=this.cameraManager.removeCamera(e);return t&&this._dispatchCamerasUpdated(),t}exportSceneState(){return CS(this)}async importSceneState(e,t){return await DS(this,e,t)}_dispatchCamerasUpdated(){this.dispatchEvent({type:P.CAMERAS_UPDATED,cameras:this.cameraManager.cameras,cameraNames:this.cameraManager.getCameraNames()})}_applyAnimationPose({meshIndices:e,visibilityChanged:t,cameras:n}){if(!this._sdf?.instanceTable)return;let r=!1;e.length>0&&(this._notePlacementsMoving(e),this._sdf.updateMeshTransforms(e),this.stages.pathTracer?.updateBufferRanges([],[this._sdf.computeTLASDirtyRange()]),this._sdf.movesEmitters(e)&&(this._emittersMoved=!0,this.animationManager.isPlaying||this._refreshMovedEmitters()),r=!0),t&&(this.stages.pathTracer?.updateAllMeshVisibility(),this._refreshEmissiveForVisibility(),r=!0),n.length>0&&this._followAnimatedCamera(n)&&(r=!0),r&&this.reset(!1,{motion:!0})}_notePlacementsMoving(e){let t=this.denoisingManager,n=this._sdf?.instanceTable;if(!(!t?.historyActive||!n))for(let r of e){let e=n.placementRunOf(r);if(e)for(let r=e.start;r<e.start+e.count;r++)t.notePlacementMoving(n.tlasLeafIndex[r],n.world,r*16)}}_refreshMovedEmitters(){if(this._emittersMoved){if(this._sdf?.spilled){this.ensureSceneResident().then(()=>this._refreshMovedEmitters());return}this._emittersMoved=!1,this._uploadEmissivePayload(this._sdf?.refreshEmissiveTransforms()??null)}}_followAnimatedCamera(e){let t=this.cameraManager,n=t.currentCameraIndex>0?t.cameras[t.currentCameraIndex]:null,i=n?.userData?.__rayzeeSourceUuid,a=i&&e.find(e=>e.uuid===i);if(!a)return!1;a.updateWorldMatrix(!0,!1);let o=new r.Vector3;a.matrixWorld.decompose(n.position,n.quaternion,o),n.scale.set(Math.sign(o.x)||1,Math.sign(o.y)||1,Math.sign(o.z)||1),a.isPerspectiveCamera&&(n.fov=a.fov);let s=t.camera,c=t.controls,l=c?c.target.distanceTo(s.position):0;if(s.position.copy(n.position),s.quaternion.copy(n.quaternion),s.scale.copy(n.scale),s.isPerspectiveCamera&&n.isPerspectiveCamera&&(s.fov=n.fov),s.updateProjectionMatrix(),s.updateMatrixWorld(!0),c){let e=new r.Vector3(0,0,-1).applyQuaternion(s.quaternion);c.target.copy(s.position).addScaledVector(e,l||1)}return!0}_interactionRenderScale(){if(this.denoisingManager?.continuousDenoise)return 1;let e=Number(this.settings.get(`interactionRenderScale`));return e>0?Math.min(1,Math.max(.125,e)):1}_requestRenderScale(e){this._pendingRenderScale=e}_applyPendingRenderScale(){this._pendingRenderScale!==null&&this._applyRenderScale(this._pendingRenderScale)}_applyRenderScale(e){this._pendingRenderScale=null,!(this._disposed||e===this._renderScale)&&(this._renderScale=e,!(!this._displayWidth||!this._displayHeight)&&(this._setDisplaySize(this._displayWidth,this._displayHeight),this.pipeline?.setSize(this._scaled(this._displayWidth),this._scaled(this._displayHeight)),this.pipeline?.eventBus.emit(`pipeline:historyReset`),this.needsReset=!0))}configureForMode(e,t={}){let n=e===`production`,r=n?it:at;this.denoisingManager?.setCadenceSuspended(n),this.timeline.stop(),this.cameraManager.controls.enabled=!n,this.settings.setMany(ot(r),{silent:!0,source:Xg.MODE_PRESET}),this.stages.pathTracer?.setUniform(`renderMode`,parseInt(r.renderMode)),n&&this._applyRenderScale(1),this.stages.pathTracer?.updateCompletionThreshold?.();let i=this.denoisingManager?.denoiser;if(i&&(i.abort(),this.denoisingManager.applyOIDNEnabled(r.enableOIDN),this.denoisingManager.applyOIDNQuality(r.oidnQuality)),this.denoisingManager?._syncGBufferStages?.(),this.denoisingManager?.upscaler?.abort(),t.canvasWidth&&t.canvasHeight&&(this.setReservedRenderResolution(Math.max(t.canvasWidth,t.canvasHeight)),this.setCanvasSize(t.canvasWidth,t.canvasHeight)),this.needsReset=!1,this.pauseRendering=!1,n){let e=this.stages.pathTracer?.vramTracker;e&&(e.measure(),e.resetPeak())}this.reset()}_presentDisplay(){if(this.animationManagerId){this._needsDisplayRefresh=!0;return}let e=this.pipeline?.context;this._deviceLost||!e||(this.stages.compositor?.render(e),this._renderHelperOverlay())}async runFinalDenoise(){let e=this.denoisingManager;if(await e?.denoiseOnce())return!0;let t=e?.denoiser?e.denoiser.enabled?`the denoise did not complete`:`OIDN was off while accumulating — call denoisingManager.setOIDNEnabled( true ) first`:`the denoiser was not built`;return this._issues.record(Y.DENOISER_UNAVAILABLE,`final denoise produced no picture: ${t}`,{reason:t}),!1}_abortPostProcess({keepDisplay:e=!1}={}){if(this.denoisingManager?.abort(this.canvas,{keepDisplay:e}),this.denoisingManager?.restoreBaseResolution()){let e=this.denoisingManager._lastRenderWidth,t=this.denoisingManager._lastRenderHeight;this.dispatchEvent({type:P.RESOLUTION_CHANGED,width:e,height:t})}}requestPostProcessRefresh(){!this.stages.pathTracer?.isReady||this._deviceLost||(this._abortPostProcess(),this.completion.renderCompleteDispatched=!1,this.wake())}profileNextDenoise(){return this.denoisingManager?.denoiser?.profileNextDenoise()??!1}async getDenoiseProfile(){let e=this.denoisingManager?.denoiser;return e?{profile:await e.getLastDenoiseProfile(),runtime:e.getRuntimeInfo()}:null}_denoiserInUse(){let e=this.denoisingManager;return!!e?.denoiser?.enabled||(e?.denoiserStrategy??`none`)!==`none`}_initAnimationAndTransforms(){let e=this.assetLoader?.animations||[];if(e.length>0){let t=this.sceneModel||this.meshScene;this.animationManager.init(this.meshScene,t,this._sdf.meshes,e),this.animationManager.onFinished=()=>{this._animRefitInFlight=!1,this._refreshMovedEmitters(),this.dispatchEvent({type:P.ANIMATION_FINISHED})}}this.transformManager?.setMeshData(this._sdf.meshes)}_setupDenoisingManager(){this.denoisingManager=new eS({renderer:this.renderer,mainCanvas:this.canvas,stages:{pathTracer:this.stages.pathTracer,normalDepth:this.stages.normalDepth,motionVector:this.stages.motionVector,asvgf:this.stages.asvgf,nrd:this.stages.nrd,variance:this.stages.variance,bilateralFilter:this.stages.bilateralFilter,edgeFilter:this.stages.edgeFilter,autoExposure:this.stages.autoExposure,compositor:this.stages.compositor},pipeline:this.pipeline,getExposure:()=>this.settings.get(`exposure`)??1,getSaturation:()=>this.settings.get(`saturation`)??1,issues:this._issues}),this.denoisingManager.setupDenoiser(),this.denoisingManager.setupUpscaler(),this.denoisingManager._syncGBufferStages();let e=this.canvas.clientWidth||1,t=this.canvas.clientHeight||1;this.denoisingManager.setRenderSize(e,t)}_setupAutoExposureListener(){this.stages.autoExposure&&this.stages.autoExposure.on(`autoexposure:updated`,e=>{this.dispatchEvent({type:P.AUTO_EXPOSURE_UPDATED,exposure:e.exposure,luminance:e.luminance})})}async _setupOverlayManager(){this.overlayManager=new lS(this.cameraManager.camera),this.overlayManager.setupDefaultHelpers({helperScene:this._sceneHelpers,meshScene:this.meshScene,pipeline:this.pipeline,denoisingManager:this.denoisingManager,app:this,renderWidth:this.denoisingManager?._lastRenderWidth||this.canvas.clientWidth||1,renderHeight:this.denoisingManager?._lastRenderHeight||this.canvas.clientHeight||1}),await this.overlayManager.initViewRenderer({device:this.renderer.backend?.device,sizeSource:this.canvas}),this._container=this._container||this.canvas.parentNode||null,this.overlayManager.mount(this._container)}_syncControlsAfterLoad(){this.cameraManager.fitOrthographic(),this.cameraManager.controls.saveState(),this.cameraManager.controls.update(),this.cameraManager.walkControls.fitSpeed(this.assetLoader.getSceneScale())}_recalibrateControlLimits(){if(!this.meshScene||!this.cameraManager)return;let e=new r.Box3,t=new r.Box3;for(let n of this.meshScene.children)n.userData?.__rayzeeSceneObject&&(t.setFromObject(n),t.isEmpty()||e.union(t));if(e.isEmpty())return;let n=Math.max(e.max.x-e.min.x,e.max.y-e.min.y,e.max.z-e.min.z);if(!Number.isFinite(n)||n<=0)return;let{camera:i,controls:a}=this.cameraManager,o=i.fov*(Math.PI/180),s=Math.abs(n/Math.sin(o/2)/2);this.cameraManager.currentCameraIndex===0&&(i.near=n/100,i.far=n*100,i.updateProjectionMatrix());let c=i.position.distanceTo(a.target);a.minDistance=Math.min(n/1e3,c),a.maxDistance=Math.max(s*10,c*1.1),a.update()}};async function FN(e){let t=await LN(e);try{return await IN(t,e)}finally{t.dispose()}}async function IN(e,{samples:t=64,colorSpace:n=`srgb`,allowEarlyRetire:r=!1,denoise:i=!1,onProgress:a=void 0}={}){let o=e.denoisingManager;i&&o&&!o.finalDenoise&&(o.applyOIDNEnabled(!0),o._syncGBufferStages());let s=await e.renderFrames(t,{onProgress:a,allowEarlyRetire:r});return i&&await e.runFinalDenoise(),{...await e.renderToBuffer({colorSpace:n,source:i?`display`:`accumulation`}),samples:s,retiredBy:s<t?`converged`:`count`,issues:e.issues,adapter:e.adapterInfo,provenance:e.getProvenance()}}async function LN({canvas:e,model:t=null,width:n=1920,height:r=1080,strict:i=!0,deterministic:a=!0,settings:o=null,storage:s=!1,hostMemoryGB:c=void 0}={}){let l=new PN(e??null,{autoResize:!1,strict:i,storage:s,hostMemoryGB:c});try{return l.setReservedRenderResolution(Math.max(n,r)),await l.init(),l.setCanvasSize(n,r),o&&l.settings.setMany(o,{silent:!0}),t&&await l.loadModel(t),o&&l.settings.setMany(o,{silent:!0}),a&&l.setDeterministicMode(!0),l}catch(e){throw l.dispose(),e}}Jg(),I(),fe();var RN=class{constructor(e){this._app=e,this._cancelled=!1,this._rendering=!1}async renderAnimation(e={}){let{clipIndex:t=0,fps:n=30,speed:r=1,samplesPerFrame:i=it.maxSamples,enableOIDN:a=!0,timeline:o=null,startFrame:s=0,onFrame:c,onProgress:l,onComplete:u}=e,d=this._app,f=d.animationManager?.hasAnimations?d.animationManager.clips[t]:null;if(!f&&!o?.animates){console.warn(d.animationManager?.hasAnimations?`VideoRenderManager: Invalid clip index ${t}`:`VideoRenderManager: No animation clips or keyframes`),u?.(!1);return}let p=f?f.duration/(r||1):o.duration,m=e.totalFrames||Math.ceil(p*n),h=1/n;if(!(m>0)){console.warn(`VideoRenderManager: No frames to render`),u?.(!1);return}this._cancelled=!1,this._rendering=!0;let g=this._saveState({view:!!o});d.stopAnimation(),d.configureForMode(`production`),d.settings.setMany({maxSamples:i},{silent:!0}),d.stages.pathTracer?.updateCompletionThreshold?.(),d.cameraManager.controls&&(d.cameraManager.controls.enabled=!1);try{for(let e=Math.max(0,s);e<m&&!this._cancelled;e++){let n=e*h*r,i=f?d.animationManager.seekTo(n,t):null;if(o?.seek(e*h)&&(d.cameraManager.resetAutoFocus(),d.cameraManager.updateAutoFocus()),i?await d.refitBVH(i):d.reset(),d.stopAnimation(),await this._accumulateFrame(d),this._cancelled||(a&&d.denoisingManager?.finalDenoise&&await this._waitForDenoise(d),this._cancelled))break;let s=d.getCanvas();if(s&&c){let t=await createImageBitmap(s);await c(t,e,m),t.close()}let u={frame:e+1,totalFrames:m,percent:(e+1)/m*100};l?.(u),d.dispatchEvent({type:P.VIDEO_RENDER_PROGRESS,...u})}}catch(e){console.error(`VideoRenderManager: Render error:`,e),this._cancelled=!0}finally{this._restoreState(g),this._rendering=!1;let e=!this._cancelled;u?.(e),d.dispatchEvent({type:P.VIDEO_RENDER_COMPLETE,success:e})}}cancel(){this._cancelled=!0}get isRendering(){return this._rendering}async _accumulateFrame(e){let t=e.stages.pathTracer;if(t?.isReady)for(;!t.isComplete&&!this._cancelled;){let n=t.readbackWait();if(n){await n;continue}e.cameraManager.camera.updateMatrixWorld(),e.pipeline.render(),t.frameCount%4==0&&(de({samples:ee(t)}),await new Promise(e=>setTimeout(e,0)))}}_waitForDenoise(e){return new Promise(t=>{let n,r=()=>{e.removeEventListener(P.DENOISING_END,i),clearTimeout(n)},i=()=>{r(),t()};n=setTimeout(()=>{console.warn(`VideoRenderManager: Denoise timed out, skipping`),r(),t()},3e4),e.addEventListener(P.DENOISING_END,i),e.denoisingManager.onRenderComplete({isStillComplete:()=>!this._cancelled,context:e.pipeline?.context})})}_saveState({view:e}){let t=this._app,n=t.settings.getEffective(),r=Object.keys(ot(it));return e&&r.push(`focusDistance`),{view:e?t.cameraManager.captureView():null,settings:r.map(e=>[e,n[e]]),renderMode:t.stages.pathTracer?.renderMode?.value,controlsEnabled:t.cameraManager.controls?.enabled,oidnEnabled:t.denoisingManager?.finalDenoise,oidnQuality:t.denoisingManager?.oidnQuality,wasPlaying:t.animationManager?.isPlaying,pauseRendering:t.pauseRendering}}_restoreState(e){let t=this._app;for(let[n,r]of e.settings)r&&t.settings.set(n,r.value,{silent:!0,reset:!1,source:r.source});t.stages.pathTracer&&e.renderMode!==void 0&&t.stages.pathTracer?.setUniform(`renderMode`,parseInt(e.renderMode)),t.stages.pathTracer?.updateCompletionThreshold?.(),t.cameraManager.controls&&(t.cameraManager.controls.enabled=e.controlsEnabled??!0),t.denoisingManager?.denoiser&&(t.denoisingManager.applyOIDNEnabled(e.oidnEnabled??!1),e.oidnQuality&&t.denoisingManager.applyOIDNQuality(e.oidnQuality)),t.pauseRendering=e.pauseRendering??!1,e.view&&t.cameraManager.applyPose(e.view),t.denoisingManager?.setCadenceSuspended(!1),t.animationManager?.stop(),t.reset(),t.wake()}};k(),I(),X(),zr(),jD(),kS(),Ms(),z_(),Ae(),wt(),La(),Ox(),Hx(),ko(),e.ARCHIVE_FORMATS=OS,e.ASVGF_QUALITY_PRESETS=hv,e.AUTO_EXPOSURE_DEFAULTS=Cy,e.AUTO_FOCUS_DEFAULTS=Qy,e.AnimationManager=dS,e.BVH_LEAF_MARKERS=St,e.CameraManager=ib,e.CameraTrack=cb,e.ColorManagement=iE,e.DEFAULT_LUT_SIZE=vT,e.DEFAULT_MAX_EV=_T,e.DEFAULT_MIN_EV=gT,e.DEFAULT_SUN_PATH=Xr,e.DEFAULT_VIEW=Oo,e.DEFAULT_WORKING_SPACE=Er,e.DENOISER_DEFAULTS=Sv,e.DOWNLOAD_POLICY=wg,e.DenoisingManager=eS,e.DownloadCache=Mg,e.ENGINE_AREAS=tn,e.ENGINE_DEFAULTS=G,e.EngineEvents=P,e.EngineIssueError=Gt,e.GoboManager=db,e.IESManager=Cb,e.INTERACTIVE_RENDER_CONFIG=at,e.ISSUE_CODES=Y,e.ISSUE_SEVERITY=Wt,e.InteractionManager=Fy,e.IssueLog=Kt,e.LEGACY_EVENT_NAMES=F,e.LOG_LEVELS=xe,e.LightManager=ev,e.Logger=Oe,e.MATERIAL_DEFAULTS=nt,e.MATERIAL_VALUE_SOURCE=gn,e.MAX_RESERVABLE_RENDER_SIZE=je,e.MAX_SCENE_BYTES=ja,e.MAX_TABLE_TRANSFORMS=xo,e.MemoryLedger=Ia,e.NRD_DEFAULTS=vv,e.NRD_HIT_DIST_A=gv,e.NRD_HIT_DIST_B=_v,e.NRD_PRESET_KEYS=yv,e.NRD_QUALITY_PRESETS=bv,e.OCIO_VIEW_BASE=bo,e.OverlayManager=lS,e.PRODUCTION_RENDER_CONFIG=it,e.PathTracerApp=PN,e.PipelineContext=sg,e.RETOUCH_DEFAULTS=Nx,e.RETOUCH_MAX_PIXELS=Fx,e.RETOUCH_RANGES=Ix,e.RayzeeRenderer=dv,e.RenderPipeline=yg,e.RenderSettings=Zg,e.RenderStage=M,e.SAFE_SCENE_BYTES=Aa,e.SCENE_STATE_VERSION=gS,e.SETTING_SOURCE=Xg,e.SKY_DEFAULTS=Qr,e.SR_MAX_INPUT=Cx,e.SR_SCALE=xx,e.STORAGE_KIND=en,e.StageExecutionMode=j,e.StorageManager=ME,e.TRIANGLE_DATA_LAYOUT=K,e.TimelineManager=ub,e.TransformManager=mS,e.VERSION=js,e.VIEW_TRANSFORMS=Eo,e.VRAMTracker=Uu,e.VideoRenderManager=RN,e.acquireLock=dE,e.addAllOcioViews=kT,e.addOcioView=OT,e.addViewTransform=mo,e.applyMatrixRGBA8=eT,e.bakeLut=sT,e.bufferBytes=Vu,e.buildOcioView=TT,e.buildToneMapWGSL=vo,e.cachedObjectURL=Fg,e.canvasColorSpaceFor=eE,e.captureHeadless=IN,e.clearBindingAuditFindings=mg,e.clearInputOverrides=WT,e.configureAssets=Pr,e.configurePlatform=rr,e.convertColor=Vw,e.convertEncodedRGBA8=Yw,e.convertPixelsF32=Hw,e.createLogger=ye,e.dayOfYearForMonth=Tr,e.deriveAlphaMode=bn,e.describeAdapter=uv,e.displayCanvasFit=cw,e.estimateSceneBytes=Ca,e.extractMatrix=tT,e.extractSceneMetadata=I_,e.fetchFile=Ng,e.fileIdentity=Bg,e.findNativeLinearSpace=rE,e.fmt=H,e.fromPortable=Ln,e.getActiveColorManagement=Or,e.getAssetConfig=Ir,e.getBindingAuditFindings=pg,e.getPlatform=ir,e.getRegistryVersion=so,e.getViewTransform=lo,e.hasColorSpace=rT,e.heldLockNames=fE,e.identityKey=Vg,e.isColorManaged=aE,e.isDataSpace=nT,e.isDataTexture=XT,e.linearToSrgb=Gw,e.listFileRules=qT,e.listInputOverrides=GT,e.listViewTransforms=uo,e.makeCpuSampler=pT,e.measureBakeError=hT,e.nameFromUrl=Og,e.onRegistryChange=co,e.openHeadless=LN,e.openStorage=VE,e.openZip=CD,e.parseSceneMetadata=F_,e.probeAddressSpace=wa,e.readZipDirectory=bD,e.removeViewTransform=ho,e.renderHeadless=FN,e.renderUpscaled=vx,e.resolveInputSpace=YT,e.sameIdentity=Hg,e.setActiveColorManagement=kr,e.setBindingAudit=fg,e.setInputOverride=UT,e.srgbToLinear=Ww,e.sunPosition=Cr,e.textureBytes=Hu,e.textureInputSpace=$T,e.timeForSunElevation=wr,e.toPortable=In});
1447
+ `)))}`}var zT=[],BT=0;function VT(){return BT}function HT(){BT++}function UT(e,t){zT.unshift({match:e,colorSpace:t}),BT++}function WT(){zT.length!==0&&(zT.length=0,BT++)}function GT(){return zT.map(e=>({match:String(e.match),colorSpace:e.colorSpace}))}function KT(e){if(!e)return null;for(let t of zT)if(t.match instanceof RegExp?t.match.test(e):e.includes(t.match))return t.colorSpace;return null}function qT(){return Cw()?.fileRules.map(e=>({index:e.index,name:e.name,colorSpace:e.colorSpace,pattern:e.pattern,extension:e.extension,regex:e.regex}))??[]}function JT(e){let t=Cw();if(!t)return null;let n=e=>t.roles.find(t=>t.name===e)?.colorSpace??null;return e===r.NoColorSpace?n(`data`):e===r.SRGBColorSpace?n(`texture_paint`)??n(`color_picking`)??t.colorSpaces.find(e=>/^srgb\b/i.test(e.name)&&!/display/i.test(e.name))?.name??null:e===r.LinearSRGBColorSpace?t.colorSpaces.find(e=>/^lin(ear)?[\s_-]*(rec\.?\s*)?709/i.test(e.name))?.name??t.colorSpaces.find(e=>/^linear.*srgb/i.test(e.name))?.name??n(`scene_linear`):null}function YT(e,{threeColorSpace:t=null}={}){if(!Cw())return null;let n=KT(e);if(n)return{colorSpace:n,via:`override`,rule:null};let r=Sw();if(r&&e){let t=r.matchFileRule(e);if(t&&!t.isDefaultRule&&rT(t.colorSpace))return{colorSpace:t.colorSpace,via:`rule`,rule:{index:t.ruleIndex,name:t.ruleName}}}let i=JT(t);if(i)return{colorSpace:i,via:`three`,rule:null};let a=Sw();if(a&&e){let t=a.matchFileRule(e);if(t&&rT(t.colorSpace))return{colorSpace:t.colorSpace,via:`rule`,rule:{index:t.ruleIndex,name:t.ruleName,isDefault:t.isDefaultRule}}}return null}function XT(e){if(!e)return!1;if(e.colorSpace===r.NoColorSpace)return!0;let t=e.userData?.ocioColorSpace;return!!(t&&nT(t))}function ZT(e,t){return t??e.userData?.sourcePath??(e.name||null)??e.image?.src??null}function QT(e,t=null){if(!Cw()||!e)return null;let n=e.userData?.ocioColorSpace;return n?rT(n)?{colorSpace:n,via:`tag`,rule:null}:null:XT(e)?null:YT(ZT(e,t),{threeColorSpace:e.colorSpace})}function $T(e,t=null){return QT(e,t)?.colorSpace??null}X(),ko(),Fn();function eE(e){return cw(e)??`srgb`}var tE=[`Linear Rec.709 (sRGB)`,`lin_rec709_srgb`,`lin_rec709`,`lin_srgb`,`Linear Rec.709`,`Utility - Linear - sRGB`,`Utility - Linear - Rec.709`,`Linear BT.709`,`linrec709`],nE=/^(lin(ear)?[\s_-]*(rec\.?\s*|bt\.?\s*)?709|linear[\s_-]*\(?srgb\)?$|utility - linear - (srgb|rec\.?709))/i;function rE(e){if(!e)return null;let t=e.colorSpaces.filter(e=>!e.isData),n=e=>[e.name,...e.aliases??[]];for(let e of tE){let r=t.find(t=>n(t).some(t=>t.toLowerCase()===e.toLowerCase()));if(r)return r.name}return t.find(e=>n(e).some(e=>nE.test(e)))?.name??null}var iE=class{constructor({issues:e=null,renderer:t=null}={}){this._issues=e,this._renderer=t,this._listeners=new Map,this._workingSpace=null,this._activeView=null,this._exportSpace=null,this._context=null,this._lastUsed=new Map,this._useClock=0,this._lastBuiltin=Do,this._fingerprint=null,xT(e),this._offRegistry=co(()=>{this._renderer&&_o(this._renderer),this._emit(`transforms`)}),Ar(this)}on(e,t){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(t),()=>this._listeners.get(e)?.delete(t)}_emit(e,t=null){for(let n of this._listeners.get(e)??[])n(t);if(e!==`change`)for(let n of this._listeners.get(`change`)??[])n({event:e,detail:t})}static async listBuiltinConfigs(){return await vw()}async loadConfig({adoptWorkingSpace:e=!1,registerViews:t=!0,display:n=null,lutSize:r,...i}={}){await _w();let a=RT(i).catch(()=>null),o=await this._bakedViewsFrom(i.builtin??i.id??null,a),s;try{s=await yw(i)}catch(e){throw this._issues?.warn(Y.COLOR_CONFIG_LOAD_FAILED,`colour config failed to load; the previous one stays in effect: ${e.message}`,{builtin:i.builtin??null,configPath:i.configPath??null}),e}this._releaseViews(new Set(o.filter(e=>e.ocio.baked.ocioVersion===s.ocioVersion).map(e=>e.id))),this._fingerprint=a,HT(),Bw(),this._context=null;let c=this._workingSpace;if(e?this._workingSpace=s.sceneLinear:c&&!rT(c)&&(this._workingSpace=null),rE(Cw())||this._issues?.warn(Y.COLOR_CONFIG_LOAD_FAILED,`"${s.id}" names no linear Rec.709 space, so until a working space is adopted its views treat the render as ${s.sceneLinear} — colours will be off by that primaries change`,{sceneLinear:s.sceneLinear}),this._publishWorkingMatrix(),this._emit(`config`,s),t){let e=n??s.defaultDisplay,{added:t,skipped:i}=kT({display:e,context:this._context,source:this.workingSpace,...r?{size:r}:{}});if(t.length){let n=s.defaultViews[e],r=t.find(e=>e.ocio.view===n)??t[0];this.setActiveView(r.id)}this._emit(`transforms`,{added:t,skipped:i})}return(this._workingSpace??null)!==(c??null)&&this._emit(`workingSpace`,this.workingSpace),s}unloadConfig(){this.workingSpaceAdopted&&this._issues?.warn(Y.COLOR_CONFIG_LOAD_FAILED,`unloaded while rendering in ${this._workingSpace}; the environment stays converted into it — use app.unloadColorConfig(), which reverts the scene first`,{workingSpace:this._workingSpace}),this._releaseViews(),bw(),Bw(),WT(),HT(),this._fingerprint=null,this._workingSpace=null,this._activeView=null,this._exportSpace=null,this._context=null,On(null),this._applyRendererOutputColorSpace(),this._emit(`config`,null),this._emit(`workingSpace`,this.workingSpace)}_releaseViews(e=null){jT(e),go(e);for(let t of this._lastUsed.keys())e?.has(t)||this._lastUsed.delete(t);this._renderer&&lo(this._renderer.toneMapping)===null&&(this._renderer.toneMapping=lo(this._lastBuiltin)?this._lastBuiltin:Do,this._activeView=null,this._applyRendererOutputColorSpace())}async _bakedViewsFrom(e,t){let n=[...Eo.values()].filter(t=>t.ocio?.baked&&e!==null&&t.ocio.configId===e);if(n.length===0)return[];let r=await t;return r?n.filter(e=>e.ocio.baked.fingerprint===r):[]}async loadBakedView(e,{expect:t=null}={}){let n=await LT(e);for(let[e,r]of Object.entries(t??{}))if((n[e]??null)!==(r??null))throw Error(`baked view has ${e} "${n[e]}", expected "${r}"`);let r=ww();if(r&&(r.id!==n.configId||await this._fingerprint!==n.fingerprint))throw Error(`baked view is from "${n.configId}", not the loaded "${r.id}"`);let i=[...Eo.values()].find(e=>e.source===`ocio`&&e.ocio.display===n.display&&e.ocio.view===n.view&&(e.ocio.look??null)===(n.look??null));return i||this._makeRoomForTable(),mo(ET(n,i?.id??null))}async saveBakedView(e){let t=lo(e);if(t?.source!==`ocio`)throw Error(`no OCIO view with id ${e}`);let n=ww();return await IT(t,{configId:n?.id??t.ocio.configId,fingerprint:(n?await this._fingerprint:null)??t.ocio.baked?.fingerprint??null,ocioVersion:n?.ocioVersion??t.ocio.baked?.ocioVersion??null})}get hasConfig(){return xw()}describe(){return ww()}get workingSpace(){return this._workingSpace?this._workingSpace:xw()?this.nativeLinearSpace??ww()?.sceneLinear??`Linear Rec.709 (sRGB)`:Er}get workingSpaceAdopted(){return this._workingSpace!==null}setWorkingSpace(e){if(e!==null){if(!xw())throw Error(`load an OCIO config before choosing a working space`);if(!rT(e))throw Error(`config has no colour space "${e}"`)}(this._workingSpace??null)!==(e??null)&&(this._workingSpace=e,Pw(),this._publishWorkingMatrix(),this._rebakeViews(),this._emit(`workingSpace`,this.workingSpace))}matrixToWorking(e){return xw()?tT(e,this.workingSpace,{context:this._context}):null}listViews(){return uo()}get activeView(){return this._activeView}setActiveView(e){let t=lo(e);if(!t)throw Error(`no view transform with id ${e}`);return this._isStale(t)&&(t=this._rebakeView(t)??t),this._activeView=t.source===`ocio`?{...t.ocio,id:t.id,name:t.name}:null,this._lastUsed.set(e,++this._useClock),t.source===`builtin`&&(this._lastBuiltin=e),this._renderer&&(this._renderer.toneMapping=e),this._applyRendererOutputColorSpace(),this._emit(`view`,t),t}setView({display:e,view:t,look:n=null,size:r}={}){if(!xw())throw Error(`load an OCIO config first`);let i=[...Eo.values()].find(i=>i.source===`ocio`&&i.ocio.display===e&&i.ocio.view===t&&(i.ocio.look??null)===(n??null)&&(!r||i.ocio.size===r));i||this._makeRoomForTable();let a=i??OT({display:e,view:t,look:n,context:this._context,source:this.workingSpace,...r?{size:r}:{}});return this.setActiveView(a.id),lo(a.id)}_makeRoomForTable(){if(fo()<12)return;let e=this._renderer?.toneMapping??this._activeView?.id??null,t=[...Eo.values()].filter(t=>t.source===`ocio`&&t.id!==e).sort((e,t)=>(this._lastUsed.get(e.id)??0)-(this._lastUsed.get(t.id)??0))[0];t&&(AT(t.id),ho(t.id),this._lastUsed.delete(t.id))}setLook(e){if(!this._activeView)throw Error(`no OCIO view is active`);return this.setView({...this._activeView,look:e})}setContext(e){let t=e&&Object.keys(e).length?{...e}:null;JSON.stringify(t)!==JSON.stringify(this._context)&&(this._context=t,xw()&&(this._context&&Sw()?.invalidateContext(this._context),Pw(),this._rebakeViews()),this._emit(`context`,this._context))}get context(){return this._context}_isStale(e){return e.source!==`ocio`||!xw()?!1:e.ocio.source!==this.workingSpace||JSON.stringify(e.ocio.context??null)!==JSON.stringify(this._context??null)}_rebakeView(e){try{let t=OT({id:e.id,display:e.ocio.display,view:e.ocio.view,look:e.ocio.look,context:this._context,source:this.workingSpace,size:e.ocio.size,minEv:e.ocio.minEv,maxEv:e.ocio.maxEv}),n=e.table?.texture;return n&&n!==t.table?.texture&&n.dispose?.(),t}catch(t){return this._issues?.warn(Y.VIEW_TRANSFORM_BAKE_FAILED,`could not rebake "${e.name}": ${t.message}`,{id:e.id}),null}}_rebakeViews(){let e=this._renderer?.toneMapping??this._activeView?.id??null,t=e===null?null:lo(e);if(!t||!this._isStale(t))return;let n=this._rebakeView(t);n&&(this._activeView={...n.ocio,id:n.id,name:n.name})}attachRenderer(e){this._renderer=e,lo(e.toneMapping)?.source===`builtin`&&(this._lastBuiltin=e.toneMapping);let t=_o(e);return this._applyRendererOutputColorSpace(),t}_applyRendererOutputColorSpace(){if(!this._renderer)return;let e=lo(this._renderer.toneMapping);this._renderer.outputColorSpace=e?.outputEncoded?r.LinearSRGBColorSpace:r.SRGBColorSpace,this._applyCanvasColorSpace(e?.source===`ocio`?eE(e.ocio.display):`srgb`)}_applyCanvasColorSpace(e){let t=(this._renderer?.domElement)?.getContext?.(`webgpu`),n=t?.getConfiguration?.();if(n){if(!t.__rayzeeConfigure){let e=t.configure.bind(t);t.__rayzeeConfigure=e,t.configure=n=>e({...n,colorSpace:t.__rayzeeColorSpace??n.colorSpace})}if(t.__rayzeeColorSpace=e,n.colorSpace!==e)try{t.configure({...n,colorSpace:e})}catch(t){this._issues?.warn(Y.VIEW_TRANSFORM_DISPLAY_MISMATCH,`the canvas could not be set to ${e}: ${t.message}`,{colorSpace:e})}}}resolveInput(e,t){return YT(e,t)}textureSpace(e,t){return $T(e,t)}resolveTexture(e,t){return QT(e,t)}describeTextureSpace(e){let t=e?.userData??{},n=t.ocioColorSpace??t.__rayzeeColorSpaceChoice??null,i=null,a=t.__rayzeeOriginalColorSpace??e?.colorSpace;return xw()&&(i=QT({...e,name:e?.name,image:e?.image,colorSpace:a,userData:{}})),i||={colorSpace:a===r.SRGBColorSpace?`sRGB`:`Linear`,via:`three`},{choice:n,auto:i}}get inputKey(){return xw()?`${ww()?.id}|${this.workingSpace}|${VT()}|${JSON.stringify(this._context)}`:`-`}overrideInput(e,t){UT(e,t)}fileRules(){return qT()}toWorkingPixels(e,t){return!xw()||!t?e:Hw(e,t,this.workingSpace,{context:this._context})}get nativeLinearSpace(){return rE(Cw())}_publishWorkingMatrix(){let e=Or();e!==null&&e!==this||On(xw()?this.primariesMatrixToWorking():null,this.workingSpace)}primariesMatrixToWorking(){if(!xw()||!this.workingSpaceAdopted)return null;let e=this.nativeLinearSpace;if(!e||e===this.workingSpace)return null;let t=tT(e,this.workingSpace,{context:this._context});return t?[1,0,0,0,1,0,0,0,1].every((e,n)=>Math.abs(t[n]-e)<1e-6)?null:t:null}convertLinearTriple(e){return jn(e)}convertLinearTriples(e,t,n){return Mn(e,t,n)}convertTexturePixels(e,{space:t=null}={}){if(!xw())return!1;let n=e?.image?.data;if(!n)return!1;let r=this.nativeLinearSpace,i=e.userData?.__rayzeeColorSpace??t??r,a=this.workingSpaceAdopted?this.workingSpace:r;if(!i||!a||i===a)return!1;let o=!1;if(n instanceof Float32Array)Hw(n,i,a,{context:this._context}),o=!0;else if(n instanceof Uint16Array){let e=lT(n);Hw(e,i,a,{context:this._context}),n.set(cT(e)),o=!0}else if(n instanceof Uint8Array||n instanceof Uint8ClampedArray)Yw(n,i,a,{context:this._context,inputEncoding:`srgb`,outputEncoding:`srgb`}),o=!0;else return this._issues?.warn(Y.VIEW_TRANSFORM_BAKE_FAILED,`texture data is ${n.constructor?.name??typeof n}, which cannot be colour-converted`,{from:i,to:a}),!1;return e.userData=e.userData??{},e.userData.__rayzeeColorSpace=a,e.needsUpdate=!0,o}convertTextureBytes(e,{space:t=null,encoding:n=`srgb`}={}){if(!xw())return!1;if(t)return t===this.workingSpace?!1:(Yw(e,t,this.workingSpace,{context:this._context,inputEncoding:`raw`,outputEncoding:n}),!0);let r=this.primariesMatrixToWorking();return r?(eT(e,r,n),!0):!1}toWorkingColor(e,t){return!xw()||!t?[e[0],e[1],e[2]]:Vw(e,t,this.workingSpace,{context:this._context})}convert(e,t,n){return Vw(e,t,n,{context:this._context})}get exportSpace(){return this._exportSpace}setExportSpace(e){if(e!=null){if(!xw())throw Error(`load an OCIO config before choosing an export space`);if(!rT(e))throw Error(`config has no colour space "${e}"`)}this._exportSpace=e??null,this._emit(`export`,this._exportSpace)}exportPixels(e,t=void 0){let n=t===void 0?this._exportSpace:t;return!n||!xw()?{rgba:e,colorSpace:this.workingSpace}:(Hw(e,this.workingSpace,n,{context:this._context}),{rgba:e,colorSpace:n})}status(){let e=ww(),t=this._renderer?lo(this._renderer.toneMapping):null;return{config:e,workingSpace:this.workingSpace,workingSpaceAdopted:this.workingSpaceAdopted,activeTransform:t?{id:t.id,name:t.name,source:t.source}:null,activeView:this._activeView,context:this._context,exportSpace:this._exportSpace,views:uo(),registryVersion:so(),bakeError:t?.error??null}}dispose(){this._offRegistry?.(),this._listeners.clear(),this._releaseViews(),xT(null),this._renderer=null,this._issues=null,Or()===this&&(On(null),kr(null))}static resetAll(){kr(null),On(null),jT(),yo(),Bw(),WT(),Dw()}};function aE(){return xw()}var oE=new Map;function sE(e,t){return e.exclusive||t===`exclusive`&&e.shared>0?!1:(t===`exclusive`?e.exclusive=!0:e.shared++,!0)}function cE(e,t,n){let r=oE.get(e);r||(r={shared:0,exclusive:!1,queue:[]},oE.set(e,r));let i=lE(()=>{for(t===`exclusive`?r.exclusive=!1:r.shared--;r.queue.length&&sE(r,r.queue[0].mode);)r.queue.shift().grant();!r.exclusive&&r.shared===0&&r.queue.length===0&&oE.delete(e)});return r.queue.length===0&&sE(r,t)?Promise.resolve(i):n?(!r.exclusive&&r.shared===0&&r.queue.length===0&&oE.delete(e),Promise.resolve(null)):new Promise(e=>r.queue.push({mode:t,grant:()=>e(i)}))}function lE(e){let t=!1;return()=>{t||(t=!0,e())}}var uE=()=>typeof navigator<`u`&&navigator.locks?.request?navigator.locks:null;function dE(e,{mode:t=`exclusive`,ifAvailable:n=!1}={}){let r=uE();return r?new Promise((i,a)=>{r.request(e,{mode:t,ifAvailable:n},e=>{if(!e){i(null);return}return new Promise(e=>i(lE(e)))}).catch(a)}):cE(e,t,n)}async function fE(){let e=uE();if(!e)return new Set(oE.keys());let{held:t=[]}=await e.query();return new Set(t.map(e=>e.name))}var pE=class{constructor(){this._handlers=new Map}addEventListener(e,t){this._handlers.has(e)||this._handlers.set(e,new Set),this._handlers.get(e).add(t)}removeEventListener(e,t){this._handlers.get(e)?.delete(t)}dispatchEvent(e){for(let t of[...this._handlers.get(e.type)??[]])t.call(this,e)}},mE=class{constructor(e){this._root=e,this._writers=new Map,this._nextId=1}async _dir(e,t){let n=await this._root;for(let r of e)n=await n.getDirectoryHandle(r,{create:t});return n}async openWriter({path:e,name:t,truncate:n=!0,length:r}){let i=await(await(await this._dir(e,!0)).getFileHandle(t,{create:!0})).createSyncAccessHandle();n?i.truncate(0):r!==void 0&&i.getSize()>r&&i.truncate(r);let a=this._nextId++;return this._writers.set(a,{handle:i,end:i.getSize()}),{id:a}}write({id:e,buffer:t,byteOffset:n=0,byteLength:r,at:i}){let a=this._writers.get(e);if(!a)throw Error(`storage: writer ${e} is not open`);let o=new Uint8Array(t,n,r??t.byteLength-n),s=i??a.end,c=0;for(;c<o.length;){let e=a.handle.write(o.subarray(c),{at:s+c});if(e<=0)throw Error(`storage: write made no progress`);c+=e}return a.end=Math.max(a.end,s+o.length),{bytes:o.length}}closeWriter({id:e,abort:t=!1}){let n=this._writers.get(e);if(!n)return{size:0};this._writers.delete(e);try{return t||n.handle.flush(),{size:n.handle.getSize()}}finally{n.handle.close()}}async writeFile({path:e,name:t,buffer:n,byteOffset:r=0,byteLength:i}){let{id:a}=await this.openWriter({path:e,name:t});try{return this.write({id:a,buffer:n,byteOffset:r,byteLength:i}),this.closeWriter({id:a})}catch(e){throw this.closeWriter({id:a,abort:!0}),e}}async readRange({path:e,name:t,offset:n=0,length:r}){let i=await(await this._dir(e,!1)).getFileHandle(t),a=null;try{a=await i.createSyncAccessHandle()}catch(e){if(e.name!==`NoModificationAllowedError`)throw e}if(!a){let e=await i.getFile(),t=r===void 0?e.size:n+r;return{buffer:await e.slice(n,t).arrayBuffer()}}try{let e=a.getSize(),t=Math.max(0,Math.min(r??e-n,e-n)),i=new ArrayBuffer(t);return a.read(i,{at:n}),{buffer:i}}finally{a.close()}}dispose(){for(let e of[...this._writers.keys()])this.closeWriter({id:e,abort:!0})}},hE=class{constructor(e){this._ops=new mE(e)}async call(e,t){return this._ops[e](t)}dispose(){this._ops.dispose()}};X(),Jg(),nn();var gE=`meta.json`,_E=1,vE=36e5,yE=.3,bE=100*1024**3,xE=64*1024**2,SE=8*1024**2,CE=4,wE=3e4,TE=new TextEncoder;function EE(e,{copy:t,transfer:n}){if(typeof e==`string`&&(e=TE.encode(e)),e instanceof ArrayBuffer){if(!t||n)return{args:{buffer:e},list:[e]};let r=e.slice(0);return{args:{buffer:r},list:[r]}}if(!ArrayBuffer.isView(e))throw TypeError(`storage: write expects an ArrayBuffer, a typed array, a Blob or a string`);let{buffer:r,byteOffset:i,byteLength:a}=e,o=typeof SharedArrayBuffer<`u`&&r instanceof SharedArrayBuffer;if(!t)return{args:{buffer:r,byteOffset:i,byteLength:a},list:[]};if(o){let e=new Uint8Array(a);return e.set(new Uint8Array(r,i,a)),{args:{buffer:e.buffer},list:[e.buffer]}}if(n&&i===0&&a===r.byteLength)return{args:{buffer:r},list:[r]};let s=r.slice(i,i+a);return{args:{buffer:s},list:[s]}}async function DE(e,t){try{let n=await(await e.getFileHandle(t)).getFile();return JSON.parse(await n.text())}catch{return null}}async function*OE(e){for await(let[t,n]of e.entries())n.kind===`directory`&&(yield[t,n])}var kE=class{constructor(e,t,n,r,i){this.area=e,this.id=t,this.key=n.key,this.meta=n,this._dir=r,this._release=i}get bytes(){return this.meta.bytes}get extra(){return this.meta.extra??{}}async file(e){try{return await(await this._dir.getFileHandle(e)).getFile()}catch(t){return this.area.manager._issue(Y.STORAGE_READ_FAILED,`could not read ${this.area.name}/${this.id}/${e}`,{error:t.message}),null}}async json(e){let t=await this.file(e);return t?JSON.parse(await t.text()):null}release(){this._release?.(),this._release=null}},AE=class{constructor(e,t,n,r,i,{sizes:a={},append:o=!1}={}){this.area=e,this.id=t,this.key=n,this._info=r,this._release=i,this._writers=new Map,this._sizes={...a},this._append=o,this._done=!1,this._committedBytes=o?Object.values(a).reduce((e,t)=>e+t,0):0}get _transport(){return this.area.manager._transport}get _path(){return[this.area.name,this.id]}async _writer(e){let t=this._writers.get(e);if(!t){let n=this._append&&e in this._sizes,r=n&&(this._info.growable??[]).includes(e)?this._sizes[e]:void 0;t=this._transport.call(`openWriter`,{path:this._path,name:e,truncate:!n,length:r}),this._writers.set(e,t)}return(await t).id}async write(e,t,{at:n,transfer:r=!1}={}){this._assertOpen();let{args:i,list:a}=(typeof Blob<`u`&&t instanceof Blob?null:EE(t,{copy:!0,transfer:r}))??EE(await t.arrayBuffer(),{copy:!0,transfer:!0}),o=await this._writer(e);return this._transport.call(`write`,{id:o,at:n,...i},a)}async writeFile(e,t){this._assertOpen(),typeof Blob<`u`&&t instanceof Blob&&(t=await t.arrayBuffer());let{args:n,list:r}=EE(t,{copy:!0,transfer:!0}),{size:i}=await this._transport.call(`writeFile`,{path:this._path,name:e,...n},r);return this._sizes[e]=i,i}writeJSON(e,t){return this.writeFile(e,JSON.stringify(t))}async writeStream(e,t,{onProgress:n=null,signal:r=null,batchBytes:i=SE}={}){let a=t.getReader(),o=[],s=new Uint8Array(i),c=0,l=0,u=async()=>{if(c===0)return;let t=c===i?s:s.slice(0,c);s=new Uint8Array(i),c=0,o.push(this.write(e,t,{transfer:!0})),o.length>=CE&&await o.shift()};try{for(;;){if(r?.aborted)throw r.reason??new DOMException(`aborted`,`AbortError`);let{done:e,value:t}=await a.read();if(e)break;let o=0;for(;o<t.length;){let e=Math.min(t.length-o,i-c);s.set(t.subarray(o,o+e),c),c+=e,o+=e,l+=e,c===i&&await u()}n?.(l)}return await u(),await Promise.all(o),l}catch(e){throw a.cancel().catch(()=>{}),await Promise.allSettled(o),e}}async commit(e={}){this._assertOpen(),this._done=!0;try{for(let[e,t]of this._writers){let{size:n}=await this._transport.call(`closeWriter`,{id:(await t).id});this._sizes[e]=n}this._writers.clear();let t=Date.now(),n={v:_E,key:this.key,label:this._info.label??``,kind:this.area.kind,files:{...this._sizes},bytes:Object.values(this._sizes).reduce((e,t)=>e+t,0),createdAt:this._info.createdAt??t,lastUsed:t,pinned:this._info.pinned===!0,extra:{...this._info.extra,...e}},r=this._info.growable??[];r.length&&(n.growable=r);let{args:i,list:a}=EE(JSON.stringify(n),{copy:!1});return await this._transport.call(`writeFile`,{path:this._path,name:gE,...i},a),this.area.kind===en.CACHE&&this.area.manager._countCacheBytes(n.bytes-this._committedBytes),this.area.manager._changed(this.area.name),n}catch(e){throw await this._discard(),this.area.manager._writeFailed(this.area.name,e),e}finally{this._release?.(),this._release=null}}async abort(){if(!this._done){this._done=!0;try{this._append?await this._closeAll(!0):await this._discard()}finally{this._release?.(),this._release=null}}}async _closeAll(e){for(let t of this._writers.values())try{await this._transport.call(`closeWriter`,{id:(await t).id,abort:e})}catch{}this._writers.clear()}async _discard(){await this._closeAll(!0),await this.area._removeDir(this.id)}_assertOpen(){if(this._done)throw Error(`storage: entry ${this.area.name}/${this.id} is already committed or aborted`)}},jE=class{constructor(e,t,n){this.manager=e,this.name=t,this.kind=n}_lockName(e){return`${this.manager.namespace}:store:${this.name}:${e}`}async _dir(e=!1){try{return await this.manager._root.getDirectoryHandle(this.name,{create:e})}catch(e){if(e.name===`NotFoundError`)return null;throw e}}async _entryDir(e,t=!1){let n=await this._dir(t);if(!n)return null;try{return await n.getDirectoryHandle(e,{create:t})}catch(e){if(e.name===`NotFoundError`)return null;throw e}}async _removeDir(e){let t=await this._dir(!1);if(t)try{await t.removeEntry(e,{recursive:!0})}catch(e){if(e.name!==`NotFoundError`)throw e}}async _validMeta(e,t=null){let n=await DE(e,gE);if(!n||n.v!==_E||typeof n.key!=`string`||t!==null&&n.key!==t)return null;let r=n.growable??[];for(let[t,i]of Object.entries(n.files??{}))try{let n=await(await e.getFileHandle(t)).getFile();if(n.size!==i&&!(r.includes(t)&&n.size>i))return null}catch{return null}return n}async open(e,{wait:t=!1}={}){let n=await Rg(e),r=await dE(this._lockName(n),{mode:`shared`,ifAvailable:!t});if(!r)return null;try{let t=await this._entryDir(n),i=t?await this._validMeta(t,e):null;return i?(Date.now()-i.lastUsed>vE&&this._touch(n,i),new kE(this,n,i,t,r)):(r(),null)}catch(e){return r(),this.manager._issue(Y.STORAGE_READ_FAILED,`could not open ${this.name} entry`,{error:e.message}),null}}async has(e){let t=await this.open(e);return t?.release(),!!t}_touch(e,t){let n={...t,lastUsed:Date.now()},{args:r,list:i}=EE(JSON.stringify(n),{copy:!1});this.manager._transport.call(`writeFile`,{path:[this.name,e],name:gE,...r},i).catch(()=>{}),t.lastUsed=n.lastUsed}async create(e,{label:t=``,pinned:n=!1,expectedBytes:r=0,extra:i={},growable:a=[]}={}){let o=await Rg(e),s=await dE(this._lockName(o),{mode:`exclusive`});try{return r>0&&!await this.manager.ensureSpace(r,this.kind)?(s(),this.manager._issue(Y.STORAGE_QUOTA_EXCEEDED,`no room for ${(r/1048576).toFixed(0)} MB in ${this.name}`,{area:this.name,expectedBytes:r}),null):(await this._removeDir(o),await this._entryDir(o,!0),new AE(this,o,e,{label:t,pinned:n,extra:i,growable:a},s))}catch(e){return s(),this.manager._writeFailed(this.name,e),null}}async patchMeta(e,t){let n=await Rg(e),r=await dE(this._lockName(n),{mode:`shared`,ifAvailable:!0});if(!r)return!1;try{let r=await this._entryDir(n),i=r?await this._validMeta(r,e):null;if(!i)return!1;let{args:a,list:o}=EE(JSON.stringify({...i,...t,v:_E,key:e}),{copy:!1});return await this.manager._transport.call(`writeFile`,{path:[this.name,n],name:gE,...a},o),!0}finally{r()}}async edit(e){let t=await Rg(e),n=await dE(this._lockName(t),{mode:`exclusive`});try{let r=await this._entryDir(t),i=r?await this._validMeta(r,e):null;if(!i)return n(),null;let a={label:i.label,pinned:i.pinned,extra:i.extra,createdAt:i.createdAt,growable:i.growable};return new AE(this,t,e,a,n,{sizes:i.files,append:!0})}catch(e){return n(),this.manager._writeFailed(this.name,e),null}}async remove(e){return this.removeById(await Rg(e))}async removeById(e){let t=await dE(this._lockName(e),{mode:`exclusive`,ifAvailable:!0});if(!t)return!1;try{return await this._removeDir(e),this.manager._changed(this.name),!0}finally{t()}}async list(){let e=await this._dir(!1);if(!e)return[];let t=[];for await(let[n,r]of OE(e)){let e=await DE(r,gE);e?.v===_E&&t.push({...e,id:n})}return t}async clear(){let e=0;for(let{id:t}of await this.list())await this.removeById(t)&&e++;return e}async sweep(){let e=await this._dir(!1);if(!e)return 0;let t=await fE(),n=0;for await(let[r,i]of OE(e))t.has(this._lockName(r))||await this._validMeta(i)||await this.removeById(r)&&n++;return n}},ME=class extends pE{constructor({root:e,transport:t,namespace:n}){super(),this.namespace=n,this._root=e,this._transport=t,this._areas=new Map,this._budget=null,this._cacheTotal=null;for(let e of Object.values(tn))this.defineArea(e,{kind:e===tn.SPILL?en.SCRATCH:en.CACHE})}defineArea(e,{kind:t=en.CACHE}={}){let n=this._areas.get(e);if(n){if(n.kind!==t)throw Error(`storage: area "${e}" is already defined as ${n.kind}`);return n}let r=new jE(this,e,t);return this._areas.set(e,r),r}area(e){let t=this._areas.get(e);if(!t)throw Error(`storage: unknown area "${e}"`);return t}get areaNames(){return[...this._areas.keys()]}async estimate(){let e=typeof navigator<`u`?navigator.storage:null;if(!e?.estimate)return{quota:1/0,usage:0};let{quota:t=1/0,usage:n=0}=await e.estimate();return{quota:t,usage:n}}async persisted(){return await globalThis.navigator?.storage?.persisted?.()===!0}async persist(){let e=await globalThis.navigator?.storage?.persist?.()===!0;return this._changed(null),e}async budget(){if(this._budget!==null)return this._budget;let{quota:e}=await this.estimate();return Math.min(e*yE,bE)}setBudget(e){this._budget=e===null?null:Math.max(0,e),this._changed(null)}async _cacheBytes(){let e=this._cacheTotal;return(!e||Date.now()-e.at>wE)&&(e=this._cacheTotal={at:Date.now(),bytes:0,ready:null},e.ready=this._cacheEntries().then(t=>{e.bytes+=t.reduce((e,t)=>e+(t.meta.bytes??0),0)}),e.ready.catch(()=>{this._cacheTotal===e&&(this._cacheTotal=null)})),await e.ready,e.bytes}_countCacheBytes(e){this._cacheTotal&&(this._cacheTotal.bytes+=e)}async _cacheEntries(){let e=[];for(let t of this._areas.values())if(t.kind===en.CACHE)for(let n of await t.list())e.push({area:t,meta:n});return e}async usage(){let{quota:e,usage:t}=await this.estimate(),n={},r=0;for(let e of this._areas.values()){let t=await e.list(),i=t.reduce((e,t)=>e+(t.bytes??0),0);n[e.name]={kind:e.kind,bytes:i,entries:t.length},e.kind===en.CACHE&&(r+=i)}return{quota:e,usage:t,persisted:await this.persisted(),budget:await this.budget(),cacheBytes:r,areas:n}}async collect({freeBytes:e=null}={}){let t=await this._cacheEntries(),n=await this.budget(),r=this._cacheTotal={at:Date.now(),bytes:t.reduce((e,t)=>e+(t.meta.bytes??0),0),ready:null},i=e??Math.max(0,r.bytes-n);if(i<=0)return 0;let a=await fE(),o=t.filter(({area:e,meta:t})=>!t.pinned&&!a.has(e._lockName(t.id))).sort((e,t)=>e.meta.lastUsed-t.meta.lastUsed),s=0;for(let{area:e,meta:t}of o){if(s>=i)break;await e.removeById(t.id)&&(s+=t.bytes??0,r.bytes-=t.bytes??0)}return s}async ensureSpace(e,t=en.CACHE){let n=async()=>{let{quota:n,usage:r}=await this.estimate(),i=e+xE-(n-r);return t===en.CACHE?{free:i,budget:await this._cacheBytes()+e-await this.budget()}:{free:i,budget:0}},r=await n();return r.free<=0&&r.budget<=0?!0:(await this.collect({freeBytes:Math.max(r.free,r.budget)}),(await n()).free<=0)}async sweep(){let e=0;for(let t of this._areas.values())e+=await t.sweep(),t.kind===en.SCRATCH&&(e+=await t.clear());return e}_changed(e){this.dispatchEvent({type:`change`,area:e})}_issue(e,t,n={}){this.dispatchEvent({type:`issue`,code:e,message:t,detail:n})}_writeFailed(e,t){let n=t?.name===`QuotaExceededError`;this._issue(n?Y.STORAGE_QUOTA_EXCEEDED:Y.STORAGE_WRITE_FAILED,`${e}: ${t?.message??t}`,{area:e,error:t?.name})}dispose(){this._transport?.dispose(),this._transport=null,this._areas.clear()}};function NE({namespace:e,root:t}){let n=new hE(t);n.inline=!0;let r=new ME({root:t,transport:n,namespace:e});return r.sweep().catch(()=>{}),r}var PE="var e=class{constructor(e){this._root=e,this._writers=new Map,this._nextId=1}async _dir(e,t){let n=await this._root;for(let r of e)n=await n.getDirectoryHandle(r,{create:t});return n}async openWriter({path:e,name:t,truncate:n=!0,length:r}){let i=await(await(await this._dir(e,!0)).getFileHandle(t,{create:!0})).createSyncAccessHandle();n?i.truncate(0):r!==void 0&&i.getSize()>r&&i.truncate(r);let a=this._nextId++;return this._writers.set(a,{handle:i,end:i.getSize()}),{id:a}}write({id:e,buffer:t,byteOffset:n=0,byteLength:r,at:i}){let a=this._writers.get(e);if(!a)throw Error(`storage: writer ${e} is not open`);let o=new Uint8Array(t,n,r??t.byteLength-n),s=i??a.end,c=0;for(;c<o.length;){let e=a.handle.write(o.subarray(c),{at:s+c});if(e<=0)throw Error(`storage: write made no progress`);c+=e}return a.end=Math.max(a.end,s+o.length),{bytes:o.length}}closeWriter({id:e,abort:t=!1}){let n=this._writers.get(e);if(!n)return{size:0};this._writers.delete(e);try{return t||n.handle.flush(),{size:n.handle.getSize()}}finally{n.handle.close()}}async writeFile({path:e,name:t,buffer:n,byteOffset:r=0,byteLength:i}){let{id:a}=await this.openWriter({path:e,name:t});try{return this.write({id:a,buffer:n,byteOffset:r,byteLength:i}),this.closeWriter({id:a})}catch(e){throw this.closeWriter({id:a,abort:!0}),e}}async readRange({path:e,name:t,offset:n=0,length:r}){let i=await(await this._dir(e,!1)).getFileHandle(t),a=null;try{a=await i.createSyncAccessHandle()}catch(e){if(e.name!==`NoModificationAllowedError`)throw e}if(!a){let e=await i.getFile(),t=r===void 0?e.size:n+r;return{buffer:await e.slice(n,t).arrayBuffer()}}try{let e=a.getSize(),t=Math.max(0,Math.min(r??e-n,e-n)),i=new ArrayBuffer(t);return a.read(i,{at:n}),{buffer:i}}finally{a.close()}}dispose(){for(let e of[...this._writers.keys()])this.closeWriter({id:e,abort:!0})}};let t=null;async function n(e,t){return t||(await navigator.storage.getDirectory()).getDirectoryHandle(e,{create:!0})}self.onmessage=async({data:r})=>{let{id:i,op:a,args:o}=r;try{if(a===`init`){t=new e(n(o.namespace,o.root)),postMessage({id:i,result:{}});return}let r=await t[a](o),s=r?.buffer instanceof ArrayBuffer?[r.buffer]:[];postMessage({id:i,result:r},s)}catch(e){postMessage({id:i,error:{name:e.name,message:e.message}})}};",FE=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,PE],{type:`text/javascript;charset=utf-8`});function IE(e){let t;try{if(t=FE&&(self.URL||self.webkitURL).createObjectURL(FE),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(PE),{type:`module`,name:e?.name})}}function LE({name:e,message:t}){let n=Error(t);return n.name=e,n}var RE=class{constructor({namespace:e,root:t=null}){this._worker=new IE,this._pending=new Map,this._nextId=0,this._worker.onmessage=({data:e})=>{let t=this._pending.get(e.id);t&&(this._pending.delete(e.id),e.error?t.reject(LE(e.error)):t.resolve(e.result))},this._ready=this.call(`init`,{namespace:e,root:t})}call(e,t,n=[]){return this._worker?new Promise((r,i)=>{let a=this._nextId++;this._pending.set(a,{resolve:r,reject:i}),this._worker.postMessage({id:a,op:e,args:t},n)}):Promise.reject(Error(`storage: transport disposed`))}dispose(){this._worker?.terminate(),this._worker=null;for(let{reject:e}of this._pending.values())e(Error(`storage: transport disposed`));this._pending.clear()}};function zE(){return typeof WorkerGlobalScope<`u`&&globalThis instanceof WorkerGlobalScope}Nr();async function BE(e){let t=typeof navigator<`u`?navigator.storage:null;if(!t?.getDirectory)return{root:null,reason:`this browser has no origin private file system`};try{return{root:await(await t.getDirectory()).getDirectoryHandle(e,{create:!0})}}catch(e){return{root:null,reason:`${e.name}: ${e.message}`}}}async function VE({namespace:e,root:t=null,transport:n=`auto`}={}){let r=t?{root:t}:await BE(e);if(!r.root)return{storage:null,reason:r.reason};if(n===`inline`||n===`auto`&&(zE()||typeof Worker>`u`))return{storage:NE({namespace:e,root:r.root})};let i=new RE({namespace:e,root:t}),a=new ME({root:r.root,transport:i,namespace:e});return a.sweep().catch(()=>{}),{storage:a}}async function HE(e){let t=Mr.get(e);t||(t={refs:0,opened:VE({namespace:e})},Mr.set(e,t)),t.refs++;let{storage:n,reason:r}=await t.opened;t.storage=n;let i=!1,a=()=>{i||(i=!0,t.refs--,!(t.refs>0)&&(Mr.get(e)===t&&Mr.delete(e),n?.dispose()))};return n?{storage:n,release:a}:(a(),{storage:null,reason:r,release:()=>{}})}function UE(e){return e.length>=2&&e[0]===31&&e[1]===139}function WE(e){return e.length>=4&&e[0]===80&&e[1]===75&&(e[2]===3||e[2]===5||e[2]===7)}function GE(e){return e.length>=263&&String.fromCharCode(...e.subarray(257,262))===`ustar`}function KE(e){return UE(e)?`gzip`:WE(e)?`zip`:GE(e)?`tar`:null}function qE(e,t,n){let r=t,i=t+n;for(;r<i&&e[r]!==0;)r++;return dD.decode(e.subarray(t,r))}function JE(e,t,n){if(e[t]&128){let r=e[t]&127;for(let i=t+1;i<t+n;i++)r=r*256+e[i];return r}let r=qE(e,t,n).trim();if(!r)return 0;let i=parseInt(r,8);return Number.isFinite(i)?i:0}function YE(e){let t=[];for(let n of e.replace(/\\/g,`/`).split(`/`))n===``||n===`.`||(n===`..`?t.pop():t.push(n));return t.join(`/`)}function XE(e){let t=dD.decode(e).match(/^\d+ path=(.*)$/m);return t?t[1]:null}function ZE(e){let t=qE(e,345,155),n=qE(e,0,100);return{type:String.fromCharCode(e[156]||48),size:JE(e,124,12),name:t?`${t}/${n}`:n}}function QE(e,t){return e===`5`||e===`g`||e===`K`||t.endsWith(`/`)||e!==`0`&&e!==` `?null:YE(t)||null}function $E(e){for(let t=0;t<cD;t++)if(e[t]!==0)return!1;return!0}async function eD(e,t){if(typeof DecompressionStream<`u`&&typeof e?.stream==`function`){let n=e.stream().pipeThrough(new DecompressionStream(`gzip`)).getReader();for(;;){let{done:e,value:r}=await n.read();if(e)break;t(r)}return}let n=null,r=new m.Gunzip((e,r)=>{e instanceof Error?n=e:e&&e.length&&t(e)});await tD(e,(e,t)=>{if(r.push(e,t),n)throw n})}async function tD(e,t){if(e instanceof Uint8Array){for(let n=0;n<e.length;n+=lD){let r=Math.min(n+lD,e.length);t(e.subarray(n,r),r===e.length)}e.length===0&&t(e,!0);return}let n=e.size;for(let r=0;r<n;r+=lD){let i=Math.min(r+lD,n);t(new Uint8Array(await e.slice(r,i).arrayBuffer()),i===n)}n===0&&t(new Uint8Array,!0)}async function nD(e,t={}){let{onProgress:n,...r}=t,i=new mD(r),a=0,o=0;return await eD(e,e=>{i.push(e),a+=e.length,n&&a>=o&&(o=a+(64<<20),n({entries:i.listing.length,bytes:a}))}),i.end(),i.result()}async function rD(e,{onProgress:t=null}={}){let n=e.size,r=[],i=null,a=0,o=null,s=0,c=0,l=async(t,r)=>{if(i&&t>=a&&t+r<=a+i.length)return i.subarray(t-a,t-a+r);let o=Math.min(n,t+Math.max(r,hD));return i=new Uint8Array(await e.slice(t,o).arrayBuffer()),a=t,i.subarray(0,r)};for(;s+cD<=n;){let e=await l(s,cD);if($E(e))break;let{type:n,size:i,name:a}=ZE(e),u=o??a;o=null;let d=s+cD;if(pD(n)){let e=await l(d,i);o=n===`L`?qE(e,0,e.length):XE(e)}else{let e=QE(n,u);e&&r.push({path:e,size:i,offset:d})}s=d+fD(i),t&&s>=c&&(c=s+(256<<20),t({entries:r.length,bytes:s}))}return r}function iD({filter:e=null,sink:t=null}={}){let n=new mD({retain:()=>!1,filter:e,sink:t});return{push:e=>n.push(e),finish:()=>(n.end(),n.listing.filter(e=>e.offset!==void 0))}}async function aD(e,t={}){let{index:n=null,headersOnly:r=!1,onProgress:i=null,...a}=t,o,s,c,l,u=null;if(n||r){u=n?.listing??await rD(e,{onProgress:i});let{filter:t}=a;s=u.map(e=>!t||t(e.path,e.size)?{...e}:{path:e.path,size:e.size}),o=Object.create(null),c=0,l=!1}else{let t=new mD({...a});await tD(e,e=>t.push(e)),t.end(),{entries:o,listing:s,retainedBytes:c,truncated:l}=t.result()}let d=new Map;for(let e of s)e.offset!==void 0&&d.set(e.path,e);return{entries:o,listing:s,read:async t=>{if(o[t])return o[t];let n=d.get(t);return n?new Uint8Array(await e.slice(n.offset,n.offset+n.size).arrayBuffer()):null},readHead:async(t,n)=>{if(o[t])return o[t].subarray(0,n);let r=d.get(t);return r?new Uint8Array(await e.slice(r.offset,r.offset+Math.min(r.size,n)).arrayBuffer()):null},retainedBytes:c,truncated:l,indexed:d.size,index:u?{v:1,listing:u}:null}}function oD(e){let t=(Array.isArray(e)?e:[e]).filter(Boolean).map(e=>{let t=YE(e);return{p:t,inside:t+`/`}});return t.length===0?()=>!0:e=>{let n=e.lastIndexOf(`/`),r=n<0?``:e.slice(0,n);if(r===``)return!0;let i=r.lastIndexOf(`/textures`),a=i>=0&&i===r.length-9?r.slice(0,i)+`/`:null;for(let{p:n,inside:i}of t)if(e===n||e.startsWith(i)||i.startsWith(r+`/`)||a!==null&&i.startsWith(a))return!0;return!1}}function sD(e){let t=e.filter(e=>e.path.toLowerCase().endsWith(`.pbrt`)).sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.length-t.path.length||(e.path<t.path?-1:1));if(!t.length)return{root:null,elements:[]};let n=t[0].path,r=n.lastIndexOf(`/`),i=r<0?``:n.slice(0,r),a=i?i+`/`:``,o=new Map;for(let t of e){if(!t.path.startsWith(a))continue;let e=t.path.slice(a.length),n=e.indexOf(`/`);if(n<0)continue;let r=e.slice(0,n),i=o.get(r);i||o.set(r,i={name:r,prefix:a+r,files:0,bytes:0,scenes:0}),i.files++,i.bytes+=t.size,t.path.toLowerCase().endsWith(`.pbrt`)&&i.scenes++}return{root:i,elements:[...o.values()].filter(e=>e.scenes>0).sort((e,t)=>e.bytes-t.bytes)}}var cD,lD,uD,dD,fD,pD,mD,hD,gD=g((()=>{cD=512,lD=4<<20,uD=15e8,dD=new TextDecoder,fD=e=>e+(cD-e%cD)%cD,pD=e=>e===`L`||e===`x`||e===`X`,mD=class{constructor({filter:e=null,retain:t=null,byteBudget:n=uD,onEntry:r=null,sink:i=null}={}){this.filter=e,this.sink=i,this._sunk=0,this.retain=t,this.byteBudget=n,this.onEntry=r,this.entries=Object.create(null),this.listing=[],this.retainedBytes=0,this.truncated=!1,this.finished=!1,this._header=new Uint8Array(cD),this._headerLen=0,this._state=`header`,this._remaining=0,this._size=0,this._copied=0,this._dst=null,this._special=null,this._pendingName=null,this._abs=0}push(e){let t=this._abs;this._abs+=e.length;let n=0;for(;n<e.length&&!this.finished;)if(this._state===`header`){let r=Math.min(cD-this._headerLen,e.length-n);this._header.set(e.subarray(n,n+r),this._headerLen),this._headerLen+=r,n+=r,this._headerLen===cD&&(this._headerLen=0,this._bodyStart=t+n,this._readHeader())}else{let t=Math.min(this._remaining,e.length-n);if(this.sink&&this._indexed&&this._sinkLeft>0){let r=Math.min(t,this._sinkLeft);this.sink(e.subarray(n,n+r)),this._sinkLeft-=r}if(this._dst&&this._copied<this._size){let r=Math.min(t,this._size-this._copied);this._dst.set(e.subarray(n,n+r),this._copied),this._copied+=r}this._remaining-=t,n+=t,this._remaining===0&&this._endBody()}}end(){this.finished=!0}result(){return{entries:this.entries,listing:this.listing,retainedBytes:this.retainedBytes,truncated:this.truncated}}_readHeader(){let e=this._header,t=!0;for(let n=0;n<cD;n++)if(e[n]!==0){t=!1;break}if(t){this.finished=!0;return}let{type:n,size:r,name:i}=ZE(e),a=this._pendingName??i;if(this._pendingName=null,this._size=r,this._copied=0,this._remaining=fD(r),this._dst=null,this._special=null,this._indexed=!1,this._state=this._remaining>0?`body`:`header`,pD(n)){this._special=n===`L`?`longname`:`pax`,this._dst=new Uint8Array(r);return}let o=QE(n,a);o&&(this.listing.push({path:o,size:r}),this._indexed=this.filter?this.filter(o,r):!0,this.sink&&this._indexed&&(this._sinkStart=this._sunk,this._sinkLeft=r,this._sunk+=r),this._indexed&&!(this.retain&&!this.retain(o,r))&&(this.retainedBytes+r>this.byteBudget?this.truncated=!0:(this._dst=new Uint8Array(r),this.retainedBytes+=r)),this._remaining===0&&this._endBody())}_endBody(){if(this._state=`header`,this._special===`longname`){this._pendingName=qE(this._dst,0,this._dst.length),this._dst=null;return}if(this._special===`pax`){let e=XE(this._dst);e&&(this._pendingName=e),this._dst=null;return}let e=this.listing[this.listing.length-1];this._indexed&&e&&(e.offset=this.sink?this._sinkStart:this._bodyStart,this._indexed=!1),this._dst&&=(this.entries[e.path]=this._dst,this.onEntry?.(e.path,this._dst),null)}},hD=1<<20}));async function _D(e,t,n){return new Uint8Array(await e.slice(t,n).arrayBuffer())}function vD(e,t){return e.getUint32(t+4,!0)*4294967296+e.getUint32(t,!0)}function yD(e){let t=``;for(let n=0;n<e.length;n+=8192)t+=String.fromCharCode(...e.subarray(n,n+8192));return t}async function bD(e){let t=e.size,n=await _D(e,Math.max(0,t-kD-20),t),r=new DataView(n.buffer),i=-1;for(let e=n.length-22;e>=0;e--)if(r.getUint32(e,!0)===wD){i=e;break}if(i<0)throw Error(`zip: end of central directory not found`);let a=r.getUint16(i+10,!0),o=r.getUint32(i+12,!0),s=r.getUint32(i+16,!0);if(a===65535||o===4294967295||s===4294967295){let t=i-20;if(t<0||r.getUint32(t,!0)!==TD)throw Error(`zip: ZIP64 locator missing`);let n=vD(r,t+8),c=new DataView((await _D(e,n,n+56)).buffer);if(c.getUint32(0,!0)!==ED)throw Error(`zip: ZIP64 end record missing`);a=vD(c,32),o=vD(c,40),s=vD(c,48)}let c=await _D(e,s,s+o),l=new DataView(c.buffer),u=[],d=0;for(let e=0;e<a&&d+46<=c.length;e++){if(l.getUint32(d,!0)!==DD)throw Error(`zip: corrupt central directory`);let e=l.getUint16(d+8,!0),t=l.getUint16(d+10,!0),n=l.getUint32(d+20,!0),r=l.getUint32(d+24,!0),i=l.getUint16(d+28,!0),a=l.getUint16(d+30,!0),o=l.getUint16(d+32,!0),s=l.getUint32(d+42,!0),f=c.subarray(d+46,d+46+i),p=e&2048?AD.decode(f):yD(f);for(let e=d+46+i,t=e+a;e+4<=t;){let t=l.getUint16(e,!0),i=l.getUint16(e+2,!0);if(t===1){let t=e+4;r===4294967295&&(r=vD(l,t),t+=8),n===4294967295&&(n=vD(l,t),t+=8),s===4294967295&&(s=vD(l,t))}e+=4+i}p.endsWith(`/`)||u.push({name:p,size:r,compSize:n,method:t,local:s,encrypted:(e&1)!=0}),d+=46+i+a+o}return u}async function xD(e,t){if(t.encrypted)throw Error(`zip: "${t.name}" is encrypted`);let n=new DataView((await _D(e,t.local,t.local+30)).buffer);if(n.getUint32(0,!0)!==OD)throw Error(`zip: bad local header for "${t.name}"`);return t.local+30+n.getUint16(26,!0)+n.getUint16(28,!0)}async function SD(e,t){let n=await xD(e,t),r=await _D(e,n,n+t.compSize);if(t.method===0)return r;if(t.method===8)return t.size===0?new Uint8Array:(0,m.inflateSync)(r,{out:new Uint8Array(t.size)});throw Error(`zip: "${t.name}" uses compression method ${t.method}, which is not supported`)}async function CD(e,{filter:t=null}={}){let n=await bD(e),r=new Map,i=n.map(e=>t&&!t(e.name,e.size)?{path:e.name,size:e.size}:(r.set(e.name,e),{path:e.name,size:e.size,offset:e.local})),a=async t=>{let n=r.get(t);return n?SD(e,n):null},o=async t=>{let n=r.get(t);if(!n)return null;if(n.method!==0)return new Blob([await SD(e,n)]);let i=await xD(e,n);return e.slice(i,i+n.compSize)};return{entries:Object.create(null),listing:i,read:a,readHead:async(e,t)=>{let n=await o(e);return n?new Uint8Array(await n.slice(0,t).arrayBuffer()):null},slice:o,retainedBytes:0,truncated:!1,indexed:r.size}}var wD,TD,ED,DD,OD,kD,AD,jD=g((()=>{wD=101010256,TD=117853008,ED=101075792,DD=33639248,OD=67324752,kD=65557,AD=new TextDecoder}));async function MD(e,t){return`${e}:${Vg(await Bg(t))}`}async function ND(e,{storage:t,label:n=e.name,onProgress:r=null,filter:i=null,part:a=null}){if(!t||typeof DecompressionStream>`u`)return null;let o=t.area(tn.ARCHIVES),s=await MD(`gunzip`,e),c=s,l=await o.open(s);!l&&i&&(l=await o.open(c=`${s}|${a}`));let u=!!l;if(!l){let s=await o.create(c,i?{label:`${n} (${a})`}:{label:n,expectedBytes:e.size*LD});if(!s)return null;let u=null,d=iD(i?{filter:i,sink:e=>u.enqueue(e)}:{}),f=new TransformStream({start(e){u=e},transform(e,t){d.push(e),i||t.enqueue(e)}});try{let t=e.stream().pipeThrough(new DecompressionStream(`gzip`)).pipeThrough(f),n=await s.writeStream(`data.tar`,t,{onProgress:r});await s.writeJSON(`index.json`,{v:ID,listing:d.finish()}),await s.commit({compressedBytes:e.size,tarBytes:n})}catch(e){if(await s.abort(),e?.name!==`QuotaExceededError`)throw e;return t._issue(Y.STORAGE_QUOTA_EXCEEDED,`ran out of room unpacking ${n}; reading it in memory instead`,{area:tn.ARCHIVES}),null}if(l=await o.open(c,{wait:!0}),!l)return null}let d=await l.file(`data.tar`),f=await l.json(`index.json`);return!d||f?.v!==ID?(l.release(),null):{file:d,index:f,release:()=>l.release(),cached:u}}async function PD(e,t){if(!t)return null;let n=await t.area(tn.ARCHIVES).open(await MD(`tarindex`,e));if(!n)return null;try{let e=await n.json(`index.json`);return e?.v===ID?e:null}finally{n.release()}}async function FD(e,t,n){if(!t||!n)return!1;let r=await t.area(tn.ARCHIVES).create(await MD(`tarindex`,e),{label:`${e.name} (index)`});if(!r)return!1;try{return await r.writeJSON(`index.json`,n),await r.commit(),!0}catch{return await r.abort(),!1}}var ID,LD,RD=g((()=>{gD(),nn(),Jg(),X(),ID=1,LD=3}));function zD(e){return e.isInstancedMesh?`InstancedMesh`:e.isSkinnedMesh||e.isBatchedMesh?null:e.isMesh?`Mesh`:e.isPerspectiveCamera?`PerspectiveCamera`:e.isOrthographicCamera?`OrthographicCamera`:e.isDirectionalLight?`DirectionalLight`:e.isPointLight?`PointLight`:e.isSpotLight?`SpotLight`:e.isLight||e.isPoints||e.isLine||e.isSprite||e.isLOD?null:e.isGroup?`Group`:e.constructor===r.Object3D?`Object3D`:null}function BD(e,t){try{let t=JSON.parse(JSON.stringify(e??{}));return delete t[tO],delete t[nO],t}catch{throw new uO(`${t}: userData is not plain JSON`)}}function VD(e,t,n){if(e.isInterleavedBufferAttribute||!ArrayBuffer.isView(e.array))throw new uO(`${n}: interleaved or non-typed attribute`);return{section:t.add(e.array),itemSize:e.itemSize,normalized:e.normalized===!0,name:e.name??``}}function HD(e,t){let n=`geometry ${e.name||e.uuid}`;if(Object.keys(e.morphAttributes??{}).length)throw new uO(`${n}: morph targets`);let r={};for(let[i,a]of Object.entries(e.attributes))r[i]=VD(a,t,n);return{uuid:e.uuid,name:e.name,attributes:r,index:e.index?VD(e.index,t,n):null,groups:e.groups.map(e=>({...e})),drawRange:{...e.drawRange},userData:BD(e.userData,n)}}function UD(e,t){let n={uuid:e.uuid,userData:BD(e.userData,`texture ${e.uuid}`)};for(let t of sO)n[t]=e[t];for(let t of[`repeat`,`offset`,`center`])n[t]=e[t].toArray();n.rotation=e.rotation;let r=e.userData?.[tO];if(r)n.path=r,n.loader=e.userData.__rayzeeArchiveLoader??`image`;else if(e.isDataTexture&&ArrayBuffer.isView(e.image?.data))n.data={section:t.add(e.image.data),width:e.image.width,height:e.image.height};else throw new uO(`texture ${e.name||e.uuid}: no archive path and no pixel data to keep`);return n}function WD(e,t){let n=e.toJSON(t);n.exactColors={};for(let[t,r]of Object.entries(e))r?.isColor&&(n.exactColors[t]=[r.r,r.g,r.b]);e.ior!==void 0&&(n.exactIor=e.ior),e.diffuseTransmission!==void 0&&(n.diffuseTransmission=e.diffuseTransmission);for(let t of eO)e[t]?.isTexture&&((n.engineTextures??={})[t]=e[t].uuid);return n}function GD(e,t){for(let n of Object.values(e))n?.isTexture&&t.set(n.uuid,n)}function KD(e,{environment:t=null,animations:n=[],stats:i={}}={}){let a=new dO,o=[],s=new Map,c=new Map,l=new Map,u=(e,t)=>{let n=zD(e);if(!n)throw new uO(`${e.type} "${e.name}" cannot be cached`);let r={type:n,uuid:e.uuid,parent:t,userData:BD(e.userData,`${n} "${e.name}"`)};for(let t of lO)r[t]=e[t];if(r.position=e.position.toArray(),r.quaternion=e.quaternion.toArray(),r.scale=e.scale.toArray(),r.layers=e.layers.mask,e.matrixAutoUpdate||(r.matrix=e.matrix.toArray()),e.isMesh){s.set(e.geometry.uuid,e.geometry);let t=Array.isArray(e.material)?e.material:[e.material];for(let e of t)c.set(e.uuid,e),GD(e,l);r.geometry=e.geometry.uuid,r.material=Array.isArray(e.material)?t.map(e=>e.uuid):e.material.uuid}if(e.isInstancedMesh&&(r.count=e.count,r.instanceMatrix=a.add(e.instanceMatrix.array),r.instanceColor=e.instanceColor?a.add(e.instanceColor.array):null),e.isCamera)for(let t of[`fov`,`aspect`,`near`,`far`,`zoom`,`focus`,`filmGauge`,`filmOffset`,`left`,`right`,`top`,`bottom`])e[t]!==void 0&&(r[t]=e[t]);if(e.isLight){r.color=e.color.toArray();for(let t of cO)e[t]!==void 0&&(r[t]=e[t]);e.target&&(r.target=e.target.uuid)}let i=o.push(r)-1;for(let t of e.children)u(t,i)};u(e,-1),t&&l.set(t.uuid,t);let d={textures:{},images:{}};for(let e of l.keys())d.textures[e]={uuid:e};return{manifest:{v:2,nodes:o,geometries:[...s.values()].map(e=>HD(e,a)),textures:[...l.values()].map(e=>UD(e,a)),materials:[...c.values()].map(e=>WD(e,d)),animations:n.map(e=>r.AnimationClip.toJSON(e)),environment:t?t.uuid:null,stats:i},sections:a.sections,byteLength:a.length}}async function qD(e,{manifest:t,sections:n},{release:r=!1}={}){for(let t of n){let{offset:n,array:i}=t,a=new Uint8Array(i.buffer,i.byteOffset,i.byteLength);for(let t=0;t<a.length;t+=iO)await e.write(`data.bin`,a.subarray(t,Math.min(a.length,t+iO)),{at:n+t});r&&(t.array=null)}n.length===0&&await e.write(`data.bin`,new Uint8Array),await e.writeJSON(`graph.json`,t)}function JD(e){let t=oO[e];if(!t)throw Error(`scene graph: unknown array type ${e}`);return t}async function YD(e,t){let n=new Map,r=[...t].sort((e,t)=>e.offset-t.offset),i=null,a=0;for(let t of r){let{offset:r,byteLength:o,type:s}=t,c=JD(s),l=r+o;if(o>aO){n.set(r,new c(await e.slice(r,l).arrayBuffer()));continue}(!i||r<a||l>a+i.byteLength)&&(a=r,i=await e.slice(r,Math.min(e.size,r+aO)).arrayBuffer()),n.set(r,new c(i.slice(r-a,l-a)))}return n}function XD(e){let t=[];for(let n of e.nodes)n.instanceMatrix&&t.push(n.instanceMatrix),n.instanceColor&&t.push(n.instanceColor);for(let n of e.geometries){for(let e of Object.values(n.attributes))t.push(e.section);n.index&&t.push(n.index.section)}for(let n of e.textures)n.data&&t.push(n.data.section);return t}function ZD(e,t){let n=new r.BufferAttribute(e.get(t.section.offset),t.itemSize,t.normalized);return n.name=t.name,n}function QD(e,t){for(let n of sO)t[n]!==void 0&&(e[n]=t[n]);e.repeat.fromArray(t.repeat),e.offset.fromArray(t.offset),e.center.fromArray(t.center),e.rotation=t.rotation,e.uuid=t.uuid,Object.assign(e.userData,t.userData),e.needsUpdate=!0}async function $D(e,t,{loadTexture:n}){if(e?.v!==2)throw Error(`scene graph: unknown format`);let i=await YD(t,XD(e)),a=e=>i.get(e.offset),o={};for(let t of e.textures){let e;if(t.path){if(e=await n(t.path,t.loader),!e)throw Error(`scene graph: "${t.path}" is missing from the archive`);e.userData[tO]=t.path,e.userData[nO]=t.loader}else e=new r.DataTexture(a(t.data.section),t.data.width,t.data.height);QD(e,t),o[t.uuid]=e}let s=new r.MaterialLoader().setTextures(o),c={};for(let t of e.materials){let e=s.parse(t);for(let[n,i]of Object.entries(t.exactColors??{}))n===`diffuseTransmissionColor`&&(e[n]=new r.Color),e[n]?.setRGB(i[0],i[1],i[2]);t.exactIor!==void 0&&(e.ior=t.exactIor),t.diffuseTransmission!==void 0&&(e.diffuseTransmission=t.diffuseTransmission);for(let[n,r]of Object.entries(t.engineTextures??{}))o[r]&&(e[n]=o[r]);c[t.uuid]=e}let l={};for(let t of e.geometries){let e=new r.BufferGeometry;e.uuid=t.uuid,e.name=t.name;for(let[n,r]of Object.entries(t.attributes))e.setAttribute(n,ZD(i,r));t.index&&e.setIndex(ZD(i,t.index));for(let n of t.groups)e.addGroup(n.start,n.count,n.materialIndex);e.setDrawRange(t.drawRange.start,t.drawRange.count),e.userData=t.userData,l[t.uuid]=e}let u=[];for(let t of e.nodes){let e=Array.isArray(t.material)?t.material.map(e=>c[e]):c[t.material],n;switch(t.type){case`InstancedMesh`:n=new r.InstancedMesh(l[t.geometry],e,1),n.instanceMatrix=new r.InstancedBufferAttribute(a(t.instanceMatrix),16),n.count=t.count,t.instanceColor&&(n.instanceColor=new r.InstancedBufferAttribute(a(t.instanceColor),3));break;case`Mesh`:n=new r.Mesh(l[t.geometry],e);break;case`PerspectiveCamera`:n=new r.PerspectiveCamera;break;case`OrthographicCamera`:n=new r.OrthographicCamera;break;case`Group`:n=new r.Group;break;case`DirectionalLight`:n=new r.DirectionalLight;break;case`PointLight`:n=new r.PointLight;break;case`SpotLight`:n=new r.SpotLight;break;default:n=new r.Object3D}n.uuid=t.uuid;for(let e of lO)n[e]=t[e];if(n.position.fromArray(t.position),n.quaternion.fromArray(t.quaternion),n.scale.fromArray(t.scale),n.layers.mask=t.layers,n.userData=t.userData,t.matrix&&n.matrix.fromArray(t.matrix),n.isCamera){for(let e of[`fov`,`aspect`,`near`,`far`,`zoom`,`focus`,`filmGauge`,`filmOffset`,`left`,`right`,`top`,`bottom`])t[e]!==void 0&&(n[e]=t[e]);n.updateProjectionMatrix()}if(n.isLight){n.color.fromArray(t.color);for(let e of cO)t[e]!==void 0&&(n[e]=t[e])}u.push(n),t.parent>=0&&u[t.parent].add(n)}let d=new Map(u.map(e=>[e.uuid,e]));return e.nodes.forEach((e,t)=>{e.target&&d.has(e.target)&&(u[t].target=d.get(e.target))}),{root:u[0],environment:e.environment?o[e.environment]:null,animations:e.animations.map(e=>r.AnimationClip.parse(e)),stats:e.stats}}var eO,tO,nO,rO,iO,aO,oO,sO,cO,lO,uO,dO,fO=g((()=>{eO=[`diffuseTransmissionMap`,`diffuseTransmissionColorMap`],tO=`__rayzeeArchivePath`,nO=`__rayzeeArchiveLoader`,rO=64,iO=32<<20,aO=64<<20,oO={Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Uint8ClampedArray},sO=[`name`,`mapping`,`channel`,`wrapS`,`wrapT`,`magFilter`,`minFilter`,`anisotropy`,`format`,`type`,`flipY`,`generateMipmaps`,`premultiplyAlpha`,`unpackAlignment`,`colorSpace`],cO=[`intensity`,`distance`,`decay`,`angle`,`penumbra`],lO=[`name`,`visible`,`castShadow`,`receiveShadow`,`frustumCulled`,`renderOrder`,`matrixAutoUpdate`],uO=class extends Error{constructor(e){super(e),this.name=`SceneGraphUnsupported`}},dO=class{constructor(){this.sections=[],this.length=0}add(e){let t=Math.ceil(this.length/rO)*rO;return this.sections.push({offset:t,array:e}),this.length=t+e.byteLength,{offset:t,byteLength:e.byteLength,type:e.constructor.name,length:e.length}}}}));function pO(e){e&&hO(e)&&e.buffer.transfer(0)}function mO(e,t){let n=e.constructor;if(hO(e))return new n(e.buffer.transfer(t*n.BYTES_PER_ELEMENT));let r=new n(t);return r.set(t<e.length?e.subarray(0,t):e),r}var hO,gO=g((()=>{hO=e=>e.byteOffset===0&&e.byteLength===e.buffer.byteLength&&typeof e.buffer.transfer==`function`&&!(typeof SharedArrayBuffer<`u`&&e.buffer instanceof SharedArrayBuffer)}));function _O(e,t,n){if(n-t===0)return``;let r=!0;for(let i=t;i<n;i++)if(e[i]>127){r=!1;break}if(!r)return BO.decode(e.subarray(t,n));let i=``;for(let r=t;r<n;r++)i+=String.fromCharCode(e[r]);return i}var vO,yO,bO,xO,SO,CO,wO,TO,EO,DO,OO,kO,AO,jO,MO,NO,PO,FO,IO,LO,RO,zO,BO,VO,HO=g((()=>{vO={STRING:`string`,NUMBER:`number`,WORD:`word`,LBRACKET:`[`,RBRACKET:`]`},yO=9,bO=10,xO=12,SO=13,CO=32,wO=34,TO=35,EO=43,DO=45,OO=46,kO=48,AO=57,jO=91,MO=93,NO=69,PO=101,FO=e=>e===CO||e===yO||e===bO||e===SO||e===xO,IO=e=>e>=kO&&e<=AO,LO=15,RO=22,zO=(()=>{let e=new Float64Array(RO+1);for(let t=0;t<e.length;t++)e[t]=10**t;return e})(),BO=new TextDecoder,VO=class{constructor(e){this.bytes=typeof e==`string`?new TextEncoder().encode(e):e,this.i=0,this.n=this.bytes.length,this._ahead=null}peek(){return this._ahead===null&&(this._ahead=this._scan()),this._ahead}next(){let e=this.peek();return this._ahead=null,e}_scan(){let e=this.bytes,t=this.i,n=this.n;for(;;){for(;t<n&&FO(e[t]);)t++;if(t<n&&e[t]===TO){for(;t<n&&e[t]!==bO;)t++;continue}break}if(t>=n)return this.i=t,null;let r=e[t];if(r===jO)return this.i=t+1,{type:vO.LBRACKET};if(r===MO)return this.i=t+1,{type:vO.RBRACKET};if(r===wO){let r=++t;for(;t<n&&e[t]!==wO;)t++;if(t>=n)throw Error(`PBRT tokenizer: unterminated string literal`);return this.i=t+1,{type:vO.STRING,value:_O(e,r,t)}}if(IO(r)||r===OO&&IO(e[t+1])||(r===DO||r===EO)&&(IO(e[t+1])||e[t+1]===OO&&IO(e[t+2])))return this._scanNumber(t);let i=t;for(;t<n;){let n=e[t];if(FO(n)||n===wO||n===jO||n===MO||n===TO)break;t++}return this.i=t,{type:vO.WORD,value:_O(e,i,t)}}_scanNumber(e){let t=this.bytes,n=this.n,r=e,i=!1;t[r]===DO?(i=!0,r++):t[r]===EO&&r++;let a=0,o=0,s=0;for(;r<n&&IO(t[r]);)a=a*10+(t[r]-kO),o++,r++;if(r<n&&t[r]===OO)for(r++;r<n&&IO(t[r]);)a=a*10+(t[r]-kO),o++,s++,r++;let c=0;if(r<n&&(t[r]===PO||t[r]===NO)){let e=r+1,i=!1;if(e<n&&(t[e]===DO||t[e]===EO)&&(i=t[e]===DO,e++),e<n&&IO(t[e])){let a=0;for(;e<n&&IO(t[e]);)a=a*10+(t[e]-kO),e++;c=i?-a:a,r=e}}if(this.i=r,o===0)throw Error(`PBRT tokenizer: invalid number "${_O(t,e,r)}"`);let l=c-s;if(!(o<=LO&&l>=-RO&&l<=RO)){let n=Number(_O(t,e,r));if(Number.isNaN(n))throw Error(`PBRT tokenizer: invalid number "${_O(t,e,r)}"`);return{type:vO.NUMBER,value:n}}let u=l===0?a:l>0?a*zO[l]:a/zO[-l];return i&&(u=-u),{type:vO.NUMBER,value:u}}}}));function UO(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function WO(e){return e[0]*(e[5]*e[10]-e[6]*e[9])-e[4]*(e[1]*e[10]-e[2]*e[9])+e[8]*(e[1]*e[6]-e[2]*e[5])}function GO(e,t,n,r){for(let i=0;i<4;i++){let a=r[i*4],o=r[i*4+1],s=r[i*4+2],c=r[i*4+3];for(let r=0;r<4;r++)e[i*4+r]=t[n+r]*a+t[n+4+r]*o+t[n+8+r]*s+t[n+12+r]*c}return e}function KO(e,t){let n=e[0],r=e[1],i=e[2],a=e[3],o=e[4],s=e[5],c=e[6],l=e[7],u=e[8],d=e[9],f=e[10],p=e[11],m=e[12],h=e[13],g=e[14],_=e[15],v=t[0],y=t[1],b=t[2],x=t[3],S=t[4],C=t[5],w=t[6],T=t[7],E=t[8],D=t[9],O=t[10],k=t[11],A=t[12],j=t[13],M=t[14],N=t[15];return[n*v+o*y+u*b+m*x,r*v+s*y+d*b+h*x,i*v+c*y+f*b+g*x,a*v+l*y+p*b+_*x,n*S+o*C+u*w+m*T,r*S+s*C+d*w+h*T,i*S+c*C+f*w+g*T,a*S+l*C+p*w+_*T,n*E+o*D+u*O+m*k,r*E+s*D+d*O+h*k,i*E+c*D+f*O+g*k,a*E+l*D+p*O+_*k,n*A+o*j+u*M+m*N,r*A+s*j+d*M+h*N,i*A+c*j+f*M+g*N,a*A+l*j+p*M+_*N]}function qO(e,t,n){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,n,1]}function JO(e,t,n){return[e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1]}function YO(e,t,n,r){let i=Math.hypot(t,n,r)||1;t/=i,n/=i,r/=i;let a=e*Math.PI/180,o=Math.cos(a),s=Math.sin(a),c=1-o,l=c*t*t+o,u=c*t*n-s*r,d=c*t*r+s*n,f=c*t*n+s*r,p=c*n*n+o,m=c*n*r-s*t;return[l,f,c*t*r-s*n,0,u,p,c*n*r+s*t,0,d,m,c*r*r+o,0,0,0,0,1]}function XO(e,t){return[e[0]-t[0],e[1]-t[1],e[2]-t[2]]}function ZO(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function QO(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function $O(e,t,n){let r=QO(XO(t,e)),i=QO(ZO(QO(n),r)),a=ZO(r,i);return[i[0],i[1],i[2],0,a[0],a[1],a[2],0,r[0],r[1],r[2],0,e[0],e[1],e[2],1]}function ek(e){let t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13],h=e[14],g=e[15],_=u*h*c-m*d*c+m*s*f-o*h*f-u*s*g+o*d*g,v=p*d*c-l*h*c-p*s*f+a*h*f+l*s*g-a*d*g,y=l*m*c-p*u*c+p*o*f-a*m*f-l*o*g+a*u*g,b=p*u*s-l*m*s-p*o*d+a*m*d+l*o*h-a*u*h,x=t*_+n*v+r*y+i*b;if(x===0)return UO();let S=1/x;return[_*S,(m*d*i-u*h*i-m*r*f+n*h*f+u*r*g-n*d*g)*S,(o*h*i-m*s*i+m*r*c-n*h*c-o*r*g+n*s*g)*S,(u*s*i-o*d*i-u*r*c+n*d*c+o*r*f-n*s*f)*S,v*S,(l*h*i-p*d*i+p*r*f-t*h*f-l*r*g+t*d*g)*S,(p*s*i-a*h*i-p*r*c+t*h*c+a*r*g-t*s*g)*S,(a*d*i-l*s*i+l*r*c-t*d*c-a*r*f+t*s*f)*S,y*S,(p*u*i-l*m*i-p*n*f+t*m*f+l*n*g-t*u*g)*S,(a*m*i-p*o*i+p*n*c-t*m*c-a*n*g+t*o*g)*S,(l*o*i-a*u*i-l*n*c+t*u*c+a*n*f-t*o*f)*S,b*S,(l*m*r-p*u*r+p*n*d-t*m*d-l*n*h+t*u*h)*S,(p*o*r-a*m*r-p*n*s+t*m*s+a*n*h-t*o*h)*S,(a*u*r-l*o*r+l*n*s-t*u*s-a*n*d+t*o*d)*S]}var tk=g((()=>{}));function nk(e,t){if(e===t)return!0;for(let n=0;n<16;n++)if(e[n]!==t[n])return!1;return!0}var rk,ik,ak,ok,sk,ck,lk,uk=g((()=>{gO(),HO(),tk(),rk=8,ik=1,ak=2,ok=3,sk=new Set([`Identity`,`Transform`,`CoordinateSystem`,`CoordSysTransform`,`ActiveTransform`,`TransformTimes`,`Camera`,`Film`,`WorldBegin`,`MakeNamedMaterial`,`Texture`,`MakeNamedMedium`,`LightSource`,`AreaLightSource`,`ObjectBegin`,`ObjectEnd`,`ObjectInstance`]),ck={integer:Int32Array,point3:Float32Array,point2:Float32Array,vector3:Float32Array,vector2:Float32Array,vector:Float32Array,normal:Float32Array,rgb:Float32Array},lk=class{constructor(e={}){this.releaseInclude=e.releaseInclude||null,this.resolveInclude=e.resolveInclude||(()=>{throw Error(`PBRTParser: Include used but no resolveInclude provided`)}),this.maxPlacements=e.maxPlacements??1/0,this.instanceIncludes=e.instanceIncludes!==!1,this._includes=new Map,this._stateIds=new WeakMap,this._nextStateId=1,this._effects=0,this._movedShapes=!1,this.ir={film:null,camera:null,namedMaterials:new Map,namedTextures:new Map,shapes:[],lights:[],instances:new Map,instanceCount:0,skippedInstances:0,objects:new Map,media:new Map,transformTimes:{start:0,end:1},hasMotion:!1,warnings:[]},this.ctm=UO(),this.ctmEnd=null,this.activeTransform=ok,this._ctmSource=null,this._ctmValue=null,this.state={material:null,areaLight:null,reverseOrientation:!1,interior:null},this.attributeStack=[],this.transformStack=[],this.coordSystems=new Map,this.currentObject=null,this.dirStack=[``],this.stream=null,this._warnedUnknown=new Set}async parse(e,t=``){this.dirStack=[t],await this._run(new VO(e)),this._movedShapes&&(this.ir.shapes=this.ir.shapes.filter(Boolean));for(let e of this.ir.instances.values())e.matrices=mO(e.matrices,e.count*16),e.matricesEnd&&=mO(e.matricesEnd,e.count*16);return this.ir}_addInstance(e,t=this.ctm){if(this.ir.instanceCount>=this.maxPlacements){this.ir.skippedInstances++;return}let n=this.ir.instances.get(e);n||this.ir.instances.set(e,n={name:e,count:0,matrices:new Float32Array(512),matricesEnd:null});let r=(n.count+1)*16;if(r>n.matrices.length){let e=Math.max(r,n.matrices.length*2);n.matrices=mO(n.matrices,e),n.matricesEnd&&=mO(n.matricesEnd,e)}let i=n.count*16;for(let e=0;e<16;e++)n.matrices[i+e]=t[e];let a=this._ctmEndSnapshot();if(a&&!n.matricesEnd&&(n.matricesEnd=n.matrices.slice()),n.matricesEnd){let e=a||t;for(let t=0;t<16;t++)n.matricesEnd[i+t]=e[t]}n.count++,this.ir.instanceCount++}_ctmSnapshot(){return this._ctmSource!==this.ctm&&(this._ctmSource=this.ctm,this._ctmValue=this.ctm.slice()),this._ctmValue}_ctmEndSnapshot(){return this.ctmEnd===null||nk(this.ctmEnd,this.ctm)?null:(this.ir.hasMotion=!0,this.ctmEnd.slice())}_concat(e){if(this.activeTransform===ok&&this.ctmEnd===null){this.ctm=KO(this.ctm,e);return}let t=this.ctmEnd??this.ctm;this.ctmEnd=this.activeTransform&ak?KO(t,e):t,this.activeTransform&ik&&(this.ctm=KO(this.ctm,e))}_setCTM(e){if(this.activeTransform===ok){this.ctm=e,this.ctmEnd=null;return}let t=this.ctmEnd??this.ctm;this.ctmEnd=this.activeTransform&ak?e:t,this.activeTransform&ik&&(this.ctm=e)}_pushGraphicsState(){this.attributeStack.push({ctm:this.ctm,ctmEnd:this.ctmEnd,activeTransform:this.activeTransform,material:this.state.material,areaLight:this.state.areaLight,reverseOrientation:this.state.reverseOrientation,interior:this.state.interior})}_popGraphicsState(){let e=this.attributeStack.pop();e&&(this.ctm=e.ctm,this.ctmEnd=e.ctmEnd,this.activeTransform=e.activeTransform,this.state={material:e.material,areaLight:e.areaLight,reverseOrientation:e.reverseOrientation,interior:e.interior})}_peek(){return this.stream.peek()}_next(){return this.stream.next()}_expectNumber(e){let t=this._next();if(!t||t.type!==vO.NUMBER)throw Error(`PBRT parser: expected number for ${e}, got ${t?t.value:`EOF`}`);return t.value}_expectString(e){let t=this._next();if(!t||t.type!==vO.STRING)throw Error(`PBRT parser: expected string for ${e}, got ${t?t.value:`EOF`}`);return t.value}_readNumbers(e){let t=[];for(let n=0;n<e;n++)t.push(this._expectNumber(`matrix/transform`));return t}_readBracketedOrBareNumbers(e){if(this._peek()&&this._peek().type===vO.LBRACKET){this._next();let e=[];for(;this._peek()&&this._peek().type!==vO.RBRACKET;)e.push(this._expectNumber(`transform element`));return this._next(),e}return this._readNumbers(e)}_parseParams(){let e={};for(;this._peek()&&this._peek().type===vO.STRING;){let t=this._next().value.trim().split(/\s+/),n=t[0],r=t[1]===void 0?t[0]:t[1];e[r]={type:n,value:this._parseParamValue(n)}}return e}_parseParamValue(e){let t=this._peek()&&this._peek().type===vO.LBRACKET;t&&this._next();let n=()=>{let e=this._peek();return t?e&&e.type!==vO.RBRACKET:!1};if(!t)return[this._coerceValueToken(this._next())];if(this._peek()&&this._peek().type===vO.NUMBER){let t=[];for(;n()&&t.length<rk;){let e=this._next();if(e.type!==vO.NUMBER)return this._finishMixedValue(t,t.length,e);t.push(e.value)}if(!n())return this._next(),t;let r=new(ck[e]||Float64Array)(rk*4);r.set(t);let i=t.length;for(;n();){let e=this._next();if(e.type!==vO.NUMBER)return this._finishMixedValue(r,i,e);i===r.length&&(r=mO(r,r.length*2)),r[i++]=e.value}return this._next(),i===r.length?r:mO(r,i)}let r=[];for(;n();)r.push(this._coerceValueToken(this._next()));return this._next(),r}_finishMixedValue(e,t,n){let r=[];for(let n=0;n<t;n++)r.push(e[n]);for(r.push(this._coerceValueToken(n));this._peek()&&this._peek().type!==vO.RBRACKET;)r.push(this._coerceValueToken(this._next()));return this._next(),r}_coerceValueToken(e){if(!e)throw Error(`PBRT parser: unexpected EOF in parameter value`);if(e.type===vO.NUMBER||e.type===vO.STRING)return e.value;if(e.type===vO.WORD)return e.value===`true`?!0:e.value===`false`?!1:e.value;throw Error(`PBRT parser: unexpected token in parameter value: ${e.type}`)}async _run(e){let t=this.stream;this.stream=e;for(let e=this._next();e!==null;e=this._next()){if(e.type!==vO.WORD)throw Error(`PBRT parser: expected directive, got ${e.type} ${e.value??``}`);sk.has(e.value)&&this._effects++;let t=this._directive(e.value);t!==void 0&&await t}this.stream=t}_directive(e){switch(e){case`Identity`:this._setCTM(UO());break;case`Translate`:{let[e,t,n]=this._readNumbers(3);this._concat(qO(e,t,n));break}case`Scale`:{let[e,t,n]=this._readNumbers(3);this._concat(JO(e,t,n));break}case`Rotate`:{let[e,t,n,r]=this._readNumbers(4);this._concat(YO(e,t,n,r));break}case`LookAt`:{let e=this._readNumbers(9),t=$O([e[0],e[1],e[2]],[e[3],e[4],e[5]],[e[6],e[7],e[8]]);this._concat(ek(t));break}case`Transform`:this._setCTM(this._readBracketedOrBareNumbers(16));break;case`ConcatTransform`:this._concat(this._readBracketedOrBareNumbers(16));break;case`CoordinateSystem`:this.coordSystems.set(this._expectString(`CoordinateSystem`),{ctm:this.ctm,ctmEnd:this.ctmEnd});break;case`CoordSysTransform`:{let e=this.coordSystems.get(this._expectString(`CoordSysTransform`));e&&(this.ctm=e.ctm,this.ctmEnd=e.ctmEnd);break}case`Camera`:{let e=this._expectString(`Camera type`),t=this._parseParams();this.ir.camera={type:e,params:t,cameraToWorld:ek(this.ctm)};let n=this._ctmEndSnapshot();n&&(this.ir.camera.cameraToWorldEnd=ek(n));break}case`Film`:{this._expectString(`Film type`);let e=this._parseParams();this.ir.film={xresolution:this._num(e.xresolution,1280),yresolution:this._num(e.yresolution,720),resolutionGiven:!!(e.xresolution||e.yresolution),filename:this._str(e.filename,null)};break}case`Integrator`:{this._expectString(`Integrator type`);let e=this._parseParams();e.maxdepth&&(this.ir.integrator={maxdepth:this._num(e.maxdepth,5)});break}case`Sampler`:{this._expectString(`Sampler type`);let e=this._parseParams();e.pixelsamples&&(this.ir.sampler={pixelsamples:this._num(e.pixelsamples,16)});break}case`PixelFilter`:case`Filter`:case`Accelerator`:case`ColorSpace`:case`Option`:this._skipTypeAndParams();break;case`WorldBegin`:this.ctm=UO(),this.ctmEnd=null,this.activeTransform=ok,this.state={material:null,areaLight:null,reverseOrientation:!1,interior:null};break;case`WorldEnd`:break;case`AttributeBegin`:this._pushGraphicsState();break;case`AttributeEnd`:this._popGraphicsState();break;case`TransformBegin`:this.transformStack.push({ctm:this.ctm,ctmEnd:this.ctmEnd,activeTransform:this.activeTransform});break;case`TransformEnd`:{let e=this.transformStack.pop();e&&(this.ctm=e.ctm,this.ctmEnd=e.ctmEnd,this.activeTransform=e.activeTransform);break}case`ReverseOrientation`:this.state.reverseOrientation=!this.state.reverseOrientation;break;case`Attribute`:this._expectString(`Attribute target`),this._parseParams();break;case`ActiveTransform`:{let e=this._next()?.value;e===`StartTime`?this.activeTransform=ik:e===`EndTime`?this.activeTransform=ak:e===`All`?this.activeTransform=ok:this._warn(`ActiveTransform "${e}" not recognised`);break}case`TransformTimes`:{let[e,t]=this._readNumbers(2);this.ir.transformTimes={start:e,end:t};break}case`MediumInterface`:{let e=this._peek()?.type===vO.STRING?this._next().value:``;this._peek()?.type===vO.STRING&&this._next(),this.state.interior=e||null;break}case`MakeNamedMedium`:{let e=this._expectString(`MakeNamedMedium name`);this.ir.media.set(e,this._parseParams());break}case`Material`:{let e=this._expectString(`Material type`),t=this._parseParams();this.state.material={type:e,params:t};break}case`MakeNamedMaterial`:{let e=this._expectString(`MakeNamedMaterial name`),t=this._parseParams(),n=this._str(t.type,`diffuse`);this.ir.namedMaterials.set(e,{type:n,params:t});break}case`NamedMaterial`:{let e=this._expectString(`NamedMaterial name`),t=this.ir.namedMaterials.get(e);this.state.material=t||{type:`diffuse`,params:{},_missingRef:e},t||this._warn(`NamedMaterial "${e}" referenced before definition`);break}case`Texture`:{let e=this._expectString(`Texture name`),t=this._expectString(`Texture data type`),n=this._expectString(`Texture class`),r=this._parseParams();this.ir.namedTextures.set(e,{dataType:t,class:n,params:r});break}case`AreaLightSource`:{let e=this._expectString(`AreaLightSource type`),t=this._parseParams();this.state.areaLight={type:e,params:t};break}case`LightSource`:{let e=this._expectString(`LightSource type`),t=this._parseParams();this.ctmEnd!==null&&!nk(this.ctmEnd,this.ctm)&&this._warnOnce(`animated-light`,`animated LightSource transforms are not supported — using the start transform`),this.ir.lights.push({type:e,params:t,ctm:this._ctmSnapshot()});break}case`Shape`:{let e=this._expectString(`Shape type`),t=this._parseParams(),n=t.alpha;if(n?.type===`float`&&n.value[0]<=0)break;let r={type:e,params:t,ctm:this._ctmSnapshot(),material:this.state.material,areaLight:this.state.areaLight,reverseOrientation:this.state.reverseOrientation,interior:this.state.interior},i=this.currentObject===null?this._ctmEndSnapshot():null;i?r.ctmEnd=i:this.currentObject!==null&&this.ctmEnd!==null&&!nk(this.ctmEnd,this.ctm)&&this._warnOnce(`animated-template`,`animated transforms inside ObjectBegin are not supported — using the start transform`),this._emitShape(r);break}case`ObjectBegin`:{let e=this._expectString(`ObjectBegin name`);this._pushGraphicsState(),this.currentObject=e,this.ir.objects.has(e)||this.ir.objects.set(e,[]);break}case`ObjectEnd`:this.currentObject=null,this._popGraphicsState();break;case`ObjectInstance`:{let e=this._expectString(`ObjectInstance name`);this._addInstance(e);break}case`Include`:case`Import`:{let t=this._expectString(e);return this._include(t)}default:this._warnUnknown(e),this._parseParams();break}}_emitShape(e){this.currentObject===null?this.ir.shapes.push(e):this.ir.objects.get(this.currentObject).push(e)}async _include(e){let t=this.dirStack[this.dirStack.length-1],n=this._includeKey(e,t);if(n!==null&&this._placeRepeat(n,e))return;let r=await this.resolveInclude(e,t);if(r==null){this._warn(`Include target not found: ${e}`);return}let i=n===null?null:this._includeState(),a=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)):``;this.dirStack.push(a);try{await this._run(new VO(r))}finally{this.dirStack.pop(),this.releaseInclude?.(e,t,r)}i&&this._sameIncludeState(i)&&!this._includes.has(n)&&this._includes.set(n,{start:i.shapes,end:this.ir.shapes.length,ctm:i.ctm.slice(),template:null})}_includeKey(e,t){return!this.instanceIncludes||this.currentObject!==null||this.ctmEnd!==null||this.activeTransform!==ok||this.state.areaLight?null:`${t}\0${e}\0${this._stateId(this.state.material)}\0${this.state.reverseOrientation}\0${this.state.interior}`}_stateId(e){if(!e)return 0;let t=this._stateIds.get(e);return t===void 0&&this._stateIds.set(e,t=this._nextStateId++),t}_includeState(){return{shapes:this.ir.shapes.length,effects:this._effects,ctm:this.ctm,attributes:this.attributeStack.length,transforms:this.transformStack.length,material:this.state.material,reverseOrientation:this.state.reverseOrientation,interior:this.state.interior}}_sameIncludeState(e){return this._effects===e.effects&&this.ctmEnd===null&&this.activeTransform===ok&&nk(this.ctm,e.ctm)&&this.attributeStack.length===e.attributes&&this.transformStack.length===e.transforms&&this.state.material===e.material&&this.state.areaLight===null&&this.state.reverseOrientation===e.reverseOrientation&&this.state.interior===e.interior}_placeRepeat(e,t){let n=this._includes.get(e);if(!n)return!1;if(n.template===null){let{start:r,end:i}=n;if(i===r||this.ir.instanceCount+2>this.maxPlacements)return!1;for(let t=r;t<i;t++)if(!this.ir.shapes[t])return this._includes.delete(e),!1;let a=`${t}#${this.ir.objects.size}`,o=ek(n.ctm),s=[],c=null,l=null;for(let e=r;e<i;e++){let t=this.ir.shapes[e];t.ctm!==c&&(l=KO(o,c=t.ctm)),t.relativeCTM=l,s.push(t),this.ir.shapes[e]=null}this.ir.objects.set(a,s),this._addInstance(a,n.ctm),n.template=a,this._movedShapes=!0}return this._addInstance(n.template),!0}_skipTypeAndParams(){this._peek()&&this._peek().type===vO.STRING&&this._next(),this._parseParams()}_skipNamedAndParams(){this._peek()&&this._peek().type===vO.STRING&&this._next(),this._parseParams()}_num(e,t){return e&&e.value.length?e.value[0]:t}_str(e,t){return e&&e.value.length?e.value[0]:t}_warn(e){this.ir.warnings.push(e)}_warnOnce(e,t){this._warnedUnknown.has(e)||(this._warnedUnknown.add(e),this._warn(t))}_warnUnknown(e){this._warnedUnknown.has(e)||(this._warnedUnknown.add(e),this._warn(`Unsupported directive ignored: ${e}`))}}}));function dk(e){let t=mk[e];return t?{sigmaS:t[0].slice(),sigmaA:t[1].slice()}:null}function fk(e,t){let n=-1.44/(t*t)+.71/t+.668+.0636*t,r=(1+n)/(1-n),i=Math.sqrt(3*(1-e));return e/2*(1+Math.exp(-4/3*r*i))*Math.exp(-i)}function pk(e,t){let n=Math.min(Math.max(e,0),fk(1,t)),r=0,i=1;for(let e=0;e<48;e++){let e=(r+i)/2;fk(e,t)<n?r=e:i=e}return(r+i)/2}var mk,hk=g((()=>{mk={Apple:[[2.29,2.39,1.97],[.003,.0034,.046]],Chicken1:[[.15,.21,.38],[.015,.077,.19]],Chicken2:[[.19,.25,.32],[.018,.088,.2]],Cream:[[7.38,5.47,3.15],[2e-4,.0028,.0163]],Ketchup:[[.18,.07,.03],[.061,.97,1.45]],Marble:[[2.19,2.62,3],[.0021,.0041,.0071]],Potato:[[.68,.7,.55],[.0024,.009,.12]],Skimmilk:[[.7,1.22,1.9],[.0014,.0025,.0142]],Skin1:[[.74,.88,1.01],[.032,.17,.48]],Skin2:[[1.09,1.59,1.79],[.013,.07,.145]],Spectralon:[[11.6,20.4,14.9],[0,0,0]],Wholemilk:[[2.55,3.21,3.77],[.0011,.0024,.014]],"Lowfat Milk":[[.89187,1.5136,2.532],[.002875,.00575,.0115]],"Reduced Milk":[[2.4858,3.1669,4.5214],[.0025556,.0051111,.012778]],"Regular Milk":[[4.5513,5.8294,7.136],[.0015333,.0046,.019933]],Espresso:[[.72378,.84557,1.0247],[4.7984,6.5751,8.8493]],"Mint Mocha Coffee":[[.31602,.38538,.48131],[3.772,5.8228,7.82]],"Lowfat Soy Milk":[[.30576,.34233,.61664],[.0014375,.0071875,.035937]],"Regular Soy Milk":[[.59223,.73866,1.4693],[.0019167,.0095833,.065167]],"Lowfat Chocolate Milk":[[.64925,.83916,1.1057],[.0115,.0368,.1564]],"Regular Chocolate Milk":[[1.4585,2.1289,2.9527],[.010063,.043125,.14375]],Coke:[[89053e-9,8372e-8,0],[.10014,.16503,.2468]],Pepsi:[[61697e-9,42564e-9,0],[.091641,.14158,.20729]],Sprite:[[60306e-10,64139e-10,65504e-10],[.001886,.0018308,.0020025]],Gatorade:[[.0024574,.003007,.0037325],[.024794,.019289,.008878]],Chardonnay:[[17982e-9,13758e-9,12023e-9],[.010782,.011855,.023997]],"White Zinfandel":[[17501e-9,19069e-9,1288e-8],[.012072,.016184,.019843]],Merlot:[[21129e-9,0,0],[.11632,.25191,.29434]],"Budweiser Beer":[[24356e-9,24079e-9,10564e-9],[.011492,.024911,.057786]],"Coors Light Beer":[[50922e-9,4301e-8,0],[.006164,.013984,.034983]],Clorox:[[.0024035,.0031373,.003991],[.0033542,.014892,.026297]],"Apple Juice":[[13612e-8,15836e-8,227e-6],[.012957,.023741,.052184]],"Cranberry Juice":[[10402e-8,11646e-8,78139e-9],[.039437,.094223,.12426]],"Grape Juice":[[5382e-8,0,0],[.10404,.23958,.29325]],"Ruby Grapefruit Juice":[[.011002,.010927,.011036],[.085867,.18314,.25262]],"White Grapefruit Juice":[[.22826,.23998,.32748],[.0138,.018831,.056781]],Shampoo:[[7176e-7,8303e-7,9016e-7],[.014107,.045693,.061717]],"Strawberry Shampoo":[[15671e-8,15947e-8,1518e-8],[.01449,.05796,.075823]],"Head & Shoulders Shampoo":[[.023805,.028804,.034306],[.084621,.15688,.20365]],"Lemon Tea Powder":[[.040224,.045264,.051081],[2.4288,4.5757,7.2127]],"Orange Powder":[[15617e-8,17482e-8,1762e-7],[.001449,.003441,.007863]],"Pink Lemonade Powder":[[12103e-8,13073e-8,12528e-8],[.001165,.002366,.003195]],"Cappuccino Powder":[[1.8436,2.5851,2.1662],[35.844,49.547,61.084]],"Salt Powder":[[.027333,.032451,.031979],[.28415,.3257,.34148]],"Sugar Powder":[[22272e-8,25513e-8,271e-6],[.012638,.031051,.050124]],"Suisse Mocha Powder":[[2.7979,3.5452,4.3365],[17.502,27.004,35.433]],"Pacific Ocean Surface Water":[[1764e-7,32095e-8,19617e-8],[.031845,.031324,.030147]]}}));function gk(e){let t=Math.max(1e3,Math.min(4e4,e))/100,n,r,i;t<=66?(n=255,r=99.47*Math.log(t)-161.12):(n=329.7*(t-60)**-.1332,r=288.12*(t-60)**-.0755),i=t>=66?255:t<=19?0:138.52*Math.log(t-10)-305.04;let a=e=>Math.max(0,Math.min(255,e))/255;return[a(n)**2.2,a(r)**2.2,a(i)**2.2]}function _k(e,t,n){let r=e[t];return r&&typeof r.value[0]==`number`?r.value[0]:n}function vk(e,t,n){let r=e[t];return r&&typeof r.value[0]==`string`?r.value[0]:n}function yk(e,t,n){let r=e[t]?.value?.[0];return r===void 0?n:r===!0||r===`true`}async function bk(e,t,n,r=null){let i=e[t];if(!i)return{rgb:r,texture:null};if(i.type===`texture`){let e=i.value[0],t=await n.resolveNamedTexture(e);return t&&t.texture?{rgb:t.constant??null,texture:t.texture}:t&&t.constant?{rgb:t.constant,texture:null}:(n.warn(`texture "${e}" could not be resolved`),{rgb:r,texture:null})}if(i.type===`rgb`||i.type===`color`)return{rgb:[i.value[0],i.value[1],i.value[2]],texture:null};if(i.type===`float`){let e=i.value[0];return{rgb:[e,e,e],texture:null}}if(i.type===`blackbody`)return{rgb:gk(i.value[0]),texture:null};if(i.type===`spectrum`){if(typeof i.value[0]==`string`){let e=xk(i.value[0]);return e&&kk[e]?{rgb:kk[e].slice(),texture:null}:(n.warn(`named spectrum "${i.value[0]}" approximated to gray`),{rgb:[.5,.5,.5],texture:null})}let e=0,t=0;for(let n=1;n<i.value.length;n+=2)e+=i.value[n],t++;let r=t?e/t:.5;return{rgb:[r,r,r],texture:null}}return{rgb:r,texture:null}}function xk(e){let t=e.toLowerCase().match(/metal-([a-z]+)/);if(t)return t[1];for(let t of Object.keys(kk))if(e.toLowerCase().includes(t))return t;return null}async function Sk(e,t,n){let r=e[t];return r?typeof r.value[0]==`number`?r.value[0]:r.type===`texture`?await n.floatTextureMean?.(r.value[0])??null:null:null}async function Ck(e,t,n,r=``){let i=jk(e),a=e=>i?Math.sqrt(Math.max(e,0)):e,o=null,s=await Sk(e,`${r}roughness`,n);if(s!==null)o=a(s);else{let t=await Sk(e,`${r}uroughness`,n),i=await Sk(e,`${r}vroughness`,n);t!==null&&(o=i===null?a(t):(a(t)+a(i))/2)}return o===null?t:Math.sqrt(Math.max(o,0))}async function wk(e,t,n,r,i,a=``){let o=n[`${a}roughness`]?[`${a}roughness`]:[`${a}uroughness`,`${a}vroughness`].filter(e=>n[e]);if(i.bakeFloatMap&&o.some(e=>n[e].type===`texture`)){let r=jk(n),a=e=>r?Math.sqrt(Math.max(e,0)):Math.max(e,0),s=await i.bakeFloatMap(n,o,e=>Math.sqrt(e.reduce((e,t)=>e+a(t),0)/e.length));if(s){e[`${t}Map`]=s,e[t]=1;return}}e[t]=await Ck(n,r,i,a)}async function Tk(e,t,n,r){let i=e[t];return i?.type===`texture`?await n.textureMeanRGB?.(i.value[0])??r:(await bk(e,t,n,r)).rgb??r}async function Ek(e,t,n){let i=_k(t,`eta`,1.33),a=_k(t,`scale`,1),o=e=>e.map(e=>Math.max(0,e*a)),s=_k(t,`g`,0),c,l,u=vk(t,`name`,``),d=u?dk(u):null;if(u&&!d&&n.warn(`subsurface: no medium named "${u}" — using pbrt's default`),d)c=o(d.sigmaA),l=o(d.sigmaS),s=0;else if(t.sigma_a&&t.sigma_s)c=o(await Tk(t,`sigma_a`,n,Mk)),l=o(await Tk(t,`sigma_s`,n,Nk));else if(t.reflectance&&!u){let e=await Tk(t,`reflectance`,n,[.5,.5,.5]),r=o(t.mfp?await Tk(t,`mfp`,n,[1,1,1]):[1,1,1]);c=[],l=[];for(let t=0;t<3;t++){let n=1/Math.max(r[t],1e-9),a=pk(e[t],i);l[t]=a*n/(1-s+a*s),c[t]=n-l[t]}}else c=o(Mk),l=o(Nk);let f=c.map((e,t)=>e+l[t]);e.subsurface=1,e.subsurfaceColor=new r.Color(...f.map((e,t)=>e>0?l[t]/e:0)),e.subsurfaceRadius=f.map(e=>e>0?1/e:1e6),e.subsurfaceRadiusScale=1,e.subsurfaceAnisotropy=Math.max(-.99,Math.min(.99,s)),e.ior=i,e.metalness=0,e.color.setRGB(...f.map((e,t)=>{let n=(1-s)*l[t];return e>0?fk(n/(c[t]+n),i):0})),await wk(e,`roughness`,t,0,n)}async function Dk(e,t,n,r,i,a){let o=await bk(t,`reflectance`,n,null),s=t[`${r}eta`],c=t[`${r}k`],l=s&&s.type===`spectrum`&&typeof s.value[0]==`string`;if(o.rgb||o.texture)i(o);else if(s&&c&&!l){let e=(await bk(t,`${r}eta`,n,[.2,.92,1.1])).rgb,i=(await bk(t,`${r}k`,n,[3.9,2.45,2.14])).rgb,o=(e,t)=>((e-1)**2+t**2)/((e+1)**2+t**2);a([o(e[0],i[0]),o(e[1],i[1]),o(e[2],i[2])])}else a(s?(await bk(t,`${r}eta`,n,Ak)).rgb||Ak:kk.cu);e.metalness=1}async function Ok(e,t){let n=e?.type||`diffuse`,i=e?.params||{},a=new r.MeshPhysicalMaterial({side:r.DoubleSide,roughness:1,metalness:0}),o=e=>{e&&a.color.setRGB(e[0],e[1],e[2])},s=e=>{o(e.rgb),e.texture&&(a.map=e.texture,e.rgb||a.color.setRGB(1,1,1))};switch(n){case`diffuse`:s(await bk(i,`reflectance`,t,[.5,.5,.5])),a.roughness=1,a.metalness=0,a.specularIntensity=0;break;case`conductor`:case`metal`:await Dk(a,i,t,``,s,o),await wk(a,`roughness`,i,.1,t);break;case`coatedconductor`:await Dk(a,i,t,`conductor.`,s,o),await wk(a,`roughness`,i,0,t,`conductor.`),a.clearcoat=1,await wk(a,`clearcoatRoughness`,i,0,t,`interface.`);break;case`dielectric`:case`thindielectric`:a.transmission=1,a.metalness=0,a.color.setRGB(1,1,1),a.ior=_k(i,`eta`,1.5),await wk(a,`roughness`,i,0,t),a.thickness=n===`thindielectric`?0:_k(i,`thickness`,0);break;case`coateddiffuse`:s(await bk(i,`reflectance`,t,[.5,.5,.5])),a.roughness=.6,a.metalness=0,a.clearcoat=1,await wk(a,`clearcoatRoughness`,i,0,t);break;case`diffusetransmission`:{let e=_k(i,`scale`,1),n=t=>Math.min(1,Math.max(0,e*t)),o=await bk(i,`transmittance`,t,[.25,.25,.25]),c=o.rgb?o.rgb.map(n):[.5,.5,.5],l=Math.min(.99,Math.max(...c)),u=await bk(i,`reflectance`,t,[.25,.25,.25]),d=e=>Math.min(1,n(e)/(1-l));s({texture:u.texture,rgb:u.rgb?u.rgb.map(d):u.texture?[1,1,1].map(d):null}),o.texture&&t.warn(`diffusetransmission: a textured "transmittance" is not supported — using 0.5`),a.diffuseTransmission=l,a.diffuseTransmissionColor=new r.Color().setRGB(...c.map(e=>l>0?Math.min(1,e/l):1)),a.roughness=1,a.metalness=0,a.specularIntensity=0;break}case`interface`:case`none`:case``:a.transmission=1,a.ior=1,a.roughness=0,a.color.setRGB(1,1,1);break;case`mix`:{let e=i.materials?.value||[],n=Math.max(0,Math.min(1,_k(i,`amount`,.5))),o=e[0]?t.namedMaterials?.get(e[0]):null,s=e[1]?t.namedMaterials?.get(e[1]):null;if(o&&s){let[e,c]=await Promise.all([Ok(o,t),Ok(s,t)]),l=i.amount,u=l?.type===`texture`?await t.bakeMaterialMix?.(e,c,l.value[0]):null;u&&(n=u.mean);let d=(e,t)=>e*(1-n)+t*n;a.color.lerpColors(e.color,c.color,n),a.roughness=d(e.roughness,c.roughness),a.metalness=d(e.metalness,c.metalness),a.ior=d(e.ior??1.5,c.ior??1.5),a.transmission=d(e.transmission??0,c.transmission??0),a.thickness=d(e.thickness??0,c.thickness??0),a.clearcoat=d(e.clearcoat??0,c.clearcoat??0),a.clearcoatRoughness=d(e.clearcoatRoughness??0,c.clearcoatRoughness??0),a.emissive.lerpColors(e.emissive,c.emissive,n);let f=e.diffuseTransmission??0,p=c.diffuseTransmission??0;(f>0||p>0)&&(a.diffuseTransmission=d(f,p),a.diffuseTransmissionColor=new r.Color().lerpColors(e.diffuseTransmissionColor??new r.Color(1,1,1),c.diffuseTransmissionColor??new r.Color(1,1,1),n)),a.emissiveIntensity=d(e.emissiveIntensity??0,c.emissiveIntensity??0),a.map=(n<.5?e.map:c.map)||null,a.normalMap=(n<.5?e.normalMap:c.normalMap)||null,u?.texture&&(a.map=u.texture,a.color.setRGB(1,1,1));break}t.warn(`material "mix" — could not resolve inner materials [${e.join(`, `)}], falling back to diffuse`),a.color.set(new r.Color(.6,.6,.6));break}case`subsurface`:await Ek(a,i,t);break;case`hair`:case`measured`:t.warn(`material "${n}" not supported — using diffuse approximation`),o((await bk(i,`reflectance`,t,[.5,.5,.5])).rgb),a.roughness=1;break;default:t.warn(`unknown material "${n}" — using neutral diffuse`),a.color.set(new r.Color(.6,.6,.6));break}let c=vk(i,`normalmap`,null);return c&&t.resolveNormalMap&&(a.normalMap=await t.resolveNormalMap(c)),a.roughness=Math.max(0,Math.min(1,a.roughness)),a}var kk,Ak,jk,Mk,Nk,Pk=g((()=>{hk(),kk={au:[1,.78,.34],gold:[1,.78,.34],cu:[.95,.64,.54],copper:[.95,.64,.54],ag:[.97,.96,.91],silver:[.97,.96,.91],al:[.91,.92,.92],aluminium:[.91,.92,.92],aluminum:[.91,.92,.92],mgo:[.9,.9,.9],tio2:[.9,.9,.9]},Ak=[.92,.92,.92],jk=e=>{let t=e.remaproughness?.value?.[0];return t!==!1&&t!==`false`},Mk=[.0011,.0024,.014],Nk=[2.55,3.21,3.77]}));function Fk(e,{channels:t,decode:n=null,scale:r=1,invert:i=!1,mapping:a=null}){let{width:o,height:s}=e,c=e.channels??4,l=new Float32Array(o*s*t),u=e.topDown!==!1,d=t=>n?n(e.data[t]/255):e.data[t],f=t===1&&c===4&&Ik(e),p=t===1&&c>=3&&!f;for(let e=0;e<s;e++){let n=u?e:s-1-e;for(let a=0;a<o;a++){let s=(n*o+a)*c,u=(e*o+a)*t;for(let e=0;e<t;e++){let t=r*(f?d(s+3):p?(d(s)+d(s+1)+d(s+2))/3:d(s+Math.min(e,c-1)));l[u+e]=i?Math.max(0,1-t):t}}}return{width:o,height:s,channels:t,data:l,su:1,sv:1,du:0,dv:0,...a}}function Ik(e){let{data:t}=e,n=e.float?1:255;for(let e=3;e<t.length;e+=4)if(t[e]!==n)return!0;return!1}function Lk(e){let t=0;for(let n=0;n<e.data.length;n++)t+=e.data[n];return e.data.length?t/e.data.length:0}function Rk(e,t,n,r){let{width:i,height:a,channels:o,data:s}=e,c=t*i-.5,l=(1-n)*a-.5,u=Math.floor(c),d=Math.floor(l),f=c-u,p=l-d,m=(e,t)=>(e%t+t)%t,h=m(u,i),g=m(u+1,i),_=m(d,a),v=m(d+1,a);for(let e=0;e<3;e++){let t=Math.min(e,o-1),n=s[(_*i+h)*o+t]*(1-f)+s[(_*i+g)*o+t]*f,a=s[(v*i+h)*o+t]*(1-f)+s[(v*i+g)*o+t]*f;r[e]=n*(1-p)+a*p}return r}function zk(e,t,{alphaOf:n=null,linear:r=!1}={}){let i=null;for(let t of e)t.layer&&(!i||t.layer.width*t.layer.height>i.width*i.height)&&(i=t.layer);if(!i)return null;let a=Math.min(i.width,Bk),o=Math.min(i.height,Bk),s=new Uint8Array(a*o*4),c=e.map(()=>[0,0,0]);for(let l=0;l<o;l++){let u=(l+.5)/o,d=(u-i.dv)/i.sv;for(let o=0;o<a;o++){let f=(o+.5)/a,p=(f-i.du)/i.su;for(let t=0;t<e.length;t++){let n=e[t],r=c[t];if(n.layer){let e=n.layer;if(Rk(e,e===i?f:e.su*p+e.du,e===i?u:e.sv*d+e.dv,r),n.tint)for(let e=0;e<3;e++)r[e]*=n.tint[e]}else r[0]=n.rgb[0],r[1]=n.rgb[1],r[2]=n.rgb[2];if(n.clamp)for(let e=0;e<3;e++)r[e]=Math.min(1,Math.max(0,r[e]))}let m=t(c),h=(l*a+o)*4;for(let e=0;e<3;e++){let t=Math.min(1,Math.max(0,m[e]));s[h+e]=Math.round(255*(r?t:Hk(t)))}s[h+3]=n?Math.round(255*Math.min(1,Math.max(0,n(c)))):255}}return{data:s,width:a,height:o,mapping:{su:i.su,sv:i.sv,du:i.du,dv:i.dv}}}var Bk,Vk,Hk,Uk,Wk=g((()=>{Bk=4096,Vk=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4,Hk=e=>e<=.0031308?e*12.92:1.055*e**(1/2.4)-.055,Uk=([e,t,n])=>{let r=n[0];return[e[0]+(t[0]-e[0])*r,e[1]+(t[1]-e[1])*r,e[2]+(t[2]-e[2])*r]}}));function Gk(e){return e===3?3/16:3/(8*e)}function Kk(e){return 1/(e+3/(8*Gk(e)))}function qk(e,t){let n=new Map,r=[],i=[],a=[],o=[],s=[],c=t.length/3;for(let l=0;l<c;l++)for(let c=0;c<3;c++){let u=t[l*3+c],d=t[l*3+(c+1)%3],f=t[l*3+(c+2)%3],p=u<d?u:d,m=u<d?d:u,h=p*e+m,g=n.get(h);g===void 0?(n.set(h,r.length),r.push(p),i.push(m),a.push(f),o.push(-1),s.push(1)):(o[g]<0&&(o[g]=f),s[g]++)}let l=Array.from({length:e},()=>[]),u=Array.from({length:e},()=>[]);for(let e=0;e<r.length;e++){let t=r[e],n=i[e];l[t].push(n),l[n].push(t),s[e]===1&&(u[t].push(n),u[n].push(t))}return{edgeIndex:n,edgeV0:r,edgeV1:i,edgeOpp0:a,edgeOpp1:o,edgeFaces:s,ring:l,boundaryRing:u}}function Jk(e,t,n,r,i){let a=new Float64Array(e.length);for(let o=0;o<n;o++){let n=o*3,s=t.boundaryRing[o];if(s.length===2){let t=s[0]*3,r=s[1]*3,o=1-2*i;for(let s=0;s<3;s++)a[n+s]=o*e[n+s]+i*(e[t+s]+e[r+s]);continue}let c=t.ring[o],l=c.length;if(l===0||s.length>0){for(let t=0;t<3;t++)a[n+t]=e[n+t];continue}let u=r(l),d=0,f=0,p=0;for(let t=0;t<l;t++){let n=c[t]*3;d+=e[n],f+=e[n+1],p+=e[n+2]}let m=1-l*u;a[n]=m*e[n]+u*d,a[n+1]=m*e[n+1]+u*f,a[n+2]=m*e[n+2]+u*p}return a}function Yk(e,t){let n=e.length/3,r=qk(n,t),i=r.edgeV0.length,a=Jk(e,r,n,Gk,1/8),o=new Float64Array((n+i)*3);o.set(a);for(let t=0;t<i;t++){let i=r.edgeV0[t]*3,a=r.edgeV1[t]*3,s=(n+t)*3,c=r.edgeOpp1[t];if(c<0)for(let t=0;t<3;t++)o[s+t]=.5*(e[i+t]+e[a+t]);else{let n=r.edgeOpp0[t]*3,l=c*3;for(let t=0;t<3;t++)o[s+t]=.375*(e[i+t]+e[a+t])+.125*(e[n+t]+e[l+t])}}let s=t.length/3,c=new Int32Array(s*12),l=(e,t)=>n+r.edgeIndex.get((e<t?e:t)*n+(e<t?t:e));for(let e=0;e<s;e++){let n=t[e*3],r=t[e*3+1],i=t[e*3+2],a=l(n,r),o=l(r,i),s=l(i,n),u=e*12;c[u]=n,c[u+1]=a,c[u+2]=s,c[u+3]=a,c[u+4]=r,c[u+5]=o,c[u+6]=s,c[u+7]=o,c[u+8]=i,c[u+9]=a,c[u+10]=o,c[u+11]=s}return{positions:o,indices:c}}function Xk(e,t,n,r=2e6){let i=Float64Array.from(e),a=Int32Array.from(t),o=0;for(let e=0;e<n&&!(a.length/3*4>r);e++){let e=Yk(i,a);i=e.positions,a=e.indices,o++}let s=i.length/3,c=Jk(i,qk(s,a),s,Kk,1/5);return{positions:Float32Array.from(c),indices:Uint32Array.from(a),levels:o}}var Zk=g((()=>{}));function Qk(e,t,n){let r=Math.abs(e),i=Math.abs(t),a=Math.sqrt(Math.max(0,1-Math.abs(n))),o=Math.max(r,i),s=o===0?0:Math.min(r,i)/o,c=2/Math.PI*Math.atan(s);r<i&&(c=1-c);let l=c*a,u=a-l;if(n<0){let e=u;u=1-l,l=1-e}return e<0&&(u=-u),t<0&&(l=-l),[.5*(u+1),.5*(l+1)]}function $k(e,t,n,r,i,a,o,s){let c=Math.min(Math.max(i*t-.5,0),t-1),l=Math.min(Math.max(a*n-.5,0),n-1),u=Math.floor(c),d=Math.floor(l),f=Math.min(u+1,t-1),p=Math.min(d+1,n-1),m=c-u,h=l-d,g=(d*t+u)*r,_=(d*t+f)*r,v=(p*t+u)*r,y=(p*t+f)*r;for(let t=0;t<3;t++){let n=s?s[e[g+t]]:e[g+t],r=s?s[e[_+t]]:e[_+t],i=s?s[e[v+t]]:e[v+t],a=s?s[e[y+t]]:e[y+t],c=n*(1-m)+r*m,l=i*(1-m)+a*m;o[t]=c*(1-h)+l*h}}function eA(e,t,n=1,r=0){let i=r||Math.min(e.width,4096),a=Math.max(1,i>>1),o=new Float32Array(i*a*4),s=t?ek(t):null,c=e.srgb?tA:null,l=[0,0,0];for(let t=0;t<a;t++){let r=(1-(t+.5)/a)*Math.PI,u=Math.sin(r),d=Math.cos(r);for(let r=0;r<i;r++){let a=((r+.5)/i-.5)*2*Math.PI,f=u*Math.cos(a),p=d,m=u*Math.sin(a);if(s){let e=s,t=e[0]*f+e[4]*p+e[8]*m,n=e[1]*f+e[5]*p+e[9]*m,r=e[2]*f+e[6]*p+e[10]*m,i=Math.hypot(t,n,r)||1;f=t/i,p=n/i,m=r/i}let[h,g]=Qk(f,p,m);$k(e.data,e.width,e.height,e.channels,h,e.bottomUp?1-g:g,l,c);let _=(t*i+r)*4;o[_]=l[0]*n,o[_+1]=l[1]*n,o[_+2]=l[2]*n,o[_+3]=1}}return{data:o,width:i,height:a}}var tA,nA=g((()=>{tk(),tA=(()=>{let e=new Float32Array(256);for(let t=0;t<256;t++){let n=t/255;e[t]=n<=.04045?n/12.92:((n+.055)/1.055)**2.4}return e})()}));function rA(e,t){let n=e*e,r=n*e;t[0]=(1-3*e+3*n-r)/6,t[1]=(4-6*n+3*r)/6,t[2]=(1+3*e+3*n-3*r)/6,t[3]=r/6}function iA(e,t){let n=1-e;t[0]=n*n*n,t[1]=3*n*n*e,t[2]=3*n*e*e,t[3]=e*e*e}function aA(e){let t=Math.hypot(e[0],e[1],e[2]);return t>0&&(e[0]/=t,e[1]/=t,e[2]/=t),e}function oA(e,t,n){return n[0]=e[1]*t[2]-e[2]*t[1],n[1]=e[2]*t[0]-e[0]*t[2],n[2]=e[0]*t[1]-e[1]*t[0],n}function sA(e,t){let n=e.length/3;return t===`bspline`?n-3:Math.max(1,(n-1)/3)}function cA(e,t,n,r,i,a,o){let s=Math.floor(r);s>=n&&(s=n-1);let c=r-s;t===`bspline`?rA(c,i):iA(c,i);let l=t===`bspline`?s:s*3,u=0,d=0,f=0;for(let t=0;t<4;t++){let n=(l+t)*3;u+=i[t]*e[n],d+=i[t]*e[n+1],f+=i[t]*e[n+2]}a[o]=u,a[o+1]=d,a[o+2]=f}function lA(e,t,n){let r=sA(e,t);if(r<1)return null;let i=Math.max(1,Math.round(n*r)),a=new Float64Array((i+1)*3),o=[0,0,0,0];for(let n=0;n<=i;n++)cA(e,t,r,n/i*r,o,a,n*3);return{points:a,count:i+1,spans:r}}function uA(e,t,n,r,i){let a=e[t*3],o=e[t*3+1],s=e[t*3+2],c=n[r*3],l=n[r*3+1],u=n[r*3+2],d=n[i*3]-c,f=n[i*3+1]-l,p=n[i*3+2]-u,m=d*d+f*f+p*p,h=m>0?((a-c)*d+(o-l)*f+(s-u)*p)/m:0;return h=h<0?0:h>1?1:h,Math.hypot(a-c-h*d,o-l-h*f,s-u-h*p)}function dA(e,t,n,r,i,a){let{points:o,count:s,spans:c}=n;if(s<3)return null;let l=new Float64Array((s-1)*3),u=[0,0,0,0],d=s-1;for(let n=0;n<d;n++)cA(e,t,c,(n+.5)/d*c,u,l,n*3);let f=0;for(let e=0;e<d;e++)f=Math.max(f,uA(l,e,o,e,e+1));let p=e=>Math.max(f,r*.5*(i+(a-i)*(e/d))),m=(e,t)=>{for(let n=e+1;n<t;n++)if(uA(o,n,o,e,t)>p(n))return!1;for(let n=e;n<t;n++)if(uA(l,n,o,e,t)>p(n+.5))return!1;return!0},h=new Int32Array(s),g=0;h[g++]=0;for(let e=0;e<d;){let t=e+1;for(;t<d&&m(e,t+1);)t++;h[g++]=t,e=t}return g===s?null:h.subarray(0,g)}function fA(e){let{P:t,basis:n=`bezier`,width0:r=1,width1:i=1,N:a=null}=e,o=Math.max(1,Math.round(e.steps??pA)),s=Math.max(1,Math.round(e.sides??1));if(!t||t.length<12)return null;let c=lA(t,n,o);if(!c)return null;let{points:l,count:u}=c,d=e.tolerance>0?dA(t,n,c,e.tolerance,r,i):null,f=d?d.length:u,p=s>=3?s:s*2,m=new Float32Array(f*p*3),h=[0,0,0],g=[0,0,0],_=[0,0,0],v=[0,0,0],y=!1,b=0;for(let e=0;e<u;e++){let t=Math.max(0,e-1),n=Math.min(u-1,e+1);if(h[0]=l[n*3]-l[t*3],h[1]=l[n*3+1]-l[t*3+1],h[2]=l[n*3+2]-l[t*3+2],aA(h),y){let e=g[0]*h[0]+g[1]*h[1]+g[2]*h[2];g[0]-=e*h[0],g[1]-=e*h[1],g[2]-=e*h[2],Math.hypot(g[0],g[1],g[2])<1e-9&&oA(h,[0,1,0],g),aA(g)}else{if(a&&a.length>=3)g[0]=a[0],g[1]=a[1],g[2]=a[2],oA(h,g,v),g[0]=v[0],g[1]=v[1],g[2]=v[2];else{let e=Math.abs(h[0]),t=Math.abs(h[1]),n=Math.abs(h[2]);oA(h,e<t&&e<n?[1,0,0]:t<n?[0,1,0]:[0,0,1],g)}Math.hypot(g[0],g[1],g[2])<1e-9&&oA(h,[0,1,0],g),aA(g),y=!0}if(d&&d[b]!==e)continue;oA(h,g,_),aA(_);let o=e/(u-1||1),c=(r+(i-r)*o)*.5,f=l[e*3],x=l[e*3+1],S=l[e*3+2];for(let e=0;e<p;e++){let t,n,r;if(s>=3){let i=e/s*Math.PI*2,a=Math.cos(i),o=Math.sin(i);t=g[0]*a+_[0]*o,n=g[1]*a+_[1]*o,r=g[2]*a+_[2]*o}else{let i=e<2?g:_,a=e%2==0?-1:1;t=i[0]*a,n=i[1]*a,r=i[2]*a}let i=(b*p+e)*3;m[i]=f+t*c,m[i+1]=x+n*c,m[i+2]=S+r*c}b++}let x=s,S=new Uint32Array((f-1)*x*6),C=0;for(let e=0;e<f-1;e++)for(let t=0;t<x;t++){let n=s>=3?t:t*2,r=s>=3?(t+1)%s:t*2+1,i=e*p+n,a=e*p+r,o=(e+1)*p+r,c=(e+1)*p+n;S[C++]=i,S[C++]=a,S[C++]=o,S[C++]=i,S[C++]=o,S[C++]=c}return{positions:m,indices:C===S.length?S:mO(S,C)}}var pA,mA=g((()=>{gO(),pA=2}));async function hA(e,t,n){let r=e[t];if(r?.type===`spectrum`&&typeof r.value[0]==`string`&&r.value[0].startsWith(`stdillum`))return[1,1,1];let i=(await bk(e,t,n,[1,1,1])).rgb||[1,1,1];if(!r||r.type===`rgb`||r.type===`color`||r.type===`float`)return i;let a=.2126*i[0]+.7152*i[1]+.0722*i[2];return a>0?i.map(e=>e/a):i}function gA(e){return e instanceof Uint32Array?new r.Uint32BufferAttribute(e,1):ArrayBuffer.isView(e)&&e.BYTES_PER_ELEMENT===4?new r.Uint32BufferAttribute(new Uint32Array(e.buffer,e.byteOffset,e.length),1):new r.Uint32BufferAttribute(Uint32Array.from(e),1)}function _A(e,t){if(t<=e.length)return e;let n=e.length||1;for(;n<t;)n*=2;return mO(e,n)}function vA(e){return e instanceof Float32Array?e:Float32Array.from(e)}function yA(e,t){if(e.count!==t.count)return!1;for(let n=0,r=e.count*16;n<r;n++)if(e.matrices[n]!==t.matrices[n])return!1;return!0}function bA(e,t){let n=Math.min(e.width,VA),r=null;if(typeof OffscreenCanvas<`u`)r=new OffscreenCanvas(n,n);else if(typeof document<`u`)r=document.createElement(`canvas`),r.width=r.height=n;else return null;try{let i=r.getContext(`2d`,{willReadFrequently:!0});if(!i)return null;i.drawImage(e,0,0,n,n);let{data:a}=i.getImageData(0,0,n,n);return{data:a,width:n,height:n,channels:4,bottomUp:!1,srgb:t}}catch{return null}}function xA(e){let t=e?.image;if(!t)return null;if(ArrayBuffer.isView(t.data))return{data:t.data,width:t.width,height:t.height,channels:4,topDown:e.flipY===!0,float:!(t.data instanceof Uint8Array||t.data instanceof Uint8ClampedArray)};let{width:n,height:r}=t;if(!n||!r)return null;let i=null;if(typeof OffscreenCanvas<`u`)i=new OffscreenCanvas(n,r);else if(typeof document<`u`)i=document.createElement(`canvas`),i.width=n,i.height=r;else return null;try{let e=i.getContext(`2d`,{willReadFrequently:!0});return e?(e.drawImage(t,0,0),{data:e.getImageData(0,0,n,r).data,width:n,height:r,channels:4,topDown:!0,float:!1}):null}catch{return null}}function SA(e){let t=vk(e,`encoding`,`sRGB`);if(t===`linear`)return e=>e;let n=/^gamma\s+([\d.]+)$/.exec(t);return n?e=>e**Number(n[1]):Vk}function CA(e){return{su:_k(e,`uscale`,1),sv:_k(e,`vscale`,1),du:_k(e,`udelta`,0),dv:_k(e,`vdelta`,0)}}function wA(e,{su:t,sv:n,du:r,dv:i}){e.repeat.set(t,n),e.offset.set(r,i)}function TA(e,{srgb:t}){let n=e?.image?.data;if(!ArrayBuffer.isView(n)||n instanceof Uint8Array||n instanceof Uint8ClampedArray)return e;let{width:i,height:a}=e.image,o=new Uint8Array(i*a*4),s=n.length/(i*a);for(let e=0;e<i*a;e++)for(let r=0;r<4;r++){let i=r<s?Math.min(1,Math.max(0,n[e*s+r])):1;o[e*4+r]=Math.round(255*(t&&r<3?Hk(i):i))}let c=new r.DataTexture(o,i,a,r.RGBAFormat);return c.flipY=e.flipY,c.colorSpace=t?r.SRGBColorSpace:r.NoColorSpace,c.wrapS=c.wrapT=r.RepeatWrapping,c.needsUpdate=!0,c}function EA({data:e,width:t,height:n,mapping:i},{srgb:a=!0}={}){let o=new r.DataTexture(e,t,n,r.RGBAFormat);return o.colorSpace=a?r.SRGBColorSpace:r.NoColorSpace,o.wrapS=o.wrapT=r.RepeatWrapping,wA(o,i),o.needsUpdate=!0,o}function DA(e,t,n){let r=e.isOrthographicCamera===!0,i=r?1:Math.tan(e.fov*Math.PI/360),a=r?50:12/i;return{enableDOF:!0,focusDistance:n,aperture:a*.001/(2*t),focalLength:a,apertureScale:1,anamorphicRatio:1,dofBlur:t/(n*i),autoFocusMode:`manual`,afScreenPoint:{x:.5,y:.5},orthoHeight:r?(e.top-e.bottom)/e.zoom:null}}function OA(e){let t={};return e.integrator?.maxdepth>0&&(t.maxBounces=Math.round(e.integrator.maxdepth)),e.sampler?.pixelsamples>0&&(t.samples=Math.round(e.sampler.pixelsamples)),e.film?.resolutionGiven&&(t.width=e.film.xresolution,t.height=e.film.yresolution),Object.keys(t).length?t:null}function kA(e){let t=_k(e,`radius`,1),n=_k(e,`zmin`,-t),r=_k(e,`zmax`,t),i=e=>Math.min(t,Math.max(-t,e));return{radius:t,zMin:i(Math.min(n,r)),zMax:i(Math.max(n,r)),phiMax:QA(e)}}function AA(e){let t=_k(e,`zmin`,-1),n=_k(e,`zmax`,1);return{radius:_k(e,`radius`,1),zMin:Math.min(t,n),zMax:Math.max(t,n),phiMax:QA(e)}}function jA(e){return{radius:_k(e,`radius`,1),inner:_k(e,`innerradius`,0),height:_k(e,`height`,0),phiMax:QA(e)}}function MA(e,t,n){let i=Math.max(3,Math.ceil(ZA*e/(2*Math.PI))),a=i+1,o=new Float32Array(a*(t+1)*3),s=new Float32Array(o.length),c=new Float32Array(a*(t+1)*2),l=new r.Vector3,u=new r.Vector3;for(let e=0;e<=t;e++)for(let r=0;r<=i;r++){let d=e*a+r;n(r/i,e/t,l,u),l.toArray(o,d*3),u.toArray(s,d*3),c[d*2]=r/i,c[d*2+1]=e/t}let d=0;for(let e=0;e<o.length;e++)d=Math.max(d,Math.abs(o[e]));let f=(e,t)=>Math.hypot(o[e*3]-o[t*3],o[e*3+1]-o[t*3+1],o[e*3+2]-o[t*3+2])>d*1e-6,p=[];for(let e=0;e<t;e++)for(let t=0;t<i;t++){let n=e*a+t,r=n+1,i=n+a,o=i+1;f(n,r)&&p.push(n,r,o),f(i,o)&&p.push(n,o,i)}let m=new r.BufferGeometry;return m.setAttribute(`position`,new r.Float32BufferAttribute(o,3)),m.setAttribute(`normal`,new r.Float32BufferAttribute(s,3)),m.setAttribute(`uv`,new r.Float32BufferAttribute(c,2)),m.setIndex(new r.Uint32BufferAttribute(new Uint32Array(p),1)),m}function NA(e,t){let n=e.params;switch(e.type){case`sphere`:{let{radius:e,zMin:t,zMax:r,phiMax:i}=kA(n);return i*e*(r-t)}case`cylinder`:{let{radius:e,zMin:t,zMax:r,phiMax:i}=AA(n);return i*e*(r-t)}case`disk`:{let{radius:e,inner:t,phiMax:r}=jA(n);return r*.5*(e*e-t*t)}}let i=new r.Matrix4().fromArray(e.ctm),a=t.getAttribute(`position`),o=t.index,s=o?o.count:a.count,c=new r.Vector3,l=new r.Vector3,u=new r.Vector3,d=0;for(let e=0;e+2<s;e+=3)c.fromBufferAttribute(a,o?o.getX(e):e).applyMatrix4(i),l.fromBufferAttribute(a,o?o.getX(e+1):e+1).applyMatrix4(i),u.fromBufferAttribute(a,o?o.getX(e+2):e+2).applyMatrix4(i),d+=l.sub(c).cross(u.sub(c)).length()/2;return d}function PA(e,t,n){let r=new Uint8Array(e*t*4);for(let i=0;i<t;i++)for(let a=0;a<e;a++){let o=n((a+.5)/e,(i+.5)/t),s=(i*e+a)*4;for(let e=0;e<3;e++)r[s+e]=Math.round(255*Hk(Math.min(1,Math.max(0,o[e]))));r[s+3]=255}return r}function FA(e){let t=e.clone();for(let n of Object.keys(e))n in t||(t[n]=e[n]);return t}function IA(e,t){let n=FA(e);return n.transparent=!0,n.opacity=e.opacity*t,n}function LA(e,t){if(e.float||!Ik(e))return null;let{data:n,width:i,height:a}=e,o=new Uint8Array(256);for(let e=0;e<256;e++)o[e]=Math.round(255*Math.min(1,Math.max(0,t(e/255))));let s=new Uint8Array(i*a*4),c=i*4;for(let t=0;t<a;t++){let r=(e.topDown?a-1-t:t)*c,i=t*c;for(let e=0;e<c;e+=4)s[i+e]=n[r+e],s[i+e+1]=n[r+e+1],s[i+e+2]=n[r+e+2],s[i+e+3]=o[n[r+e+3]]}let l=new r.DataTexture(s,i,a,r.RGBAFormat);return l.colorSpace=r.SRGBColorSpace,l.wrapS=l.wrapT=r.RepeatWrapping,l.needsUpdate=!0,l}function RA(e){let t=[e],n=e,r=[e=>e.replace(/-renamed-\d+$/,``),e=>e.replace(/\d+$/,``),e=>e.replace(/_Color$/i,``),e=>e.replace(/\d+$/,``)];for(let e of r){let r=e(n);r!==n&&r&&t.push(n=r)}return t}var zA,BA,VA,HA,UA,WA,GA,KA,qA,JA,YA,XA,ZA,QA,$A,ej,tj,nj,rj=g((()=>{gO(),Pk(),Wk(),Zk(),nA(),mA(),tk(),La(),zA=new Set([`distant`,`point`,`spot`]),BA=[1,0,0,0,0,1,0,0,0,0,-1,0,0,0,0,1],VA=4096,HA=1e3,UA=45e6,WA=6e6,GA=256,KA=4096,qA=5e5,JA=2,YA={flat:1,ribbon:1,cylinder:2},XA=.05,ZA=48,QA=e=>Math.min(360,Math.max(0,_k(e,`phimax`,360)))*Math.PI/180,$A=64,ej=64,tj=(e,{su:t,sv:n,du:r,dv:i})=>e.repeat.x===t&&e.repeat.y===n&&e.offset.x===r&&e.offset.y===i,nj=class{constructor(e={}){this.maxTriangles=e.maxTriangles??UA,this.maxPlacements=e.maxPlacements??WA,this.mergeShapesAbove=e.mergeShapesAbove??GA,this.curveSteps=e.curveSteps??JA,this.curveSides=e.curveSides??null,this.curveTolerance=e.curveTolerance??XA,this.resolvePLY=e.resolvePLY||(async()=>null),this.resolveImage=e.resolveImage||(async()=>null),this.resolveEnvironment=e.resolveEnvironment||e.resolveImage||(async()=>null),this.convertHandedness=e.convertHandedness===!0,this.warnings=[],this.report=[],this._materialCache=new Map,this._textureCache=new Map,this._geometryCache=new Map,this._materialBySignature=new Map,this._noUVMaterials=new Map,this._plyCache=new Map,this._imageCache=new Map,this._termCache=new Map,this._mediumMaterials=new Map,this._alphaMaterials=new Map}warn(e){this.warnings.push(e)}async build(e){this.ir=e,this._keepShapes=new Set;for(let{name:t}of e.animatedInstances??[])for(let n of e.objects.get(t)??[])this._keepShapes.add(n);this._plyUsers=new Map,this._plyHeld=new Set;for(let t of e.shapes)if(t?.type===`plymesh`){let e=vk(t.params,`filename`,null);this._plyUsers.set(e,(this._plyUsers.get(e)??0)+1)}for(let t of e.objects.values())for(let e of t)e.type===`plymesh`&&this._plyHeld.add(vk(e.params,`filename`,null));this._recoveredColors=0,this.reportedMeshes=0,this.triangleCount=0,this.placementCount=0,this.skippedForBudget=0,this._countedGeometries=new WeakSet;let t=new r.Group;t.name=`PBRTScene`,this._batches=e.shapes.length>=this.mergeShapesAbove?new Map:null,this._mergedBatches=0,this.mergedShapes=0,this.droppedNoTemplate=0,this._animated=[];for(let n=0;n<e.shapes.length;n++){if(this._overBudget()){this.skippedForBudget+=e.shapes.length-n;break}let r=e.shapes[n],[i,a]=await Promise.all([this._batches?this._createGeometry(r):this._buildGeometry(r),this._getMaterial(r)]);if(!i)continue;let o=r.areaLight?this._poweredMaterial(r,i,a):a;if(this._batches&&!r.motion&&i.getAttribute(`position`).count<=KA){this._mergeShape(r,i,o,t),e.shapes[n]=null;continue}r.type===`plymesh`&&this._plyHeld.add(vk(r.params,`filename`,null));let s=this._meshFromGeometry(r,i,o,r.ctm,`shape_${n}`);s&&(t.add(s),r.motion&&this._animate(s,r.motion))}if(this._batches){for(let e of this._batches.values())this._flushBatch(e[0],t),this._flushBatch(e[1],t);this._batches=null}await this._buildInstances(e,t),await this._buildAnimatedPlacements(e,t),this.skippedForBudget>0&&this.warn(`stopped at ${this.triangleCount.toLocaleString()} stored triangles (budget ${this.maxTriangles.toLocaleString()}) and ${this.placementCount.toLocaleString()} placements (budget ${this.maxPlacements.toLocaleString()}); ${this.skippedForBudget.toLocaleString()} placement(s) skipped`);let n=null;e.camera&&(n=this._buildCamera(e.camera,e.film),n&&t.add(n));let i=e.animation?this._buildClip(e,n):[],a=await this._buildEnvironment(e.lights);return await this._buildLamps(e.lights,t),this._reportUnsupportedLights(e.lights),this._recoveredColors>0&&this.warn(`${this._recoveredColors} unreadable texture(s) fell back to the like-named material's colour`),{group:t,camera:n,environment:a,animations:i,render:OA(e),report:this.report,meshCount:this.reportedMeshes,triangleCount:this.triangleCount,placementCount:this.placementCount,mergedShapes:this.mergedShapes,droppedNoTemplate:this.droppedNoTemplate,skippedForBudget:this.skippedForBudget,warnings:this.warnings.concat(e.warnings||[])}}_overBudget(){return this.triangleCount>=this.maxTriangles||this.placementCount>=this.maxPlacements}_accountGeometry(e){let t=e.index?e.index.count/3:e.getAttribute(`position`).count/3;return this._countedGeometries.has(e)||(this._countedGeometries.add(e),this.triangleCount+=t),t}async _buildInstances(e,t){let n=0;e.skippedInstances>0&&(this.skippedForBudget+=e.skippedInstances);let i=new Float64Array(16),a=new r.Matrix4,o=(e,o,s,c,l,u,d)=>{let f=Math.max(0,this.maxPlacements-this.placementCount),p=Math.min(e.count,f);if(p<e.count&&(this.skippedForBudget+=e.count-p),p===0)return;let m=new r.InstancedMesh(o,s,p);m.name=`instance_${n++}`,m.frustumCulled=!1;for(let t=0;t<p;t++){if(c)GO(i,e.matrices,t*16,c);else for(let n=0;n<16;n++)i[n]=e.matrices[t*16+n];m.setMatrixAt(t,a.fromArray(this.convertHandedness?KO(BA,i):i))}m.instanceMatrix.needsUpdate=!0,t.add(m),this.placementCount+=p,this.reportedMeshes+=p,this.report.length<HA&&this.report.push({mesh:`${m.name} ×${p}`,shape:l,material:u,color:`#`+s.color.getHexString(),map:s.map?`yes`:`-`,uv:o.getAttribute(`uv`)?`yes`:`NO`,normals:o.getAttribute(`normal`)?`yes`:`NO`,emissive:s.emissiveIntensity>0?`#${s.emissive.getHexString()}×${s.emissiveIntensity}`:`-`,size:`instanced`,tris:d})},s=(e,t)=>{t&&t.triangles>0&&o(e,this._batchGeometry(t),t.material,null,`merged`,`-`,t.triangles)};for(let{name:t,list:n,template:r}of this._samePlacementGroups(e)){if(!r){this.droppedNoTemplate+=n.count,this.warn(`ObjectInstance "${t}" has no template — ${n.count.toLocaleString()} placement(s) dropped`);continue}let e=0;for(let t of r)t.type!==`plymesh`&&e++;let i=e>=2?new Map:null;for(let e of r){if(this._overBudget()){this.skippedForBudget+=n.count;continue}let[r,a]=await Promise.all([this._buildGeometry(e),this._getMaterial(e)]);if(!r)continue;if(i&&e.type!==`plymesh`&&r.getAttribute(`position`).count<=KA){this._geometryCache.delete(e);let t=this._appendToBatch(i,e,r,a,e.relativeCTM||e.ctm);this._releaseMerged(e,r),s(n,t);continue}let c=this._accountGeometry(r);o(n,r,this._materialForGeometry(e,r,a,`instances_${t}`),e.relativeCTM||e.ctm,e.type,e.material?.type||`diffuse`,c)}if(i)for(let e of i.values())s(n,e[0]),s(n,e[1]);pO(n.matrices),pO(n.matricesEnd)}}_samePlacementGroups(e){let t=[],n=new Map;for(let[r,i]of e.instances){let a=e.objects.get(r);if(!a||i.matricesEnd){t.push({name:r,list:i,template:a});continue}let o=`${i.count}:${Array.prototype.join.call(i.matrices.subarray(0,16),`,`)}`,s=n.get(o);s||n.set(o,s=[]);let c=s.find(e=>yA(e.list,i));if(c){c.template===e.objects.get(c.name)&&(c.template=c.template.slice());for(let e of a)c.template.push(e);pO(i.matrices);continue}let l={name:r,list:i,template:a};s.push(l),t.push(l)}return t}async _buildAnimatedPlacements(e,t){let n=e.animatedInstances??[];for(let i=0;i<n.length;i++){let{name:a,motion:o}=n[i],s=e.objects.get(a);if(!s){this.droppedNoTemplate++;continue}if(this._overBudget()){this.skippedForBudget+=n.length-i;break}let c=new r.Group;c.name=`placement_${i}`;let l=Array.from(o.matrices.subarray(0,16));new r.Matrix4().fromArray(this.convertHandedness?KO(BA,l):l).decompose(c.position,c.quaternion,c.scale);for(let e=0;e<s.length;e++){let t=s[e],[n,r]=await Promise.all([this._buildGeometry(t),this._getMaterial(t)]);if(!n)continue;let i=this._meshFromGeometry(t,n,r,t.relativeCTM||t.ctm,`${c.name}_${e}`,!0);i&&c.add(i)}c.children.length!==0&&(t.add(c),this._animate(c,o))}}_animate(e,t){t.visible&&(e.visible=t.visible[0]===1),this._animated.push({node:e,motion:t})}_buildClip(e,t){let n=[];for(let{node:e,motion:t}of this._animated)if(this._transformTracks(n,e.name,t,(e,t)=>{let n=Array.from(e.subarray(t,t+16));return this.convertHandedness?KO(BA,n):n}),t.visible){let i=t.times,a=i.map((e,t)=>t===0?0:(i[t-1]+e)/2);n.push(new r.BooleanKeyframeTrack(`${e.name}.visible`,a,Array.from(t.visible,e=>e===1)))}let i=e.camera?.motion;if(t&&i){let e=new r.PerspectiveCamera;if(this._transformTracks(n,t.name,i,(t,n)=>(this._poseCamera(e,t.subarray(n,n+16)),e.updateMatrix(),e.matrix.elements)),i.fov&&t.isPerspectiveCamera){let e=Array.from(i.fov,e=>this._verticalFov({fov:{type:`float`,value:[e]}},t.aspect));n.push(new r.NumberKeyframeTrack(`${t.name}.fov`,i.times.slice(),e))}}for(let e of n)e.optimize();return n.length===0?[]:[new r.AnimationClip(e.animation.name,e.animation.duration,n)]}_transformTracks(e,t,n,i){let a=n.times.length,o=new Float32Array(a*3),s=new Float32Array(a*4),c=new Float32Array(a*3),l=new r.Matrix4,u=new r.Vector3,d=new r.Quaternion,f=new r.Vector3;for(let e=0;e<a;e++)l.fromArray(i(n.matrices,e*16)).decompose(u,d,f),e>0&&d.x*s[e*4-4]+d.y*s[e*4-3]+d.z*s[e*4-2]+d.w*s[e*4-1]<0&&d.set(-d.x,-d.y,-d.z,-d.w),u.toArray(o,e*3),d.toArray(s,e*4),f.toArray(c,e*3);let p=(e,t)=>{for(let n=t;n<e.length;n++)if(e[n]!==e[n%t])return!0;return!1};p(o,3)&&e.push(new r.VectorKeyframeTrack(`${t}.position`,n.times.slice(),o)),p(s,4)&&e.push(new r.QuaternionKeyframeTrack(`${t}.quaternion`,n.times.slice(),s)),p(c,3)&&e.push(new r.VectorKeyframeTrack(`${t}.scale`,n.times.slice(),c))}async _buildShapeMesh(e,t,n){let[r,i]=await Promise.all([this._buildGeometry(e),this._getMaterial(e)]);return r?this._meshFromGeometry(e,r,i,t,n):null}_meshFromGeometry(e,t,n,i,a,o=!1){let s=!!t.getAttribute(`uv`),c=this._materialForGeometry(e,t,n,a),l=new r.Mesh(t,c);l.name=a;let u=this.convertHandedness&&!o?KO(BA,i):i;new r.Matrix4().fromArray(u).decompose(l.position,l.quaternion,l.scale),l.updateMatrix(),t.boundingBox||t.computeBoundingBox();let d=t.boundingBox?t.boundingBox.clone().applyMatrix4(l.matrix).getSize(new r.Vector3):new r.Vector3,f=this._accountGeometry(t);return this.placementCount++,this.reportedMeshes++,this.report.length<HA&&this.report.push({mesh:a,shape:e.type,material:e.material?.type||`diffuse`,color:`#`+c.color.getHexString(),map:c.map?`yes`:`-`,uv:s?`yes`:`NO`,normals:t.getAttribute(`normal`)?`yes`:`NO`,emissive:c.emissiveIntensity>0?`#${c.emissive.getHexString()}×${c.emissiveIntensity}`:`-`,size:`${d.x.toFixed(2)}×${d.y.toFixed(2)}×${d.z.toFixed(2)}`,tris:f}),l}_materialForGeometry(e,t,n,r){if(!n.map||t.getAttribute(`uv`))return n;let i=this._noUVMaterials.get(n);return i||(this.warn(`${r} (${e.type}, "${e.material?.type||`diffuse`}") has a texture map but no UVs — dropping map, using base color`),i=FA(n),i.map=null,this._noUVMaterials.set(n,i)),i}_mergeShape(e,t,n,r){this.reportedMeshes++;let i=this.convertHandedness?KO(BA,e.ctm):e.ctm,a=this._appendToBatch(this._batches,e,t,n,i);this._releaseMerged(e,t),a&&this._flushBatch(a,r)}_releaseMerged(e,t){if(!this._keepShapes?.has(e)&&!(e.type===`plymesh`&&!this._lastPlyUse(vk(e.params,`filename`,null)))){for(let e in t.attributes)pO(t.attributes[e].array);pO(t.index?.array);for(let t in e.params)ArrayBuffer.isView(e.params[t]?.value)&&pO(e.params[t].value)}}_lastPlyUse(e){let t=(this._plyUsers.get(e)??1)-1;return this._plyUsers.set(e,t),t>0||this._plyHeld.has(e)?!1:(this._plyCache.delete(e),!0)}_appendToBatch(e,t,n,r,i){let a=this._materialForGeometry(t,n,r,`merged shape`),o=n.getAttribute(`position`),s=n.getAttribute(`normal`),c=n.getAttribute(`uv`),l=n.index,u=o.count;this.triangleCount+=(l?l.count:u)/3,this.mergedShapes++;let d=e.get(a);d||e.set(a,d=[null,null]);let f=+!!c,p=d[f];p||(d[f]=p={material:a,positions:new Float32Array(3072),normals:new Float32Array(3072),uvs:c?new Float32Array(2048):null,indices:new Uint32Array(3072),vertexCount:0,indexCount:0,triangles:0});let m=i,h=ek(m),g=p.vertexCount;p.positions=_A(p.positions,(g+u)*3),p.normals=_A(p.normals,(g+u)*3),c&&(p.uvs=_A(p.uvs,(g+u)*2));let _=o.array,v=p.positions,y=s?s.array:null,b=p.normals;for(let e=0;e<u;e++){let t=e*3,n=(g+e)*3,r=_[t],i=_[t+1],a=_[t+2];if(v[n]=m[0]*r+m[4]*i+m[8]*a+m[12],v[n+1]=m[1]*r+m[5]*i+m[9]*a+m[13],v[n+2]=m[2]*r+m[6]*i+m[10]*a+m[14],!y)continue;let o=y[t],s=y[t+1],c=y[t+2],l=h[0]*o+h[1]*s+h[2]*c,u=h[4]*o+h[5]*s+h[6]*c,d=h[8]*o+h[9]*s+h[10]*c,f=Math.hypot(l,u,d);f>0&&(l/=f,u/=f,d/=f),b[n]=l,b[n+1]=u,b[n+2]=d}c&&p.uvs.set(c.array.subarray(0,u*2),g*2);let x=l?l.count:u;p.indices=_A(p.indices,p.indexCount+x);let S=p.indices,C=l?l.array:null;for(let e=0;e<x;e++)S[p.indexCount+e]=g+(C?C[e]:e);return p.vertexCount+=u,p.indexCount+=x,p.triangles+=x/3,p.triangles>=qA?(d[f]=null,p):null}_batchGeometry(e){let t=new r.BufferGeometry;return t.setAttribute(`position`,new r.Float32BufferAttribute(mO(e.positions,e.vertexCount*3),3)),t.setAttribute(`normal`,new r.Float32BufferAttribute(mO(e.normals,e.vertexCount*3),3)),e.uvs&&t.setAttribute(`uv`,new r.Float32BufferAttribute(mO(e.uvs,e.vertexCount*2),2)),t.setIndex(new r.Uint32BufferAttribute(mO(e.indices,e.indexCount),1)),e.positions=e.normals=e.uvs=e.indices=null,t}_flushBatch(e,t){if(!e||e.triangles===0)return;let n=new r.Mesh(this._batchGeometry(e),e.material);n.name=`merged_${this._mergedBatches++}`,n.frustumCulled=!1,t.add(n),this.placementCount++,this.report.length<HA&&this.report.push({mesh:n.name,shape:`merged`,material:`-`,color:`#`+e.material.color.getHexString(),map:e.material.map?`yes`:`-`,uv:e.uvs?`yes`:`NO`,normals:`yes`,emissive:e.material.emissiveIntensity>0?`#${e.material.emissive.getHexString()}×${e.material.emissiveIntensity}`:`-`,size:`merged`,tris:e.triangles})}_buildGeometry(e){let t=this._geometryCache.get(e);return t||this._geometryCache.set(e,t=this._createGeometry(e)),t}async _createGeometry(e){let t=await this._shapeGeometry(e);return t&&e.areaLight&&!yk(e.areaLight.params,`twosided`,!1)?this._facingEmission(e,t):t}_facingEmission(e,t){let n=t.userData.pbrtNormals?t.getAttribute(`normal`):null;if(!n&&!e.reverseOrientation)return t;let i=t.getAttribute(`position`).array,a=n?.array,o=t.index?.array??null,s=o?o.length:t.getAttribute(`position`).count,c=new Uint32Array(s),l=0;for(let t=0;t+2<s;t+=3){let n=o?o[t]:t,r=o?o[t+1]:t+1,s=o?o[t+2]:t+2,u=e.reverseOrientation;if(a){let e=i[r*3]-i[n*3],t=i[r*3+1]-i[n*3+1],o=i[r*3+2]-i[n*3+2],c=i[s*3]-i[n*3],l=i[s*3+1]-i[n*3+1],d=i[s*3+2]-i[n*3+2],f=a[n*3]+a[r*3]+a[s*3],p=a[n*3+1]+a[r*3+1]+a[s*3+1],m=a[n*3+2]+a[r*3+2]+a[s*3+2];u=(t*d-o*l)*f+(o*c-e*d)*p+(e*l-t*c)*m<0}c[t]=n,c[t+1]=u?s:r,c[t+2]=u?r:s,u&&l++}if(l===0)return t;let u=new r.BufferGeometry;for(let e in t.attributes)u.setAttribute(e,t.getAttribute(e));return u.setIndex(new r.Uint32BufferAttribute(c,1)),u}_shapeGeometry(e){switch(e.type){case`trianglemesh`:return this._triangleMesh(e.params);case`bilinearmesh`:return this._bilinearMesh(e.params);case`loopsubdiv`:return this._loopSubdiv(e.params);case`curve`:return this._curve(e.params);case`plymesh`:return this._plyMesh(e.params);case`sphere`:return this._sphere(e.params);case`disk`:return this._disk(e.params);case`cylinder`:return this._cylinder(e.params);default:return this.warn(`shape "${e.type}" not supported — skipped`),null}}_triangleMesh(e){let t=e.P?.value;if(!t||t.length<9)return this.warn(`trianglemesh missing P`),null;let n=new r.BufferGeometry;n.setAttribute(`position`,new r.Float32BufferAttribute(vA(t),3));let i=e.N?.value;i&&i.length===t.length&&(n.setAttribute(`normal`,new r.Float32BufferAttribute(vA(i),3)),n.userData.pbrtNormals=!0);let a=(e.uv||e.st)?.value;a&&a.length===t.length/3*2&&n.setAttribute(`uv`,new r.Float32BufferAttribute(vA(a),2));let o=e.indices?.value;return o&&o.length&&n.setIndex(gA(o)),i||n.computeVertexNormals(),n}_curve(e){let t=e.P?.value;if(!t||t.length<12)return this.warn(`curve needs at least 4 control points`),null;let n=Math.round(_k(e,`degree`,3));if(n!==3)return this.warn(`curve degree ${n} not supported — only cubic`),null;let i=vk(e,`type`,`flat`),a=_k(e,`width`,1),o=fA({P:t,basis:vk(e,`basis`,`bezier`),width0:_k(e,`width0`,a),width1:_k(e,`width1`,a),N:e.N?.value||null,steps:this.curveSteps,sides:this.curveSides??YA[i]??1,tolerance:this.curveTolerance});if(!o)return this.warn(`curve could not be tessellated`),null;let s=new r.BufferGeometry;return s.setAttribute(`position`,new r.Float32BufferAttribute(o.positions,3)),s.setIndex(new r.Uint32BufferAttribute(o.indices,1)),s.computeVertexNormals(),s}_loopSubdiv(e){let t=e.P?.value,n=e.indices?.value;if(!t||t.length<9||!n||n.length<3)return this.warn(`loopsubdiv missing P/indices`),null;let i=Math.max(0,Math.min(6,Math.round(_k(e,`levels`,3)))),{positions:a,indices:o,levels:s}=Xk(t,n,i);s<i&&this.warn(`loopsubdiv refined ${s}/${i} levels — the control mesh is too dense for the triangle budget`);let c=new r.BufferGeometry;return c.setAttribute(`position`,new r.Float32BufferAttribute(a,3)),c.setIndex(new r.Uint32BufferAttribute(o,1)),c.computeVertexNormals(),c}_bilinearMesh(e){let t=e.P?.value,n=e.indices?.value??(t?.length===12?[0,1,2,3]:null);if(!t||!n)return this.warn(`bilinearmesh missing P/indices`),null;let i=t.length/3,a=e.uv?.value?.length===i*2?e.uv.value:null,o=e.N?.value?.length===i*3?e.N.value:null,s=new r.BufferGeometry;if(a){let e=[];for(let t=0;t+3<n.length;t+=4){let[r,i,a,o]=[n[t],n[t+1],n[t+2],n[t+3]];e.push(r,i,o,r,o,a)}s.setAttribute(`position`,new r.Float32BufferAttribute(Float32Array.from(t),3)),s.setAttribute(`uv`,new r.Float32BufferAttribute(Float32Array.from(a),2)),o&&s.setAttribute(`normal`,new r.Float32BufferAttribute(Float32Array.from(o),3)),s.setIndex(new r.Uint32BufferAttribute(new Uint32Array(e),1))}else{let e=Math.floor(n.length/4),i=new Float32Array(e*12),a=o?new Float32Array(e*12):null,c=new Float32Array(e*8),l=new Uint32Array(e*6);for(let r=0;r<e;r++){for(let e=0;e<4;e++){let s=n[r*4+e];for(let n=0;n<3;n++)i[r*12+e*3+n]=t[s*3+n],a&&(a[r*12+e*3+n]=o[s*3+n]);c[r*8+e*2]=e&1,c[r*8+e*2+1]=e>>1}l.set([0,1,3,0,3,2].map(e=>r*4+e),r*6)}s.setAttribute(`position`,new r.Float32BufferAttribute(i,3)),s.setAttribute(`uv`,new r.Float32BufferAttribute(c,2)),a&&s.setAttribute(`normal`,new r.Float32BufferAttribute(a,3)),s.setIndex(new r.Uint32BufferAttribute(l,1))}return o?s.userData.pbrtNormals=!0:s.computeVertexNormals(),s}_plyMesh(e){let t=vk(e,`filename`,null);if(!t)return this.warn(`plymesh missing filename`),null;let n=this._plyCache.get(t);return n||this._plyCache.set(t,n=this._decodePly(t)),n}async _decodePly(e){try{let t=await this.resolvePLY(e);return t?(t.getAttribute(`normal`)?t.userData.pbrtNormals=!0:t.computeVertexNormals(),t):(this.warn(`plymesh file not found: ${e}`),null)}catch(t){return this.warn(`failed to load plymesh ${e}: ${t.message}`),null}}_sphere(e){let{radius:t,zMin:n,zMax:r,phiMax:i}=kA(e),a=Math.acos(n/t),o=Math.acos(r/t);return MA(i,Math.max(1,Math.ceil(32*(a-o)/Math.PI)),(e,n,r,s)=>{let c=e*i,l=a+n*(o-a);s.set(Math.sin(l)*Math.cos(c),Math.sin(l)*Math.sin(c),Math.cos(l)),r.copy(s).multiplyScalar(t)})}_cylinder(e){let{radius:t,zMin:n,zMax:r,phiMax:i}=AA(e);return MA(i,1,(e,a,o,s)=>{let c=e*i;s.set(Math.cos(c),Math.sin(c),0),o.set(t*s.x,t*s.y,n+a*(r-n))})}_disk(e){let{radius:t,inner:n,height:r,phiMax:i}=jA(e);return MA(i,1,(e,a,o,s)=>{let c=e*i,l=t-a*(t-n);o.set(l*Math.cos(c),l*Math.sin(c),r),s.set(0,0,1)})}async _getMaterial(e){let t=await this._surfaceMaterial(e);return e.interior&&(t=await this._inMedium(t,e.interior)),e.params.alpha?this._withAlpha(t,e.params.alpha):t}_withAlpha(e,t){let n=t.type===`texture`?t.value[0]:`#${t.value[0]}`,r=this._alphaMaterials.get(e);return r||this._alphaMaterials.set(e,r=new Map),r.has(n)||r.set(n,this._createAlphaMaterial(e,t)),r.get(n)}async _createAlphaMaterial(e,t){if(t.type!==`texture`)return t.value[0]<1?IA(e,t.value[0]):e;let n=t.value[0],r=await this._alphaMap(e.map,n);if(!r)return this.warn(`shape alpha "${n}" could not be read here — drawn opaque`),e;if(r.constant!==void 0)return r.constant<1?IA(e,r.constant):e;let i=FA(e);return i.map=r,i.transparent=!0,i}async _alphaMap(e,t){let n=this.ir.namedTextures.get(t),r=n?.class===`imagemap`?vk(n.params,`filename`,null):null;if(r&&e?.userData.pbrtImage===r&&vk(n.params,`mapping`,`uv`)===`uv`&&_k(n.params,`scale`,1)===1&&!yk(n.params,`invert`,!1)&&tj(e,CA(n.params))){let t=xA(e),r=t&&LA(t,SA(n.params));if(r)return wA(r,CA(n.params)),r}let i=await this._bakeTerm(t,1);if(!i)return null;if(!i.layer)return{constant:i.rgb[0]};let a=e?this._textureLayer(e,3):null;if(e&&!a)return null;let o=zk([a?{layer:a}:{rgb:[1,1,1]},i],([e])=>e,{alphaOf:([,e])=>e[0]});return o&&EA(o)}async _surfaceMaterial(e){let t=this._materialCache.get(e.material);if(t||(t=new Map,this._materialCache.set(e.material,t)),t.has(e.areaLight))return t.get(e.areaLight);let n=this._materialContext(),r=await Ok(e.material,n);e.areaLight&&await this._applyAreaLight(r,e.areaLight,n);let i=this._dedupeMaterial(r);return t.set(e.areaLight,i),i}_materialContext(){return this._ctx??={resolveNamedTexture:e=>this._resolveNamedTexture(e),namedMaterials:this.ir.namedMaterials,warn:e=>this.warn(e),floatTextureMean:async e=>{let t=await this._bakeTerm(e,1);return t?t.layer?Lk(t.layer):t.rgb[0]:null},bakeMaterialMix:(e,t,n)=>this._bakeMaterialMix(e,t,n),bakeFloatMap:(e,t,n)=>this._floatMap(e,t,n),textureMeanRGB:async e=>{let t=await this._bakeTerm(e,3);if(!t?.layer)return t?.rgb??null;let{data:n}=t.layer,r=[0,0,0];for(let e=0;e<n.length;e++)r[e%3]+=n[e];return r.map((e,r)=>e/(n.length/3)*(t.tint?.[r]??1))},resolveNormalMap:async e=>{let t=await this._image(e);if(!t)return null;let n=TA(t,{srgb:!1}),i=n===t?t.clone():n;return i.colorSpace=r.NoColorSpace,i}}}async _inMedium(e,t){if(!(e.transmission>0))return e;let n=this._mediumMaterials.get(e);return n||this._mediumMaterials.set(e,n=new Map),n.has(t)||n.set(t,this._attenuated(e,t)),n.get(t)}async _attenuated(e,t){let n=this.ir.media?.get(t),r=n&&vk(n,`type`,``);if(r!==`homogeneous`)return this.warn(n?`medium "${t}" (${r}) is not supported — "${t}" glass left clear`:`medium "${t}" not defined`),e;n.preset&&this.warn(`medium preset "${vk(n,`preset`,``)}" is not supported — using sigma_a / sigma_s`);let i=this._materialContext(),a=(await bk(n,`sigma_a`,i,[1,1,1])).rgb,o=(await bk(n,`sigma_s`,i,[1,1,1])).rgb,s=_k(n,`scale`,1),c=[0,1,2].map(e=>(a[e]+o[e])*s),l=Math.max(...c);if(!(l>0))return e;let u=FA(e);return u.attenuationDistance=1/l,u.attenuationColor.setRGB(...c.map(e=>Math.exp(-e/l))),this._dedupeMaterial(u)}_dedupeMaterial(e){let t=e.color,n=e.emissive,r=`${t.r},${t.g},${t.b}|${n.r},${n.g},${n.b}|${e.emissiveIntensity}|${e.map?e.map.uuid:`-`}|${e.roughness}|${e.roughnessMap?.uuid??`-`}|${e.metalness}|${e.transmission}|${e.ior}|${e.thickness}|${e.clearcoat}|${e.clearcoatRoughness}|${e.clearcoatRoughnessMap?.uuid??`-`}|${e.opacity}|${e.side}|${e.normalMap?e.normalMap.uuid:`-`}|${e.attenuationDistance}|${e.attenuationColor.toArray()}|${e.specularIntensity}|${e.diffuseTransmission??0}|${e.diffuseTransmissionColor?.toArray()??`-`}|${e.subsurface??0}|${e.subsurfaceColor?.toArray()??`-`}|${e.subsurfaceRadius??`-`}|${e.subsurfaceAnisotropy??0}`;return this._materialBySignature.get(r)||(this._materialBySignature.set(r,e),e)}_poweredMaterial(e,t,n){let r=_k(e.areaLight.params,`power`,-1);if(!(r>0))return n;let i=NA(e,t)*(yk(e.areaLight.params,`twosided`,!1)?2:1);if(!(i>0))return n;let a=FA(n);return a.emissiveIntensity=n.emissiveIntensity*r/(Math.PI*i),a}async _applyAreaLight(e,t,n){let i=await hA(t.params,`L`,n),a=_k(t.params,`scale`,1);e.emissive.setRGB(i[0],i[1],i[2]),e.emissiveIntensity=a,e.side=yk(t.params,`twosided`,!1)?r.DoubleSide:r.FrontSide}async _resolveNamedTexture(e){if(this._textureCache.has(e))return this._textureCache.get(e);let t=this.ir.namedTextures.get(e),n=null;if(!t)this.warn(`named texture "${e}" not defined`);else if(t.class===`imagemap`)n=await this._imageMapTexture(e,t);else if(t.class===`mix`)n=await this._mixTexture(e,t);else if(t.class===`constant`){let e=t.params.value;e&&e.type===`rgb`?n={constant:[e.value[0],e.value[1],e.value[2]]}:e&&(n={constant:[e.value[0],e.value[0],e.value[0]]})}else if(t.class===`checkerboard`||t.class===`bilerp`)n=await this._proceduralTexture(e,t);else if(t.class===`scale`)n=await this._resolveScaleTexture(e,t);else{let r=this._colorFromLikeNamedMaterial(e);r?(n={constant:r.rgb},this._recoveredColors++):this.warn(`texture class "${t.class}" not supported (texture "${e}")`)}return this._textureCache.set(e,n),n}async _proceduralTexture(e,t){let n=t.params,r=this._materialContext(),i=async(e,t)=>{let i=n[e];return i?.type===`texture`?await r.textureMeanRGB(i.value[0])??t:(await bk(n,e,r,t)).rgb??t},a=vk(n,`mapping`,`uv`);a!==`uv`&&this.warn(`texture "${e}": "${a}" mapping is not supported — using the mesh's uv`);let{su:o,sv:s,du:c,dv:l}=CA(n);if(t.class===`checkerboard`){if(_k(n,`dimension`,2)!==2)return this.warn(`texture "${e}": a 3D checkerboard is not supported`),null;let[t,r]=await Promise.all([i(`tex1`,[1,1,1]),i(`tex2`,[0,0,0])]),a=2*$A;return{texture:EA({data:PA(a,a,(e,n)=>(Math.floor(2*e)+Math.floor(2*n))%2?r:t),width:a,height:a,mapping:{su:o/2,sv:s/2,du:c/2,dv:l/2}})}}let[u,d,f,p]=await Promise.all([i(`v00`,[0,0,0]),i(`v01`,[1,1,1]),i(`v10`,[0,0,0]),i(`v11`,[1,1,1])]);return{texture:EA({data:PA(ej,ej,(e,t)=>[0,1,2].map(n=>(1-e)*(1-t)*u[n]+e*(1-t)*f[n]+(1-e)*t*d[n]+e*t*p[n])),width:ej,height:ej,mapping:{su:o,sv:s,du:c,dv:l}})}}_image(e){let t=this._imageCache.get(e);return t||(t=Promise.resolve().then(()=>this.resolveImage(e)).catch(t=>(this.warn(`failed to load image ${e}: ${t.message}`),null)),this._imageCache.set(e,t)),t}async _imageMapTexture(e,t){let n=vk(t.params,`filename`,null);if(!n)return null;let r=await this._image(n);if(!r)return this.warn(`image not found for texture "${e}": ${n}`),null;let i=vk(t.params,`mapping`,`uv`);i!==`uv`&&this.warn(`texture "${e}": "${i}" mapping is not supported — using the mesh's uv`);let a=_k(t.params,`scale`,1);if(a>1||yk(t.params,`invert`,!1)){let t=await this._bakeTerm(e,3),n=t?.layer&&zk([{...t,clamp:!0}],([e])=>e);if(n)return{texture:EA(n)};this.warn(`texture "${e}": its scale or invert could not be baked here — ignored`)}let o=TA(r,{srgb:!0}),s=o===r?r.clone():o;return s.userData.pbrtImage=n,wA(s,CA(t.params)),s.needsUpdate=!0,a<1?{texture:s,constant:[a,a,a]}:{texture:s}}async _floatMap(e,t,n){let r=await Promise.all(t.map(t=>this._paramTerm(e,t,1,[0,0,0])));if(r.some(e=>!e))return null;let i=zk(r,e=>{let t=n(e.map(e=>e[0]));return[t,t,t]},{linear:!0});return i&&EA(i,{srgb:!1})}async _mixTexture(e,t){let[n,r,i]=await Promise.all([this._paramTerm(t.params,`tex1`,3,[0,0,0]),this._paramTerm(t.params,`tex2`,3,[1,1,1]),this._paramTerm(t.params,`amount`,1,[.5,.5,.5])]);if(!n||!r||!i)return this.warn(`texture "${e}": a "mix" input could not be read here`),null;let a=e=>e.map(e=>Math.min(1,Math.max(0,e))),o=zk([{...n,clamp:!0},{...r,clamp:!0},i],Uk);return o?{texture:EA(o)}:{constant:Uk([a(n.rgb),a(r.rgb),i.rgb])}}async _paramTerm(e,t,n,r){let i=e[t];if(!i)return{rgb:r};if(i.type===`texture`)return this._bakeTerm(i.value[0],n);let a=(await bk(e,t,this._materialContext(),r)).rgb;return a?{rgb:a}:null}_bakeTerm(e,t){let n=`${e}\0${t}`,r=this._termCache.get(n);return r||this._termCache.set(n,r=this._createBakeTerm(e,t)),r}async _createBakeTerm(e,t){let n=this.ir.namedTextures.get(e);if(n?.class===`imagemap`){if(vk(n.params,`mapping`,`uv`)!==`uv`)return null;let e=vk(n.params,`filename`,null),r=xA(e&&await this._image(e));return r?{layer:Fk(r,{channels:t,decode:r.float?null:SA(n.params),scale:_k(n.params,`scale`,1),invert:yk(n.params,`invert`,!1),mapping:CA(n.params)})}:null}let r=await this._resolveNamedTexture(e);if(!r)return null;if(!r.texture)return r.constant?{rgb:r.constant}:null;let i=this._textureLayer(r.texture,t);return i?{layer:i,tint:r.constant??null}:null}_textureLayer(e,t){let n=xA(e);if(!n)return null;let i=!n.float&&e.colorSpace===r.SRGBColorSpace;return Fk(n,{channels:t,decode:n.float?null:i?Vk:e=>e,mapping:{su:e.repeat.x,sv:e.repeat.y,du:e.offset.x,dv:e.offset.y}})}async _bakeMaterialMix(e,t,n){let r=await this._bakeTerm(n,1);if(!r)return null;if(!r.layer)return{mean:r.rgb[0],texture:null};let i=Lk(r.layer),a=e=>{if(!e.map)return{rgb:e.color.toArray(),clamp:!0};let t=this._textureLayer(e.map,3);return t&&{layer:t,tint:e.color.toArray(),clamp:!0}},o=a(e),s=a(t);if(!o||!s)return{mean:i,texture:null};let c=zk([o,s,r],Uk);return{mean:i,texture:c?EA(c):null}}_colorFromLikeNamedMaterial(e){for(let t of RA(e)){let e=(this.ir?.namedMaterials?.get(t))?.params?.reflectance;if(e&&(e.type===`rgb`||e.type===`color`))return{name:t,rgb:[e.value[0],e.value[1],e.value[2]]}}return null}async _resolveScaleTexture(e,t){if(t.params.scale?.type===`texture`){let[n,r]=await Promise.all([this._paramTerm(t.params,`tex`,3,[1,1,1]),this._paramTerm(t.params,`scale`,1,[1,1,1])]),i=([e,t])=>[e[0]*t[0],e[1]*t[0],e[2]*t[0]];if(n&&r){let e=zk([{...n,clamp:!0},r],i);return e?{texture:EA(e)}:{constant:i([n.rgb,r.rgb])}}this.warn(`texture "${e}": its "scale" texture could not be read here — ignored`)}let n=t.params.tex,r=null;if(n?.type===`texture`&&typeof n.value[0]==`string`)r=await this._resolveNamedTexture(n.value[0]);else if(n?.type===`rgb`||n?.type===`color`)r={constant:[n.value[0],n.value[1],n.value[2]]};else if(n?.type===`float`){let e=n.value[0];r={constant:[e,e,e]}}let i=t.params.scale,a=[1,1,1];if(i?.type===`rgb`||i?.type===`color`)a=[i.value[0],i.value[1],i.value[2]];else if(i?.type===`float`){let e=i.value[0];a=[e,e,e]}if(r?.texture){let e=r.constant||[1,1,1];return{texture:r.texture,constant:[e[0]*a[0],e[1]*a[1],e[2]*a[2]]}}let o=r?.constant||[1,1,1];return{constant:[o[0]*a[0],o[1]*a[1],o[2]*a[2]]}}_buildCamera(e,t){let n=t&&t.yresolution?t.xresolution/t.yresolution:16/9,i;if(e.type===`orthographic`){let t=e.params?.screenwindow?.value,a=t?.length===4?(t[3]-t[2])/2:Math.max(1,1/n);i=new r.OrthographicCamera(-a*n,a*n,a,-a,.01,1e4)}else i=new r.PerspectiveCamera(this._verticalFov(e.params,n),n,.01,1e4);i.name=`PBRT Camera`,this._poseCamera(i,e.cameraToWorld),i.updateMatrixWorld(!0);let a=_k(e.params,`lensradius`,0);return a>0&&(i.userData.__rayzeeEffects=DA(i,a,_k(e.params,`focaldistance`,1e6))),i}_poseCamera(e,t){let n=t,i=new r.Vector3(n[12],n[13],n[14]),a=new r.Vector3(n[8],n[9],n[10]),o=new r.Vector3(n[4],n[5],n[6]);this.convertHandedness&&(i.z*=-1,a.z*=-1,o.z*=-1),e.up.copy(o.normalize()),e.position.copy(i),e.scale.set(1,1,1),e.lookAt(i.clone().add(a)),WO(t)>0!==this.convertHandedness&&(e.scale.x=-1)}_verticalFov(e,t){let n=_k(e,`fov`,90);if(t>=1)return n;let r=n*Math.PI/180;return 2*Math.atan(Math.tan(r/2)/t)*180/Math.PI}_equirectFromInfiniteLight(e,t,n,i){let a=e.image;if(!a?.width||a.width!==a.height)return a?.width!==a?.height&&this.warn(`infinite-light image "${i}" is ${a?.width}x${a?.height}, not square — read as equirectangular, but pbrt would read it as equal-area octahedral`),null;let o=null;if(a.data){let e=a.data.length/(a.width*a.height);if(!Number.isInteger(e)||e<3)return null;o={data:a.data,width:a.width,height:a.height,channels:e,bottomUp:!0}}else if(o=bA(a,e.colorSpace===r.SRGBColorSpace),!o)return this.warn(`infinite-light image "${i}" could not be read back for octahedral conversion`),null;let{data:s,width:c,height:l}=eA(o,t.ctm,n),u=new r.DataTexture(s,c,l,r.RGBAFormat,r.FloatType);return u.mapping=r.EquirectangularReflectionMapping,u.minFilter=r.LinearFilter,u.magFilter=r.LinearFilter,u.needsUpdate=!0,u}async _buildEnvironment(e){let t=e.find(e=>e.type===`infinite`);if(!t)return null;let n=_k(t.params,`scale`,1),i=vk(t.params,`filename`,null);if(i)try{let e=await this.resolveEnvironment(i);if(e){let a=this._equirectFromInfiniteLight(e,t,n,i);return a?{texture:a}:(e.mapping=r.EquirectangularReflectionMapping,{texture:e})}this.warn(`infinite-light image not found: ${i}`)}catch(e){this.warn(`failed to load infinite-light image ${i}: ${e.message}`)}let a=(await hA(t.params,`L`,{resolveNamedTexture:async()=>null,warn:e=>this.warn(e)})).map(e=>e*n),o=new Float32Array(8);for(let e=0;e<2;e++)o[e*4+0]=a[0],o[e*4+1]=a[1],o[e*4+2]=a[2],o[e*4+3]=1;let s=new r.DataTexture(o,2,1,r.RGBAFormat,r.FloatType);return s.mapping=r.EquirectangularReflectionMapping,s.minFilter=r.LinearFilter,s.magFilter=r.LinearFilter,s.needsUpdate=!0,{texture:s}}async _buildLamps(e,t){let n={resolveNamedTexture:async()=>null,warn:e=>this.warn(e)};for(let i of e){if(!zA.has(i.type))continue;let e=new r.Matrix4().fromArray(this.convertHandedness?KO(BA,i.ctm):i.ctm),a=(t,n)=>{let a=i.params[t]?.value;return new r.Vector3().fromArray(a?.length>=3?a:n).applyMatrix4(e)},o=await hA(i.params,i.type===`distant`?`L`:`I`,n),s=_k(i.params,`scale`,1),c=a(`from`,[0,0,0]),l=a(`to`,[0,0,1]),u;if(i.type===`distant`){let e=_k(i.params,`illuminance`,-1);e>0&&(s*=e),u=new r.DirectionalLight,u.userData.__luxConverted=!0}else if(i.type===`point`){let e=_k(i.params,`power`,-1);s*=e>0?e:4*Math.PI,u=new r.PointLight,u.userData.__candelaConverted=!0}else{let e=Math.min(Math.max(_k(i.params,`coneangle`,30),0),90)*Math.PI/180,t=Math.min(Math.max(_k(i.params,`conedeltaangle`,5)*Math.PI/180,0),e),n=Math.cos(e),a=Math.cos(e-t),o=_k(i.params,`power`,-1);o>0&&(s*=o/(2*Math.PI*(1-a+(a-n)/2))),s*=4*Math.PI,u=new r.SpotLight,u.angle=e,u.penumbra=n<1?Math.min((a-n)/(1-n),1):0,u.userData.__candelaConverted=!0}let d=Math.max(o[0],o[1],o[2]);!(d>0)||!(s>0)||(u.color.setRGB(o[0]/d,o[1]/d,o[2]/d),u.intensity=d*s,u.name=`pbrt ${i.type}`,u.position.copy(c),u.decay=2,u.distance=0,u.target&&(u.target.position.subVectors(l,c),u.add(u.target)),t.add(u))}}_reportUnsupportedLights(e){for(let t of e)t.type!==`infinite`&&!zA.has(t.type)&&this.warn(`light "${t.type}" not supported (only infinite, distant, point and spot lights and emissive area lights are mapped)`)}}}));function ij(e){let t=e[0],n=e=>{let t=e.lastIndexOf(`/`),n=/^(.*?)(\d+)\.pbrt$/i.exec(e.slice(t+1));return n?{group:e.slice(0,t+1)+`\0`+n[1].toLowerCase(),number:parseInt(n[2],10)}:null},r=t?n(t):null;if(!r)return null;let i=new Map;for(let t of e){let e=n(t);e&&e.group===r.group&&!i.has(e.number)&&i.set(e.number,t)}return i.size<2?null:[...i].sort((e,t)=>e[0]-t[0]).slice(0,hj).map(([e,t])=>({path:t,number:e}))}function aj(e){let t=e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint32Array?new Uint32Array(e.buffer,e.byteOffset,e.length):null;t||=new Uint32Array(Float32Array.from(e).buffer);let n=2166136261;for(let e=0;e<t.length;e++)n=Math.imul(n^t[e],16777619),n^=n>>>15;return(n>>>0).toString(36)+`:`+e.length}function oj(e){let t=``;for(let n of Object.keys(e).sort()){let{type:r,value:i}=e[n],a=ArrayBuffer.isView(i)||i.length>16&&typeof i[0]==`number`;t+=`${r} ${n}=${a?`#`+aj(i):i.join(`,`)};`}return t}function sj(e,t){let n=new Int32Array(t.length).fill(-1),r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];)n[r]=r,r++;let i=e.length,a=t.length;for(;i>r&&a>r&&e[i-1]===t[a-1];)n[--a]=--i;return r<i&&r<a&&!cj(e,r,i,t,r,a,n)&&uj(e,r,i,t,r,a,n),n}function cj(e,t,n,r,i,a,o){let s=n-t,c=a-i,l=Math.min(s+c,gj),u=l+1,d=new Int32Array(2*l+3),f=[];for(let n=0;n<=l;n++){for(let a=-n;a<=n;a+=2){let l=a===-n||a!==n&&d[u+a-1]<d[u+a+1]?d[u+a+1]:d[u+a-1]+1,p=l-a;for(;l<s&&p<c&&e[t+l]===r[i+p];)l++,p++;if(d[u+a]=l,l>=s&&p>=c)return f.push(d.slice(u-n,u+n+1)),lj(f,s,c,t,i,o),!0}f.push(d.slice(u-n,u+n+1))}return!1}function lj(e,t,n,r,i,a){let o=t,s=n;for(let t=e.length-1;t>0;t--){let n=e[t-1],c=e=>n[e+t-1],l=o-s,u=l===-t||l!==t&&c(l-1)<c(l+1)?l+1:l-1,d=c(u),f=d-u;for(;o>d&&s>f;)a[i+--s]=r+--o;o=d,s=f}for(;o>0&&s>0;)a[i+--s]=r+--o}function uj(e,t,n,r,i,a,o){let s=new Map;for(let r=t;r<n;r++){let t=s.get(e[r]);t?t.push(r):s.set(e[r],[r])}let c=new Map;for(let e=i;e<a;e++){let t=s.get(r[e]);if(!t)continue;let n=c.get(r[e])??0;n<t.length&&(o[e]=t[n],c.set(r[e],n+1))}}function dj(e,t,n,r){for(let i=0;i<16;i++)if(e[t+i]!==n[r+i])return!1;return!0}function fj(e,t,n){let r=e.length,i=new Float32Array(16*r),a=null,o=-1;for(let e=0;e<r;e++)if(t(e)){if(i.set(n(e),e*16),o<0)for(let t=0;t<e;t++)i.copyWithin(t*16,e*16,e*16+16);o=e}else a??=new Uint8Array(r).fill(1),a[e]=0,o>=0&&i.copyWithin(e*16,o*16,o*16+16);return{times:e,matrices:i,visible:a}}function pj(e){if(e.visible)return!1;let t=e.matrices;for(let e=16;e<t.length;e+=16)if(!dj(t,0,t,e))return!1;return!0}function mj(e){if(!e.hasMotion)return e;let{start:t,end:n}=e.transformTimes,r=n-t;if(!(r>0))return e;let i=Float32Array.of(0,r),a=(e,t,n,r)=>{let a=new Float32Array(32);for(let i=0;i<16;i++)a[i]=e[t+i],a[16+i]=n[r+i];return{times:i,matrices:a,visible:null}};for(let t of e.shapes)t.ctmEnd&&(t.motion=a(t.ctm,0,t.ctmEnd,0));e.animatedInstances=[];for(let t of e.instances.values()){if(!t.matricesEnd)continue;let n=[];for(let r=0;r<t.count;r++){let i=r*16;dj(t.matrices,i,t.matricesEnd,i)||e.animatedInstances.length>=_j?n.push(r):e.animatedInstances.push({name:t.name,motion:a(t.matrices,i,t.matricesEnd,i)})}if(n.length!==t.count){let r=new Float32Array(n.length*16);n.forEach((e,n)=>r.set(t.matrices.subarray(e*16,e*16+16),n*16)),e.instanceCount-=t.count-n.length,t.matrices=r,t.count=n.length}t.matricesEnd=null}return e.camera?.cameraToWorldEnd&&(e.camera.motion={...a(e.camera.cameraToWorld,0,e.camera.cameraToWorldEnd,0),fov:null}),e.animation={name:`Shutter motion`,duration:r,frames:2},e}var hj,gj,_j,vj,yj,bj=g((()=>{hj=1e3,gj=2048,_j=1e5,vj=class{constructor(e){this.materialNames=new Map;for(let[t,n]of e.namedMaterials)this.materialNames.set(n,t);this.cache=new Map}of(e){return`${e.type}|${+!!e.reverseOrientation}|${oj(e.params)}|${this._material(e.material)}|${this._light(e.areaLight)}`}_material(e){if(!e)return`-`;let t=this.cache.get(e);if(t===void 0){let n=this.materialNames.get(e)??e._missingRef;t=n===void 0?`I:`+e.type+`:`+oj(e.params):`N:`+n,this.cache.set(e,t)}return t}_light(e){if(!e)return`-`;let t=this.cache.get(e);return t===void 0&&this.cache.set(e,t=`L:`+e.type+`:`+oj(e.params)),t}},yj=class{constructor(e,t){this.times=Float32Array.from(e),this.name=t,this.base=null,this.frame=-1,this.keyIds=new Map,this.tracks=[],this.prev=null,this.placements=new Map,this.templates=new Map,this.cameras=[],this.warnings=new Set}addFrame(e){let t=++this.frame;t===0?this.base=e:this._adoptDefinitions(e);for(let t of e.warnings)this.warnings.add(t);let n=new vj(e),r=new Int32Array(e.shapes.length);for(let t=0;t<r.length;t++){let i=n.of(e.shapes[t]),a=this.keyIds.get(i);a===void 0&&this.keyIds.set(i,a=this.keyIds.size),r[t]=a}let i=this.prev?sj(this.prev.keys,r):null,a=Array(r.length);for(let o=0;o<r.length;o++){let r=e.shapes[o],s=i&&i[o]>=0?this.prev.tracks[i[o]]:null;s?(s.last=t,s.ctms?s.ctms.push(r.ctm):r.ctm!==s.shape.ctm&&!dj(r.ctm,0,s.shape.ctm,0)&&(s.ctms=Array(t-s.first).fill(s.shape.ctm),s.ctms.push(r.ctm))):(s={shape:r,first:t,last:t,ctms:null},t>0&&this._adoptMaterial(r,n.materialNames),this.tracks.push(s)),a[o]=s}this.prev={keys:r,tracks:a},this._addPlacements(e,t,this._resolveTemplates(e,t,n)),this.cameras.push(e.camera?{cameraToWorld:e.camera.cameraToWorld,fov:e.camera.params?.fov?.value?.[0]}:null)}_adoptDefinitions(e){for(let[t,n]of e.namedMaterials)this.base.namedMaterials.has(t)||this.base.namedMaterials.set(t,n);for(let[t,n]of e.namedTextures)this.base.namedTextures.has(t)||this.base.namedTextures.set(t,n)}_resolveTemplates(e,t,n){let r=new Map;for(let[i,a]of e.objects){let e=``;for(let t of a)e+=n.of(t)+`@`+Array.prototype.join.call(t.relativeCTM||t.ctm,`,`)+`;`;let o=i+`\0`+e,s=this.templates.get(o);if(s===void 0&&(s=t===0||!this.base.objects.has(i)?i:`${i} @${t}`,this.templates.set(o,s),t>0)){for(let e of a)this._adoptMaterial(e,n.materialNames);this.base.objects.set(s,a)}r.set(i,s)}return r}_adoptMaterial(e,t){let n=e.material&&t.get(e.material);n!==void 0&&(e.material=this.base.namedMaterials.get(n)??e.material)}_addPlacements(e,t,n){for(let[r,i]of e.instances){let e=n.get(r)??r,a=this.placements.get(e);if(a||this.placements.set(e,a={counts:new Int32Array(this.times.length),diffs:new Map}),a.counts[t]=i.count,t===0)continue;let o=this.base.instances.get(e),s=o?.count??0;for(let e=0;e<i.count;e++){let n=e*16;if(e<s&&dj(i.matrices,n,o.matrices,n))continue;let r=a.diffs.get(e);r||a.diffs.set(e,r=new Map),r.set(t,i.matrices.slice(n,n+16))}}}finish(){let e=this.base,t=this.times,n=this.frame+1;e.shapes=this.tracks.map(e=>{let{shape:r,first:i,last:a,ctms:o}=e;return(i>0||a<n-1||o)&&(r.motion=fj(t,e=>e>=i&&e<=a,e=>o?o[e-i]:r.ctm)),r}),e.warnings=[...this.warnings],e.animatedInstances=this._finishPlacements(e,t,n);let r=this.cameras;if(r[0]&&r.every(Boolean)){let n=fj(t,()=>!0,e=>r[e].cameraToWorld),i=r.map(e=>e.fov??r[0].fov),a=i.some(e=>e!==i[0]);(!pj(n)||a)&&(e.camera.motion={...n,fov:a?Float32Array.from(i):null})}return e.animation={name:this.name,duration:t[n-1],frames:n},e}_finishPlacements(e,t,n){let r=[],i=0;for(let[a,{counts:o,diffs:s}]of this.placements){let c=e.instances.get(a),l=c?.count??0,u=Math.max(...o.subarray(0,n)),d=[];for(let e=0;e<u;e++){let u=s.get(e),f=!!u;for(let t=0;t<n&&!f;t++)f=e>=o[t];if(f&&r.length<_j){let n=fj(t,t=>e<o[t],t=>u?.get(t)??c.matrices.subarray(e*16,e*16+16));r.push({name:a,motion:n})}else f&&i++,e<l&&d.push(e)}if(c&&d.length!==l){let t=new Float32Array(d.length*16);d.forEach((e,n)=>t.set(c.matrices.subarray(e*16,e*16+16),n*16)),e.instanceCount-=l-d.length,c.matrices=t,c.matricesEnd=null,c.count=d.length}}return i>0&&e.warnings.push(`${i.toLocaleString()} moving placement(s) past ${_j.toLocaleString()} left static`),r}}}));function xj(e){let t=e.replace(/\\/g,`/`).split(`/`),n=[];for(let e of t)e===``||e===`.`||(e===`..`?n.pop():n.push(e));return n.join(`/`)}function Sj(e,t){return!e||t.startsWith(`/`)?xj(t):xj(`${e}/${t}`)}function Cj(e,t,n=0){let r=t[0],i=e.length-t.length;outer:for(let a=n;a<=i;a++)if(e[a]===r){for(let n=1;n<t.length;n++)if(e[a+n]!==t[n])continue outer;return a}return-1}function wj(e,t){for(let n=t-1;n>=0;n--){let t=e[n];if(t===10)return!0;if(t!==32&&t!==9)return!1}return!0}function Tj(e){for(let t=Cj(e,Rj);t>=0;t=Cj(e,Rj,t+1))if(wj(e,t))return!0;return!1}function Ej(e,t){for(let n of zj)for(let r=Cj(e,n);r>=0;r=Cj(e,n,r+1)){if(!wj(e,r))continue;let i=r+n.length;for(;i<e.length&&(e[i]===32||e[i]===9);)i++;if(e[i]!==34)continue;let a=++i;for(;i<e.length&&e[i]!==34&&e[i]!==10;)i++;if(e[i]!==34)continue;let o=Pj.decode(e.subarray(a,i));t.add(xj(o).toLowerCase().split(`/`).pop())}}function Dj(e){let t=Object.keys(e).filter(e=>e.toLowerCase().endsWith(`.pbrt`));if(t.length<=1)return t;let n=new Set,r=new Map;for(let i of t){let t=e[i];r.set(i,Tj(t)),Ej(t,n)}return Oj(t,r,n)}function Oj(e,t,n){let r=(e,t)=>{let n=e.filter(t);return n.length?n:e},i=r(e,e=>t.get(e));return i=r(i,e=>!n.has(e.toLowerCase().split(`/`).pop())),i=r(i,e=>/(^|\/)(scene|main)\.pbrt$/i.test(e)),i.sort((e,t)=>{let n=e.split(`/`).length,r=t.split(`/`).length;return n===r?e.length===t.length?e<t?-1:+(e>t):e.length-t.length:n-r})}function kj(e){return Dj(e)[0]||null}async function Aj(e){let t=e.records.filter(e=>e.norm.endsWith(`.pbrt`));if(t.length===0)return[];if(t.length===1)return[t[0].key];let n=async n=>{let r=new Set,i=new Map,a=!1;for(let o of t){let t=await n(o);t&&(i.set(o.key,Tj(t)),Ej(t,r),t.length>=Lj&&(a=!0),o.lazy&&(e.release(o),pO(t)))}return{included:r,worlds:i,cut:a}},r=await n(t=>e.readHead(t,Lj)),{included:i,worlds:a}=[...r.worlds.values()].filter(Boolean).length===1||!r.cut?r:await n(t=>e.read(t));return Oj(t.map(e=>e.key),a,i)}async function jj(e){let{vfs:t,source:n,plyParser:r,imageFromBytes:i,envFromBytes:a,convertHandedness:o}=e,s=new Fj(t,n),c=[],l=await Aj(s);if(l.length===0)throw Error(`PBRT loader: no .pbrt file found in archive`);let u=e.entryPath&&l.includes(e.entryPath)?e.entryPath:null;e.entryPath&&!u&&c.push(`PBRT entry "${e.entryPath}" is not a scene in this archive — auto-detecting instead`);let d=u||l[0],f=async t=>{let n=await s.readPath(t);if(!n)throw Error(`PBRT loader: entry "${t}" not readable`);let r=await new lk({resolveInclude:(e,t)=>s.readPath(e,t),releaseInclude:(e,t,n)=>s.releasePath(e,t,n),maxPlacements:e.maxPlacements,instanceIncludes:e.instanceIncludes}).parse(n,t.includes(`/`)?t.slice(0,t.lastIndexOf(`/`)):``);return s.releasePath(t,null,n),r},p=performance.now(),m=!u&&e.animation!==!1?ij(l):null,h;if(m){let e=await f(m[0].path);if(e.shapes.length+e.instanceCount>Nj)c.push(`${m.length} animation frames found, but the scene is too large to parse once per frame — loaded "${m[0].path}" only`),m=null,h=mj(e);else{let t=new yj(m.map(e=>(e.number-m[0].number)/30),Mj(m));t.addFrame(e);for(let e=1;e<m.length;e++)t.addFrame(await f(m[e].path));h=t.finish()}}else h=mj(await f(d));let g=performance.now()-p;s.releaseScenes();let _=e=>e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),v=new Map,y=async e=>{let t=await s.read(e);return t?(s.release(e),r(_(t))):null},b=new nj({convertHandedness:o,maxTriangles:e.maxTriangles,maxPlacements:e.maxPlacements,mergeShapesAbove:e.mergeShapesAbove,curveSteps:e.curveSteps,curveSides:e.curveSides,curveTolerance:e.curveTolerance,resolvePLY:async e=>{let t=s.findRecord(e);return t?(v.has(t.norm)||v.set(t.norm,await y(t)),v.get(t.norm)):null},resolveImage:async e=>{let t=await s.readPath(e);return t?i(t,e):null},resolveEnvironment:async e=>{let t=await s.readPath(e);return t?(a||i)(t,e):null}}),x=performance.now(),S=await b.build(h);return{...S,entryPath:m?m[0].path:d,frames:m?m.map(e=>e.path):null,candidates:l,warnings:[...c,...S.warnings??[]],parseMs:g,buildMs:performance.now()-x}}function Mj(e){let t=e[0].path.split(`/`);return`${t.length>1?t[t.length-2]:t[0].replace(/\d+\.pbrt$/i,``)||`frames`} · frames ${e[0].number}–${e[e.length-1].number}`}var Nj,Pj,Fj,Ij,Lj,Rj,zj,Bj=g((()=>{gO(),uk(),rj(),bj(),HO(),Nj=2e6,Pj=new TextDecoder,Fj=class{constructor(e,t=null){this.entries=e,this.source=t,this.records=[],this.byPath=new Map,this.byBase=new Map;let n=(e,t,n)=>{let r=xj(e).toLowerCase();if(this.byPath.has(r))return;let i={key:e,norm:r,bytes:t,lazy:n};this.records.push(i),this.byPath.set(r,i);let a=r.split(`/`).pop(),o=this.byBase.get(a);o?o.push(i):this.byBase.set(a,[i])};for(let t in e)n(t,e[t],!1);for(let e of t?.listing??[])e.offset!==void 0&&n(e.path,null,!0)}async read(e){return e?e.bytes?e.bytes:!e.lazy||!this.source?null:this.source.read(e.key):null}async readHead(e,t){return e?e.bytes?e.bytes.subarray(0,t):!e.lazy||!this.source?null:this.source.readHead?this.source.readHead(e.key,t):this.source.read(e.key):null}async readPath(e,t=null){let n=t!==null&&this.findRecord(Sj(t,e))||this.findRecord(e);return this.read(n)}release(e){e.bytes=null,delete this.entries[e.key]}releasePath(e,t=null,n=null){let r=t!==null&&this.findRecord(Sj(t,e))||this.findRecord(e);r?.lazy&&(this.release(r),pO(n))}releaseScenes(){for(let e of this.records)e.norm.endsWith(`.pbrt`)&&this.release(e)}findRecord(e){let t=xj(e).toLowerCase();if(this.byPath.has(t))return this.byPath.get(t);let n=this.byBase.get(t.split(`/`).pop());return n?n.find(e=>e.norm.endsWith(`/`+t))||(n.length===1?n[0]:null):null}find(e){return this.findRecord(e)?.bytes??null}},Ij=e=>Uint8Array.from(e,e=>e.charCodeAt(0)),Lj=4*1024*1024,Rj=Ij(`WorldBegin`),zj=[Ij(`Include`),Ij(`Import`)]}));function Vj(e){let t=0,n=()=>{for(;t<e.length&&e[t]<=32;)t++;let n=t;for(;t<e.length&&e[t]>32;)t++;return String.fromCharCode(...e.subarray(n,t))},r=n();if(r!==`PF`&&r!==`Pf`)throw Error(`not a PFM image`);let i=parseInt(n(),10),a=parseInt(n(),10),o=parseFloat(n());t++;let s=r===`PF`?3:1,c=i*a;if(!(i>0&&a>0)||!Number.isFinite(o)||o===0)throw Error(`bad PFM header`);if(e.length-t<c*s*4)throw Error(`PFM image is truncated`);let l=new DataView(e.buffer,e.byteOffset+t,c*s*4),u=o<0,d=Math.abs(o),f=new Float32Array(c*4);for(let e=0;e<c;e++){for(let t=0;t<3;t++)f[e*4+t]=l.getFloat32((e*s+(s===3?t:0))*4,u)*d;f[e*4+3]=1}return{data:f,width:i,height:a}}function Hj(e){let{data:t,width:n,height:i}=Vj(e),a=new r.DataTexture(t,n,i,r.RGBAFormat,r.FloatType);return a.minFilter=r.LinearFilter,a.magFilter=r.LinearFilter,a.needsUpdate=!0,a}var Uj=g((()=>{})),Wj=_({ARCHIVE_ELEMENT_PROMPT_BYTES:()=>Jj,ArchiveImporter:()=>Yj}),Gj,Kj,qj,Jj,Yj,Xj=g((()=>{gD(),jD(),RD(),Jr(),Jg(),nn(),fO(),Is(),Ms(),fe(),Bj(),Uj(),z_(),X(),Gj=/\.(usd|usda|usdc)$/i,Kj=/\.(png|jpg|jpeg|avif)$/i,qj=3e4,Jj=4e9,Yj=class e{static FORMATS=OS;constructor(e){this.loader=e,this._pendingGraph=null,this.lastPBRTStats=null}release(){this._pendingGraph=null}async _readHead(e,t=512){return e instanceof Uint8Array?e.subarray(0,t):typeof e.slice==`function`&&typeof e.arrayBuffer==`function`?new Uint8Array(await e.slice(0,t).arrayBuffer()):new Uint8Array((await this.loader.readFileAsArrayBuffer(e)).slice(0,t))}async inspectArchive(e){let t=KE(await this._readHead(e)),n=e=>z({isLoading:!0,status:`Scanning archive… ${(e.bytes/1e9).toFixed(1)} GB`,progress:4}),r;if(t===`gzip`){let t=await this._unpackGzip(e,e.name);t?(r=t.index.listing,t.release()):{listing:r}=await nD(e,{filter:()=>!1,onProgress:n})}else r=t===`tar`?(await PD(e,this.loader.storage))?.listing??await rD(e,{onProgress:n}):(await bD(e)).map(e=>({path:e.name,size:e.size}));let{root:i,elements:a}=sD(r);return{kind:t??`zip`,root:i,elements:a,entryCount:r.length,totalBytes:r.reduce((e,t)=>e+t.size,0)}}async _unpackGzip(e,t,n=null){let r=(Array.isArray(n)?n:[n]).filter(Boolean);try{return await ND(e,{storage:this.loader.storage,label:t,...r.length?{filter:oD(r),part:[...r].sort().join(`,`)}:{},onProgress:e=>z({isLoading:!0,status:`Unpacking archive… ${(e/1e9).toFixed(1)} GB`,progress:4})})}catch(e){return console.warn(`Unpacking "${t}" to storage failed, reading it in memory: ${e.message}`),null}}async loadArchiveFromFile(e,t,{pbrtEntry:n=null,element:r=null,byteBudget:i,promptBytes:a,...o}={}){try{let s=KE(await this._readHead(e)),c=this.loader.storage?Vg(await Bg(e)):null,l={element:r,promptBytes:a,pbrtEntry:n,pbrt:o,archiveId:c};if(s===`tar`)return await this._loadSeekable(e,t,l);if(s===`gzip`){let a=await this._unpackGzip(e,t,r);if(a)try{return await this._loadSeekable(a.file,t,{...l,index:a.index})}finally{a.release()}let u=await this._readStreamedArchive(e,t,s,r,i);if(kj(u))return await this.loadPBRTFromZip(u,t,n,o);let d=await this._loadNonPBRTArchive(u,t);return this.loader._sourceKey=this.loader._keyed(`archive`,c),d}return await this._loadSeekable(e,t,{...l,zip:!0})}catch(e){throw e?.code!==`ARCHIVE_NEEDS_ELEMENT`&&console.error(`Error loading archive:`,e),e}}async _loadNonPBRTArchive(e,t){return await this.processObjMtlPairsInZip(e,t)||await this.findAndLoadModelFromZip(e,t)}async _loadSeekable(e,t,{element:n,promptBytes:r,pbrtEntry:i,pbrt:a,index:o=null,zip:s=!1,archiveId:c=null}){let l=await this._openSeekableArchive(e,t,n,r,{index:o,zip:s});if(l.archiveId=c,l.elements=(Array.isArray(n)?n:[n]).filter(Boolean),l.listing.some(e=>e.path.toLowerCase().endsWith(`.pbrt`)))return await this.loadPBRTFromZip({},t,i,a,l);for(let e of l.listing)e.offset!==void 0&&(l.entries[e.path]??=await l.read(e.path));let u=await this._loadNonPBRTArchive(l.entries,t);return this.loader._sourceKey=this.loader._keyed(`archive`,c),u}async _loadStoredGraph(e,t,{imageFromBytes:n,envFromBytes:r}){let i=this.loader.storage?.area(tn.SCENES),a=i?await i.open(e):null;if(!a)return null;let o=performance.now(),s=null;try{z({isLoading:!0,status:`Opening the stored scene...`,progress:6});let e=await a.json(`graph.json`),i=await a.file(`data.bin`),s=new Fj({},t),c=await $D(e,i,{loadTexture:async(e,t)=>{let i=await s.readPath(e);return i?t===`environment`?r(i,e):n(i,e):null}});return{...c.stats,group:c.root,environment:c.environment?{texture:c.environment}:null,animations:c.animations,report:null,parseMs:0,buildMs:performance.now()-o,fromStorage:!0}}catch(e){return s=e,null}finally{a.release(),s&&(console.warn(`The stored scene could not be used, parsing the archive instead: ${s.message}`),this.loader._issues?.warn(Y.STORAGE_ENTRY_CORRUPT,`stored scene unusable: ${s.message}`,{key:e}),i.remove(e).catch(()=>{}))}}_storeGraph(e,t,n){let r=this.loader.storage?.area(tn.SCENES);if(!r)return;let i;try{i=KD(t.group,{environment:t.environment?.texture??null,animations:t.animations??[],stats:{meshCount:t.meshCount,entryPath:t.entryPath,candidates:t.candidates,frames:t.frames,warnings:t.warnings,triangleCount:t.triangleCount,placementCount:t.placementCount,mergedShapes:t.mergedShapes,skippedForBudget:t.skippedForBudget,droppedNoTemplate:t.droppedNoTemplate,render:t.render??null}})}catch(e){e instanceof uO?console.info(`Scene not stored for next time: ${e.message}`):console.warn(`Scene not stored for next time:`,e);return}let a={key:e,encoded:i,label:n,parseMs:(t.parseMs??0)+(t.buildMs??0),triangles:t.triangleCount??null};Ns(a.parseMs,i.byteLength)?this._writeGraph(r,a):this._pendingGraph=a}flushPendingGraph(e){let t=this._pendingGraph;this._pendingGraph=null;let n=this.loader.storage?.area(tn.SCENES);!t||!n||!Ns(t.parseMs+e,t.encoded.byteLength)||this._writeGraph(n,t)}_writeGraph(e,t){(async()=>{let n=await e.create(t.key,{label:`${t.label} (scene)`,expectedBytes:t.encoded.byteLength});if(n)try{await qD(n,t.encoded,{release:!0}),await n.commit({triangles:t.triangles})}catch(e){await n.abort(),console.warn(`Storing the scene failed:`,e)}})().catch(e=>console.warn(`Storing the scene failed:`,e))}async _openSeekableArchive(e,t,n,r,{index:i=null,zip:a=!1}={}){let o=Array.isArray(n)?n.filter(Boolean):n?[n]:[],s=o.length?oD(o):null,c;if(a)c=await CD(e,{filter:s});else{let t=i??await PD(e,this.loader.storage);c=await aD(e,{index:t,headersOnly:!0,filter:s,onProgress:e=>z({isLoading:!0,status:`Indexing archive… ${(e.bytes/1e9).toFixed(1)} GB`,progress:4})}),t||FD(e,this.loader.storage,c.index).catch(()=>{})}let l=c.listing.reduce((e,t)=>e+t.size,0);return o.length===0&&this._requireElementChoice(t,c.listing,l,r),console.info(`Archive "${t}": indexed ${c.indexed} entries, ${(l/1e9).toFixed(1)} GB, none resident`+(o.length?`, ${o.length} part${o.length>1?`s`:``} selected.`:`.`)),c}_requireElementChoice(e,t,n,r=Jj){if(n<r)return;let{root:i,elements:a}=sD(t);if(a.length<2)return;let o=Error(`"${e}" holds ${(n/1e9).toFixed(1)} GB across ${a.length} parts. Choose which to load — loading all of them at once may exhaust memory.`);throw o.code=`ARCHIVE_NEEDS_ELEMENT`,o.root=i,o.elements=a,o.totalBytes=n,this.loader._issues?.record(Y.ASSET_ARCHIVE_TOO_LARGE,`archive holds ${(n/1e9).toFixed(1)} GB across ${a.length} parts; choose which to load`,{root:i,elements:a.map(e=>e.prefix),totalBytes:n},Wt.WARNING),o}async _readStreamedArchive(e,t,n,r,i){let a=Array.isArray(r)?r.filter(Boolean):r?[r]:[],{entries:o,listing:s,retainedBytes:c,truncated:l}=await nD(e,{filter:a.length?oD(a):null,...i===void 0?{}:{byteBudget:i},onProgress:e=>z({isLoading:!0,status:`Reading archive… ${(e.bytes/1e9).toFixed(1)} GB`,progress:4})});if(l&&a.length===0){let{root:e,elements:n}=sD(s),r=s.reduce((e,t)=>e+t.size,0),i=Error(`"${t}" unpacks to ${(r/1e9).toFixed(1)} GB, past the load budget. Load one of its ${n.length} parts instead.`);throw i.code=`ARCHIVE_NEEDS_ELEMENT`,i.root=e,i.elements=n,i.totalBytes=r,this.loader._issues?.record(Y.ASSET_ARCHIVE_TOO_LARGE,`archive unpacks to ${(r/1e9).toFixed(1)} GB; choose one of ${n.length} parts`,{root:e,elements:n.map(e=>e.prefix),totalBytes:r},Wt.WARNING),i}if(l){let e=oD(a),t=s.filter(t=>e(t.path,t.size)&&!o[t.path]).length;this.loader._issues?.record(Y.ASSET_ARCHIVE_TOO_LARGE,`${t} files of the chosen parts were left out: they did not fit the ${((i??15e8)/1e9).toFixed(1)} GB in-memory read budget`,{elements:a,missing:t,retainedBytes:c},Wt.WARNING)}return a.length&&console.info(`Archive "${t}": loaded ${a.map(e=>`"${e}"`).join(`, `)} — ${Object.keys(o).length} of ${s.length} files, ${(c/1048576).toFixed(1)} MB.`),o}async loadPBRTFromZip(e,t,n=null,i={},a=null){if(z({isLoading:!0,status:`Parsing PBRT scene...`,progress:5}),!this.loader.loaderCache.ply){let{PLYLoader:e}=await import(`three/examples/jsm/loaders/PLYLoader.js`);this.loader.loaderCache.ply=new e}let o=e=>this.loader.loaderCache.ply.parse(e),s=async(e,t)=>{let n=await this._pbrtTextureFromBytes(e,t);return n&&(n.userData[tO]=t),n},c=async(e,t)=>{let n=t.split(`.`).pop().toLowerCase(),i=new Blob([e]),a=n===`pfm`?null:URL.createObjectURL(i);try{let o=a?await this.loader.loadEnvironmentByExtension(a,n,{loader:n===`exr`?this._exrLoader():null}):Hj(e);return o.mapping=r.EquirectangularReflectionMapping,Br(o,`bytes:${await zg(i)}`),o.userData[tO]=t,o.userData[nO]=`environment`,o}finally{a&&URL.revokeObjectURL(a)}},l=performance.now(),u={animation:i.animation,maxTriangles:i.maxTriangles,maxPlacements:i.maxPlacements,mergeShapesAbove:i.mergeShapesAbove,curveSteps:i.curveSteps,curveSides:i.curveSides,curveTolerance:i.curveTolerance,instanceIncludes:i.instanceIncludes},d=a?.archiveId?this.loader._keyed(`pbrt:2.9:${js}`,`${a.archiveId}|${n??``}|${[...a.elements??[]].sort().join(`,`)}|${JSON.stringify(u)}`):null,f=d?await this._loadStoredGraph(d,a,{imageFromBytes:s,envFromBytes:c}):null,p=f??await jj({vfs:e,source:a,entryPath:n,plyParser:o,imageFromBytes:s,envFromBytes:c,...u}),{group:m,environment:h,animations:g,report:_,warnings:v,meshCount:y,entryPath:b,candidates:x,frames:S,parseMs:C,buildMs:w,triangleCount:T,placementCount:E,mergedShapes:D,skippedForBudget:O,droppedNoTemplate:k}=p;f&&console.info(`PBRT scene "${b}" opened from storage in ${(w/1e3).toFixed(1)} s, skipping the parse`),this.lastPBRTStats={parseMs:C,buildMs:w,loaderMs:performance.now()-l,triangleCount:T,placementCount:E,mergedShapes:D,skippedForBudget:O,droppedNoTemplate:k,meshCount:y,frames:S?.length??1};let A=new Set(S??[b]),j=x.filter(e=>!A.has(e));if(j.length>0&&(console.warn(`PBRT archive holds ${x.length} scenes; loaded "${b}". Others: ${j.join(`, `)}`),this.loader._issues?.record(Y.ASSET_AMBIGUOUS_ENTRY,`archive holds ${x.length} pbrt scenes; loaded "${b}"`,{loaded:b,alternatives:j},Wt.WARNING)),_&&_.length&&typeof console.table==`function`){let e=_.length<y?` (first ${_.length} of ${y})`:``;console.groupCollapsed(`PBRT loader: ${y} mesh(es) from "${b}"${e}`),console.table(_),console.groupEnd()}return v&&v.length&&(console.warn(`PBRT loader: ${v.length} warning(s) parsing "${b}"`),v.forEach(e=>console.warn(` •`,e))),h?.texture&&(h.texture.generateMipmaps=!0,this.loader.applyEnvironmentToScene(h.texture)),m.name=b||t,this.loader.releaseTargetModel(),this.loader._sourceKey=d,d&&!f&&this._storeGraph(d,p,t),this.loader.targetModel=m,this.loader.animations=g??[],this.loader.sceneMetadata={environment:h?.texture?{rotation:0,intensity:1}:{enabled:!1},...p.render?{render:{...p.render}}:{}},z({isLoading:!0,status:`Processing PBRT geometry...`,progress:10}),await this.loader.onModelLoad(this.loader.targetModel),this.loader.dispatchEvent({type:`load`,model:m,filename:`${b} (from ZIP)`}),m}_exrLoader(){return this.loader.loaderCache.exr??=new p.EXRLoader().setDataType(r.FloatType)}async _pbrtTextureFromBytes(e,t){let n=t.split(`.`).pop().toLowerCase(),i;if(n===`exr`||n===`hdr`){let t=n===`hdr`?this.loader.loaderCache.hdr||(this.loader.loaderCache.hdr=new s.HDRLoader().setDataType(r.FloatType)):this._exrLoader();i=await this._loadViaObjectURL(t,e)}else if(n===`pfm`)i=Hj(e);else if(n===`tga`){if(!this.loader.loaderCache.tga){let{TGALoader:e}=await import(`three/examples/jsm/loaders/TGALoader.js`);this.loader.loaderCache.tga=new e}i=await this._loadViaObjectURL(this.loader.loaderCache.tga,e),i.colorSpace=r.SRGBColorSpace}else i=new r.Texture(await createImageBitmap(new Blob([e]))),i.colorSpace=r.SRGBColorSpace;return i.wrapS=i.wrapT=r.RepeatWrapping,i.needsUpdate=!0,i}async _loadViaObjectURL(e,t){let n=URL.createObjectURL(new Blob([t]));try{return await e.loadAsync(n)}finally{URL.revokeObjectURL(n)}}async processObjMtlPairsInZip(e,t){let n=[],r=[];for(let t in e){let i=t.toLowerCase();i.endsWith(`.obj`)?n.push({path:t,content:e[t]}):i.endsWith(`.mtl`)&&r.push({path:t,content:e[t]})}if(n.length>0&&r.length>0){console.log(`Found ${n.length} OBJ files and ${r.length} MTL files in ZIP`);let i=this.findMatchingObjMtlPairs(n,r);if(i.length>0)return console.log(`Found ${i.length} matching OBJ+MTL pairs`),await this.loadOBJMTLPairFromZip(i[0].obj,i[0].mtl,e,t);if(i.length===0)return console.log(`No matching pairs by name, using first OBJ and MTL files`),await this.loadOBJMTLPairFromZip(n[0],r[0],e,t)}return null}findMatchingObjMtlPairs(e,t){let n=[];for(let r of e){let e=r.path.split(`/`).pop().replace(/\.obj$/i,``).toLowerCase();for(let i of t){let t=i.path.split(`/`).pop().replace(/\.mtl$/i,``).toLowerCase();if(e===t||e.includes(t)||t.includes(e)){n.push({obj:r,mtl:i});break}}}return n}async findAndLoadModelFromZip(e){for(let t of[`scene.gltf`,`scene.glb`,`model.gltf`,`model.glb`,`main.gltf`,`main.glb`,`asset.gltf`,`asset.glb`])if(e[t]){console.log(`Found main model file: ${t}`);let n=t.split(`.`).pop().toLowerCase();return await this.loadModelFromZipEntry(e[t],t,n,e)}for(let t in e){let n=t.split(`.`).pop().toLowerCase();if(n===`obj`||this.loader.getFileFormat(t)?.type===`model`)return Gj.test(t)?await this.loadUSDHierarchyFromZip(e):(console.log(`Loading model file from ZIP: ${t}`),await this.loadModelFromZipEntry(e[t],t,n,e))}throw Error(`No supported model files found in the ZIP archive`)}async loadUSDHierarchyFromZip(t){let n=Object.keys(t).filter(e=>Gj.test(e));if(n.length===0)throw Error(`No USD layers found in the ZIP archive`);let r=e._pickUSDRootLayer(n);console.log(`Loading USD scene from ZIP: ${r} (${n.length} layers)`);let i={[r]:[t[r],{level:0}]};for(let e of Object.keys(t))e!==r&&(Gj.test(e)||Kj.test(e))&&(i[e]=[t[e],{level:0}]);return await this.loader._loadModelFileByExtension(new File([(0,m.zipSync)(i)],r),r)}static _pickUSDRootLayer(e){let t=e=>e.split(`/`).length,n=Math.min(...e.map(t)),r=e.filter(e=>t(e)===n);return r.find(e=>{let t=e.split(`/`);return t.length>1&&t[t.length-1].replace(Gj,``)===t[t.length-2]})||r[0]}async loadModelFromZipEntry(e,t,n,r){try{z({isLoading:!0,status:`Processing ${n.toUpperCase()} from ZIP...`,progress:5});let i=new Blob([e.buffer],{type:`application/octet-stream`}),a=URL.createObjectURL(i),o;switch(n){case`glb`:case`gltf`:o=await this.handleGltfFromZip(n,e,t,r);break;case`obj`:o=await this.handleObjFromZip(e,t,r);break;default:o=await this.loader._loadModelFileByExtension(new File([e],t),t)}return URL.revokeObjectURL(a),this.loader.dispatchEvent({type:`load`,model:this.loader.targetModel,filename:`${t} (from ZIP)`}),o}catch(e){throw console.error(`Error loading ${n} from ZIP:`,e),this.loader.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async handleGltfFromZip(e,t,n,i){if(e===`gltf`){let e=(0,m.strFromU8)(t),a=new r.LoadingManager,o=n.split(`/`).slice(0,-1).join(`/`);a.setURLModifier(e=>this.resolveZipResource(e,o,i));let s=await this.loader.createGLTFLoader();s.manager=a;try{return await new Promise((t,n)=>{s.parse(e,``,e=>{try{this.loader._throwDeferred()}catch(e){n(e);return}this.loader.releaseTargetModel(),this.loader.targetModel=e.scene,this.loader.sceneMetadata=I_(e),this.loader.onModelLoad(this.loader.targetModel).then(()=>t(e))},e=>n(e))})}finally{this.loader._disposeGLTFLoader(s)}}else return await this.loader.loadGLBFromArrayBuffer(t.buffer,n)}async handleObjFromZip(e,t,n){let r=(0,m.strFromU8)(e),i=r.match(/mtllib\s+([^\s]+)/),a=null;i&&i[1]&&(a=await this.loadMtlFromZip(i[1],t,n));let{OBJLoader:o}=await import(`three/examples/jsm/loaders/OBJLoader.js`),s=new o;a&&s.setMaterials(a);let c=s.parse(r);return c.name=t,this.loader.releaseTargetModel(),this.loader.targetModel=c,await this.loader.onModelLoad(this.loader.targetModel),c}async preloadMtlTextures(e){let t=[],n=e.loadTexture.bind(e);if(e.loadTexture=(e,r,i,a,o)=>{let s;return t.push(new Promise(e=>s=e)),n(e,r,e=>{s(),i?.(e)},a,e=>{s(),o?.(e)})},e.preload(),t.length===0)return e;let r,i=await Promise.race([Promise.all(t).then(()=>!0),new Promise(e=>r=setTimeout(()=>e(!1),qj))]);return clearTimeout(r),i||this.loader._issues?.record(Y.TEXTURE_BUILD_FAILED,`MTL textures did not decode within ${qj}ms; affected materials render untextured`,{pending:t.length}),e}async loadMtlFromZip(e,t,n){let i=t.split(`/`).slice(0,-1).join(`/`),a=[e,`${i}/${e}`,e.split(`/`).pop()];for(let e of a)if(n[e]){let{MTLLoader:t}=await import(`three/examples/jsm/loaders/MTLLoader.js`),a=(0,m.strFromU8)(n[e]),o=new r.LoadingManager;o.setURLModifier(e=>this.resolveZipResource(e,i,n));let s=new t(o).parse(a,i);return await this.preloadMtlTextures(s),s}return null}resolveZipResource(e,t,n){let r=e.replace(/^\.\/|^\//,``),i=[r,`${t}/${r}`,r.split(`/`).pop()];for(let e of i)if(n[e]){let t=new Blob([n[e].buffer],{type:`application/octet-stream`});return URL.createObjectURL(t)}return console.warn(`Resource not found in ZIP: ${e}`),e}async loadOBJMTLPairFromZip(e,t,n,i){let{MTLLoader:a}=await import(`three/examples/jsm/loaders/MTLLoader.js`),{OBJLoader:o}=await import(`three/examples/jsm/loaders/OBJLoader.js`),s=[],c=new r.LoadingManager,l=e.path.split(`/`).slice(0,-1).join(`/`),u=t.path.split(`/`).slice(0,-1).join(`/`);c.setURLModifier(e=>this.resolveTextureInZip(e,l,u,t,n,s));let d=this.prepareFixedMtlContent(t),f=new a(c).parse(d,u);await this.preloadMtlTextures(f);let p=new o(c);p.setMaterials(f);let h=(0,m.strFromU8)(e.content),g=p.parse(h);return this.loader.releaseTargetModel(),this.loader.targetModel=g,await this.loader.onModelLoad(this.loader.targetModel),s.forEach(e=>URL.revokeObjectURL(e)),this.loader.dispatchEvent({type:`load`,model:g,filename:`${e.path} (from ${i})`}),g}prepareFixedMtlContent(e){return(0,m.strFromU8)(e.content).replace(RegExp(`${e.path.split(`/`).pop()}\\s+`,`g`),` `).replace(/([a-zA-Z_]+)([\\/])/g,`$1 $2`)}resolveTextureInZip(e,t,n,r,i,a){let o=e.split(`?`)[0].split(`#`)[0].replace(/^\.\/|^\//,``),s=r.path.split(`/`).pop();o.startsWith(s)&&(o=o.substring(s.length).replace(/^\.\/|^\/|^\./,``));let c=[o,`${t}/${o}`,`${n}/${o}`,`textures/${o}`,`texture/${o}`,`materials/${o}`,o.split(`/`).pop()];for(let e of c)if(i[e]){let t=new Blob([i[e].buffer],{type:`application/octet-stream`}),n=URL.createObjectURL(t);return a.push(n),n}return this.findTextureWithFuzzyMatch(o,i,a)||e}findTextureWithFuzzyMatch(e,t,n){let r=e.split(`/`).pop();for(let e in t)if(e.endsWith(r)){let r=new Blob([t[e].buffer],{type:`application/octet-stream`}),i=URL.createObjectURL(r);return n.push(i),i}if(r&&r.length>5)for(let e in t){let i=e.split(`/`).pop();if(i.includes(r)||r.includes(i)){let r=new Blob([t[e].buffer],{type:`application/octet-stream`}),i=URL.createObjectURL(r);return n.push(i),i}}return null}}}));function Zj(e){let t=(e/1e3)**2;return .002152*(1.0455996-341.29061/t-.9023085*t)/(1+.0027059889/t-85.968563*t)}function Qj(e,t,n,r,i=1,a=0){let o=e.length/i,s=(r-t)/n;if(s<=0)return e[a];if(s>=o-1)return e[(o-1)*i+a];let c=Math.floor(s),l=s-c;return e[c*i+a]*(1-l)+e[(c+1)*i+a]*l}function $j(e,t){let n=0,r=bM+e*xM;for(let e=0;e<xM;e++)n+=t(r+e+.5);return n/xM}function eM(e){let t=new Float64Array(16);for(let n=0;n<16;n++)t[n]=$j(n,e);return t}function tM(e=1){let t=new Float32Array(48);for(let n=0;n<16;n++){let r=NM[n*3],i=NM[n*3+1],a=NM[n*3+2];for(let o=0;o<3;o++){let s=EM;t[o*16+n]=(s[o*3]*r+s[o*3+1]*i+s[o*3+2]*a)*e}}return t}function nM(e){let t=0,n=0,r=0;for(let i=0;i<16;i++)t+=e[i]*NM[i*3],n+=e[i]*NM[i*3+1],r+=e[i]*NM[i*3+2];return[t,n,r]}function rM([e,t,n]){let r=EM;return[r[0]*e+r[1]*t+r[2]*n,r[3]*e+r[4]*t+r[5]*n,r[6]*e+r[7]*t+r[8]*n]}function iM(e){return Math.max(0,.0460836582205*e-.04586025928522)}function aM([e,t,n]){let r=(e,t,n)=>{let r=Math.min(Math.max((n-e)/(t-e),0),1);return r*r*(3-2*r)};return Float64Array.from(OM,i=>{let a=1-r(470,520,i),o=r(560,610,i);return n*a+e*o+t*(1-a-o)})}function oM({airDensity:e=1,turbidity:t=2,ozone:n=300,groundAlbedo:r=[.3,.3,.3]}={}){let i=iM(t)/gM,a=n*DM/(15*1e3)*1e3,o=new Float64Array(16),s=new Float64Array(16),c=new Float64Array(16),l=new Float64Array(16);for(let t=0;t<16;t++)o[t]=AM[t]*e,s[t]=MM[t]*i,c[t]=s[t]*_M,l[t]=jM[t]*a;return{rayleigh:o,mieScattering:c,mieExtinction:s,ozone:l,albedo:aM(r)}}function sM(e){let t=Math.max(e,0);return Math.sqrt(t*(2*mM+t))/(mM+t)}function cM(e,t,n=1024){let r=Math.max(e,0),i=mM+r,a=i*t,o=r*(2*mM+r);if(t<0&&a*a>=o)return null;let s=-a+Math.sqrt(a*a+(hM-i)*(hM+i)),c=0,l=0,u=0;for(let e=0;e<n;e++){let t=s*(e/n)**2,r=s*((e+1)/n)**2,d=.5*(t+r),f=(o+d*(d+2*a))/(Math.sqrt(i*i+d*(d+2*a))+mM),p=r-t;c+=PM(f)*p,l+=FM(f)*p,u+=IM(f)*p}return[c,l,u]}function lM(e,t){let n=new Float64Array(16);if(!t)return n;let[r,i,a]=t;for(let t=0;t<16;t++)n[t]=Math.exp(-(e.rayleigh[t]*r+e.mieExtinction[t]*i+e.ozone[t]*a));return n}function uM(e){let t=Math.sin(e/2);return 4*Math.PI*t*t}function dM({direction:e,altitude:t,angularDiameter:n,strength:r=1,coefficients:i}){let a=n/2,o=uM(a),s=sM(t),[c,l,u]=e,d=Math.sin(a),f=new Float64Array(16),p=0,m=e=>{if(e<-s)return;let n=lM(i,cM(t,e,512));for(let e=0;e<16;e++)f[e]+=n[e];p++};if(l-d>.1)m(l);else{let e=Math.sqrt(Math.max(0,1-l*l));for(let t=0;t<48;t++){let n=(t+.5)/48,r=-1,i=1;for(let e=0;e<30;e++){let e=.5*(r+i);(Math.asin(e)+e*Math.sqrt(1-e*e)+Math.PI/2)/Math.PI<n?r=e:i=e}m(l+.5*(r+i)*d*e)}}let h=new Float64Array(16),g=l-d>.1?1:48;if(p>0)for(let e=0;e<16;e++)h[e]=kM[e]*r/o*f[e]/p;return{radiance:rM(nM(h)).map(e=>Math.max(0,e*SM)),visibleFraction:p/g,solidAngle:o,direction:[c,l,u]}}function fM(e,t=vM){let n=t*t;return 3/(8*Math.PI)*(1-n)/(2+n)*(1+e*e)/(1+n-2*t*e)**1.5}function pM(e,t,n,r,i=8){let a=n*r,o=e*t,s=new Float32Array(2*o*a);return[LM,e=>fM(e)].forEach((c,l)=>{for(let u=0;u<o;u++){let d=-1+2*Math.floor(u/t)/(e-1),f=u%t*Math.PI/(t-1),p=Math.sqrt(Math.max(0,1-d*d)),m=(l*o+u)*a,h=0;for(let e=0;e<a;e++){let t=Math.floor(e/r),a=e%r,o=0;for(let e=0;e<i;e++){let s=-1+2*(t+(e+.5)/i)/n,l=Math.sqrt(Math.max(0,1-s*s));for(let e=0;e<i;e++){let t=Math.PI*(a+(e+.5)/i)/r;o+=c(d*s+p*l*Math.cos(f-t))+c(d*s+p*l*Math.cos(f+t))}}s[m+e]=o,h+=o}for(let e=0;e<a;e++)s[m+e]/=h}}),s}var mM,hM,gM,_M,vM,yM,bM,xM,SM,CM,wM,TM,EM,DM,OM,kM,AM,jM,MM,NM,PM,FM,IM,LM,RM=g((()=>{om(),mM=6360,hM=6420,gM=1.2,_M=.9,vM=.76,yM=1.3,bM=380,xM=25,SM=1/32,CM=[1.11776,1.14259,1.01249,1.14716,1.72765,1.73054,1.6887,1.61253,1.91198,2.03474,2.02042,2.02212,1.93377,1.95809,1.91686,1.8298,1.8685,1.8931,1.85149,1.8504,1.8341,1.8345,1.8147,1.78158,1.7533,1.6965,1.68194,1.64654,1.6048,1.52143,1.55622,1.5113,1.474,1.4482,1.41018,1.36775,1.34188,1.31429,1.28303,1.26758,1.2367,1.2082,1.18737,1.14683,1.12362,1.1058,1.07124,1.04992],wM=[118e-29,2182e-31,2818e-31,6636e-31,1527e-30,2763e-30,552e-29,8451e-30,1582e-29,2316e-29,3669e-29,4924e-29,7752e-29,9016e-29,148e-27,1602e-28,2139e-28,2755e-28,3091e-28,35e-26,4266e-28,4672e-28,4398e-28,4701e-28,5019e-28,4305e-28,374e-27,3215e-28,2662e-28,2238e-28,1852e-28,1473e-28,1209e-28,9423e-29,7455e-29,6566e-29,5105e-29,415e-28,4228e-29,3237e-29,2451e-29,2801e-29,2534e-29,1624e-29,1465e-29,2078e-29,1383e-29,7105e-30],TM=[1299e-7,3917e-9,6061e-7,2321e-7,6965e-9,.001086,4149e-7,1239e-8,.001946,7416e-7,2202e-8,.003486,.001368,39e-6,.006450001,.002236,64e-6,.01054999,.004243,12e-5,.02005001,.00765,217e-6,.03621,.01431,396e-6,.06785001,.02319,64e-5,.1102,.04351,.00121,.2074,.07763,.00218,.3713,.13438,.004,.6456,.21477,.0073,1.0390501,.2839,.0116,1.3856,.3285,.01684,1.62296,.34828,.023,1.74706,.34806,.0298,1.7826,.3362,.038,1.77211,.3187,.048,1.7441,.2908,.06,1.6692,.2511,.0739,1.5281,.19536,.09098,1.28764,.1421,.1126,1.0419,.09564,.13902,.8129501,.05795001,.1693,.6162,.03201,.20802,.46518,.0147,.2586,.3533,.0049,.323,.272,.0024,.4073,.2123,.0093,.503,.1582,.0291,.6082,.1117,.06327,.71,.07824999,.1096,.7932,.05725001,.1655,.862,.04216,.2257499,.9148501,.02984,.2904,.954,.0203,.3597,.9803,.0134,.4334499,.9949501,.008749999,.5120501,1,.005749999,.5945,.995,.0039,.6784,.9786,.002749999,.7621,.952,.0021,.8425,.9154,.0018,.9163,.87,.001650001,.9786,.8163,.0014,1.0263,.757,.0011,1.0567,.6949,.001,1.0622,.631,8e-4,1.0456,.5668,6e-4,1.0026,.503,34e-5,.9384,.4412,24e-5,.8544499,.381,19e-5,.7514,.321,1e-4,.6424,.265,4999999e-11,.5419,.217,3e-5,.4479,.175,2e-5,.3608,.1382,1e-5,.2835,.107,0,.2187,.0816,0,.1649,.061,0,.1212,.04458,0,.0874,.032,0,.0636,.0232,0,.04677,.017,0,.0329,.01192,0,.0227,.00821,0,.01584,.005723,0,.01135916,.004102,0,.008110916,.002929,0,.005790346,.002091,0,.004109457,.001484,0,.002899327,.001047,0,.00204919,74e-5,0,.001439971,52e-5,0,.0009999493,3611e-7,0,.0006900786,2492e-7,0,.0004760213,1719e-7,0,.0003323011,12e-5,0,.0002348261,848e-7,0,.0001661505,6e-5,0,117413e-9,424e-7,0,8307527e-11,3e-5,0,5870652e-11,212e-7,0,4150994e-11,1499e-8,0,2935326e-11,106e-7,0,2067383e-11,74657e-10,0,1455977e-11,52578e-10,0,1025398e-11,37029e-10,0,7221456e-12,26078e-10,0,5085868e-12,18366e-10,0,3581652e-12,12934e-10,0,2522525e-12,9.1093e-7,0,1776509e-12,6.4153e-7,0,1251141e-12,4.5181e-7,0],EM=[3.2406,-1.5372,-.4986,-.9689,1.8758,.0415,.0557,-.204,1.057],DM=0xe90f62a5dcb760000,OM=Float64Array.from({length:16},(e,t)=>bM+(t+.5)*xM),kM=eM(e=>Qj(CM,360,10,e)),AM=eM(e=>Zj(e)/8),jM=eM(e=>Qj(wM,360,10,e)),MM=eM(e=>(e/1e3)**-yM),NM=(()=>{let e=new Float64Array(48);for(let t=0;t<16;t++)for(let n=0;n<3;n++)e[t*3+n]=$j(t,e=>Qj(TM,360,5,e,3,n))*xM;return e})(),PM=e=>Math.exp(-e/8),FM=e=>Math.exp(-e/gM),IM=e=>Math.max(0,1-Math.abs(e-25)/15),LM=e=>3/(16*Math.PI)*(1+e*e)}));function zM(e){return{r:(0,n.exp)(e.mul(-1/8)),m:(0,n.exp)(e.mul(-1/gM)),o:(0,n.max)((0,n.float)(0),(0,n.float)(1).sub((0,n.abs)(e.sub(25)).div(15)))}}function BM(e,t){return cN(n=>e.rayleigh[n].mul(t.r).add(e.mieExtinction[n].mul(t.m)).add(e.ozone[n].mul(t.o)))}function VM(e,t){return cN(r=>{let i=e[r].mul(t),a=(0,n.exp)(i.negate()),o=(0,n.float)(1).sub(a).div((0,n.max)(i,1e-12));return{weight:(0,n.mix)((0,n.float)(1).sub(i.mul(.5)),o,(0,n.step)(.001,i)).mul(t),transmittance:a}})}function HM(e,t,r,i,a,o=1,s=0){let c=(0,n.clamp)(i,0,t-1),l=(0,n.clamp)(a,0,r-1),u=(0,n.floor)(c),d=(0,n.floor)(l),f=c.sub(u),p=l.sub(d),m=(0,n.uint)(u),h=(0,n.uint)(d),g=(0,n.min)(m.add(1),(0,n.uint)(t-1)),_=(0,n.min)(h.add(1),(0,n.uint)(r-1)),v=(n,r)=>e.element(r.mul(t).add(n).mul(o).add(s));return(0,n.mix)((0,n.mix)(v(m,h),v(g,h),f),(0,n.mix)(v(m,_),v(g,_),f),p)}function UM(e,t){let r=e.add(mM),i=(0,n.sqrt)((0,n.max)(e.mul(e.add(2*mM)),0)),a=r.mul(t),o=a.negate().add((0,n.sqrt)((0,n.max)(a.mul(a).add(iN*iN).sub(i.mul(i)),0))),s=(0,n.float)(aN).sub(e),c=i.add(iN);return{x:o.sub(s).div((0,n.max)(c.sub(s),1e-6)).mul(255),y:i.div(iN).mul(63),rho:i,r}}function WM(e,t,r,i,a){let o=UM(r,i),s=HM(e,256,64,o.x,o.y).xyz,c=(0,n.smoothstep)(a.negate(),a,i.add(o.rho.div(o.r)));return cN(e=>(0,n.exp)(t.rayleigh[e].mul(s.x).add(t.mieExtinction[e].mul(s.y)).add(t.ozone[e].mul(s.z)).negate()).mul(c))}function GM(e,t,r,i,a){let o=[[(0,n.clamp)(gN(r,64),0,63),64],[(0,n.clamp)(uN(t),0,15),16],[(0,n.clamp)(i.add(1).mul(.5*15),0,15),16],[(0,n.clamp)((0,n.acos)((0,n.clamp)(a,-1,1)).mul(7/oN),0,7),8]].map(([e,t])=>{let r=(0,n.floor)(e),i=e.sub(r).toVar(),a=(0,n.uint)(r).toVar();return{t:i,i0:a,i1:(0,n.min)(a.add(1),(0,n.uint)(t-1)).toVar()}}),s=[128,8192,8,1],c=[];for(let e=0;e<16;e++){let t=(0,n.uint)(0);o.forEach((n,r)=>{t=t.add((e>>r&1?n.i1:n.i0).mul(s[r]))}),c.push(t.mul(8).toVar())}return Array.from({length:8},(t,r)=>{let i=c.map(t=>e.element(t.add(r)));for(let e=0;e<4;e++){let t=[];for(let r=0;r<i.length;r+=2)t.push((0,n.mix)(i[r],i[r+1],o[e].t));i=t}return(0,n.exp)(i[0])})}function KM(e,t){let r=gN(t,128);return cN(t=>(0,n.exp)(HM(e,128,1,r,(0,n.float)(0),4,t)))}function qM(e,t){let r=e.add(mM).toVar(),i=r.mul(t).toVar(),a=e.mul(e.add(2*mM)).toVar(),o=i.mul(i).sub(a),s=t.lessThan(0).and(o.greaterThanEqual(0)).toVar(),c=a.div((0,n.max)(i.negate().add((0,n.sqrt)((0,n.max)(o,0))),1e-9)),l=i.negate().add((0,n.sqrt)((0,n.max)(i.mul(i).add((0,n.float)(hM).sub(r).mul(r.add(hM))),0)));return{r,b:i,cGround:a,hitsGround:s,tMax:s.select(c,l).toVar()}}function JM(e,t,r,i){let a=t.mul(t.add(e.b.mul(2))),o=(0,n.sqrt)(e.r.mul(e.r).add(a));return{h:(0,n.max)(e.cGround.add(a).div(o.add(mM)),0),muS:(0,n.clamp)(e.r.mul(r).add(t.mul(i)).div(o),-1,1),mu:(0,n.clamp)(e.b.add(t).div(o),-1,1)}}function YM(e,t){let r=t*t,i=3/(8*oN)*(1-r)/(2+r),a=(0,n.max)((0,n.float)(1+r).sub(e.mul(2*t)),1e-6);return e.mul(e).add(1).mul(i).div(a.mul((0,n.sqrt)(a)))}function XM({transmittance:e},t=256){let r=256*64;return(0,n.Fn)(()=>{let i=n.instanceIndex;(0,n.If)(i.greaterThanEqual((0,n.uint)(r)),()=>{(0,n.Return)()});let a=(0,n.float)(i.mod(256)).div(255),o=(0,n.float)(i.div(256)).div(63).mul(iN).toVar(),s=(0,n.sqrt)(o.mul(o).add(mM*mM)).toVar(),c=(0,n.float)(hM).sub(s),l=o.add(iN),u=c.add(a.mul(l.sub(c))).toVar(),d=(0,n.clamp)((0,n.float)(iN*iN).sub(o.mul(o)).sub(u.mul(u)).div((0,n.max)(s.mul(u).mul(2),1e-9)),-1,1).toVar(),f=o.mul(o).toVar(),p=s.mul(d).mul(2).toVar(),m=(0,n.vec3)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(t),type:`int`,condition:`<`},({i:e})=>{let r=(0,n.float)(e).div(t),i=(0,n.float)(e).add(1).div(t),a=u.mul(r.mul(r)),o=u.mul(i.mul(i)),c=a.add(o).mul(.5),l=c.mul(c.add(p)),d=zM((0,n.max)(f.add(l).div((0,n.sqrt)(s.mul(s).add(l)).add(mM)),0));m.addAssign((0,n.vec3)(d.r,d.m,d.o).mul(o.sub(a)))}),e.element(i).assign((0,n.vec4)(m,0))})().compute(r,[64])}function ZM(e,t,r,i){let a=(0,n.float)(e).add((0,n.float)(r.div(i)).add(.5).div(i)).div(16).mul(2).sub(1),o=(0,n.sqrt)((0,n.max)((0,n.float)(1).sub(a.mul(a)),0)),s=(0,n.float)(t).add((0,n.float)(r.mod(i)).add(.5).div(i)).mul(oN/8);return(0,n.vec3)(o.mul((0,n.cos)(s)),a,o.mul((0,n.sin)(s)))}function QM(e,t){let r=gN(t,64);return cN(t=>HM(e,64,1,r,(0,n.float)(0),4,t))}function $M(e,{first:t,out:r,cellSamples:i=2,steps:a=20}){let{transmittance:o,transfer:s,multipleScattering:c,groundE:l,coefficients:u,sunSinRadius:d,mieG:f}=e,p=1024*128,m=i*i;return(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(p)),()=>{(0,n.Return)()});let h=e.mod(128),g=e.div(128),_=hN(g.mod(64),64).toVar(),v=(0,n.max)(lN(g.div(64)),.001).toVar(),y=(0,n.vec3)((0,n.sqrt)((0,n.max)((0,n.float)(1).sub(_.mul(_)),0)),_,0).toVar(),b=cN(()=>(0,n.vec4)(0).toVar()),x=t?cN(()=>(0,n.vec4)(0).toVar()):null;(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(m),type:`int`,condition:`<`,name:`ray`},({ray:e})=>{let r=ZM(h.div(8),h.mod(8),e,i).toVar(),s=(0,n.dot)(r,y).toVar(),p=t?bN(s).toVar():null,m=t?YM(s,f).toVar():null,g=t?null:Array.from({length:8},()=>(0,n.vec4)(0).toVar()),S=qM(v,r.y),C=cN(()=>(0,n.vec4)(1).toVar());(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(a),type:`int`,condition:`<`},({i:e})=>{let r=(0,n.float)(e).div(a),i=(0,n.float)(e).add(1).div(a),l=S.tMax.mul(r.mul(r)),f=S.tMax.mul(i.mul(i)).sub(l),h=JM(S,l.add(f.mul(.5)),_,s),v=zM(h.h),y=cN(e=>u.rayleigh[e].mul(v.r)),w=cN(e=>u.mieScattering[e].mul(v.m)),T=VM(BM(u,v),f),E;if(t){let e=WM(o,u,h.h,h.muS,d);E=cN(t=>e[t].mul(y[t].mul(p).add(w[t].mul(m))))}else (0,n.If)(e.mod(2).equal(0),()=>{let e=GM(c,h.h,h.muS,h.mu,yN(s,h.mu,h.muS));for(let t=0;t<8;t++)g[t].assign(e[t])}),E=cN(e=>y[e].mul(g[e]).add(w[e].mul(g[4+e])));for(let e of sN)b[e].addAssign(C[e].mul(E[e]).mul(T[e].weight)),x&&x[e].addAssign(C[e].mul(y[e].add(w[e])).mul(T[e].weight)),C[e].mulAssign(T[e].transmittance)}),(0,n.If)(S.hitsGround,()=>{let e=(0,n.clamp)(S.r.mul(_).add(S.tMax.mul(s)).div(mM),-1,1),r;if(t){let t=WM(o,u,(0,n.float)(0),e,d);r=cN(r=>t[r].mul((0,n.max)(e,0)))}else r=QM(l,e);for(let e of sN)b[e].addAssign(C[e].mul(r[e]).mul(u.albedo[e]).mul(1/oN))})});for(let t of sN)r.element(e.mul(4).add(t)).assign(b[t].div(m)),x&&s.element(e.mul(4).add(t)).assign(x[t].div(m))})().compute(p,[64])}function eN(e,{incoming:t,stage:r}){let{transfer:i,phaseCells:a,multipleScattering:o,psiSum:s,groundE:c}=e,l=1024*128,u=r===`last`;return(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(l)),()=>{(0,n.Return)()});let d=e.mod(128),f=e.div(128),p=f.mul(128),m=null;if(u){let e=cN(()=>(0,n.vec4)(0).toVar());(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(128),type:`int`,condition:`<`},({i:t})=>{for(let r of sN)e[r].addAssign(i.element(p.add((0,n.uint)(t)).mul(4).add(r)))}),m=cN(t=>{let r=(0,n.min)(e[t].div(128),.95);return r.div((0,n.float)(1).sub(r)).toVar()})}for(let i=0;i<2;i++){let c=cN(()=>(0,n.vec4)(0).toVar());(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(32),type:`int`,condition:`<`},({i:e})=>{let r=a.element((0,n.uint)(i*128).add(d).mul(32).add((0,n.uint)(e))).toVar();for(let i=0;i<4;i++){let a=p.add((0,n.uint)(e).mul(4).add(i)).mul(4),o=r.element((0,n.int)(i));for(let e of sN)c[e].addAssign(t.element(a.add(e)).mul(o))}});for(let t of sN){let n=e.mul(8).add(i*4+t);r===`first`?(s.element(n).assign(c[t]),o.element(n).assign(vN(c[t]))):r===`middle`?(s.element(n).addAssign(c[t]),o.element(n).assign(vN(c[t]))):o.element(n).assign(vN(s.element(n).add(c[t].mul(m[t].add(1)))))}}u||(0,n.If)(f.lessThan((0,n.uint)(64)).and(d.equal((0,n.uint)(0))),()=>{let e=cN(()=>(0,n.vec4)(0).toVar());(0,n.Loop)({start:(0,n.int)(128/2),end:(0,n.int)(128),type:`int`,condition:`<`},({i:r})=>{let i=(0,n.float)((0,n.uint)(r).div(8)).add(.5).div(16).mul(2).sub(1);for(let a of sN)e[a].addAssign(t.element(p.add((0,n.uint)(r)).mul(4).add(a)).mul(i))});for(let t of sN)c.element(f.mul(4).add(t)).assign(e[t].mul(xN))})})().compute(l,[64])}function tN({transmittance:e,multipleScattering:t,coefficients:r,sunSinRadius:i,mieG:a},o,s,c,l){let u=cN(()=>(0,n.vec4)(0).toVar()),d=cN(()=>(0,n.vec4)(1).toVar()),f=t?Array.from({length:8},()=>(0,n.vec4)(0).toVar()):null,p=bN(c).toVar(),m=YM(c,a).toVar(),h=o.tMax;return(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(l),type:`int`,condition:`<`},({i:a})=>{let g=(0,n.float)(a).div(l),_=(0,n.float)(a).add(1).div(l),v=h.mul(g.mul(g)),y=h.mul(_.mul(_)).sub(v),b=JM(o,v.add(y.mul(.5)),s,c),x=zM(b.h),S=cN(e=>r.rayleigh[e].mul(x.r)),C=cN(e=>r.mieScattering[e].mul(x.m)),w=WM(e,r,b.h,b.muS,i),T=VM(BM(r,x),y);f&&(0,n.If)(a.mod(SN).equal(0),()=>{let e=GM(t,b.h,b.muS,b.mu,yN(c,b.mu,b.muS));for(let t=0;t<8;t++)f[t].assign(e[t])});for(let e of sN){let t=w[e].mul(S[e].mul(p).add(C[e].mul(m)));f&&(t=t.add(S[e].mul(f[e])).add(C[e].mul(f[4+e]))),u[e].addAssign(d[e].mul(t).mul(T[e].weight)),d[e].mulAssign(T[e].transmittance)}}),{L:u,throughput:d}}function nN(e,{sqrtDirections:t=12,steps:r=32}={}){let{irradiance:i}=e,a=t*t,o=(0,n.float)(.001);return(0,n.Fn)(()=>{let s=n.instanceIndex;(0,n.If)(s.greaterThanEqual((0,n.uint)(128)),()=>{(0,n.Return)()});let c=hN(s,128).toVar(),l=(0,n.vec3)((0,n.sqrt)((0,n.max)((0,n.float)(1).sub(c.mul(c)),0)),c,0).toVar(),u=cN(()=>(0,n.vec4)(0).toVar());(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(a),type:`int`,condition:`<`,name:`dirIndex`},({dirIndex:i})=>{let a=(0,n.float)(i.div(t)).add(.5).div(t),s=(0,n.float)(i.mod(t)).add(.5).div(t),d=(0,n.sqrt)(a),f=s.mul(2*oN),p=(0,n.vec3)(d.mul((0,n.cos)(f)),(0,n.sqrt)((0,n.max)((0,n.float)(1).sub(a),0)),d.mul((0,n.sin)(f))).toVar(),{L:m}=tN(e,qM(o,p.y),c,(0,n.dot)(p,l),r);for(let e of sN)u[e].addAssign(m[e])});for(let e of sN)i.element(s.mul(4).add(e)).assign(vN(u[e].mul(oN/a)))})().compute(128,[64])}function rN(e,{width:t,height:r,steps:i=40,multipleScattering:a=!0}){let{sky:o,skyRows:s,irradiance:c,coefficients:l,rgb:u,sunDirection:d,altitude:f,sunSinRadius:p,transmittance:m}=e,h=a?e:{...e,multipleScattering:null},g=256*r;return[(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(g)),()=>{(0,n.Return)()});let t=(0,n.float)(1).sub((0,n.float)(e.div(256)).add(.5).div(r)).mul(oN),a=(0,n.cos)(t).toVar(),o=(0,n.max)(f,.001).toVar(),_=d.y.toVar(),v=(0,n.sin)(t).mul((0,n.cos)(CN(e.mod(256)))).mul((0,n.sqrt)((0,n.max)((0,n.float)(1).sub(_.mul(_)),0))).add(a.mul(_)).toVar(),y=qM(o,a),{L:b,throughput:x}=tN(h,y,_,v,i);(0,n.If)(y.hitsGround,()=>{let e=(0,n.clamp)(y.r.mul(_).add(y.tMax.mul(v)).div(mM),-1,1).toVar(),t=WM(m,l,(0,n.float)(0),e,p),r=KM(c,e);for(let i of sN)b[i].addAssign(x[i].mul(l.albedo[i]).mul(1/oN).mul(t[i].mul((0,n.max)(e,0)).add(r[i])))});let S=cN(e=>b[e].mul(l.solar[e])),C=e=>S.reduce((t,r,i)=>t.add((0,n.dot)(r,u[e*4+i])),(0,n.float)(0));s.element(e).assign((0,n.vec4)((0,n.max)((0,n.vec3)(C(0),C(1),C(2)),(0,n.vec3)(0)),1))})().compute(g,[64]),(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(t*r)),()=>{(0,n.Return)()});let i=(0,n.float)(e.mod(t)).add(.5).div(t).sub(.5).mul(2*oN).sub((0,n.atan)(d.z,d.x)),a=(0,n.sqrt)((0,n.abs)((0,n.atan)((0,n.sin)(i),(0,n.cos)(i))).div(oN)).mul(255).toVar(),c=(0,n.min)((0,n.floor)(a),254).toVar(),l=e.div(t).mul(256).add((0,n.uint)(c)).toVar();o.element(e).assign((0,n.mix)(s.element(l),s.element(l.add(1)),a.sub(c)))})().compute(t*r,[64])]}var iN,aN,oN,sN,cN,lN,uN,dN,fN,pN,mN,hN,gN,_N,vN,yN,bN,xN,SN,CN,wN=g((()=>{RM(),iN=Math.sqrt(hM*hM-mM*mM),aN=hM-mM,oN=Math.PI,sN=[0,1,2,3],cN=e=>sN.map(e),lN=e=>(0,n.float)(e).div(15).pow(2).mul(aN),uN=e=>(0,n.sqrt)((0,n.clamp)(e.div(aN),0,1)).mul(15),dN=-3*oN/180,fN=15*oN/180,pN=.5+Math.atan((-oN/2-dN)/fN)/oN,mN=.5+Math.atan((oN/2-dN)/fN)/oN,hN=(e,t)=>(0,n.sin)((0,n.clamp)((0,n.tan)((0,n.float)(e).div(t-1).mul(mN-pN).add(pN-.5).mul(oN)).mul(fN).add(dN),-oN/2,oN/2)),gN=(e,t)=>(0,n.atan)((0,n.asin)((0,n.clamp)(e,-1,1)).sub(dN).div(fN)).div(oN).add(.5-pN).div(mN-pN).mul(t-1),_N=1e-30,vN=e=>(0,n.log)((0,n.max)(e,(0,n.vec4)(_N))),yN=(e,t,r)=>e.sub(t.mul(r)).div((0,n.max)((0,n.sqrt)((0,n.float)(1).sub(t.mul(t)).mul((0,n.float)(1).sub(r.mul(r)))),1e-4)),bN=e=>e.mul(e).add(1).mul(3/(16*oN)),xN=4*oN/128,SN=4,CN=e=>(0,n.float)(e).div(255).pow(2).mul(oN)}));function TN(e,t,r){let i=(0,n.int)(0).toVar(),a=(0,n.int)(e-1).toVar();return(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(Math.ceil(Math.log2(e))+1),type:`int`,condition:`<`,name:`step`},()=>{(0,n.If)(i.lessThan(a),()=>{let e=i.add(a).div(2).toVar();(0,n.If)(t(e).lessThanEqual(r),()=>{i.assign(e.add(1))}).Else(()=>{a.assign(e)})})}),i}function EN({pixels:e,rows:t,prefix:r,stats:i,cdf:a,width:o,height:s}){let c=DN(o),l=(e,t,r)=>(0,n.uint)(t).mul((0,n.uint)(c)).add((0,n.uint)(e).mul((0,n.uint)(4))).add((0,n.uint)(r)),u=e=>(0,n.sin)((0,n.float)(e).add(.5).mul(Math.PI/s)),d=(t,r,i)=>(0,n.dot)(e.element(t.mul(o).add(r)).xyz,Ic).mul(i),f=()=>(0,n.If)(n.instanceIndex.greaterThan((0,n.uint)(0)),()=>{(0,n.Return)()}),p=(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(s)),()=>{(0,n.Return)()});let r=u(e).toVar(),i=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(o),type:`int`,condition:`<`},({i:t})=>{i.addAssign(d(e,(0,n.uint)(t),r))}),t.element(e).assign((0,n.vec4)(i,0,0,0))})().compute(s,[64]),m=(0,n.Fn)(()=>{f();let e=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(s),type:`int`,condition:`<`},({i:n})=>{e.addAssign(t.element(n).x)}),i.element(0).assign((0,n.vec4)(e,e.div(o*s),0,0))})().compute(1,[1]),h=(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(s)),()=>{(0,n.Return)()});let a=u(e).toVar(),c=i.element(0).y.toVar(),l=(0,n.float)(0).toVar(),f=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(o),type:`int`,condition:`<`},({i:t})=>{let i=d(e,(0,n.uint)(t),a).toVar();l.addAssign(i),f.addAssign((0,n.max)(i.sub(c),0)),r.element(e.mul(o).add((0,n.uint)(t))).assign((0,n.vec2)(l,f))}),t.element(e).assign((0,n.vec4)(l,f,0,0))})().compute(s,[64]),g=(0,n.Fn)(()=>{f();let e=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(s),type:`int`,condition:`<`},({i:n})=>{e.addAssign(t.element(n).y)});let r=i.element(0).toVar();i.element(1).assign((0,n.select)(e.greaterThan(0),(0,n.vec4)(e,r.y,1,0),(0,n.vec4)(r.x,0,0,0)))})().compute(1,[1]),_=()=>i.element(0).x.mul(1e-4/(o*s)),v=(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(s)),()=>{(0,n.Return)()});let c=_().toVar(),u=i.element(1).z.greaterThan(0).toVar(),d=t.element(e).toVar(),f=(0,n.select)(u,d.y,d.x).add(c.mul(o)).toVar(),p=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(o),type:`int`,condition:`<`},({i:t})=>{let i=r.element(e.mul(o).add((0,n.uint)(t))).toVar(),s=(0,n.select)(u,i.y,i.x).add(c.mul((0,n.float)(t).add(1))).div((0,n.max)(f,1e-30)),d=(0,n.select)(f.greaterThan(0),(0,n.select)(t.equal((0,n.int)(o-1)),(0,n.float)(1),s),(0,n.float)(0)).toVar();a.element(l(t,e,0)).assign(d),a.element(l(t,e,1)).assign(p),p.assign(d)})})().compute(s,[64]),y=(0,n.Fn)(()=>{f();let e=_().mul(o).toVar(),r=i.element(1).z.greaterThan(0).toVar(),c=i=>{let a=t.element(i);return(0,n.select)(r,a.y,a.x).add(e)},u=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(s),type:`int`,condition:`<`},({i:e})=>{u.addAssign(c(e))});let d=(0,n.float)(0).toVar(),p=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(s),type:`int`,condition:`<`},({i:e})=>{d.addAssign(c(e));let t=(0,n.select)(e.equal((0,n.int)(s-1)),(0,n.float)(1),d.div((0,n.max)(u,1e-30))),r=(0,n.select)(u.greaterThan(0),t,(0,n.float)(0)).toVar();a.element(l(o,e,0)).assign(r),a.element(l(o,e,1)).assign(p),p.assign(r)})})().compute(1,[1]),b=2*o*s;return[p,m,h,g,v,y,(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.uint)(b+2*s)),()=>{(0,n.Return)()}),(0,n.If)(e.lessThan((0,n.uint)(b)),()=>{let t=e.mod(2*o).toVar(),r=e.div(2*o).toVar(),i=TN(o,e=>a.element(l(e,r,0)),(0,n.float)(t).div(2*o));a.element(l(t.shiftRight((0,n.uint)(1)),r,(0,n.uint)(2).add(t.bitAnd((0,n.uint)(1))))).assign((0,n.float)(i))}).Else(()=>{let t=e.sub((0,n.uint)(b)).toVar(),r=TN(s,e=>a.element(l(o,e,0)),(0,n.float)(t).div(2*s));a.element(l(o,t.shiftRight((0,n.uint)(1)),(0,n.uint)(2).add(t.bitAnd((0,n.uint)(1))))).assign((0,n.float)(r))})})().compute(b+2*s,[64])]}var DN,ON=g((()=>{ml(),DN=e=>Math.ceil((e+1)*16/256)*64})),kN=_({PhysicalSky:()=>jN});function AN(e,t,n){let i=new r.DataTexture(null,e,t,n,r.FloatType);return i.source.dataReady=!1,i.needsUpdate=!0,i._isPhysicalSky=!0,i}var jN,MN=g((()=>{k(),Au(),wN(),ON(),Fn(),RM(),jN=class{constructor(e=1024,t=512,n={}){this.width=e,this.height=t,this._quality=n,this.lastRenderTime=0,this._texture=AN(e,t,r.RGBAFormat),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1,this._cdfTexture=AN(e+1,t,r.RGBAFormat),this._rec709Weights=tM(SM),this._attrs=null,this._kernels=null,this._airKey=null,this._transmittanceBuilt=!1}_init(){let e=e=>Array.from({length:e},()=>(0,n.uniform)(new r.Vector4)),i=e(24);this._uniforms={coefficient:i,rgb:e(12),sunDirection:(0,n.uniform)(new r.Vector3(0,1,0)),altitude:(0,n.uniform)(.05),sunSinRadius:(0,n.uniform)(.0046)};let a=e=>v(e,4);this._attrs={transmittance:a(256*64),incomingA:a(1024*128*4),incomingB:a(1024*128*4),transfer:a(1024*128*4),multipleScattering:a(1024*128*8),psiSum:a(1024*128*8),groundE:a(256),irradiance:a(512),sky:a(this.width*this.height),skyRows:a(256*this.height),cdfRows:a(this.height),cdfPrefix:v(this.width*this.height,2),cdfStats:a(2),cdf:v(DN(this.width)*this.height,1),phaseCells:new t.StorageInstancedBufferAttribute(pM(16,8,16,8),4)};let o=(e,t=`vec4`)=>(0,n.storage)(this._attrs[e],t,this._attrs[e].count),s=e=>i.slice(e*4,e*4+4),c={transmittance:o(`transmittance`),transfer:o(`transfer`),psiSum:o(`psiSum`),groundE:o(`groundE`),phaseCells:o(`phaseCells`),multipleScattering:o(`multipleScattering`),irradiance:o(`irradiance`),sky:o(`sky`),skyRows:o(`skyRows`),coefficients:{rayleigh:s(0),mieScattering:s(1),mieExtinction:s(2),ozone:s(3),solar:s(4),albedo:s(5)},rgb:this._uniforms.rgb,sunDirection:this._uniforms.sunDirection,altitude:this._uniforms.altitude,sunSinRadius:this._uniforms.sunSinRadius,mieG:vM},l=this._quality,u=o(`incomingA`),d=o(`incomingB`);this._kernels={transmittance:XM(c),air:[$M(c,{first:!0,out:u,...l.incoming}),eN(c,{incoming:u,stage:`first`}),$M(c,{first:!1,out:d,...l.incoming}),eN(c,{incoming:d,stage:`middle`}),$M(c,{first:!1,out:u,...l.incoming}),eN(c,{incoming:u,stage:`last`}),nN(c,l.irradiance)],sky:rN(c,{width:this.width,height:this.height,...l.sky}),cdf:EN({pixels:c.sky,rows:o(`cdfRows`),prefix:o(`cdfPrefix`,`vec2`),stats:o(`cdfStats`),cdf:o(`cdf`,`float`),width:this.width,height:this.height})},this._setSpectrum(4,kM)}_setColorWeights(){let e=this._rec709Weights,t=kn(),n=[0,0,0,0];for(let r=0;r<3;r++)for(let i=0;i<4;i++){for(let a=0;a<4;a++){let o=i*4+a;n[a]=t?t[r*3]*e[o]+t[r*3+1]*e[16+o]+t[r*3+2]*e[32+o]:e[r*16+o]}this._uniforms.rgb[r*4+i].value.fromArray(n)}}_copyToTextures(e){let t=e.backend;e.initTexture(this._texture),e.initTexture(this._cdfTexture);let n=t.device.createCommandEncoder({label:`PhysicalSky`});n.copyBufferToTexture({buffer:t.get(this._attrs.sky).buffer,bytesPerRow:this.width*16,rowsPerImage:this.height},{texture:t.get(this._texture).texture},[this.width,this.height]),n.copyBufferToTexture({buffer:t.get(this._attrs.cdf).buffer,bytesPerRow:DN(this.width)*4,rowsPerImage:this.height},{texture:t.get(this._cdfTexture).texture},[this.width+1,this.height]),t.device.queue.submit([n.finish()])}_setSpectrum(e,t){for(let n=0;n<4;n++)this._uniforms.coefficient[e*4+n].value.set(t[n*4],t[n*4+1],t[n*4+2],t[n*4+3])}bake(e,t){let n=performance.now();this._kernels||this._init();let r={airDensity:t.airDensity,turbidity:t.turbidity,ozone:t.ozone,groundAlbedo:[...t.groundAlbedo]},i=oM(r),a=Math.max(t.altitude,1)/1e3,o=t.sunAngularDiameter/2,s=this._uniforms;s.sunDirection.value.fromArray(t.sunDirection).normalize(),s.altitude.value=a,s.sunSinRadius.value=Math.sin(o),this._setColorWeights();let c=[];this._transmittanceBuilt||=(c.push(this._kernels.transmittance),!0);let l=JSON.stringify([r,s.sunSinRadius.value]);l!==this._airKey&&(this._setSpectrum(0,i.rayleigh),this._setSpectrum(1,i.mieScattering),this._setSpectrum(2,i.mieExtinction),this._setSpectrum(3,i.ozone),this._setSpectrum(5,i.albedo),c.push(...this._kernels.air),this._airKey=l),c.push(...this._kernels.sky,...this._kernels.cdf),e.compute(c),this._copyToTextures(e);let u=e.getArrayBufferAsync(this._attrs.cdfStats).then(e=>{let t=new Float32Array(e);return{totalSum:t[4],radianceIntegral:2*Math.PI*Math.PI*t[0]/(this.width*this.height)}}),d=dM({direction:[s.sunDirection.value.x,s.sunDirection.value.y,s.sunDirection.value.z],altitude:a,angularDiameter:t.sunAngularDiameter,strength:t.sunStrength??1,coefficients:i});return d.cosHalfAngle=Math.cos(o),d.sinHalfAngle=Math.sin(o),d.horizonSin=sM(a),this.lastRenderTime=performance.now()-n,{texture:this._texture,cdfTexture:this._cdfTexture,sun:d,stats:u}}async readBack(e){let[t,n,r]=await Promise.all([`sky`,`cdf`,`cdfStats`].map(t=>e.getArrayBufferAsync(this._attrs[t])));return{pixels:new Float32Array(t),cdf:new Float32Array(n),cdfStride:DN(this.width),stats:new Float32Array(r)}}getLastRenderTime(){return this.lastRenderTime}dispose(e=null){for(let e of Object.values(this._kernels??{}).flat())e.dispose();for(let t of Object.values(this._attrs??{}))bl(e,t);this._kernels=null,this._attrs=null,this._texture.dispose(),this._cdfTexture.dispose()}}}));Ae(),I(),X(),kS();var NN=ye(`engine`),PN=class extends dv{constructor(e,t={}){super(e,t),this.setColorManagement(iE),this.setStorageOpener(HE),this.settings.define(`interactionRenderScale`,{default:.5,apply:()=>{this.stages?.pathTracer?.interactionMode&&this._requestRenderScale(this._interactionRenderScale())},reset:!1}),this._container=t.container||null,this._animRefitInFlight=!1,this._emittersMoved=!1,this._pendingRenderScale=null,this.cameraManager=null,this.timeline=null,this.goboManager=null,this.iesManager=null,this.denoisingManager=null,this.overlayManager=null,this.interactionManager=null,this.transformManager=null,this.animationManager=new dS}_createCamera(){return this.cameraManager=new ib(this.canvas),this.timeline=new ub({cameraManager:this.cameraManager,onReset:()=>this.reset()}),this.cameraManager.camera}_initAssetPipeline(){super._initAssetPipeline(),this.assetLoader.controls=this.cameraManager.controls,this.assetLoader.registerFormat(...AS),this.assetLoader.setArchiveImporterLoader(()=>Promise.resolve().then(()=>(Xj(),Wj)).then(e=>new e.ArchiveImporter(this.assetLoader)),OS);let e=()=>{this.needsReset=!0,this.stages.pathTracer?.enterInteractionMode(),this.wake()};this._addTrackedListener(this.cameraManager.controls,`change`,e),this._addTrackedListener(this.cameraManager.walkControls,`change`,e),this._addTrackedListener(this.cameraManager.walkControls,`start`,()=>this.wake())}_createExtraStages(){let{renderer:e,stages:t}=this;return t.normalDepth=new Cv(e,{pathTracer:t.pathTracer}),t.motionVector=new wv(e,this.camera,{pathTracer:t.pathTracer}),t.asvgf=new Dv(e,{enabled:!1}),t.nrd=new dy(e,{enabled:!1,pathTracer:t.pathTracer}),t.variance=new my(e,{enabled:!1}),t.bilateralFilter=new gy(e,{enabled:!1}),t.edgeFilter=new Sy(e,{enabled:!1}),t.autoExposure=new Ay(e,{enabled:Cy.autoExposure}),[t.normalDepth,t.motionVector,t.nrd,t.asvgf,t.variance,t.bilateralFilter,t.edgeFilter,t.autoExposure]}_initPipeline(){super._initPipeline(),this.pipeline.eventBus.on(`pathtracer:interactionStart`,()=>this._requestRenderScale(this._interactionRenderScale())),this.pipeline.eventBus.on(`pathtracer:interactionEnd`,()=>this._applyRenderScale(1))}async _initManagers(){await super._initManagers(),this.environmentManager.setProceduralSkyLoader(()=>Promise.resolve().then(()=>(MN(),kN)).then(e=>e.PhysicalSky)),this.stages.pathTracer.registerIntegrator([`bidirectional`,`vcm`],e=>new sw(e)),this.stages.pathTracer.requestOutput(`gBuffer`),this.interactionManager=new Fy({scene:this.meshScene,camera:this.camera,canvas:this.canvas,assetLoader:this.assetLoader,pathTracer:null,floorPlane:this.assetLoader.floorPlane}),this.interactionManager.wireAppEvents(this),this.cameraManager.setInteractionManager(this.interactionManager),this.goboManager=new db(this.stages.pathTracer,{onReset:()=>this.reset(),issues:this._issues}),this.iesManager=new Cb(this.stages.pathTracer,{onReset:()=>this.reset(),issues:this._issues}),this._setupDenoisingManager(),this._headless||(await this._setupOverlayManager(),this.transformManager=new mS({camera:this.camera,canvas:this.canvas,orbitControls:this.cameraManager.controls,app:this}),this.overlayManager.register(`transform`,new hS(this.transformManager))),this.interactionManager.setDependencies({overlayManager:this.overlayManager,transformManager:this.transformManager,appDispatch:e=>this.dispatchEvent(e),orbitControls:this.cameraManager.controls,helperScene:this._sceneHelpers.scene}),this.denoisingManager.setOverlayManager(this.overlayManager),this.denoisingManager.setResetCallback(()=>this.reset()),this.denoisingManager.setPostProcessRefreshCallback(()=>this.requestPostProcessRefresh()),this.denoisingManager.setDisplayRefreshCallback(()=>this._presentDisplay()),this.denoisingManager.setSettings(this.settings)}_wireEvents(){this._addTrackedListener(this.cameraManager,P.CAMERA_SWITCHED,e=>this.dispatchEvent(e)),this._addTrackedListener(this.cameraManager,P.AUTO_FOCUS_UPDATED,e=>this.dispatchEvent(e)),this._addTrackedListener(this.cameraManager,P.ORTHO_HEIGHT_UPDATED,e=>this.dispatchEvent(e)),this._addTrackedListener(this.timeline,P.TIMELINE_CHANGED,e=>this.dispatchEvent(e)),this._forwardEvents(this.denoisingManager,[P.DENOISING_START,P.DENOISING_END,P.UPSCALING_START,P.UPSCALING_PROGRESS,P.UPSCALING_END,P.RESOLUTION_CHANGED]),this._setupAutoExposureListener(),this.animationManager.wakeCallback=()=>this.wake(),this.animationManager.applyPoseCallback=e=>this._applyAnimationPose(e),this._forwardEvents(this.animationManager,[P.ANIMATION_STARTED,P.ANIMATION_PAUSED,P.ANIMATION_STOPPED]),this._addTrackedListener(this.animationManager,P.ANIMATION_PAUSED,()=>{this._animRefitInFlight=!1,this._refreshMovedEmitters()}),this._addTrackedListener(this.animationManager,P.ANIMATION_STOPPED,()=>{this._animRefitInFlight=!1}),this.cameraManager.initCallbacks({onResize:()=>this.onResize(),onReset:()=>this.reset(),getSettings:e=>this.settings.get(e),applySettings:e=>this.settings.setMany(e,{silent:!0,reset:!1})}),this.cameraManager.initAutoFocus({assetLoader:this.assetLoader,pathTracer:this.stages.pathTracer,settings:this.settings,softReset:()=>this.reset(!0),hardReset:()=>this.reset()}),super._wireEvents(),this._addTrackedListener(this.assetLoader,`modelProcessed`,e=>{let t=[this.cameraManager.camera,...e.cameras||[]];this.cameraManager.setCameras(t),this.timeline.clear(),this.interactionManager&&(this.interactionManager.floorPlane=this.assetLoader.floorPlane)})}_displaySources(){return[`oidn:output`,`edgeFiltering:output`,`bilateralFiltering:output`,`asvgf:output`,`nrd:output`]}_settingsBindings(){let e=super._settingsBindings();return{...e,applyExposure:t=>{this.stages.autoExposure?.enabled||e.applyExposure(t)},onCameraProjection:e=>{this.cameraManager.applyProjection(e),e===`equirectangular`&&this.denoisingManager?.requiresMotionVectors&&this.denoisingManager.setDenoiserStrategy(`edgeaware`)}}}_beginFrame(){if(this.timeline.update(),this.cameraManager.updateControls(),this._applyPendingRenderScale(),this.animationManager?.isPlaying&&!this._animRefitInFlight){let e=this.animationManager.update();e&&(this._animRefitInFlight=!0,this.refitBVH(e).catch(e=>NN.error(`animation refit error:`,e)).finally(()=>{this._animRefitInFlight=!1}))}}_beforeTrace(){this.cameraManager.updateAutoFocus()}_holdTrace(e){return this.denoisingManager?.skipsTrace()?(e&&this.stages.pathTracer.enterInteractionMode(),!0):!1}_afterTrace(e,t){this.denoisingManager?.afterTrace(),t&&!e.isComplete&&this.denoisingManager?.tickContinuousDenoise(e.frameCount)}_renderCompleted(){this.denoisingManager.onRenderComplete({isStillComplete:()=>this.completion.renderCompleteDispatched,context:this.pipeline?.context})}_renderHelperOverlay(){super._renderHelperOverlay(),this.overlayManager?.render()}_beforeReset(e){this.denoisingManager?.beforeReset({keepHistory:e})}_afterReset(){this.denoisingManager?.afterReset(),this._abortPostProcess({keepDisplay:!0})}_dropDisplay(){this.denoisingManager?.dropDisplay()}_releaseSceneState({keepSelection:e=!1}={}){e||(this.interactionManager?.deselect(),this.transformManager?.detach?.()),this.animationManager?.dispose(),this._animRefitInFlight=!1,this._emittersMoved=!1}_modelReplaced(){this._syncControlsAfterLoad(),this.cameraManager.currentCameraIndex=0,this.cameraManager.cameras.length>1&&this.cameraManager.switchCamera(1)}_modelAnnounced(){this._dispatchCamerasUpdated()}_sceneRebuilt(){this._initAnimationAndTransforms()}_sceneBoundsChanged(){this._recalibrateControlLimits()}_lightRemoved(e){this.interactionManager?.selectedObject===e&&this.interactionManager.deselect()}_renderSizeChanged(e,t){this.denoisingManager?.setRenderSize(e,t)}_completionReopened(){this.denoisingManager?.abort(this.canvas)}async _finalDenoise(){return this.denoisingManager?.finalDenoise?await this.runFinalDenoise():!1}_displayCanvas(){let e=this.denoisingManager?.upscalerCanvas;return e&&e.style.display!==`none`?e:null}_registerVRAM(e){e.register(`denoiser`,()=>({bytes:this.denoisingManager?.gpuBytes()??0}))}_canvasResources(){return this.overlayManager?.gpuResources()??[]}_deterministicSnapshot(){return{autoFocusMode:this.cameraManager?.autoFocusMode,autoExposure:this.stages.autoExposure?.enabled,continuousDenoise:this.denoisingManager?.continuousDenoise}}_setDeterministicExtras(e,t){if(e){this.cameraManager?.setAutoFocusMode(`manual`),this.stages.autoExposure&&(this.stages.autoExposure.enabled=!1),this.denoisingManager?.setContinuousDenoise(!1);return}t.autoFocusMode!==void 0&&this.cameraManager?.setAutoFocusMode(t.autoFocusMode),this.stages.autoExposure&&t.autoExposure!==void 0&&(this.stages.autoExposure.enabled=t.autoExposure),t.continuousDenoise!==void 0&&this.denoisingManager?.setContinuousDenoise(t.continuousDenoise)}_disposeExtensions(){this.interactionManager?.deselect?.(),this.transformManager?.detach?.(),this.animationManager?.dispose(),this.transformManager?.dispose(),this.overlayManager?.dispose(),this.goboManager?.dispose(),this.iesManager?.dispose(),this.denoisingManager?.dispose(),this.interactionManager?.dispose(),this.timeline?.dispose(),this.cameraManager?.dispose()}get currentCameraIndex(){return this.cameraManager?.currentCameraIndex??0}addCamera({name:e}={}){let t=this.cameraManager.addCameraFromView(e);return this.cameraManager.switchCamera(t),this._dispatchCamerasUpdated(),t}removeCamera(e){let t=this.cameraManager.removeCamera(e);return t&&this._dispatchCamerasUpdated(),t}exportSceneState(){return CS(this)}async importSceneState(e,t){return await DS(this,e,t)}_dispatchCamerasUpdated(){this.dispatchEvent({type:P.CAMERAS_UPDATED,cameras:this.cameraManager.cameras,cameraNames:this.cameraManager.getCameraNames()})}_applyAnimationPose({meshIndices:e,visibilityChanged:t,cameras:n}){if(!this._sdf?.instanceTable)return;let r=!1;e.length>0&&(this._notePlacementsMoving(e),this._sdf.updateMeshTransforms(e),this.stages.pathTracer?.updateBufferRanges([],[this._sdf.computeTLASDirtyRange()]),this._sdf.movesEmitters(e)&&(this._emittersMoved=!0,this.animationManager.isPlaying||this._refreshMovedEmitters()),r=!0),t&&(this.stages.pathTracer?.updateAllMeshVisibility(),this._refreshEmissiveForVisibility(),r=!0),n.length>0&&this._followAnimatedCamera(n)&&(r=!0),r&&this.reset(!1,{motion:!0})}_notePlacementsMoving(e){let t=this.denoisingManager,n=this._sdf?.instanceTable;if(!(!t?.historyActive||!n))for(let r of e){let e=n.placementRunOf(r);if(e)for(let r=e.start;r<e.start+e.count;r++)t.notePlacementMoving(n.tlasLeafIndex[r],n.world,r*16)}}_refreshMovedEmitters(){if(this._emittersMoved){if(this._sdf?.spilled){this.ensureSceneResident().then(()=>this._refreshMovedEmitters());return}this._emittersMoved=!1,this._uploadEmissivePayload(this._sdf?.refreshEmissiveTransforms()??null)}}_followAnimatedCamera(e){let t=this.cameraManager,n=t.currentCameraIndex>0?t.cameras[t.currentCameraIndex]:null,i=n?.userData?.__rayzeeSourceUuid,a=i&&e.find(e=>e.uuid===i);if(!a)return!1;a.updateWorldMatrix(!0,!1);let o=new r.Vector3;a.matrixWorld.decompose(n.position,n.quaternion,o),n.scale.set(Math.sign(o.x)||1,Math.sign(o.y)||1,Math.sign(o.z)||1),a.isPerspectiveCamera&&(n.fov=a.fov);let s=t.camera,c=t.controls,l=c?c.target.distanceTo(s.position):0;if(s.position.copy(n.position),s.quaternion.copy(n.quaternion),s.scale.copy(n.scale),s.isPerspectiveCamera&&n.isPerspectiveCamera&&(s.fov=n.fov),s.updateProjectionMatrix(),s.updateMatrixWorld(!0),c){let e=new r.Vector3(0,0,-1).applyQuaternion(s.quaternion);c.target.copy(s.position).addScaledVector(e,l||1)}return!0}_interactionRenderScale(){if(this.denoisingManager?.continuousDenoise)return 1;let e=Number(this.settings.get(`interactionRenderScale`));return e>0?Math.min(1,Math.max(.125,e)):1}_requestRenderScale(e){this._pendingRenderScale=e}_applyPendingRenderScale(){this._pendingRenderScale!==null&&this._applyRenderScale(this._pendingRenderScale)}_applyRenderScale(e){this._pendingRenderScale=null,!(this._disposed||e===this._renderScale)&&(this._renderScale=e,!(!this._displayWidth||!this._displayHeight)&&(this._setDisplaySize(this._displayWidth,this._displayHeight),this.pipeline?.setSize(this._scaled(this._displayWidth),this._scaled(this._displayHeight)),this.pipeline?.eventBus.emit(`pipeline:historyReset`),this.needsReset=!0))}configureForMode(e,t={}){let n=e===`production`,r=n?it:at;this.denoisingManager?.setCadenceSuspended(n),this.timeline.stop(),this.cameraManager.controls.enabled=!n,this.settings.setMany(ot(r),{silent:!0,source:Xg.MODE_PRESET}),this.stages.pathTracer?.setUniform(`renderMode`,parseInt(r.renderMode)),n&&this._applyRenderScale(1),this.stages.pathTracer?.updateCompletionThreshold?.();let i=this.denoisingManager?.denoiser;if(i&&(i.abort(),this.denoisingManager.applyOIDNEnabled(r.enableOIDN),this.denoisingManager.applyOIDNQuality(r.oidnQuality)),this.denoisingManager?._syncGBufferStages?.(),this.denoisingManager?.upscaler?.abort(),t.canvasWidth&&t.canvasHeight&&(this.setReservedRenderResolution(Math.max(t.canvasWidth,t.canvasHeight)),this.setCanvasSize(t.canvasWidth,t.canvasHeight)),this.needsReset=!1,this.pauseRendering=!1,n){let e=this.stages.pathTracer?.vramTracker;e&&(e.measure(),e.resetPeak())}this.reset()}_presentDisplay(){if(this.animationManagerId){this._needsDisplayRefresh=!0;return}let e=this.pipeline?.context;this._deviceLost||!e||(this.stages.compositor?.render(e),this._renderHelperOverlay())}async runFinalDenoise(){let e=this.denoisingManager;if(await e?.denoiseOnce())return!0;let t=e?.denoiser?e.denoiser.enabled?`the denoise did not complete`:`OIDN was off while accumulating — call denoisingManager.setOIDNEnabled( true ) first`:`the denoiser was not built`;return this._issues.record(Y.DENOISER_UNAVAILABLE,`final denoise produced no picture: ${t}`,{reason:t}),!1}_abortPostProcess({keepDisplay:e=!1}={}){if(this.denoisingManager?.abort(this.canvas,{keepDisplay:e}),this.denoisingManager?.restoreBaseResolution()){let e=this.denoisingManager._lastRenderWidth,t=this.denoisingManager._lastRenderHeight;this.dispatchEvent({type:P.RESOLUTION_CHANGED,width:e,height:t})}}requestPostProcessRefresh(){!this.stages.pathTracer?.isReady||this._deviceLost||(this._abortPostProcess(),this.completion.renderCompleteDispatched=!1,this.wake())}profileNextDenoise(){return this.denoisingManager?.denoiser?.profileNextDenoise()??!1}async getDenoiseProfile(){let e=this.denoisingManager?.denoiser;return e?{profile:await e.getLastDenoiseProfile(),runtime:e.getRuntimeInfo()}:null}_denoiserInUse(){let e=this.denoisingManager;return!!e?.denoiser?.enabled||(e?.denoiserStrategy??`none`)!==`none`}_initAnimationAndTransforms(){let e=this.assetLoader?.animations||[];if(e.length>0){let t=this.sceneModel||this.meshScene;this.animationManager.init(this.meshScene,t,this._sdf.meshes,e),this.animationManager.onFinished=()=>{this._animRefitInFlight=!1,this._refreshMovedEmitters(),this.dispatchEvent({type:P.ANIMATION_FINISHED})}}this.transformManager?.setMeshData(this._sdf.meshes)}_setupDenoisingManager(){this.denoisingManager=new eS({renderer:this.renderer,mainCanvas:this.canvas,stages:{pathTracer:this.stages.pathTracer,normalDepth:this.stages.normalDepth,motionVector:this.stages.motionVector,asvgf:this.stages.asvgf,nrd:this.stages.nrd,variance:this.stages.variance,bilateralFilter:this.stages.bilateralFilter,edgeFilter:this.stages.edgeFilter,autoExposure:this.stages.autoExposure,compositor:this.stages.compositor},pipeline:this.pipeline,getExposure:()=>this.settings.get(`exposure`)??1,getSaturation:()=>this.settings.get(`saturation`)??1,issues:this._issues}),this.denoisingManager.setupDenoiser(),this.denoisingManager.setupUpscaler(),this.denoisingManager._syncGBufferStages();let e=this.canvas.clientWidth||1,t=this.canvas.clientHeight||1;this.denoisingManager.setRenderSize(e,t)}_setupAutoExposureListener(){this.stages.autoExposure&&this.stages.autoExposure.on(`autoexposure:updated`,e=>{this.dispatchEvent({type:P.AUTO_EXPOSURE_UPDATED,exposure:e.exposure,luminance:e.luminance})})}async _setupOverlayManager(){this.overlayManager=new lS(this.cameraManager.camera),this.overlayManager.setupDefaultHelpers({helperScene:this._sceneHelpers,meshScene:this.meshScene,pipeline:this.pipeline,denoisingManager:this.denoisingManager,app:this,renderWidth:this.denoisingManager?._lastRenderWidth||this.canvas.clientWidth||1,renderHeight:this.denoisingManager?._lastRenderHeight||this.canvas.clientHeight||1}),await this.overlayManager.initViewRenderer({device:this.renderer.backend?.device,sizeSource:this.canvas}),this._container=this._container||this.canvas.parentNode||null,this.overlayManager.mount(this._container)}_syncControlsAfterLoad(){this.cameraManager.fitOrthographic(),this.cameraManager.controls.saveState(),this.cameraManager.controls.update(),this.cameraManager.walkControls.fitSpeed(this.assetLoader.getSceneScale())}_recalibrateControlLimits(){if(!this.meshScene||!this.cameraManager)return;let e=new r.Box3,t=new r.Box3;for(let n of this.meshScene.children)n.userData?.__rayzeeSceneObject&&(t.setFromObject(n),t.isEmpty()||e.union(t));if(e.isEmpty())return;let n=Math.max(e.max.x-e.min.x,e.max.y-e.min.y,e.max.z-e.min.z);if(!Number.isFinite(n)||n<=0)return;let{camera:i,controls:a}=this.cameraManager,o=i.fov*(Math.PI/180),s=Math.abs(n/Math.sin(o/2)/2);this.cameraManager.currentCameraIndex===0&&(i.near=n/100,i.far=n*100,i.updateProjectionMatrix());let c=i.position.distanceTo(a.target);a.minDistance=Math.min(n/1e3,c),a.maxDistance=Math.max(s*10,c*1.1),a.update()}};async function FN(e){let t=await LN(e);try{return await IN(t,e)}finally{t.dispose()}}async function IN(e,{samples:t=64,colorSpace:n=`srgb`,allowEarlyRetire:r=!1,denoise:i=!1,onProgress:a=void 0}={}){let o=e.denoisingManager;i&&o&&!o.finalDenoise&&(o.applyOIDNEnabled(!0),o._syncGBufferStages());let s=await e.renderFrames(t,{onProgress:a,allowEarlyRetire:r});return i&&await e.runFinalDenoise(),{...await e.renderToBuffer({colorSpace:n,source:i?`display`:`accumulation`}),samples:s,retiredBy:s<t?`converged`:`count`,issues:e.issues,adapter:e.adapterInfo,provenance:e.getProvenance()}}async function LN({canvas:e,model:t=null,width:n=1920,height:r=1080,strict:i=!0,deterministic:a=!0,settings:o=null,storage:s=!1,hostMemoryGB:c=void 0}={}){let l=new PN(e??null,{autoResize:!1,strict:i,storage:s,hostMemoryGB:c});try{return l.setReservedRenderResolution(Math.max(n,r)),await l.init(),l.setCanvasSize(n,r),o&&l.settings.setMany(o,{silent:!0}),t&&await l.loadModel(t),o&&l.settings.setMany(o,{silent:!0}),a&&l.setDeterministicMode(!0),l}catch(e){throw l.dispose(),e}}Jg(),I(),fe();var RN=class{constructor(e){this._app=e,this._cancelled=!1,this._rendering=!1}async renderAnimation(e={}){let{clipIndex:t=0,fps:n=30,speed:r=1,samplesPerFrame:i=it.maxSamples,enableOIDN:a=!0,timeline:o=null,startFrame:s=0,onFrame:c,onProgress:l,onComplete:u}=e,d=this._app,f=d.animationManager?.hasAnimations?d.animationManager.clips[t]:null;if(!f&&!o?.animates){console.warn(d.animationManager?.hasAnimations?`VideoRenderManager: Invalid clip index ${t}`:`VideoRenderManager: No animation clips or keyframes`),u?.(!1);return}let p=f?f.duration/(r||1):o.duration,m=e.totalFrames||Math.ceil(p*n),h=1/n;if(!(m>0)){console.warn(`VideoRenderManager: No frames to render`),u?.(!1);return}this._cancelled=!1,this._rendering=!0;let g=this._saveState({view:!!o});d.stopAnimation(),d.configureForMode(`production`),d.settings.setMany({maxSamples:i},{silent:!0}),d.stages.pathTracer?.updateCompletionThreshold?.(),d.cameraManager.controls&&(d.cameraManager.controls.enabled=!1);try{for(let e=Math.max(0,s);e<m&&!this._cancelled;e++){let n=e*h*r,i=f?d.animationManager.seekTo(n,t):null;if(o?.seek(e*h)&&(d.cameraManager.resetAutoFocus(),d.cameraManager.updateAutoFocus()),i?await d.refitBVH(i):d.reset(),d.stopAnimation(),await this._accumulateFrame(d),this._cancelled||(a&&d.denoisingManager?.finalDenoise&&await this._waitForDenoise(d),this._cancelled))break;let s=d.getCanvas();if(s&&c){let t=await createImageBitmap(s);await c(t,e,m),t.close()}let u={frame:e+1,totalFrames:m,percent:(e+1)/m*100};l?.(u),d.dispatchEvent({type:P.VIDEO_RENDER_PROGRESS,...u})}}catch(e){console.error(`VideoRenderManager: Render error:`,e),this._cancelled=!0}finally{this._restoreState(g),this._rendering=!1;let e=!this._cancelled;u?.(e),d.dispatchEvent({type:P.VIDEO_RENDER_COMPLETE,success:e})}}cancel(){this._cancelled=!0}get isRendering(){return this._rendering}async _accumulateFrame(e){let t=e.stages.pathTracer;if(t?.isReady)for(;!t.isComplete&&!this._cancelled;){let n=t.readbackWait();if(n){await n;continue}e.cameraManager.camera.updateMatrixWorld(),e.pipeline.render(),t.frameCount%4==0&&(de({samples:ee(t)}),await new Promise(e=>setTimeout(e,0)))}}_waitForDenoise(e){return new Promise(t=>{let n,r=()=>{e.removeEventListener(P.DENOISING_END,i),clearTimeout(n)},i=()=>{r(),t()};n=setTimeout(()=>{console.warn(`VideoRenderManager: Denoise timed out, skipping`),r(),t()},3e4),e.addEventListener(P.DENOISING_END,i),e.denoisingManager.onRenderComplete({isStillComplete:()=>!this._cancelled,context:e.pipeline?.context})})}_saveState({view:e}){let t=this._app,n=t.settings.getEffective(),r=Object.keys(ot(it));return e&&r.push(`focusDistance`),{view:e?t.cameraManager.captureView():null,settings:r.map(e=>[e,n[e]]),renderMode:t.stages.pathTracer?.renderMode?.value,controlsEnabled:t.cameraManager.controls?.enabled,oidnEnabled:t.denoisingManager?.finalDenoise,oidnQuality:t.denoisingManager?.oidnQuality,wasPlaying:t.animationManager?.isPlaying,pauseRendering:t.pauseRendering}}_restoreState(e){let t=this._app;for(let[n,r]of e.settings)r&&t.settings.set(n,r.value,{silent:!0,reset:!1,source:r.source});t.stages.pathTracer&&e.renderMode!==void 0&&t.stages.pathTracer?.setUniform(`renderMode`,parseInt(e.renderMode)),t.stages.pathTracer?.updateCompletionThreshold?.(),t.cameraManager.controls&&(t.cameraManager.controls.enabled=e.controlsEnabled??!0),t.denoisingManager?.denoiser&&(t.denoisingManager.applyOIDNEnabled(e.oidnEnabled??!1),e.oidnQuality&&t.denoisingManager.applyOIDNQuality(e.oidnQuality)),t.pauseRendering=e.pauseRendering??!1,e.view&&t.cameraManager.applyPose(e.view),t.denoisingManager?.setCadenceSuspended(!1),t.animationManager?.stop(),t.reset(),t.wake()}};k(),I(),X(),zr(),jD(),kS(),Ms(),z_(),Ae(),wt(),La(),Ox(),Hx(),ko(),e.ARCHIVE_FORMATS=OS,e.ASVGF_QUALITY_PRESETS=hv,e.AUTO_EXPOSURE_DEFAULTS=Cy,e.AUTO_FOCUS_DEFAULTS=Qy,e.AnimationManager=dS,e.BVH_LEAF_MARKERS=St,e.CameraManager=ib,e.CameraTrack=cb,e.ColorManagement=iE,e.DEFAULT_LUT_SIZE=vT,e.DEFAULT_MAX_EV=_T,e.DEFAULT_MIN_EV=gT,e.DEFAULT_SUN_PATH=Xr,e.DEFAULT_VIEW=Oo,e.DEFAULT_WORKING_SPACE=Er,e.DENOISER_DEFAULTS=Sv,e.DOWNLOAD_POLICY=wg,e.DenoisingManager=eS,e.DownloadCache=Mg,e.ENGINE_AREAS=tn,e.ENGINE_DEFAULTS=G,e.EngineEvents=P,e.EngineIssueError=Gt,e.GoboManager=db,e.IESManager=Cb,e.INTERACTIVE_RENDER_CONFIG=at,e.ISSUE_CODES=Y,e.ISSUE_SEVERITY=Wt,e.InteractionManager=Fy,e.IssueLog=Kt,e.LEGACY_EVENT_NAMES=F,e.LOG_LEVELS=xe,e.LightManager=ev,e.Logger=Oe,e.MATERIAL_DEFAULTS=nt,e.MATERIAL_VALUE_SOURCE=gn,e.MAX_RESERVABLE_RENDER_SIZE=je,e.MAX_SCENE_BYTES=ja,e.MAX_TABLE_TRANSFORMS=xo,e.MemoryLedger=Ia,e.NRD_DEFAULTS=vv,e.NRD_HIT_DIST_A=gv,e.NRD_HIT_DIST_B=_v,e.NRD_PRESET_KEYS=yv,e.NRD_QUALITY_PRESETS=bv,e.OCIO_VIEW_BASE=bo,e.OverlayManager=lS,e.PRODUCTION_RENDER_CONFIG=it,e.PathTracerApp=PN,e.PipelineContext=sg,e.RETOUCH_DEFAULTS=Nx,e.RETOUCH_MAX_PIXELS=Fx,e.RETOUCH_RANGES=Ix,e.RayzeeRenderer=dv,e.RenderPipeline=yg,e.RenderSettings=Zg,e.RenderStage=M,e.SAFE_SCENE_BYTES=Aa,e.SCENE_STATE_VERSION=gS,e.SETTING_SOURCE=Xg,e.SKY_DEFAULTS=Qr,e.SR_MAX_INPUT=Cx,e.SR_SCALE=xx,e.STORAGE_KIND=en,e.StageExecutionMode=j,e.StorageManager=ME,e.TRIANGLE_DATA_LAYOUT=K,e.TimelineManager=ub,e.TransformManager=mS,e.VERSION=js,e.VIEW_TRANSFORMS=Eo,e.VRAMTracker=Uu,e.VideoRenderManager=RN,e.acquireLock=dE,e.addAllOcioViews=kT,e.addOcioView=OT,e.addViewTransform=mo,e.applyMatrixRGBA8=eT,e.bakeLut=sT,e.bufferBytes=Vu,e.buildOcioView=TT,e.buildToneMapWGSL=vo,e.cachedObjectURL=Fg,e.canvasColorSpaceFor=eE,e.captureHeadless=IN,e.clearBindingAuditFindings=mg,e.clearInputOverrides=WT,e.configureAssets=Pr,e.configurePlatform=rr,e.convertColor=Vw,e.convertEncodedRGBA8=Yw,e.convertPixelsF32=Hw,e.createLogger=ye,e.dayOfYearForMonth=Tr,e.deriveAlphaMode=bn,e.describeAdapter=uv,e.displayCanvasFit=cw,e.estimateSceneBytes=Ca,e.extractMatrix=tT,e.extractSceneMetadata=I_,e.fetchFile=Ng,e.fileIdentity=Bg,e.findNativeLinearSpace=rE,e.fmt=H,e.fromPortable=Ln,e.getActiveColorManagement=Or,e.getAssetConfig=Ir,e.getBindingAuditFindings=pg,e.getPlatform=ir,e.getRegistryVersion=so,e.getViewTransform=lo,e.hasColorSpace=rT,e.heldLockNames=fE,e.identityKey=Vg,e.isColorManaged=aE,e.isDataSpace=nT,e.isDataTexture=XT,e.linearToSrgb=Gw,e.listFileRules=qT,e.listInputOverrides=GT,e.listViewTransforms=uo,e.makeCpuSampler=pT,e.measureBakeError=hT,e.nameFromUrl=Og,e.onRegistryChange=co,e.openHeadless=LN,e.openStorage=VE,e.openZip=CD,e.parseSceneMetadata=F_,e.probeAddressSpace=wa,e.readZipDirectory=bD,e.removeViewTransform=ho,e.renderHeadless=FN,e.renderUpscaled=vx,e.resolveInputSpace=YT,e.sameIdentity=Hg,e.setActiveColorManagement=kr,e.setBindingAudit=fg,e.setInputOverride=UT,e.srgbToLinear=Ww,e.sunPosition=Cr,e.textureBytes=Hu,e.textureInputSpace=$T,e.timeForSunElevation=wr,e.toPortable=In});